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

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

PythonRustDefaultMeaning
cost_matricesmatsRequiredPairwise matrices in combinations order.
neighborhoodalgo / opts.dv / opts.refine"1dv" / Dv::One internallySelect the DV neighborhood for refinement or ILS; sDV needs k≤16.
start-NonePython local_search rejects a non-None start together with initial.
initialcliques in k_assignment_fromNone / required by k_assignment_fromA complete solution without a threshold; partial or empty solutions with one. See warm starts.
max_sweepsopts.max_iter for DV100Local-search sweep limit; nonnegative.
max_iteropts.max_iter for ILSNone / 100ILS perturbations per chain; Python resolves None to 100 or sys.maxsize with a time limit.
n_chainsopts.n_trials1Positive ILS chain count.
time_limitopts.time_limitNonePython: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply.
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.
random_stateopts.seedNone / 0Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64.
-algoRequiredAm, 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

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.
ValueErrorKapError::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.

PythonRustCondition
ValueErrorKapError::BadMatchingEmpty clique, invalid index, repeated vertex, or two vertices from one part in a clique.
ValueErrorKapError::IncompleteInitialWithout a threshold, restoring unlisted vertices as singletons does not give exactly max(part sizes) nodes.
ValueErrorKapError::ForbiddenInitialWith 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=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.

  • 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 AssignmentResult or an iterable of cliques. Only the result’s cliques field 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