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

Memetic search

Memetic search evolves a population of DV local optima by mutation and common-clique crossover. Use it to compare population search with ILS on your data.

Signature

The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.

def memetic(cost_matrices, *, generations=None, population=None, time_limit=None,
            neighborhood="1dv", maximize=False, return_free=False, random_state=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.
generationsopts.max_iterNone / 100Nonnegative generation limit. Python resolves None to 100, or sys.maxsize with a time limit.
populationopts.populationNoneAt least 2 if supplied; otherwise 12 without a time limit, or sized from measured local-search time with one.
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.
-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 generation counts. It raises ValueError for negative generations, a population that is not an integer at least 2, an invalid neighborhood, or an invalid time budget. Rust returns KapError::BadOption("population") for a population below 2 and KapError::Unsupported for sDV above 16 parts.

Example

import numpy as np
import kap

C01 = np.array([[12, 10, 22], [12, 23, 17], [4, 15, 12]], dtype=np.int64)
C02 = np.array([[17, 17, 17], [17, 26, 10], [3, 20, 22]], dtype=np.int64)
C12 = np.array([[14, 24, 9], [21, 20, 12], [23, 28, 8]], dtype=np.int64)
costs = [C01, C02, C12]

result = kap.memetic(costs, generations=4, population=4, 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 = [12, 10, 22, 12, 23, 17, 4, 15, 12i64];
    let c02 = [17, 17, 17, 17, 26, 10, 3, 20, 22i64];
    let c12 = [14, 24, 9, 21, 20, 12, 23, 28, 8i64];
    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: 4,
        population: Some(4),
        seed: 0,
        ..Options::default()
    };
    let result = k_assignment(&costs, Algo::Memetic, &opts)?;
    println!("cliques = {:?}", result.cliques);
    println!("costs = {:?}", result.costs);
    println!("free = {:?}", result.free);
    Ok(())
}

Python output:

cliques = [[(0, 0), (1, 1), (2, 1)], [(0, 1), (1, 2), (2, 2)], [(0, 2), (1, 0), (2, 0)]]
costs = [47, 35, 21]
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::Memetic in Rust. opts.n_trials is ignored. Warm starts are not supported.

  • The deadline counts from entry. An in-progress batch or generation finishes after it. Rust still applies its default 100-generation limit unless changed.

  • Zero generations returns the best member of the initial population. Each candidate undergoes DV; the initialization starts from Shift.

  • Integer seeds reproduce iteration-limited runs, including parallel execution. Time limits depend on machine speed.

  • The measured multi-chain ILS runs had lower or equal costs at the 60 s budget. See the benchmark table for each size.

See also

ILS · DV neighborhoods · Algorithm details