use ndarray::{Array1, ArrayView1};
use num_traits::Float;
use rand::Rng;
use rand_distr::uniform::SampleUniform;
use rand_distr::{Distribution, Uniform};
#[derive(Clone, Debug)]
pub struct Bounds<T: Float> {
pub low: Array1<T>,
pub high: Array1<T>,
pub slack: T,
pub dims: usize,
}
impl<T> Bounds<T>
where
T: Float + SampleUniform + 'static,
Uniform<T>: Distribution<T>,
{
pub fn new(low: Array1<T>, high: Array1<T>, slack: T) -> Self {
let dims = low.len();
assert_eq!(low.len(), high.len(), "low and high have different shapes");
Self {
low,
high,
slack,
dims,
}
}
pub fn contains(&self, x: ArrayView1<T>) -> bool {
x.iter()
.enumerate()
.all(|(i, &xi)| xi >= self.low[i] - self.slack && xi <= self.high[i] + self.slack)
}
pub fn mkpoint<R: Rng>(&self, rng: &mut R) -> Array1<T> {
Array1::from_iter((0..self.dims).map(|i| {
Uniform::new(self.low[i], self.high[i])
.expect("low < high required for Uniform sampling")
.sample(rng)
}))
}
pub fn clip(&self, x: ArrayView1<T>) -> Array1<T> {
Array1::from_iter(
x.iter()
.enumerate()
.map(|(i, &xi)| xi.max(self.low[i]).min(self.high[i])),
)
}
}