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

21. Extension Interfaces: core and utils

core and utils expose the infrastructure the solvers use internally: validated callback invocation, strict budgets, best-point recording, observers, box projection and random number generators. External algorithms can build new solvers on these public pieces alone. The theory is in chapters 12 and 8.

21.1 EvaluationContext

pub struct EvaluationContext<'a, P: Evaluator + ?Sized> { /* ... */ }

impl<'a, P: Evaluator + ?Sized> EvaluationContext<'a, P> {
    pub fn new(problem: &'a P, dimension: usize, budget: &BudgetOptions)
        -> Result<Self, Error>;
    pub fn with_observer(self, observer: &'a mut Observer<'a>) -> Self;
    pub fn counts(&self) -> EvaluationCounts;
    pub fn best(&self) -> Option<&EvaluatedPoint>;
    pub fn stop_reason(&self) -> Option<SearchTermination>;
    pub fn evaluate(&mut self, x: &[f64]) -> Result<f64, Error>;
    pub fn evaluate_into(&mut self, x: &[f64], gradient: Option<&mut [f64]>)
        -> Result<f64, Error>;
    pub fn failure(&self, source: Error) -> Error;
}

API pages (docs.rs): EvaluationContext, BudgetOptions, EvaluationCounts, EvaluatedPoint, SearchTermination.

Call semantics:

  1. inputs with an invalid shape or a wrong gradient-buffer length are rejected up front and stay uncounted;
  2. with a budget/target/cancellation criterion already met, the call returns Error::SearchStopped(SearchTermination) and invokes no callback;
  3. a valid call first counts objective (gradient additionally on a gradient request), then invokes the application callback;
  4. non-finite outputs or unwritten gradient-buffer elements report an error; the attempt stays counted;
  5. with all outputs valid, the best point updates (ties keep the earlier point);
  6. the observer runs last, and Control::Stop or an error ends subsequent calls.

EvaluatedPoint fields:

FieldTypeMeaning
xVectorSuccessfully evaluated point
valuef64Finite objective at that point

best() returns the smallest valid point recorded; ties keep the earlier point.

Example:

#![allow(unused)]
fn main() {
use nlopt4r::{core::{BudgetOptions, EvaluationContext}, value_only};

let problem = value_only(|x: &[f64]| Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0]));
let budget = BudgetOptions { max_evaluations: 2, target_value: None };
let mut context = EvaluationContext::new(&problem, 1, &budget)?;
context.evaluate(&[2.0])?;
context.evaluate(&[1.0])?;
assert_eq!(context.best().unwrap().value, 1.0);
assert_eq!(context.counts().objective, 2);
assert!(context.evaluate(&[0.5]).is_err());   // budget is exhausted
Ok::<(), nlopt4r::Error>(())
}

21.2 Observers and failure wrapping

pub enum Control { Continue, Stop }

pub struct EvaluationEvent<'a> {
    pub x: &'a [f64],
    pub value: f64,
    pub best_value: f64,
    pub evaluations: EvaluationCounts,
}

pub type Observer<'a> =
    dyn for<'b> FnMut(&EvaluationEvent<'b>) -> Result<Control, EvaluationError> + 'a;

API pages (docs.rs): Control, EvaluationEvent, Observer.

failure(source), with a best point present, wraps the error as Error::SearchFailure { source, last_point, evaluations } and keeps the checkpoint.

#![allow(unused)]
fn main() {
use nlopt4r::{core::{BudgetOptions, EvaluationContext}, value_only};

let problem = value_only(|x: &[f64]| {
    if x[0] < 0.0 {
        return Err("simulation failed".into());
    }
    Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0])
});
let mut context = EvaluationContext::new(&problem, 1, &BudgetOptions::default())?;
context.evaluate(&[2.0])?;
let source = context.evaluate(&[-1.0]).unwrap_err();
let error = context.failure(source);
assert_eq!(error.last_point().unwrap().value, 4.0);
assert_eq!(context.counts().objective, 2);
Ok::<(), nlopt4r::Error>(())
}

21.3 Bounds

