fetish_lib/
array_utils.rs

1extern crate ndarray;
2extern crate ndarray_linalg;
3
4use ndarray::*;
5use noisy_float::prelude::*;
6
7///Copies a `noisy_float` vector to a `f32` one.
8pub fn from_noisy(vec : ArrayView1<R32>) -> Array1<f32> {
9    let n = vec.len();
10    let mut mean : Array1::<f32> = Array::zeros((n,));
11    for i in 0..n {
12        mean[[i,]] = vec[[i,]].raw();
13    }
14    mean
15}
16
17///Copies a `f32` vector to a `noisy_float` one.
18pub fn to_noisy(vec : ArrayView1<f32>) -> Array1<R32> {
19    let n = vec.len();
20    let mut result : Array1::<R32> = Array::zeros((n,));
21    for i in 0..n {
22        result[[i,]] = r32(vec[[i,]]);
23    }
24    result
25}
26
27///Returns `true` only if all elements of `vec` are finite floats.
28pub fn all_finite(vec : ArrayView1<f32>) -> bool {
29    let n = vec.shape()[0];
30    for i in 0..n {
31        if (!vec[[i,]].is_finite()) {
32            return false;
33        }
34    }
35    true
36}
37
38///Vectorizes (flattens) the given matrix `mat`.
39pub fn flatten_matrix(mat : ArrayView2<f32>) -> ArrayView1<f32> {
40    let full_dim = mat.shape()[0] * mat.shape()[1];
41    let reshaped = mat.clone().into_shape((full_dim,)).unwrap();
42    reshaped
43}
44
45///Given a vector of floats, yields the index and the value of the largest
46///float in `vec`.
47pub fn max_index_and_value(vec : ArrayView1<f32>) -> (usize, f32) {
48    let mut max_index = 0; 
49    let mut max_value = vec[[0,]];
50    for i in 1..vec.shape()[0] {
51        if (vec[[i,]] > max_value) {
52            max_value = vec[[i,]];
53            max_index = i;
54        }
55    }
56    (max_index, max_value)
57}