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

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

PythonRustDefaultMeaning
cost_matricesmatsRequiredPairwise matrices in combinations order. Part sizes may differ.
thresholdopts.thresholdNoneFinite real pair-cost threshold; Python rejects booleans and non-numbers.
maximizeopts.senseFalse / Sense::MinimizeMaximise the shifted objective when true / Sense::Maximize.
initialcliques in k_assignment_fromNone / required by k_assignment_fromFor ILS and local search, partial and empty solutions are accepted with a threshold.
return_free-FalseInclude singleton vertices in Python free; Rust always returns them.
max_iteropts.max_iterNone / 100ILS perturbations per chain; Python resolves None to 100, or sys.maxsize with a time limit.
n_chainsopts.n_trials1Positive number of ILS chains.
time_limitopts.time_limitNoneFinite positive seconds in Python; Option<Duration> in Rust. Both iteration and time limits apply.
neighborhoodopts.dv"1dv" / Dv::OneILS DV neighborhood: 1DV or sDV.
random_stateopts.seedNone / 0Integer 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

PythonRustCondition
TypeErrorRejected by the Option<f64> typeBoolean or non-real Python threshold.
ValueErrorKapError::BadOption("threshold")Non-finite threshold, a fractional threshold with all-integer matrices, or an unrepresentable threshold for integer arithmetic.
ValueErrorKapError::LapNaN entry or wrong-sign infinity.
ValueErrorKapError::ForbiddenInitialinitial places a forbidden pair in one clique.
ValueErrorKapError::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

  • exact and lower_bound do 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 None for the unchanged objective.
  • Thresholding and forbidden pairs also apply during refinement and search.

See also

Warm starts · ILS · Local search · Multiple Hungarian methods