impl Bounds {
    pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Result<Self, Error>;
    pub fn uniform(n: usize, lower: f64, upper: f64) -> Result<Self, Error>;
    pub fn dimension(&self) -> usize;
    pub fn lower(&self) -> &[f64];
    pub fn upper(&self) -> &[f64];
    pub fn width(&self, i: usize) -> f64;
    pub fn validate_point(&self, x: &[f64]) -> Result<(), Error>;
    pub fn contains(&self, x: &[f64]) -> bool;
    pub fn project(&self, x: &mut [f64]) -> Result<(), Error>;
    pub fn midpoint(&self) -> Vector;
    pub fn from_unit(&self, unit: &[f64]) -> Result<Vector, Error>;
    pub fn to_unit(&self, x: &[f64]) -> Result<Vector, Error>;
    pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R, x: &mut [f64])
        -> Result<(), Error>;
}

API page (docs.rs): Bounds.

Conventions:

  • construction requires finite lower and upper bounds, \(l_i\le u_i\) per coordinate and a positive dimension;
  • width(i) = u_i - l_i, with zero-width coordinates treated as fixed variables;
  • from_unit/to_unit map between the unit box and the physical box, sending zero-width coordinates to the fixed value;
  • project clips out-of-range coordinates to the interval endpoints.

21.4 utils

FunctionRole
validate_slice(x, n, context)Checks slice length and finiteness
solve_dense(a, b)Validates and solves a square linear system
directional_difference(context, x, direction, step)Central difference \((f(x+sd)-f(x-sd))/(2s)\), with both calls counted in the context budget

RNG re-exports: utils::ChaCha8Rng, utils::Rng, utils::SeedableRng. The global algorithms create reproducible streams with ChaCha8Rng::seed_from_u64(seed).

API pages (docs.rs): validate_slice, solve_dense, directional_difference, ChaCha8Rng, Rng, SeedableRng.

The algorithm below uses public pieces alone and completes a full “start at the midpoint, poll coordinates, halve on failure” search in about 30 lines:

use nlopt4r::{Bounds, Error, value_only};
use nlopt4r::core::{BudgetOptions, EvaluationContext};

fn main() -> Result<(), Error> {
    let problem = value_only(|x: &[f64]| {
        Ok::<_, nlopt4r::EvaluationError>((x[0] - 0.3).powi(2) + (x[1] + 0.4).powi(2))
    });
    let bounds = Bounds::uniform(2, -1.0, 1.0)?;
    let budget = BudgetOptions {
        max_evaluations: 400,
        target_value: Some(1e-10),
    };
    let mut context = EvaluationContext::new(&problem, bounds.dimension(), &budget)?;
    let mut x = bounds.midpoint();
    context.evaluate(x.as_slice())?;
    let mut step = 0.5;
    while step > 1e-7 && context.stop_reason().is_none() {
        let before = context.best().expect("initial evaluation").value;
        for i in 0..x.len() {
            if bounds.width(i) == 0.0 {
                continue;
            }
            for sign in [-1.0, 1.0] {
                if context.stop_reason().is_some() {
                    break;
                }
                let mut trial = x.clone();
                trial[i] += sign * step * bounds.width(i);
                bounds.project(trial.as_mut_slice())?;
                context.evaluate(trial.as_slice())?;
            }
        }
        let best = context.best().expect("evaluated point");
        x.copy_from(&best.x);
        if best.value >= before {
            step *= 0.5;
        }
    }
    println!("best f = {}", context.best().unwrap().value);
    Ok(())
}

Key points:

  • stop_reason() covers target hits, budgets, iterations and observer cancellation;
  • checking the stop state before each evaluate keeps callbacks from running after budget exhaustion;
  • Bounds::project keeps trial points feasible;
  • the final state comes from stop_reason(), with None corresponding to the step threshold (this example exits at step <= 1e-7).

The complete external solver example in the repository lives in tools/extension and runs directly as the benchmark tool’s external-pattern algorithm:

cargo test -p nlopt4r-extension-example
cargo run --release --locked -p nlopt4r-bench -- \
  --suite smoke --algorithms external-pattern --seeds 0..3 \
  --dimension 2 --budget-per-dimension 1000 --output target/extension.jsonl

21.6 Composition guide

NeedBuilding block
Strict budget and best pointEvaluationContext
Cancellation and external loggingwith_observer + Control
Checkpoint retention on failurecontext.failure(error)
Finite boxBounds + project/sample
Reproducible random streamChaCha8Rng::seed_from_u64
Difference gradients (diagnostics)utils::directional_difference
Dense linear solveutils::solve_dense

Theory background

  • Budgets, target values and counting semantics: see chapter 12.
  • Box projection and pattern search: see chapter 8.
  • Population initialization and seeds: see chapter 9.