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

15. Objectives and Callback Interfaces

The nlopt4r solvers read objective values, gradients, Hessians, residuals and constraints through one callback interface family. This chapter lists the three interfaces, their adapters and the output validation rules.

API reference (docs.rs): Objective, Evaluator, Function, ValueOnly, value_only, EvaluationError, Vector, Matrix.

15.1 Type aliases

pub type Vector<T = f64> = nalgebra::DVector<T>;
pub type Matrix<T = f64> = nalgebra::DMatrix<T>;

Solver entries use Vector<f64> and Matrix<f64>. Dimensions are determined at runtime, and every solver accepts any nonempty dimension.

15.2 Infallible objective: Objective

pub trait Objective {
    fn value(&self, x: &Vector<f64>) -> f64;
    fn gradient(&self, x: &Vector<f64>) -> Vector<f64>;
    fn hessian(&self, x: &Vector<f64>) -> Option<Matrix<f64>> { None }
}
  • implement the trait for an application type, or pass a closure tuple at the call site;
  • a (value, gradient) tuple implements the trait;
  • a (value, gradient, hessian) tuple implements the trait with the Hessian returning Some.

Example (application type implementation):

#![allow(unused)]
fn main() {
use nlopt4r::{Objective, Vector};

struct Bowl;

impl Objective for Bowl {
    fn value(&self, x: &Vector<f64>) -> f64 {
        (x[0] - 1.0).powi(2) + (x[1] + 2.0).powi(2)
    }
    fn gradient(&self, x: &Vector<f64>) -> Vector<f64> {
        Vector::from_vec(vec![2.0 * (x[0] - 1.0), 2.0 * (x[1] + 2.0)])
    }
}
}

Objective comes with an automatic Evaluator adapter that builds the gradient vector on each call.

15.3 Buffered, fallible callbacks: Evaluator and Function

pub trait Evaluator {
    fn evaluate(&self, x: &[f64], gradient: Option<&mut [f64]>) -> Result<f64, Error>;
    fn evaluate_hessian(&self, x: &[f64]) -> Result<Option<Matrix<f64>>, Error> {
        Ok(None)
    }
}

Function is the closure adapter:

#![allow(unused)]
fn main() {
use nlopt4r::{EvaluationError, Function};

let problem = Function::new(|x: &[f64], gradient: Option<&mut [f64]>| {
    if let Some(g) = gradient {
        for (out, &value) in g.iter_mut().zip(x) {
            *out = 2.0 * value;
        }
    }
    Ok::<_, EvaluationError>(x.iter().map(|v| v * v).sum::<f64>())
});
}

The Hessian variant:

#![allow(unused)]
fn main() {
use nlopt4r::{EvaluationError, Function, Matrix};

let problem = Function::new(|x: &[f64], gradient: Option<&mut [f64]>| {
    if let Some(g) = gradient {
        g.copy_from_slice(x);
    }
    Ok::<_, EvaluationError>(0.5 * x.iter().map(|v| v * v).sum::<f64>())
})
.with_hessian(|_: &[f64]| Ok::<_, EvaluationError>(Matrix::from_element(2, 2, 1.0)));
}

Conventions:

  • gradient: None requests the objective value alone;
  • on a gradient request, the callback writes every element of the buffer;
  • on non-finite outputs, unwritten buffer elements or shape mismatches, the solver returns an explicit error;
  • buffers are filled with NaN before the call, which makes missed writes detectable.

15.4 Value-only objectives: value_only

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

let problem = value_only(|x: &[f64]| {
    Ok::<_, EvaluationError>(x.iter().map(|v| v * v).sum())
});
}

The ValueOnly adapter produced by value_only returns an explicit error on a gradient request. This interface serves global, derivative_free and core::EvaluationContext.

15.5 Application errors

EvaluationError carries a display message:

#![allow(unused)]
fn main() {
use nlopt4r::EvaluationError;

let error: EvaluationError = "mesh solver diverged".into();
let error = EvaluationError::new(std::io::Error::other("model failed"));
}

When a callback returns EvaluationError, the solver reports Error::Evaluation { operation, source } in the error chain, with operation values such as "objective", "Hessian", "residuals", "Jacobian", "constraints" or "observer".

15.6 Least-squares and constraint interfaces

Least squares uses a (residuals, jacobian) tuple or the least_squares::LeastSquares trait; nonlinear constraints use the constrained::ConstrainedProblem trait returning Constraints. Chapters 18 and 19 cover the two interfaces.

15.7 Interface selection

NeedInterface
Analytic objective returning values directlyObjective or a closure tuple
Buffered writes, shared value/gradient computationFunction or Evaluator
Application errors reported upwardFunction, Evaluator or try_* hooks
Objective values alonevalue_only
Hessian-vector productslocal::HessianVector (chapter 16)

A type picks one interface implementation. Objective provides the Evaluator adapter, so an application type implementing Objective works with every solver.

Theory background