Overview
kap provides Python and Rust solvers for k-partite assignment from pairwise cost matrices. It includes heuristic searches, an optimum bound for equal-size parts, and a linear assignment solver; Python also provides an exact MILP solver.
Documentation
Example
import numpy as np
import kap
costs = [np.array([[4, 1], [2, 3]]) for _ in range(3)]
result = kap.ils(costs, max_iter=10, random_state=0)
print(result.cliques, result.costs)
use kap::{Algo, MatrixView, Options, k_assignment};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let data = [4i64, 1, 2, 3];
let matrix = MatrixView::from_row_major(&data, 2, 2)?;
let costs = [matrix, matrix, matrix];
let result = k_assignment(&costs, Algo::Ils, &Options::default())?;
println!("{:?} {:?}", result.cliques, result.costs);
Ok(())
}
Python output:
[[(0, 0), (1, 1), (2, 1)], [(0, 1), (1, 0), (2, 0)]] [5, 8]
The Rust example prints the same cliques and costs in the same format.
Initial solutions
Use a warm start to supply a complete assignment to ILS or local search. For implementation details and the original algorithms, see the algorithms reference.
Reference
B. Gabrovšek, T. Novak, J. Povh, D. Rupnik Poklukar, and J. Žerovnik, “Multiple Hungarian Method for k-Assignment Problem,” Mathematics 8(11), 2050, 2020. doi:10.3390/math8112050.
The papers behind the other methods are listed in the algorithms reference.
Installation
PyPI wheels
The Python package requires Python 3.10 or newer and NumPy. The wheel workflow builds CPython abi3 wheels with a Python 3.10 minimum for these targets:
| System | Architecture |
|---|---|
| Linux | x86-64, AArch64 |
| macOS | x86-64 and Apple Silicon (AArch64), as one universal2 wheel |
| Windows | x86-64 |
The workflow tests Python 3.10 and 3.14. Each abi3 wheel serves compatible CPython versions from 3.10 onward; it does not require a separate wheel for every Python minor version.
python -m pip install kap
The wheel includes the native Rust core and its LAP solver. It requires no Rust compiler at installation time.
Optional Python backends
SciPy supplies both the exact solver’s HiGHS MILP implementation and the optional SciPy LAP backend:
python -m pip install "kap[scipy]"
The other LAP extras are kap[lap], kap[lapjv], and kap[munkres]. lapjv requires square matrices. See linear assignment for the interfaces and benchmarks for timings.
Build from source
The workspace declares Rust 1.85 as its minimum toolchain version and uses Rust edition 2024. Create a Python virtual environment and install maturin before building:
git clone https://github.com/inspiros/kap
cd kap
python -m venv .venv
. .venv/bin/activate
python -m pip install "maturin>=1.9,<2"
maturin develop --release
maturin develop installs the extension into the active virtual environment. A source installation through python -m pip install . also builds with maturin and requires Rust.
Rust crate
The package is kap-solver; the library import is kap. For the version documented here, use:
[dependencies]
kap-solver = "0.3.0"
The crate’s default feature set is empty. Enable rayon for parallel chains, trials, or neighborhood work:
[dependencies]
kap-solver = { version = "0.3.0", features = ["rayon"] }
MatrixView::from_row_major and MatrixView::from_strided require no optional features.
Problem definition
Let V₀, …, Vₖ₋₁ be disjoint parts. For each i < j, Cᵢⱼ[u,v] gives the cost of pairing vertex u in Vᵢ with vertex v in Vⱼ. A solution partitions the vertices into N = maxᵢ |Vᵢ| cliques, counting singletons, with at most one vertex from each part in each clique.
For a clique Q, define its cost as:
cost(Q) = Σi<j; (i,u),(j,v)∈Q Cᵢⱼ[u,v]
The objective is:
minimize ΣQ in the partition cost(Q)
Use maximization for weights instead of costs. Equal-size parts give full k-vertex cliques; unequal sizes can leave parts absent from a clique or produce free singleton vertices.
With threshold=tau, optional matching instead optimizes the sum of (cost − tau) over pairs sharing a clique, over all partitions into cliques with at most one vertex per part, singletons allowed; returned costs stay in original units.
See input and results for matrix order and the result representation.
Reference
B. Gabrovšek, T. Novak, J. Povh, D. Rupnik Poklukar, and J. Žerovnik, “Multiple Hungarian Method for k-Assignment Problem,” Mathematics 8(11), 2050, 2020. doi:10.3390/math8112050.
Input and results
The k-assignment functions accept pairwise cost matrices and return cliques with their summed costs. Use unequal part sizes when some cliques may omit parts.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def k_assignment(cost_matrices: Sequence[Array2DLike], algo: Optional[str] = None,
max_iter: Optional[int] = None, n_trials: int = 1, maximize: bool = False,
return_free: bool = False, backend: str = "kap",
random_state: Optional[Union[np.random.RandomState, int]] = None,
refine: Optional[str] = None, time_limit: Optional[float] = None,
population: Optional[int] = None) -> AssignmentResult:
...
#![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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
algo | algo | None / required | Python: ILS with native kap, otherwise Cm. Rust always requires an Algo. |
max_iter | opts.max_iter | None / 100 | Moves, sweeps, perturbations per chain, or generations; Python resolves None by algorithm and time mode. |
n_trials | opts.n_trials | 1 | Em trials or ILS chains; positive for those methods. |
maximize | opts.sense | False / Sense::Minimize | Maximize the original costs when true / Sense::Maximize. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
backend | - | "kap" | Native kap or optional scipy, lap, lapjv, munkres; newer methods require native kap. |
random_state | opts.seed | None / 0 | Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64. |
refine | opts.refine or opts.dv | None / None or Dv::One | 1DV or sDV after construction; inside ILS/memetic it selects the search neighborhood. |
time_limit | opts.time_limit | None | Python: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply. |
population | opts.population | None | Memetic population size; supplied values must be integers at least 2. |
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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | All Python matrices are integer or boolean and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A constituent LAP encounters an invalid numeric entry or an infeasible assignment. |
Matrix order
For k=4, supply the matrices in this order. Rows index the first part; columns index the second part.
| Position | Pair | Matrix shape |
|---|---|---|
| 0 | (0, 1) | C01: n0 × n1 |
| 1 | (0, 2) | C02: n0 × n2 |
| 2 | (0, 3) | C03: n0 × n3 |
| 3 | (1, 2) | C12: n1 × n2 |
| 4 | (1, 3) | C13: n1 × n3 |
| 5 | (2, 3) | C23: n2 × n3 |
Example
import numpy as np
import kap
C01 = np.array([[9, 2, 7], [6, 4, 3], [5, 8, 1]], dtype=np.int64)
C02 = np.array([[3, 8], [7, 2], [6, 4]], dtype=np.int64)
C12 = np.array([[4, 9], [1, 5], [8, 2]], dtype=np.int64)
costs = [C01, C02, C12]
print("shapes =", [matrix.shape for matrix in costs])
result = kap.multiple_hungarian(costs, method="Am", return_free=True)
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
result = kap.multiple_hungarian(costs, method="Am", maximize=True, return_free=True)
print("maximize:")
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
use kap::{Algo, MatrixView, Options, Sense, k_assignment};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let c01 = [9, 2, 7, 6, 4, 3, 5, 8, 1i64];
let c02 = [3, 8, 7, 2, 6, 4i64];
let c12 = [4, 9, 1, 5, 8, 2i64];
let costs = [
MatrixView::from_row_major(&c01, 3, 3)?,
MatrixView::from_row_major(&c02, 3, 2)?,
MatrixView::from_row_major(&c12, 3, 2)?,
];
println!(
"shapes = {:?}",
costs
.iter()
.map(|m| (m.rows(), m.cols()))
.collect::<Vec<_>>()
);
let result = k_assignment(&costs, Algo::Am, &Options::default())?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
let opts = Options {
sense: Sense::Maximize,
..Options::default()
};
let result = k_assignment(&costs, Algo::Am, &opts)?;
println!("maximize:");
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
shapes = [(3, 3), (3, 2), (3, 2)]
cliques = [[(0, 0), (1, 1), (2, 0)], [(0, 2), (1, 2), (2, 1)], [(0, 1), (1, 0)]]
costs = [6, 7, 6]
free = []
maximize:
cliques = [[(0, 0), (1, 2), (2, 0)], [(0, 1), (1, 0), (2, 1)], [(0, 2), (1, 1)]]
costs = [18, 17, 8]
free = []
The Rust example prints the same cliques and costs, with the same free vertices.
Here k=3, with part sizes 3, 3, and 2. C01 has shape (3, 3); C02 and C12 each have shape (3, 2). Each cliques entry lists the vertices in one clique. costs gives the cost of that clique, summed over its pairs. free is empty because every vertex belongs to a clique of size at least two; a part missing from a clique does not make the other vertices free.
The minimizing result contains these cliques:
| Vertices (part, vertex) | Pairwise cost calculation | Clique cost |
|---|---|---|
| (0, 0), (1, 1), (2, 0) | C01[0,1] + C02[0,0] + C12[1,0] = 2 + 3 + 1 | 6 |
| (0, 2), (1, 2), (2, 1) | C01[2,2] + C02[2,1] + C12[2,1] = 1 + 4 + 2 | 7 |
| (0, 1), (1, 0) | C01[1,0] = 6 | 6 |
The second solve maximizes the same pairwise costs. The costs printed in that result retain their original signs.
Dtype promotion
The native Python k-assignment methods and lower bound promote all integer/boolean matrices to int64. If any matrix is floating-point, every matrix becomes float64. Complex, object, and string dtypes are rejected.
A uint64 value above the signed 64-bit maximum raises OverflowError on the all-integer path. Conversion to float64 permits larger magnitudes but can lose integer precision. The linear-assignment function has its own dtype conversion rules; the exact solver forms its MILP objective in float64.
Rust matrix views
MatrixView::from_row_major(data, rows, cols) borrows a row-major slice. The slice must contain at least rows*cols elements; extra elements are allowed. MatrixView::from_strided(data, offset, rows, cols, row_stride, col_stride) borrows a general strided view, with strides in elements and negative strides permitted when every addressed element stays inside the slice. Both constructors return Result<MatrixView, LapError>.
t() returns a transposed view; rows(), cols(), and get(row, col) inspect it. There is no MatrixView::new constructor. All views passed to a solve share an element type supported by Cost.
Notes and limits
- The native core accepts 2 through 64 parts. A valid matrix count is k(k−1)/2, with consistent dimensions across every occurrence of a part.
- Part sizes may differ for the heuristic methods; exact and lower_bound require equal sizes.
- Free vertices are singleton nodes. They contribute zero pairwise cost and are excluded from the clique and cost lists.
- Select maximize=True in Python, or Sense::Maximize in Rust. The returned costs use the original objective sense.
See also
Dispatcher options · Warm starts · Linear assignment
Solver selection
Use iterated local search for heuristic k-assignment. Use linear assignment for a two-part problem.
By task
| Need | Function | When |
|---|---|---|
| Default heuristic search | ils / Algo::Ils | Use time_limit and several chains; compare the measured gaps to the optimum. |
| Original multiple Hungarian methods | multiple_hungarian / Am–Fm | Reproduce the paper’s methods; Am, Dm, and Shift limit construction work, while Bm-based methods grow rapidly with k. |
| Refine a complete solution | local_search / DV | Apply deterministic 1DV or sDV sweeps, with a constructed start or a supplied complete solution. |
| Population search | memetic / Algo::Memetic | Compare with ILS on your instances; optional matching changes their relative results. |
| Choose a method by name | k_assignment | Retain a common Python dispatcher or select an explicit Rust Algo. |
| Allow vertices to stay unmatched | threshold= / Options::threshold | Use optional matching with the native heuristics; forbidden infinities exclude individual pairs. |
| Prove an optimum | exact (Python only) | Use small equal-size inputs, with about 10⁵ tuple variables as a practical limit. |
| Bound the remaining improvement | lower_bound | Measured k=3 and metric-cost gaps were small; random costs at k≥4 gave looser bounds. |
| Solve a two-part LAP | linear_sum_assignment | Compute an optimal rectangular linear assignment. |
See the benchmarks for instance definitions, hardware, timings, and gaps.
Usage
- Define your parts and pairwise cost matrices.
- Run ILS with an iteration limit or time budget.
- Refine an existing complete assignment with a warm start.
- For equal-size parts, compare against a lower bound, or use the Python exact solver on a small instance.
For the mathematical objective and unequal-size parts, see problem definition.
Iterated local search
ILS perturbs a solution and applies dimensionwise variation (DV) after each perturbation. Use a time budget and several chains when solution quality matters; see the measured comparisons.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def ils(cost_matrices, *, max_iter=None, n_chains=1, time_limit=None, neighborhood="1dv",
maximize=False, return_free=False, random_state=None, initial=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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
max_iter | opts.max_iter | None / 100 | Nonnegative perturbations per chain. Python resolves None to 100, or sys.maxsize with a time limit. |
n_chains | opts.n_trials | 1 | Positive number of independent chains. |
time_limit | opts.time_limit | None | Python: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply. |
neighborhood | opts.dv | "1dv" / Dv::One | Use "1dv" or "sdv" / Dv::Subsets; aliases "dv1" and "dvs" are accepted in Python, case-insensitively. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
random_state | opts.seed | None / 0 | Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64. |
initial | cliques in k_assignment_from | None / required by k_assignment_from | A complete solution without a threshold; partial or empty solutions with one. See warm starts. |
| - | opts.refine | None | Optional DV pass after the search; separate from the internal opts.dv. |
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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A constituent LAP encounters an invalid numeric entry or an infeasible assignment. |
Python raises RuntimeError if the required native core is unavailable without a threshold; with a threshold it raises ValueError.
Python raises ValueError for a negative integer seed and TypeError for an unsupported seed object.
Python raises TypeError for non-integer or boolean iteration and chain counts, and ValueError for counts below their permitted minimum, invalid neighborhoods, or an invalid time budget. Rust returns KapError::BadOption("n_trials") for zero chains and KapError::Unsupported for sDV above 16 parts. Invalid starts use the errors listed under warm starts.
Example
import numpy as np
import kap
C01 = np.array([[18, 8, 29], [28, 2, 6], [6, 6, 17]], dtype=np.int64)
C02 = np.array([[11, 14, 7], [28, 20, 20], [4, 5, 26]], dtype=np.int64)
C12 = np.array([[10, 25, 23], [1, 14, 16], [14, 4, 21]], dtype=np.int64)
costs = [C01, C02, C12]
result = kap.ils(costs, max_iter=20, n_chains=2, random_state=0, 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 = [18, 8, 29, 28, 2, 6, 6, 6, 17i64];
let c02 = [11, 14, 7, 28, 20, 20, 4, 5, 26i64];
let c12 = [10, 25, 23, 1, 14, 16, 14, 4, 21i64];
let costs = [
MatrixView::from_row_major(&c01, 3, 3)?,
MatrixView::from_row_major(&c02, 3, 3)?,
MatrixView::from_row_major(&c12, 3, 3)?,
];
let opts = Options {
max_iter: 20,
n_trials: 2,
seed: 0,
..Options::default()
};
let result = k_assignment(&costs, Algo::Ils, &opts)?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
cliques = [[(0, 0), (1, 1), (2, 2)], [(0, 1), (1, 2), (2, 1)], [(0, 2), (1, 0), (2, 0)]]
costs = [31, 30, 20]
free = []
The Rust example prints the same cliques and costs, with the same free vertices.
Notes and limits
-
threshold=Nonepreserves 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 raisesValueError. See optional matching for the shifted objective, forbidden pairs, and validation. -
Select
Algo::Ilsin Rust. The initial Am solution, or a supplied start, passes through DV before the chains begin. -
The deadline starts after the full start solution has been computed. It is checked before each perturbation; an ongoing DV descent can finish after it.
-
Rust retains its default 100 perturbations even with
time_limit; setmax_iterexplicitly, for example tousize::MAX, for a time budget alone. -
An integer seed and iteration limits make runs reproducible. Timed runs depend on machine speed. Chains run in parallel in the Python native core, and in Rust with
rayon. -
After 50 unsuccessful perturbations, the current chain moves to its latest candidate. The function still returns the best solution seen.
-
Each 1DV sweep uses k LAPs (one for k=2). sDV visits 2^(k−1)−1 subsets and supports at most 16 parts.
See also
Warm starts · Local search · Algorithm details
Memetic search
Memetic search evolves a population of DV local optima by mutation and common-clique crossover. Use it to compare population search with ILS on your data.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def memetic(cost_matrices, *, generations=None, population=None, time_limit=None,
neighborhood="1dv", maximize=False, return_free=False, 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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
generations | opts.max_iter | None / 100 | Nonnegative generation limit. Python resolves None to 100, or sys.maxsize with a time limit. |
population | opts.population | None | At least 2 if supplied; otherwise 12 without a time limit, or sized from measured local-search time with one. |
time_limit | opts.time_limit | None | Python: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply. |
neighborhood | opts.dv | "1dv" / Dv::One | Use "1dv" or "sdv" / Dv::Subsets; aliases "dv1" and "dvs" are accepted in Python, case-insensitively. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
random_state | opts.seed | None / 0 | Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64. |
| - | opts.refine | None | Optional DV pass after the search; separate from the internal opts.dv. |
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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A constituent LAP encounters an invalid numeric entry or an infeasible assignment. |
Python raises RuntimeError if the required native core is unavailable without a threshold; with a threshold it raises ValueError.
Python raises ValueError for a negative integer seed and TypeError for an unsupported seed object.
Python raises TypeError for non-integer or boolean generation counts. It raises ValueError for negative generations, a population that is not an integer at least 2, an invalid neighborhood, or an invalid time budget. Rust returns KapError::BadOption("population") for a population below 2 and KapError::Unsupported for sDV above 16 parts.
Example
import numpy as np
import kap
C01 = np.array([[12, 10, 22], [12, 23, 17], [4, 15, 12]], dtype=np.int64)
C02 = np.array([[17, 17, 17], [17, 26, 10], [3, 20, 22]], dtype=np.int64)
C12 = np.array([[14, 24, 9], [21, 20, 12], [23, 28, 8]], dtype=np.int64)
costs = [C01, C02, C12]
result = kap.memetic(costs, generations=4, population=4, random_state=0, 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 = [12, 10, 22, 12, 23, 17, 4, 15, 12i64];
let c02 = [17, 17, 17, 17, 26, 10, 3, 20, 22i64];
let c12 = [14, 24, 9, 21, 20, 12, 23, 28, 8i64];
let costs = [
MatrixView::from_row_major(&c01, 3, 3)?,
MatrixView::from_row_major(&c02, 3, 3)?,
MatrixView::from_row_major(&c12, 3, 3)?,
];
let opts = Options {
max_iter: 4,
population: Some(4),
seed: 0,
..Options::default()
};
let result = k_assignment(&costs, Algo::Memetic, &opts)?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
cliques = [[(0, 0), (1, 1), (2, 1)], [(0, 1), (1, 2), (2, 2)], [(0, 2), (1, 0), (2, 0)]]
costs = [47, 35, 21]
free = []
The Rust example prints the same cliques and costs, with the same free vertices.
Notes and limits
-
threshold=Nonepreserves 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 raisesValueError. See optional matching for the shifted objective, forbidden pairs, and validation. -
Select
Algo::Memeticin Rust.opts.n_trialsis ignored. Warm starts are not supported. -
The deadline counts from entry. An in-progress batch or generation finishes after it. Rust still applies its default 100-generation limit unless changed.
-
Zero generations returns the best member of the initial population. Each candidate undergoes DV; the initialization starts from Shift.
-
Integer seeds reproduce iteration-limited runs, including parallel execution. Time limits depend on machine speed.
-
The measured multi-chain ILS runs had lower or equal costs at the 60 s budget. See the benchmark table for each size.
See also
ILS · DV neighborhoods · Algorithm details
Local search and neighborhoods
Local search improves a constructed or supplied solution using DV sweeps. Use it for deterministic refinement without perturbations or a population.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def local_search(cost_matrices, *, neighborhood="1dv", start=None, initial=None, max_sweeps=100,
maximize=False, return_free=False, 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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
neighborhood | Algo::Dv1, Algo::DvS, or opts.refine | "1dv" / explicit Algo | Select 1DV or sDV; Python accepts case-insensitive dv1 / dvs aliases. |
start | algo before opts.refine | None (Am) / explicit Algo | Am, Bm, Dm, or Shift. Cannot combine with Python initial. |
initial | cliques in k_assignment_from | None / required by k_assignment_from | A complete solution without a threshold; partial or empty solutions with one. See warm starts. |
max_sweeps | opts.max_iter | 100 | Nonnegative maximum number of DV sweeps. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A constituent LAP encounters an invalid numeric entry or an infeasible assignment. |
Python raises RuntimeError if the required native core is unavailable without a threshold; with a threshold it raises ValueError.
Python raises ValueError for invalid start or neighborhood names, start together with initial, or negative max_sweeps. Non-integer and boolean sweep limits raise TypeError. Rust returns KapError::Unsupported for sDV above 16 parts. Supplied starts can also produce the warm-start errors.
Example
import numpy as np
import kap
C01 = np.array([[12, 6, 13], [12, 13, 26], [28, 12, 27]], dtype=np.int64)
C02 = np.array([[20, 14, 15], [27, 16, 14], [26, 7, 8]], dtype=np.int64)
C12 = np.array([[3, 5, 22], [10, 5, 12], [1, 20, 26]], dtype=np.int64)
costs = [C01, C02, C12]
result = kap.local_search(costs, start="Dm", neighborhood="sdv", max_sweeps=10, return_free=True)
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
use kap::{Algo, Dv, MatrixView, Options, k_assignment};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let c01 = [12, 6, 13, 12, 13, 26, 28, 12, 27i64];
let c02 = [20, 14, 15, 27, 16, 14, 26, 7, 8i64];
let c12 = [3, 5, 22, 10, 5, 12, 1, 20, 26i64];
let costs = [
MatrixView::from_row_major(&c01, 3, 3)?,
MatrixView::from_row_major(&c02, 3, 3)?,
MatrixView::from_row_major(&c12, 3, 3)?,
];
let opts = Options {
max_iter: 10,
refine: Some(Dv::Subsets),
..Options::default()
};
let result = k_assignment(&costs, Algo::Dm, &opts)?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
cliques = [[(0, 0), (1, 2), (2, 0)], [(0, 1), (1, 0), (2, 1)], [(0, 2), (1, 1), (2, 2)]]
costs = [34, 33, 32]
free = []
The Rust example prints the same cliques and costs, with the same free vertices.
Notes and limits
-
threshold=Nonepreserves 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 raisesValueError. See optional matching for the shifted objective, forbidden pairs, and validation. -
1DV reassigns one part against its complement. Each sweep uses k LAPs, or one for k=2.
-
sDV visits one member of each subset/complement pair: 2^(k−1)−1 subsets per full sweep. It supports at most 16 parts.
-
Each accepted move strictly improves the objective. A sweep without an improvement ends the search; zero sweeps returns the start.
-
For an Am start in Rust, select
Algo::Dv1orAlgo::DvS. For Bm, Dm, or Shift, select thatAlgoand setopts.refine. -
The method is deterministic. Part sizes may differ.
See also
Warm starts · ILS · DV algorithm
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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
method | algo | "Cm" / explicit Algo | Am, Bm, Cm, Dm, Em, Fm, or Shift; Python names are case-insensitive. |
max_iter | opts.max_iter | 100 | Cm/Em/Fm move limit; positive for Em/Fm. Ignored by Am/Bm/Dm/Shift. |
n_trials | opts.n_trials | 1 | Positive independent Em trial count; ignored by other methods. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include 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_state | opts.seed | None / 0 | Python 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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A 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=Nonepreserves 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 raisesValueError. 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
Dispatcher
k_assignment selects a k-assignment method and optionally applies DV refinement. Use the explicit Python functions when their named parameters describe your task more directly.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def k_assignment(cost_matrices: Sequence[Array2DLike], algo: Optional[str] = None,
max_iter: Optional[int] = None, n_trials: int = 1, maximize: bool = False,
return_free: bool = False, backend: str = "kap",
random_state: Optional[Union[np.random.RandomState, int]] = None,
refine: Optional[str] = None, time_limit: Optional[float] = None,
population: Optional[int] = None, *, threshold=None) -> AssignmentResult:
...
#![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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
algo | algo | None / required | Python: ILS with native kap, otherwise Cm. Rust always requires an Algo. |
max_iter | opts.max_iter | None / 100 | Moves, sweeps, perturbations per chain, or generations; Python resolves None by algorithm and time mode. |
n_trials | opts.n_trials | 1 | Em trials or ILS chains; positive for those methods. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
backend | - | "kap" | Native kap or optional scipy, lap, lapjv, munkres; newer methods require native kap. |
random_state | opts.seed | None / 0 | Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64. |
refine | opts.refine or opts.dv | None / None or Dv::One | 1DV or sDV after construction; inside ILS/memetic it selects the search neighborhood. |
time_limit | opts.time_limit | None | Python: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply. |
population | opts.population | None | Memetic population size; supplied values must be integers at least 2. |
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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A 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 unknown algorithm or neighborhood, time_limit outside ILS/memetic, population outside memetic, or a newer method/refinement without native kap. Selected methods also apply their own ILS, memetic, local-search, and multiple-Hungarian checks. Rust uses KapError::BadOption for zero Em/Fm moves, zero Em/ILS trials, or a population below 2; sDV above 16 parts produces KapError::Unsupported.
Example
import numpy as np
import kap
C01 = np.array([[6, 10, 12], [1, 29, 2], [28, 29, 28]], dtype=np.int64)
C02 = np.array([[26, 29, 16], [7, 29, 26], [29, 2, 12]], dtype=np.int64)
C12 = np.array([[15, 10, 28], [20, 17, 1], [13, 17, 13]], dtype=np.int64)
costs = [C01, C02, C12]
result = kap.k_assignment(costs, algo="Shift", refine="1dv", maximize=True, return_free=True)
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
use kap::{Algo, Dv, MatrixView, Options, Sense, k_assignment};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let c01 = [6, 10, 12, 1, 29, 2, 28, 29, 28i64];
let c02 = [26, 29, 16, 7, 29, 26, 29, 2, 12i64];
let c12 = [15, 10, 28, 20, 17, 1, 13, 17, 13i64];
let costs = [
MatrixView::from_row_major(&c01, 3, 3)?,
MatrixView::from_row_major(&c02, 3, 3)?,
MatrixView::from_row_major(&c12, 3, 3)?,
];
let opts = Options {
sense: Sense::Maximize,
refine: Some(Dv::One),
..Options::default()
};
let result = k_assignment(&costs, Algo::Shift, &opts)?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
cliques = [[(0, 0), (1, 0), (2, 2)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 0)]]
costs = [50, 75, 70]
free = []
The Rust example prints the same cliques and costs, with the same free vertices.
Notes and limits
-
threshold=Nonepreserves 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 raisesValueError. See optional matching for the shifted objective, forbidden pairs, and validation. -
Python accepts Am–Fm, Shift, 1DV, sDV, ILS, and memetic, case-insensitively.
initialis available throughilsandlocal_search, not this dispatcher. -
Python defaults to 100 iterations, or an effectively unlimited count for timed ILS/memetic. Explicit iteration and time limits both apply; Rust always retains the supplied
max_iter. -
Negative dispatcher limits act as zero, except that Em and Fm require positive limits. Explicit Python method functions reject negative search limits.
-
Seeded iteration-limited randomized methods are reproducible. Time-limited runs depend on machine speed.
-
Choose
Algo::IlsandOptions::dvfor ILS in Rust.Options::refineapplies a separate pass after the main Rust algorithm.
See also
ILS · Memetic · Local search · Multiple Hungarian methods
Warm starts
A warm start supplies a solution for DV refinement or ILS. Without a threshold it must be complete; with a threshold it may be partial or empty. Use it to continue from an earlier result or improve a solution produced outside kap.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def local_search(cost_matrices, *, neighborhood="1dv", start=None, initial=None, max_sweeps=100,
maximize=False, return_free=False, threshold=None):
...
def ils(cost_matrices, *, max_iter=None, n_chains=1, time_limit=None, neighborhood="1dv",
maximize=False, return_free=False, random_state=None, initial=None, threshold=None):
...
#![allow(unused)]
fn main() {
pub fn k_assignment_from<T: Cost>(
mats: &[MatrixView<'_, T>],
cliques: &[Vec<(usize, usize)>],
algo: Algo,
opts: &Options,
) -> Result<KSolution<T::Acc>, KapError>
where
T::Acc: Cost<Acc = T::Acc>;
}
Parameters
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
neighborhood | algo / opts.dv / opts.refine | "1dv" / Dv::One internally | Select the DV neighborhood for refinement or ILS; sDV needs k≤16. |
start | - | None | Python local_search rejects a non-None start together with initial. |
initial | cliques in k_assignment_from | None / required by k_assignment_from | A complete solution without a threshold; partial or empty solutions with one. See warm starts. |
max_sweeps | opts.max_iter for DV | 100 | Local-search sweep limit; nonnegative. |
max_iter | opts.max_iter for ILS | None / 100 | ILS perturbations per chain; Python resolves None to 100 or sys.maxsize with a time limit. |
n_chains | opts.n_trials | 1 | Positive ILS chain count. |
time_limit | opts.time_limit | None | Python: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
random_state | opts.seed | None / 0 | Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64. |
| - | algo | Required | Am, Bm, Dm, Shift, Dv1, DvS, or Ils; the supplied start replaces construction. |
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.
DV and ILS return a solution whose objective is no worse than the supplied start. With a threshold, this refers to the shifted objective. This guarantee is exact for integer costs; for float costs it holds up to floating-point rounding of the cost sums. Passing Am, Bm, Dm, or Shift to Rust k_assignment_from returns the supplied start unless opts.refine is set.
Errors
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A constituent LAP encounters an invalid numeric entry or an infeasible assignment. |
ValueError | KapError::Unsupported("cost overflow") | An integer clique cost or total overflows while evaluating the supplied start. |
Python raises RuntimeError if the required native core is unavailable without a threshold; with a threshold it raises ValueError.
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadMatching | Empty clique, invalid index, repeated vertex, or two vertices from one part in a clique. |
ValueError | KapError::IncompleteInitial | Without a threshold, restoring unlisted vertices as singletons does not give exactly max(part sizes) nodes. |
ValueError | KapError::ForbiddenInitial | With a threshold, the initial solution places a forbidden pair in one clique. |
ValueError | - | Python local_search receives both start and initial. |
| - | KapError::BadOption("initial") | Rust selects Cm, Em, Fm, or Memetic with supplied cliques. |
Python also rejects non-integer or boolean indices with ValueError. ILS and local-search option errors remain as documented on their guide pages.
All matrix entries are checked against the LAP’s numeric rules when a start is supplied, even with zero sweeps.
Example
import numpy as np
import kap
C01 = np.array([[28, 25, 18], [1, 12, 7], [3, 4, 14]], dtype=np.int64)
C02 = np.array([[21, 18, 10], [12, 17, 24], [2, 17, 9]], dtype=np.int64)
C12 = np.array([[8, 28, 25], [27, 8, 11], [2, 20, 3]], dtype=np.int64)
costs = [C01, C02, C12]
initial = [[(0, i), (1, i), (2, i)] for i in range(3)]
result = kap.local_search(costs, initial=initial, return_free=True)
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
use kap::{Algo, MatrixView, Options, k_assignment_from};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let c01 = [28, 25, 18, 1, 12, 7, 3, 4, 14i64];
let c02 = [21, 18, 10, 12, 17, 24, 2, 17, 9i64];
let c12 = [8, 28, 25, 27, 8, 11, 2, 20, 3i64];
let costs = [
MatrixView::from_row_major(&c01, 3, 3)?,
MatrixView::from_row_major(&c02, 3, 3)?,
MatrixView::from_row_major(&c12, 3, 3)?,
];
let initial: Vec<_> = (0..3).map(|i| vec![(0, i), (1, i), (2, i)]).collect();
let result = k_assignment_from(&costs, &initial, Algo::Dv1, &Options::default())?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
cliques = [[(0, 0), (1, 2), (2, 2)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 0), (2, 0)]]
costs = [31, 37, 13]
free = []
The Rust example prints the same cliques and costs, with the same free vertices.
Notes and limits
-
threshold=Nonepreserves 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 raisesValueError. See optional matching for the shifted objective, forbidden pairs, and validation. -
Without a threshold, a complete solution has exactly N=max(part sizes) nodes after singleton restoration. It need not contain a vertex from every part in each node.
-
Python accepts an
AssignmentResultor an iterable of cliques. Only the result’scliquesfield is used; costs are recomputed from the supplied matrices. -
Unlisted vertices become singletons. Without a threshold this permits omitted free vertices but requires a complete assignment. With a threshold, arbitrary partial and empty assignments are accepted, subject to the index, uniqueness, and forbidden-pair checks.
-
ILS refines the supplied solution before starting all chains. Its time budget starts after that initial refinement.
-
DV uses k LAPs per 1DV sweep (one for k=2), or up to 2^(k−1)−1 per sDV sweep.
See also
Input format · Local search · ILS
Optional matching
A threshold lets vertices stay unmatched when joining a clique does not improve the shifted objective. It is available on all native heuristic methods, including DV refinement and supported warm starts.
Signature
The Python declaration shows public defaults. Rust selects a method with Algo and sets Options::threshold.
def ils(cost_matrices, *, max_iter=None, n_chains=1, time_limit=None, neighborhood="1dv",
maximize=False, return_free=False, random_state=None, initial=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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. Part sizes may differ. |
threshold | opts.threshold | None | Finite real pair-cost threshold; Python rejects booleans and non-numbers. |
maximize | opts.sense | False / Sense::Minimize | Maximise the shifted objective when true / Sense::Maximize. |
initial | cliques in k_assignment_from | None / required by k_assignment_from | For ILS and local search, partial and empty solutions are accepted with a threshold. |
return_free | - | False | Include singleton vertices in Python free; Rust always returns them. |
max_iter | opts.max_iter | None / 100 | ILS perturbations per chain; Python resolves None to 100, or sys.maxsize with a time limit. |
n_chains | opts.n_trials | 1 | Positive number of ILS chains. |
time_limit | opts.time_limit | None | Finite positive seconds in Python; Option<Duration> in Rust. Both iteration and time limits apply. |
neighborhood | opts.dv | "1dv" / Dv::One | ILS DV neighborhood: 1DV or sDV. |
random_state | opts.seed | None / 0 | Integer seeds reproduce runs with iteration limits. |
threshold is keyword-only on Python ils, memetic, local_search, multiple_hungarian, and k_assignment.
Semantics
With threshold=tau, the objective is the sum of (cost − tau) over all pairs sharing a clique, over all partitions into cliques with at most one vertex per part, singletons allowed; minimised (maximised with maximize=True). A clique forms only if it improves that objective, so vertices can stay unmatched. threshold=None leaves the behaviour unchanged.
This is a soft gate: a pair costlier than tau can share a clique when the clique’s other pairs pay for it. For example, costs 1, 1, and 12 with tau=10 give a triangle a shifted cost of −16, even though one pair costs more than tau. These are heuristics for k>2; they do not guarantee the globally optimal partition. For k=2 they solve optional bipartite matching optimally.
A float cost of +inf (minimise) / -inf (maximise) forbids a pair. To forbid every pair above a limit, set those entries to inf before calling. For maximisation, use -inf to forbid pairs, for example weights below a limit. NaN and the other infinity are errors.
Returned costs are in original units, not shifted. Each reported clique cost is the sum of its original pair costs. Singletons are omitted from cliques and appear in free when return_free=True.
All-integer Python matrices require an integral threshold, including integral float thresholds such as 2.0, and keep exact int64 arithmetic. A fractional threshold raises ValueError; explicitly convert the matrices to float64 to use one. Float64 conversion can round large integer costs. Thresholds pass to Rust as float64; Python rejects integral thresholds that cannot be represented exactly as float64. Rust integer matrices require an integral threshold representable in the accumulator type.
With a threshold, initial on ils or local_search may be partial or empty. Unlisted vertices become singletons. Index, uniqueness, and one-vertex-per-part checks still apply, and an initial clique containing a forbidden pair is rejected. Improvement of a supplied start refers to the shifted objective, up to rounding for float costs. Without a threshold, the initial solution must remain complete; see warm starts.
Dm ranks intermediate merges by the shifted objective, so a large threshold does not reproduce ungated Dm.
Returns
Python returns AssignmentResult(cliques, costs, free). Rust returns KSolution with cliques, costs, total cost, and free. Costs use original units in both languages.
Errors
| Python | Rust | Condition |
|---|---|---|
TypeError | Rejected by the Option<f64> type | Boolean or non-real Python threshold. |
ValueError | KapError::BadOption("threshold") | Non-finite threshold, a fractional threshold with all-integer matrices, or an unrepresentable threshold for integer arithmetic. |
ValueError | KapError::Lap | NaN entry or wrong-sign infinity. |
ValueError | KapError::ForbiddenInitial | initial places a forbidden pair in one clique. |
ValueError | KapError::Unsupported("cost overflow") | Checked cost arithmetic overflows. |
ValueError | - | Threshold supplied to the reference backend, another LAP backend, or without the native core. |
Matrix shape, dtype, and other method-specific checks still apply.
Example
The third vertex of part 0 stays unmatched. The infinite entry forbids vertices (0, 0) and (1, 1) from sharing a clique.
import numpy as np
import kap
costs = [np.array([[1.0, np.inf], [9.0, 2.0], [8.0, 7.0]])]
result = kap.ils(costs, threshold=5, max_iter=10, random_state=0, 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 data = [1.0, f64::INFINITY, 9.0, 2.0, 8.0, 7.0];
let costs = [MatrixView::from_row_major(&data, 3, 2)?];
let opts = Options {
threshold: Some(5.0),
max_iter: 10,
seed: 0,
..Options::default()
};
let result = k_assignment(&costs, Algo::Ils, &opts)?;
println!("cliques = {:?}", result.cliques);
println!("costs = {:?}", result.costs);
println!("free = {:?}", result.free);
Ok(())
}
Python output:
cliques = [[(0, 0), (1, 0)], [(0, 1), (1, 1)]]
costs = [1.0, 2.0]
free = [(0, 2)]
The Rust example prints identical output.
Notes and limits
exactandlower_bounddo not take a threshold.- Thresholds require the native core. Python reference and other LAP backends reject them with
ValueError. - Shifted integer costs must lie strictly between −2⁶¹ and 2⁶¹, as for costs without a threshold; larger values are rejected as invalid entries.
- Float costs near the float64 limit (about 1e308) can overflow when summed; such sums are not detected in every path.
- Infinite thresholds are rejected. Use
Nonefor the unchanged objective. - Thresholding and forbidden pairs also apply during refinement and search.
See also
Warm starts · ILS · Local search · Multiple Hungarian methods
Exact solver
exact solves equal-size instances with SciPy’s HiGHS MILP solver. Integer costs are solved exactly within the magnitude limit below; float results are optimal within HiGHS’s tolerances on a scaled objective. Use it for small instances or to check heuristic costs.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def exact(cost_matrices, *, maximize=False, time_limit=None, return_free=False,
max_variables=150_000) -> AssignmentResult:
...
Parameters
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | - | Required | Pairwise cost matrices with equal part sizes. |
maximize | - | False | Maximize the sum instead of minimizing it. |
time_limit | - | None | Finite positive seconds; None sets no limit. |
return_free | - | False | Return an empty free list on these equal-size complete assignments; otherwise None. |
max_variables | - | 150_000 | Nonnegative integer guard on n**k tuple variables; booleans are rejected. |
Returns
Python returns AssignmentResult with n full k-vertex cliques and their original pairwise cost sums. free is [] when requested and None otherwise. The Rust crate has no exact solver.
Errors
| Exception | Condition |
|---|---|
ValueError | Empty or inconsistent matrices, unequal part sizes, non-finite costs (including +inf forbidden entries), non-finite tuple sums, negative max_variables, n**k above the guard, or an invalid time limit. |
TypeError | Unsupported matrix dtype or a non-integer/boolean max_variables. |
OverflowError | All matrices are integer or boolean and a uint64 value exceeds int64, or the integer objective magnitude bound exceeds 2**53. Rescale the costs. |
ImportError | SciPy is unavailable. |
ExactTimeoutError | HiGHS stops at its limit before proving optimality. |
RuntimeError | HiGHS reports another failure, or its returned solution is not a complete partition. |
ExactTimeoutError subclasses TimeoutError. Its bound and best_cost attributes use the original objective sense and scale and can be None if HiGHS supplied no value.
Example
This example is Python only; the Rust crate has no exact solver.
import numpy as np
import kap
C01 = np.array([[24, 22, 24], [22, 6, 16], [28, 15, 27]], dtype=np.int64)
C02 = np.array([[16, 7, 20], [1, 3, 9], [28, 14, 27]], dtype=np.int64)
C12 = np.array([[16, 7, 8], [24, 18, 6], [8, 4, 29]], dtype=np.int64)
costs = [C01, C02, C12]
result = kap.exact(costs, time_limit=10, return_free=True)
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
Python output:
cliques = [[(0, 0), (1, 0), (2, 1)], [(0, 1), (1, 2), (2, 0)], [(0, 2), (1, 1), (2, 2)]]
costs = [38, 25, 48]
free = []
Notes and limits
- The MILP contains n**k binary tuple variables and k*n equality constraints. Building the objective and constraints allocates arrays proportional to that model.
- The practical limit documented by the API is about 100,000 tuples: roughly k=3,n≤45; k=4,n≤17; or k=5,n≤10. Solve time depends on the costs.
- The proven-optimum measurements include k=3,n=40 (16.6 s maximum), k=4,n=16 (28.1 s), and k=6,n=6 (29.1 s).
- HiGHS can exceed the time budget during presolve. Python model construction also occurs before the solver receives the budget.
- The objective uses float64 even for integer input. Integer and boolean inputs are accepted only when U = n times the sum, over all pair matrices, of the largest absolute entry is at most 2**53. This bound is computed with Python integers. Every tuple cost and objective value is then exactly representable, and integer costs are solved exactly. Larger inputs raise
OverflowError; rescale them. - Float objectives are multiplied by a power of two so the largest absolute tuple cost lies in [512, 1024). An all-zero objective needs no scaling, and integer objectives are not scaled. Float results are optimal within HiGHS’s absolute tolerances applied to the scaled problem, about 1e-9 times the largest tuple cost magnitude. Returned clique costs are recomputed from the original matrices.
- All matrix entries must be finite. In particular, +inf forbidden entries are not supported.
- SciPy is imported when the function is called. No random seed parameter is exposed.
See also
Installation · ILS · Lower bound
Lower bound
lower_bound bounds the optimum for equal-size parts: below for minimization and above for maximization. Use it to assess the remaining gap of a heuristic solution.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def lower_bound(cost_matrices, *, maximize=False, max_iter=300) -> int | float:
...
#![allow(unused)]
fn main() {
pub fn lower_bound<T: Cost>(
mats: &[MatrixView<'_, T>],
opts: &LowerBoundOptions<T::Acc>,
) -> Result<T::Acc, KapError>
where
T::Acc: LowerBoundAcc;
}
Parameters
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
maximize | opts.sense | False / Sense::Minimize | Maximize the original costs when true / Sense::Maximize. |
max_iter | opts.max_iter | 300 | Nonnegative subgradient updates per triple; zero still evaluates the initial seeds. |
| - | opts.upper | None | Optional finite numerical upper bound on the whole optimum, in the original objective sense. The caller must establish its validity. |
Returns
Python returns an int for integer/boolean inputs and a float otherwise. Rust returns Result<T::Acc, KapError> with i64 or f64 accumulation. Integer costs give a rigorous bound. Float bounds are computed in floating point and can exceed the true minimum (or fall below the true maximum) by rounding error on the order of machine epsilon times the sum of the cost magnitudes involved. This error can be large when costs of opposite sign nearly cancel.
For a positive minimization solution cost c and bound b, (c-b)/c bounds the relative improvement still possible. The example uses this definition; division by zero or a negative c needs a different normalization.
Errors
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | All Python matrices are integer or boolean and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A constituent LAP encounters an invalid numeric entry or an infeasible assignment. |
Python raises RuntimeError if the required native core is unavailable.
Python raises TypeError for non-integer or boolean max_iter, and ValueError for negative values or unequal part sizes. Rust returns KapError::Unsupported for unequal sizes, a non-finite upper, or exhausted arithmetic headroom. Invalid numeric entries and infeasible pairwise LAPs produce KapError::Lap. If a multiplier update exhausts headroom after valid bounds were evaluated, that triple retains its best evaluated bound.
Example
import numpy as np
import kap
C01 = np.array([[19, 22, 6], [27, 16, 22], [16, 26, 10]], dtype=np.int64)
C02 = np.array([[7, 10, 22], [15, 19, 26], [9, 27, 9]], dtype=np.int64)
C12 = np.array([[6, 25, 5], [7, 3, 12], [19, 13, 2]], dtype=np.int64)
costs = [C01, C02, C12]
result = kap.local_search(costs)
cost = result.cost
bound = kap.lower_bound(costs, max_iter=30)
print("cost =", cost)
print("bound =", bound)
print(f"gap = {(cost - bound) / cost:.3f}")
use kap::{Algo, LowerBoundOptions, MatrixView, Options, k_assignment, lower_bound};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let c01 = [19, 22, 6, 27, 16, 22, 16, 26, 10i64];
let c02 = [7, 10, 22, 15, 19, 26, 9, 27, 9i64];
let c12 = [6, 25, 5, 7, 3, 12, 19, 13, 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::Dv1, &Options::default())?;
let opts = LowerBoundOptions {
max_iter: 30,
..LowerBoundOptions::default()
};
let bound = lower_bound(&costs, &opts)?;
println!("cost = {}", result.cost);
println!("bound = {bound}");
println!(
"gap = {:.3}",
(result.cost - bound) as f64 / result.cost as f64
);
Ok(())
}
Python output:
cost = 97
bound = 91
gap = 0.062
The Rust example prints the same cost, bound, and gap.
Notes and limits
- For k=2, the bound is the exact LAP optimum. For k=3, it is an axial Lagrangian bound, at best equal to the LP relaxation bound.
- For k≥4, the function averages all triple bounds with scale 1/(k−2). Random non-metric costs can leave a large gap; measured metric instances gave smaller gaps.
- Each active triple uses O(n²) scratch space. The number of triples is k(k−1)(k−2)/6.
- The initial evaluations include a pairwise-LAP sum and zero/dual multiplier seeds. Increasing max_iter retains all earlier evaluations; the returned bound does not weaken.
- Rust
upperclamps the final numerical bound in either objective sense. It is not a feasible-solution argument and is not used as the per-triple Polyak target. - The method is deterministic and has no time-limit parameter. Equal zero-sized parts return zero.
See also
Proven-optimum benchmarks · Exact solver · Input and dtypes
Linear assignment
linear_sum_assignment computes an optimal assignment with min(rows, columns) pairs from one dense cost matrix. Use it for a two-part problem; use Python linear_assignment when you also need costs, free vertices, or an alternative LAP backend.
Signature
The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.
def linear_sum_assignment(cost_matrix, maximize: bool = False):
...
def linear_assignment(cost_matrix: Array2DLike,
maximize: bool = False,
return_free: bool = False,
backend: str = "kap") -> AssignmentResult:
...
#![allow(unused)]
fn main() {
pub fn linear_sum_assignment<T: Cost>(
m: MatrixView<'_, T>,
sense: Sense,
) -> Result<LapSolution<T::Acc>, LapError>;
}
Parameters
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrix | m | Required | A dense 2-D matrix; rectangular inputs are supported. |
maximize | sense | False / explicit Sense | Maximize with True / Sense::Maximize. |
return_free (wrapper only) | - | False | Include singleton vertices in the linear_assignment result. |
backend (wrapper only) | - | "kap" | kap, scipy, lap, lapjv, or munkres; lapjv accepts square matrices only. |
Returns
Python linear_sum_assignment returns (row_ind, col_ind) as NumPy index arrays. Rows are increasing. The cost is cost_matrix[row_ind, col_ind].sum().
Python linear_assignment returns AssignmentResult: cliques is an array of (row, column) pairs, costs contains the selected entries, and optional free contains (0, row) or (1, column) singleton vertices.
Rust returns Result<LapSolution<T::Acc>, LapError> with row_ind, col_ind, and total cost. It has no backend-selector or free-vertex field.
Errors
| Python | Rust | Condition |
|---|---|---|
ValueError | LapError::BadShape from MatrixView construction | Non-2-D Python input or Rust storage/strides outside the slice. |
ValueError | LapError::InvalidCost(row, col) | NaN, wrong-sign infinity, or a magnitude outside the solver’s arithmetic headroom. |
OverflowError (native LAP) | LapError::Overflow | An integer intermediate value, dual, or total cost does not fit int64. |
ValueError | LapError::Infeasible | No assignment of min(rows, columns) pairs avoids forbidden entries. |
TypeError | Rejected by Cost at compilation | Unsupported matrix dtype. |
ValueError | - | The Python wrapper receives an unknown backend. |
ModuleNotFoundError | - | A selected optional backend is unavailable. |
Optional backends can also raise their own input errors, including square-input requirements for lapjv.
Example
import numpy as np
import kap
cost = np.array([[8, 2, 7, 6], [6, 9, 3, 5], [4, 7, 8, 1]])
rows, cols = kap.linear_sum_assignment(cost)
print("rows =", rows.tolist())
print("columns =", cols.tolist())
print("cost =", int(cost[rows, cols].sum()))
result = kap.linear_assignment(cost, return_free=True)
print("free =", result.free)
use kap::{MatrixView, Sense, linear_sum_assignment};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let data = [8i64, 2, 7, 6, 6, 9, 3, 5, 4, 7, 8, 1];
let matrix = MatrixView::from_row_major(&data, 3, 4)?;
let result = linear_sum_assignment(matrix, Sense::Minimize)?;
println!("rows = {:?}", result.row_ind);
println!("columns = {:?}", result.col_ind);
println!("cost = {}", result.cost);
Ok(())
}
Python output:
rows = [0, 1, 2]
columns = [1, 2, 3]
cost = 6
free = [(1, 0)]
The Rust example prints the same row indices, column indices, and total cost. It does not print the Python wrapper’s free field.
Notes and limits
- Positive infinity forbids a pair for minimization; negative infinity does so for maximization. These rules describe the native LAP solver.
- Square finite matrices use Jonker–Volgenant initialization and augmentation. Rectangular matrices or matrices with forbidden entries use shortest augmenting paths.
- Integer LAP arithmetic is checked. If JV dual updates overflow, the solver restarts with shortest augmenting paths. If that path or the total cost also overflows, the call returns an error; integer costs are not converted to float64.
- With tied costs, square inputs can choose a different optimum from SciPy. Rectangular inputs use SciPy’s tie-breaking order.
- Worst-case square LAP work is O(n³). Reuse Rust LapSolver when solving many matrices to retain its buffers.
- Native Python supports float32/64 and signed integer types through int64 plus uint8/16/32. Booleans become uint8; uint64 fitting int64 becomes int64. Float16, longdouble, and larger uint64 values convert to float64, with possible loss of precision.
- Rust Cost implementations support f32/f64, i8/i16/i32/i64, and u8/u16/u32; they accumulate in f64 or i64. Sparse matrices are not supported.
See also
MatrixView constructors · Backend measurements · Multiple Hungarian methods
Algorithms
kap.multiple_hungarian exposes Am–Fm and Shift. The six Am–Fm methods come from Gabrovšek et al. (2020) and build the solution by
merging parts. Solving the linear assignment problem (LAP) between
parts i and j and contracting each matched pair into one vertex gives
the quotient graph G / M_ij, which has one part fewer. The cost row of
a merged vertex is the sum of the rows of its two members, so the cost of the
final cliques is the sum of all pairwise edges inside each clique (the clique
cost). After k − 1 merges a single part remains, and each of its vertices
is a clique.
Am, Bm and Dm differ in which pairs they merge. Cm, Em and Fm start from Bm
and improve the result by local search. Their neighborhood is the same:
take the current solution, fix the pairwise matching it induces between two
parts i and j, contract, and re-solve the remaining (k − 1)-part
problem with Bm. A solution has k(k − 1)/2 such neighbors.
| Algo | Strategy |
|---|---|
| Am | Merge the first two parts, in input order, until one is left. k − 1 LAPs. |
| Bm | At each level try every pair, solve the rest recursively with Bm, and keep the pair whose final cost is lowest. |
| Dm | Greedy: at each level merge the pair whose LAP is cheapest. |
| Cm | Steepest descent from Bm: evaluate all neighbors of the current solution, move to the best one while it improves. Deterministic. max_iter caps the moves. |
| Em | First improvement from Bm: visit the neighbors in random order and move to the first that improves. n_trials independent randomized runs; the best is kept. max_iter caps the moves per run. |
| Fm | Tabu search from Bm: at each of max_iter steps move to a random best neighbor, even if it is worse, never back to the current or previous solution. Returns the best solution seen. |
The paper’s experiments (k = 3, 4; n up to 100) rank solution quality as Fm ≈ Em ≈ Cm > Bm > Dm ≈ Am. It recommends Em overall (about 0.1 % above the optimum on benchmarks with known optima) and Cm among the deterministic methods.
Shift
For each of the k cyclic orders of the parts, Shift constructs one Am
solution and keeps the first best on score ties. This uses k(k − 1) LAPs. Under clique-sum
costs, Shift is equivalent to Shift-ROM of Gutin, Goldengorin and Huang and
of Karapetyan and Gutin.
Dimensionwise variation (DV)
DV re-matching exactly re-solves the assignment between a chosen subset of
parts and its complement. Each move is nonworsening; the two sides may
have unequal sizes, so incomplete cliques are supported. 1DV re-matches one
part against the remaining parts, cycling through them; each sweep uses
k LAPs (k = 2 needs one). sDV visits canonical subsets, choosing one of
each subset/complement pair. It uses cyclic first improvement: apply an
improving move immediately and continue the sweep. A full sweep considers
2^(k−1) − 1 subsets; sDV is limited to k ≤ 16. max_iter caps DV
sweeps, and a complete cycle without an accepted move ends the search.
kap.local_search(costs, start="Am", neighborhood="1dv") builds a start and applies DV.
The dispatcher option refine can also apply 1DV or sDV after the main algo finishes. Shift, 1DV and
sDV as algo choices, and refine, require backend="kap" (the native core).
References: H.-J. Bandelt, A. Maas and F. C. R. Spieksma, “Local search for multidimensional assignment problems with decomposable costs,” European Journal of Operational Research 158, 2004; Karapetyan and Gutin, “Local search heuristics for the multidimensional assignment problem,” Journal of Heuristics 17, 2011.
Iterated local search (ILS)
kap.ils (or algo="ils" in the dispatcher) starts with Am followed by DV to convergence. Each step perturbs
some nodes of the current solution, runs DV to convergence again, and moves
to the candidate only if its score strictly improves. After 50 consecutive
steps without an improvement it moves to the latest candidate anyway, to
leave a region where it is stuck; the best solution seen is what is returned.
ILS is the default algo with backend="kap". The perturbation chooses
ceil(N/25) + 1 distinct nodes, clamped to 2..N, where N is the number of
solution nodes. It fixes the first largest original part and independently
shuffles every other part’s entries, including absent vertices, among the
chosen nodes. This preserves a valid partition for unequal sizes. With fewer
than two nodes, ILS returns the start.
max_iter caps perturbations per chain (zero returns the start), n_trials
selects independent chains from that same start, and random_state seeds them.
Chains run in parallel in the native Python core, or in Rust with the rayon
feature; the first best chain wins ties. refine selects the neighborhood
inside ILS: 1DV by default, or sDV with refine="sdv" (k <= 16). ILS requires
backend="kap".
Optional time_limit is a finite positive budget in seconds (an explicit
max_iter also applies; without one the iteration limit is unlimited), checked before
each perturbation across all chains, after computing the full start solution.
An in-progress DV descent finishes even if the deadline passes. Only iteration
budgets are reproducible; a time limit makes results depend on machine speed.
In the benchmarks, ILS with several chains gave the lowest costs of the methods tested.
This is the “Chain” method of Karapetyan and Gutin, “Local search heuristics for the multidimensional assignment problem,” Journal of Heuristics 17, 2011.
Memetic algorithm
kap.memetic (or algo="memetic" in the dispatcher) maintains a population of DV local optima. It starts from
Shift followed by DV, mutates members by swapping non-anchor coordinates,
and crosses parents while preserving their common cliques. Crossover repairs
duplicate and missing vertices, including absent vertices for unequal sizes.
Each new candidate passes through DV; selection keeps the distinct best
solutions and preserves the elite. refine selects 1DV (default) or sDV
inside the algorithm; n_trials is ignored. This requires backend="kap".
Without time_limit, population sets the target size (default 12, at least
2), and max_iter caps generations; zero returns the best first-generation
member. An integer random_state makes this mode reproducible, including
across parallel execution. With a finite positive time_limit in seconds,
the deadline counts from entry, and population size is estimated from the
budget and measured local-search time unless explicitly supplied. An explicit generation limit also applies alongside the time limit; without
one the generation limit is unlimited. An in-progress batch or generation finishes after
the deadline, so time budgets make results depend on machine speed.
In the benchmarks, memetic did not beat ILS with several chains at equal time.
kap starts from Shift instead of the paper’s Greedy construction and includes the unperturbed local optimum in the first generation. Reference: Gutin and Karapetyan, “A memetic algorithm for the multidimensional assignment problem,” and Karapetyan and Gutin, “A New Approach to Population Sizing for Memetic Algorithms: A Case Study for the Multidimensional Assignment Problem,” Evolutionary Computation 19, 2011, arXiv:1003.4314.
Cost
LAP calls made by one run of Bm, counting the intermediate levels too. The native core memoizes merges that commute (merging {0,1} then {2,3} reaches the same quotient as {2,3} then {0,1}), so it solves fewer LAPs than the Python implementation:
| k | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|
| LAPs, native | 6 | 39 | 310 | 3 000 | 34 566 | 463 981 |
LAPs, Python (backend other than "kap") | 6 | 42 | 430 | 6 465 | 135 786 | 3 802 036 |
Cm, Em and Fm run Bm once per neighbor per step, so they cost a multiple of this. Beyond about k = 6, use Am or Dm.
Differences from the paper
- The paper assumes all parts have the same size. kap also accepts unequal sizes; the vertices left over then form incomplete cliques.
- The paper breaks ties at random; kap’s Bm takes the first best pair.
- With
backend="kap"(native, default), Cm, Em and Fm follow the paper as in the table above. Other backends run the Python implementation, which keeps kap 0.2.3’s behavior: Cm updates the current solution during a pass, and Fm accepts only equal-or-better moves.
References
- B. Gabrovšek, T. Novak, J. Povh, D. Rupnik Poklukar, and J. Žerovnik, “Multiple Hungarian Method for k-Assignment Problem,” Mathematics 8(11), 2050, 2020. doi:10.3390/math8112050. Methods Am–Fm.
- H.-J. Bandelt, A. Maas, and F. C. R. Spieksma, “Local search for multidimensional assignment problems with decomposable costs,” European Journal of Operational Research 158, 2004. Dimensionwise variation.
- D. Karapetyan and G. Gutin, “Local search heuristics for the multidimensional assignment problem,” Journal of Heuristics 17(3), 201–249, 2011. arXiv:0806.3258. 1DV, sDV, and the Chain method used by ILS.
- D. Karapetyan, G. Gutin, and B. Goldengorin, “Empirical evaluation of construction heuristics for the multidimensional assignment problem,” Text in Algorithmics 11, 107–122, 2009. arXiv:0906.2960. Shift-ROM.
- G. Gutin and D. Karapetyan, “A memetic algorithm for the multidimensional assignment problem.” Memetic search.
- D. Karapetyan and G. Gutin, “A New Approach to Population Sizing for Memetic Algorithms: A Case Study for the Multidimensional Assignment Problem,” Evolutionary Computation 19(3), 345–371, 2011. arXiv:1003.4314. Memetic population sizing.
Benchmarks
Measurements include the speed of the native core against the Python implementation, and the solution quality of ILS and memetic with complete and optional matching, plus comparisons with proven optima and LAP backend timings.
The tables identify the measured source revision. They precede the later LAP integer-overflow safeguards, which add arithmetic checks; they do not measure that subsequent implementation.
Native core against the Python implementation
kap.k_assignment with the native core (backend="kap", the default) against the
Python implementation of the same algorithms (kap._reference.k_assignment, which
runs the multiple Hungarian methods in Python but calls the same native LAP solver).
kap 0.2.x used other LAP backends, which are not measured here.
Setup: 4 × Intel Xeon E7-8860 v4 at 2.20 GHz (72 cores, 144 threads),
503 GB RAM, kap 0.3.0a1 from d1877e0 with the explicit-float threshold validation
change, Python 3.12.16, and NumPy 2.5.4. Eight workers ran concurrently, each
pinned to one physical core, with RAYON_NUM_THREADS=1. Other users were active.
Costs are independent uniform integers in [0, 100) plus uniform noise (float64),
in n × n pair matrices; max_iter=100, n_trials=1, and no threshold.
Each cell reports the median time across three seeds; short calls use the minimum
of up to five repeats within each seed. Costs are means across those seeds.
| Algo | k | n | Native | Python | Speedup | Cost, native / Python |
|---|---|---|---|---|---|---|
| Am | 6 | 10 | 0.104 ms | 1.73 ms | 16.59× | = |
| Am | 6 | 100 | 1.81 ms | 7.22 ms | 4.00× | = |
| Am | 6 | 500 | 62.8 ms | 82.2 ms | 1.31× | = |
| Dm | 8 | 10 | 0.558 ms | 29.9 ms | 53.64× | = |
| Dm | 8 | 100 | 24.4 ms | 149 ms | 6.12× | = |
| Dm | 8 | 500 | 882 ms | 2.23 s | 2.52× | = |
| Bm | 4 | 100 | 8.39 ms | 56 ms | 6.68× | = |
| Bm | 6 | 10 | 10.5 ms | 1.2 s | 114.48× | = |
| Bm | 6 | 100 | 679 ms | 8.69 s | 12.79× | = |
| Bm | 6 | 200 | 2.89 s | 20.4 s | 7.04× | = |
| Cm | 4 | 100 | 19.5 ms | 158 ms | 8.13× | 1.005 |
| Cm | 5 | 10 | 5.37 ms | 242 ms | 45.13× | 0.990 |
| Cm | 5 | 100 | 296 ms | 1.64 s | 5.53× | 0.997 |
| Em | 4 | 100 | 19.6 ms | 113 ms | 5.76× | 0.999 |
| Em | 5 | 100 | 238 ms | 1.75 s | 7.36× | 0.997 |
| Fm | 3 | 100 | 4.45 ms | 46.7 ms | 10.49× | 0.931 |
| Fm | 4 | 100 | 620 ms | 151 ms | 0.24× | 0.950 |
| Fm | 5 | 100 | 7.71 s | 2.3 s | 0.30× | 0.988 |
= denotes equal mean objective costs. Am, Bm, and Dm had equal native/reference
mean costs at every measured size and dtype. Cm, Em, and Fm can differ because
the native implementation follows different search rules from the Python reference.
- Removing Python quotient-graph construction has the largest effect on small n and larger k: the displayed Bm k=6,n=10 speedup is about 114×. For Am at n=500, LAP work dominates and the displayed speedup is 1.31×.
- Native Bm also avoids repeated merges by memoizing equivalent merge forests; see algorithm costs.
- Native Fm runs all 100 tabu iterations, while the Python reference can stop at a plateau. At k=4/5 it is slower here and returns lower mean costs.
- Separate int64 workloads, without the uniform noise, ran up to 2.50× faster than the float64 workloads for n≥50. This comparison changes both the dtype and the cost structure, so it does not isolate an arithmetic-only speedup.
- Bm, Cm, Em, and Fm can use parallel execution, but each run here used one thread.
Solution quality of the search methods
This reruns the retained laptop comparison grid on 4 × Intel Xeon E7-8860 v4
at 2.20 GHz (72 cores, 144 threads), with Python 3.12.16, NumPy 2.5.4,
and kap 0.3.0a1 from d1877e0 with the explicit-float threshold validation change.
Each instance used 16 physical cores on one socket (RAYON_NUM_THREADS=16),
with four instances on disjoint core groups. Other users were active; the
machine was not reserved exclusively for these measurements.
Part sizes are equal and threshold=None. Random costs are independent uniform
integers in 1..100. Geometric costs are rounded Euclidean distances between
uniform points in [0, 1000]². Matrices use int64. There are three seeds per random
setting and one per geometric setting: 23 instances and 350 measured calls.
Values are mean percentages above the lowest cost observed for that instance across all measured methods and budgets. These are not gaps to a known optimum. The reference includes Shift, 1DV, Shift+sDV, Cm, Em with 16 trials, Fm, and ILS/memetic with both 1DV and sDV at 1 s and 10 s. The table shows a subset: ILS and memetic use 1DV; ILS × 16 uses 16 independent chains. Cm/Fm use their default iteration limits; their parentheses report mean elapsed milliseconds. Cm, Em, and Fm were omitted for k≥6.
| Kind | k | n | Seeds | Cm | Fm | ILS, 1 s | ILS × 16, 1 s | memetic, 1 s | ILS, 10 s | ILS × 16, 10 s | memetic, 10 s |
|---|---|---|---|---|---|---|---|---|---|---|---|
| random | 3 | 40 | 3 | 15.88 (0.6 ms) | 15.88 (0.5 ms) | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| random | 3 | 100 | 3 | 23.03 (2.6 ms) | 23.03 (2.5 ms) | 4.69 | 0.71 | 5.13 | 1.29 | 0.00 | 3.54 |
| random | 4 | 30 | 3 | 15.17 (2.3 ms) | 4.51 (20.4 ms) | 0.63 | 0.01 | 0.16 | 0.00 | 0.00 | 0.18 |
| random | 4 | 50 | 3 | 24.47 (3.1 ms) | 17.24 (45.0 ms) | 3.10 | 1.72 | 4.05 | 0.84 | 0.42 | 0.67 |
| random | 5 | 25 | 3 | 14.16 (8.7 ms) | 11.01 (107.9 ms) | 0.81 | 0.09 | 0.11 | 0.30 | 0.00 | 0.00 |
| random | 6 | 18 | 3 | — | — | 0.57 | 0.07 | 0.07 | 0.12 | 0.00 | 0.00 |
| random | 8 | 10 | 3 | — | — | 0.03 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| geometric | 3 | 70 | 1 | 0.20 (1.9 ms) | 0.20 (1.9 ms) | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| geometric | 4 | 50 | 1 | 0.09 (3.8 ms) | 0.09 (85.6 ms) | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
At 10 s, 16-chain ILS had mean excess at most 0.42% in this grid. Memetic’s largest mean excess was 3.54% at random k=3,n=100. All displayed ILS/memetic configurations reached the same cost on the two geometric settings. These complete-matching results do not predict the optional-matching results below.
Time limits are checked between operations, so elapsed time can exceed the requested budget. The raw measurements retain elapsed time for each call.
Optional matching: ILS and memetic
Measured on 4 × Intel Xeon E7-8860 v4 at 2.20 GHz (72 cores, 144 threads),
Python 3.12.16, NumPy 2.5.4, and kap 0.3.0a1 from commit d1877e0 with the
explicit-float threshold validation change. Each run used 16 physical cores on
one socket and RAYON_NUM_THREADS=16; four instances ran concurrently on disjoint
core groups. Other users were active, so cache and memory bandwidth were shared.
These synthetic instances test unequal part sizes, forbidden pairs, and
optional matching. The base size n gives part sizes
0.8n, n, 1.2n, repeated in that order. All methods used 1DV, minimization, and
float64 matrices so forbidden pairs could be represented by +inf.
- Random: independent uniform integer costs in 1..100, threshold 30, and 20% of pairs forbidden independently.
- Geometric: rounded Euclidean distances between uniform points in [0, 1000]², threshold 150. Distances above 250 and 5% of the remaining pairs selected independently are forbidden; about 85% of all pairs are forbidden.
There are three seeds per setting, except n=1000 with one seed per family: 32 instances and 192 method/budget calls. Every output was checked for vertex coverage, uniqueness, part membership, forbidden pairs, reported original costs, and a shifted objective no worse than the all-singleton partition.
Let J be the shifted objective, the sum of (cost − threshold) within cliques.
The table reports mean 100 × (J − J_best) / abs(J_best), where J_best is the
lowest objective any measured method found at either budget on that instance.
All J_best values here are negative. Zero denotes the best observed value;
these are not gaps to a proven optimum. Original costs alone would omit the
threshold’s dependence on the number of matched pairs.
| Kind | k | n | Seeds | ILS, 1 s | ILS × 16, 1 s | memetic, 1 s | ILS, 10 s | ILS × 16, 10 s | memetic, 10 s |
|---|---|---|---|---|---|---|---|---|---|
| geometric | 3 | 100 | 3 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| geometric | 3 | 300 | 3 | 0.05 | 0.01 | 0.03 | 0.00 | 0.00 | 0.00 |
| geometric | 3 | 1000 | 1 | 0.02 | 0.02 | 0.03 | 0.00 | 0.00 | 0.00 |
| geometric | 5 | 100 | 3 | 0.18 | 0.02 | 0.03 | 0.02 | 0.00 | 0.00 |
| geometric | 5 | 300 | 3 | 0.44 | 0.39 | 0.26 | 0.15 | 0.11 | 0.00 |
| geometric | 8 | 100 | 3 | 0.84 | 0.49 | 0.79 | 0.21 | 0.07 | 0.01 |
| random | 3 | 100 | 3 | 0.65 | 0.23 | 0.23 | 0.16 | 0.04 | 0.00 |
| random | 3 | 300 | 3 | 0.87 | 0.78 | 0.73 | 0.29 | 0.21 | 0.14 |
| random | 3 | 1000 | 1 | 0.37 | 0.43 | 0.54 | 0.00 | 0.21 | 0.01 |
| random | 5 | 100 | 3 | 4.55 | 3.00 | 2.39 | 2.60 | 1.20 | 0.00 |
| random | 5 | 300 | 3 | 3.49 | 3.70 | 3.90 | 2.07 | 1.54 | 0.39 |
| random | 8 | 100 | 3 | 8.97 | 6.80 | 6.40 | 5.34 | 3.33 | 0.00 |
At 10 s, memetic had a lower shifted objective than 16-chain ILS on 18 instances, tied it on 9, and had a higher objective on 5. This differs from the complete-matching comparison above; method selection depends on the instance family and objective.
Actual elapsed time includes initial construction and the final in-progress operation. The next table reports the maximum elapsed seconds across seeds for each method and requested budget. In particular, the 1 s request for 16-chain ILS took up to 3.83 s on the largest random instance.
| Kind | k | n | ILS, 1 s | ILS × 16, 1 s | memetic, 1 s | ILS, 10 s | ILS × 16, 10 s | memetic, 10 s |
|---|---|---|---|---|---|---|---|---|
| geometric | 3 | 100 | 1.00 | 1.01 | 1.03 | 10.00 | 10.01 | 10.07 |
| geometric | 3 | 300 | 1.06 | 1.06 | 1.06 | 10.04 | 10.05 | 10.08 |
| geometric | 3 | 1000 | 1.84 | 2.32 | 1.07 | 10.71 | 11.57 | 10.21 |
| geometric | 5 | 100 | 1.02 | 1.03 | 1.03 | 10.01 | 10.01 | 10.06 |
| geometric | 5 | 300 | 1.13 | 1.18 | 1.08 | 10.17 | 10.18 | 10.08 |
| geometric | 8 | 100 | 1.05 | 1.05 | 1.01 | 10.08 | 10.05 | 10.07 |
| random | 3 | 100 | 1.01 | 1.01 | 1.02 | 10.01 | 10.01 | 10.03 |
| random | 3 | 300 | 1.12 | 1.13 | 1.06 | 10.10 | 10.11 | 10.04 |
| random | 3 | 1000 | 1.73 | 3.83 | 1.55 | 10.85 | 12.40 | 10.73 |
| random | 5 | 100 | 1.04 | 1.02 | 1.02 | 10.02 | 10.02 | 10.04 |
| random | 5 | 300 | 1.20 | 1.22 | 1.10 | 10.20 | 10.21 | 10.08 |
| random | 8 | 100 | 1.09 | 1.07 | 1.04 | 10.07 | 10.06 | 10.03 |
ILS and the lower bound against the proven optimum
The same 33 instances previously measured on an AMD Ryzen 7 7840H were rerun
on 4 × Intel Xeon E7-8860 v4 at 2.20 GHz (72 cores, 144 threads), using
Python 3.12.16, NumPy 2.5.4, SciPy 1.18.1 (HiGHS through scipy.optimize.milp),
and kap 0.3.0a1 from d1877e0 with the explicit-float threshold validation change.
There are three seeds per size. Random and geometric costs follow the definitions
above, with int64 matrices, equal sizes, minimization, and no threshold.
Four instances ran concurrently on disjoint 16-physical-core groups, one per
socket. Rayon used 16 threads. The benchmark explicitly forwarded threads=1
to HiGHS for exact solving; ILS used one or eight chains as shown. Other users
were active. Exact elapsed time includes model construction and solving but
excludes the initial SciPy import. The solve limit was 300 s.
All 33 exact solves proved optimality, and every optimum agreed with the retained laptop result. ILS columns show mean percentage above the optimum, followed by optimum hits / seeds. The lower-bound column shows mean percentage below the optimum. Exact time is the maximum across the three seeds, in seconds.
| Kind | k | n | Exact time max (s) | ILS, 100 iterations | ILS, 1 s, 1 chain | ILS, 1 s, 8 chains | lower_bound |
|---|---|---|---|---|---|---|---|
| random | 3 | 10 | 0.09 | 0.00 (3/3) | 0.00 (3/3) | 0.00 (3/3) | 0.88 |
| random | 3 | 20 | 1.39 | 1.84 (0/3) | 0.00 (3/3) | 0.00 (3/3) | 1.00 |
| random | 3 | 30 | 9.27 | 2.29 (0/3) | 0.00 (3/3) | 0.00 (3/3) | 1.82 |
| random | 3 | 40 | 40.50 | 1.91 (0/3) | 0.00 (3/3) | 0.00 (3/3) | 2.39 |
| random | 4 | 8 | 0.82 | 0.00 (3/3) | 0.00 (3/3) | 0.00 (3/3) | 13.71 |
| random | 4 | 12 | 14.54 | 0.76 (2/3) | 0.00 (3/3) | 0.00 (3/3) | 16.50 |
| random | 4 | 16 | 64.33 | 1.94 (0/3) | 0.00 (3/3) | 0.00 (3/3) | 20.30 |
| random | 5 | 8 | 24.51 | 0.43 (1/3) | 0.00 (3/3) | 0.00 (3/3) | 19.79 |
| random | 6 | 6 | 71.35 | 0.00 (3/3) | 0.00 (3/3) | 0.00 (3/3) | 18.78 |
| geometric | 3 | 30 | 3.42 | 0.00 (3/3) | 0.00 (3/3) | 0.00 (3/3) | 0.01 |
| geometric | 4 | 16 | 28.64 | 0.00 (3/3) | 0.00 (3/3) | 0.00 (3/3) | 0.59 |
Both 1 s ILS configurations reached the proven optimum on all 33 instances. The default 100 iterations reached it on 18. The bound was within 2.39% for these k=3 cases and within 0.59% for the geometric cases; the largest mean random-instance gap was 20.30% at k=4.
An initial run with HiGHS’s default thread count created 72 solver threads per worker despite the 16-core affinity limit. It was stopped and retained separately; its partial results are excluded from this table. The table uses the explicit single-thread HiGHS configuration described above.
A separate one-seed prototype run at k=6,n=8 (262,144 variables) returned no
incumbent after 626 s despite a requested 120 s limit. That size exceeds the
public kap.exact default guard of 150,000 variables and is not included in the
table. The result illustrates why the guard and time-limit caveat remain.
LAP backends
| Backend | Algorithm | Rectangular | Notes |
|---|---|---|---|
kap | Jonker-Volgenant initialization (square) + shortest augmenting path (Crouse 2016) | yes | default; native, built in; optimal like scipy (ties may differ on square input) |
scipy | modified Jonker-Volgenant | yes | |
lap | Jonker-Volgenant | yes | |
lapjv | Jonker-Volgenant | no | see measurements below |
munkres | Hungarian | yes | pure Python, slower in these measurements |
Measured time per call in µs on 4 × Intel Xeon E7-8860 v4 at 2.20 GHz (72 cores, 144 threads), Python 3.12.16, NumPy 2.5.4, kap 0.3.0a1 from d1877e0 with the explicit-float threshold validation change, SciPy 1.18.1, lap 0.5.14, and lapjv 1.3.29. Each worker was pinned to one physical core; four input cells ran concurrently on separate sockets. Other users were active.
Uniform inputs are float64 values in [0, 1). int100 contains integer-valued
float64 costs in [0, 100), with many ties. Here the input labeled geometric
is the structured cost i*j + uniform noise; it differs from the Euclidean
instances used in the search sections. The full grid also includes integer-valued
costs in [0, 10⁶), and both n × n and n × 2n shapes.
Each solver is warmed up, then timing uses the minimum of five repeated samples,
with repetition counts calibrated to about 0.3 s total for short calls. Before
timing, assignments are checked for cardinality, uniqueness, index range, and
objective agreement with SciPy (rtol=1e-12, atol=1e-8). Inputs are generated
from a separate deterministic seed for each distribution/size/shape cell.
| Input | n | kap | SciPy 1.18.1 | lap 0.5.14 | lapjv 1.3.29 |
|---|---|---|---|---|---|
| uniform | 10 | 1.83 | 2.13 | 2.48 | 2.24 |
| uniform | 100 | 84.68 | 299.18 | 93.92 | 52.91 |
| uniform | 300 | 2 166.93 | 3 835.16 | 2 614.57 | 1 663.76 |
| uniform | 500 | 4 546.05 | 11 694.46 | 4 330.73 | 2 631.76 |
| uniform | 1000 | 20 851.80 | 54 183.01 | 47 246.04 | 34 966.02 |
| uniform | 2000 | 87 057.39 | 288 626.79 | 339 781.58 | 253 528.86 |
| int100 | 1000 | 7 788.47 | 26 058.69 | 5 476.26 | 5 780.74 |
| geometric | 1000 | 657 132.46 | 773 656.64 | 2 321 726.41 | cost mismatch |
| uniform, n × 2n | 1000 | 20 078.80 | 19 147.33 | 29 458.68 | — |
Kap is about 2.6–3.3 times faster than SciPy on the displayed uniform square inputs at n=1000 and n=2000. At n=1000 with tied costs, kap is about 1.35–1.42 times slower than lap/lapjv. For the displayed uniform rectangular case, kap takes about 1.05 times SciPy’s time. These ratios describe these inputs and versions.
cost mismatch means a feasible assignment had a higher cost than SciPy’s and
failed the objective-agreement check. With lapjv 1.3.29, the difference was
0.02962184 at structured n=1000 and 2.5415404 at n=2000. Kap and lap agreed
with SciPy on those inputs. These lapjv timings are omitted from equivalent-solution
comparisons. The discrepancy was reproduced in the second run at n=1000.
The benchmark runner was also checked on identical serial and four-worker grids (84 solver/input cells, n=10,100,300). Input hashes and returned objectives matched exactly. The median parallel/serial timing ratio was 1.00, with a range of 0.85–1.06; timing equality is not expected on shared hardware.