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

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

PythonRustDefaultMeaning
cost_matricesmatsRequiredPairwise matrices in combinations order.
max_iteropts.max_iterNone / 100Nonnegative perturbations per chain. Python resolves None to 100, or sys.maxsize with a time limit.
n_chainsopts.n_trials1Positive number of independent chains.
time_limitopts.time_limitNonePython: finite positive seconds. Rust: Option<Duration>. Both time and iteration limits apply.
neighborhoodopts.dv"1dv" / Dv::OneUse "1dv" or "sdv" / Dv::Subsets; aliases "dv1" and "dvs" are accepted in Python, case-insensitively.
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.
initialcliques in k_assignment_fromNone / required by k_assignment_fromA complete solution without a threshold; partial or empty solutions with one. See warm starts.
-opts.refineNoneOptional 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

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 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=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.

  • Select Algo::Ils in 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; set max_iter explicitly, for example to usize::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