Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

PythonRustDefaultMeaning
cost_matricesmatsRequiredPairwise matrices in combinations order.
algoalgoNone / requiredPython: ILS with native kap, otherwise Cm. Rust always requires an Algo.
max_iteropts.max_iterNone / 100Moves, sweeps, perturbations per chain, or generations; Python resolves None by algorithm and time mode.
n_trialsopts.n_trials1Em trials or ILS chains; positive for those methods.
maximizeopts.senseFalse / Sense::MinimizeMaximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective.
thresholdopts.thresholdNoneFinite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching.
return_free-FalseInclude singleton vertices in Python free; Rust always returns them.
backend-"kap"Native kap or optional scipy, lap, lapjv, munkres; newer methods require native kap.
random_stateopts.seedNone / 0Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64.
refineopts.refine or opts.dvNone / None or Dv::One1DV or sDV after construction; inside ILS/memetic it selects the search neighborhood.
time_limitopts.time_limitNonePython: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply.
populationopts.populationNoneMemetic 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

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

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

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

  • Python accepts Am–Fm, Shift, 1DV, sDV, ILS, and memetic, case-insensitively. initial is available through ils and local_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::Ils and Options::dv for ILS in Rust. Options::refine applies a separate pass after the main Rust algorithm.

See also

ILS · Memetic · Local search · Multiple Hungarian methods