extern crate rand;
extern crate ndarray;
use std::iter::FromIterator;
use rand::Rng;
use rand::distributions::Sample;
use rand::distributions::IndependentSample;
use ndarray::{
ArrayBase,
Dimension,
DataOwned,
};
pub trait RandomExt<S, D>
where S: DataOwned,
D: Dimension,
{
fn random<IdS>(dim: D, distribution: IdS) -> ArrayBase<S, D>
where IdS: IndependentSample<S::Elem>;
fn random_using<IdS, R>(dim: D, distribution: IdS, rng: &mut R) -> ArrayBase<S, D>
where IdS: IndependentSample<S::Elem>,
R: Rng;
}
impl<S, D> RandomExt<S, D> for ArrayBase<S, D>
where S: DataOwned,
D: Dimension,
{
fn random<IdS>(dim: D, dist: IdS) -> ArrayBase<S, D>
where IdS: IndependentSample<S::Elem>
{
Self::random_using(dim, dist, &mut rand::weak_rng())
}
fn random_using<IdS, R>(dim: D, dist: IdS, rng: &mut R) -> ArrayBase<S, D>
where IdS: IndependentSample<S::Elem>,
R: Rng
{
let elements = Vec::from_iter((0..dim.size()).map(move |_| dist.ind_sample(rng)));
Self::from_shape_vec(dim, elements).unwrap()
}
}
#[derive(Copy, Clone, Debug)]
pub struct F32<S>(pub S);
impl<S> Sample<f32> for F32<S>
where S: Sample<f64>
{
fn sample<R>(&mut self, rng: &mut R) -> f32 where R: Rng {
self.0.sample(rng) as f32
}
}
impl<S> IndependentSample<f32> for F32<S>
where S: IndependentSample<f64>
{
fn ind_sample<R>(&self, rng: &mut R) -> f32 where R: Rng {
self.0.ind_sample(rng) as f32
}
}