Skip to main content

eindir_core/
objective.rs

1//! The `Objective` trait: a typed function `Obj : S -> R` from the IISE manuscript.
2
3use crate::{Bounds, FPair};
4use ndarray::{Array1, ArrayView1, ArrayView2};
5use num_traits::Float;
6use rayon::prelude::*;
7
8/// Minimum batch size before the parallel `eval` fan-out is worth the spawn cost.
9pub const EVAL_BATCH_PARALLEL_MIN: usize = 16;
10
11/// A real-valued function on `R^dim` with a known feasible domain.
12///
13/// The IISE manuscript's `Obj` signature: a typed map from a state space
14/// `S = R^dim` (with `Bounds`) to `R`. Implementors may override
15/// `eval_batch` and `global_min` for performance or known-optima
16/// instrumentation.
17///
18/// A real-valued function on `R^dim` with a known feasible domain.
19///
20/// Implementors may override `eval_batch` for multi-walker / multi-start
21/// backends (Rayon-native, Python single-attach batch, CUTEst worker pools).
22pub trait Objective<T: Float>: Send + Sync {
23    /// Number of input dimensions; matches `bounds().dims`.
24    fn dim(&self) -> usize;
25
26    /// The feasible domain (typically a box).
27    fn bounds(&self) -> &Bounds<T>;
28
29    /// Evaluates the objective at a single point.
30    fn eval(&self, x: ArrayView1<T>) -> T;
31
32    /// Evaluates a batch of points (rows of `x`).
33    ///
34    /// Default: serial loop over [`Objective::eval`]. Override for
35    /// multi-walker fan-out (see [`eval_batch_parallel`] for native f64).
36    fn eval_batch(&self, x: ArrayView2<T>) -> Array1<T> {
37        x.outer_iter().map(|row| self.eval(row)).collect()
38    }
39
40    /// Optional known global minimum, used for benchmarking and convergence
41    /// checks. Default returns `None`.
42    fn global_min(&self) -> Option<&FPair<T>> {
43        None
44    }
45}
46
47/// Parallel multi-walker / multi-start batch evaluation for `Objective<f64>`.
48///
49/// Uses Rayon when `x.nrows() >= EVAL_BATCH_PARALLEL_MIN`. Prefer
50/// [`Objective::eval_batch`] when the implementor has a specialized batch
51/// path (Python/CUTEst); this helper is the native Sync hot path.
52pub fn eval_batch_parallel<O>(obj: &O, x: ArrayView2<f64>) -> Array1<f64>
53where
54    O: Objective<f64> + ?Sized,
55{
56    let n = x.nrows();
57    if n < EVAL_BATCH_PARALLEL_MIN {
58        return obj.eval_batch(x);
59    }
60    let mut out = vec![0.0_f64; n];
61    out.par_iter_mut().enumerate().for_each(|(i, slot)| {
62        *slot = obj.eval(x.row(i));
63    });
64    Array1::from(out)
65}