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
| Python | Rust | Default | Meaning |
|---|---|---|---|
cost_matrices | mats | Required | Pairwise matrices in combinations order. |
neighborhood | Algo::Dv1, Algo::DvS, or opts.refine | "1dv" / explicit Algo | Select 1DV or sDV; Python accepts case-insensitive dv1 / dvs aliases. |
start | algo before opts.refine | None (Am) / explicit Algo | Am, Bm, Dm, or Shift. Cannot combine with Python initial. |
initial | cliques in k_assignment_from | None / required by k_assignment_from | A complete solution without a threshold; partial or empty solutions with one. See warm starts. |
max_sweeps | opts.max_iter | 100 | Nonnegative maximum number of DV sweeps. |
maximize | opts.sense | False / Sense::Minimize | Maximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective. |
threshold | opts.threshold | None | Finite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching. |
return_free | - | False | Include 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
| Python | Rust | Condition |
|---|---|---|
ValueError | KapError::BadCount | The matrix count does not describe 2 through 64 parts in the native core. |
ValueError | KapError::ShapeMismatch | Matrix dimensions disagree about a part’s size. |
TypeError | Rejected by the Cost trait at compilation | A matrix has an unsupported element type. |
OverflowError | - | Python uses int64 arithmetic and a uint64 value exceeds int64. |
ValueError | KapError::TooManyVertices | A native part exceeds u32 vertex capacity. |
ValueError | KapError::Lap | A 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=Nonepreserves 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 raisesValueError. 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::Dv1orAlgo::DvS. For Bm, Dm, or Shift, select thatAlgoand setopts.refine. -
The method is deterministic. Part sizes may differ.