use crate::{Bounds, FPair};
use ndarray::{Array1, ArrayView1, ArrayView2};
use num_traits::Float;
use rayon::prelude::*;
pub const EVAL_BATCH_PARALLEL_MIN: usize = 16;
pub trait Objective<T: Float>: Send + Sync {
fn dim(&self) -> usize;
fn bounds(&self) -> &Bounds<T>;
fn eval(&self, x: ArrayView1<T>) -> T;
fn eval_batch(&self, x: ArrayView2<T>) -> Array1<T> {
x.outer_iter().map(|row| self.eval(row)).collect()
}
fn global_min(&self) -> Option<&FPair<T>> {
None
}
}
pub fn eval_batch_parallel<O>(obj: &O, x: ArrayView2<f64>) -> Array1<f64>
where
O: Objective<f64> + ?Sized,
{
let n = x.nrows();
if n < EVAL_BATCH_PARALLEL_MIN {
return obj.eval_batch(x);
}
let mut out = vec![0.0_f64; n];
out.par_iter_mut().enumerate().for_each(|(i, slot)| {
*slot = obj.eval(x.row(i));
});
Array1::from(out)
}