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

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

PythonRustDefaultMeaning
cost_matricesmatsRequiredPairwise matrices in combinations order.
neighborhoodAlgo::Dv1, Algo::DvS, or opts.refine"1dv" / explicit AlgoSelect 1DV or sDV; Python accepts case-insensitive dv1 / dvs aliases.
startalgo before opts.refineNone (Am) / explicit AlgoAm, Bm, Dm, or Shift. Cannot combine with Python 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_iter100Nonnegative maximum number of DV sweeps.
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.

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

  • 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::Dv1 or Algo::DvS. For Bm, Dm, or Shift, select that Algo and set opts.refine.

  • The method is deterministic. Part sizes may differ.

See also

Warm starts · ILS · DV algorithm