qust_io/output/
array.rs

1use qust::prelude::Itertools;
2use ndarray::{Array, Array1, Array2, Axis};
3use num_traits::{Num, Float, FromPrimitive};
4use ndarray_stats::CorrelationExt;
5
6pub trait ToArray<R> {
7    fn to_array(&self) -> R;
8}
9
10
11impl<T: Num + Clone> ToArray<Array1<T>> for [T] {
12    fn to_array(&self) -> Array1<T> {
13        Array::from_vec(self.to_vec())
14    }
15}
16
17impl<T, R> ToArray<Array2<R>> for [T]
18where
19    T: AsRef<[R]>,
20    R: Num + Default + Copy,
21{
22    fn to_array(&self) -> Array2<R> {
23        let mut res = Array2::<R>::default((self.len(), self[0].as_ref().len()));
24        for (i, mut row) in res.axis_iter_mut(Axis(0)).enumerate() {
25            let b = self[i].as_ref();
26            for (j, col) in row.iter_mut().enumerate() {
27                *col = b[j];
28            }
29        }
30        res
31    }
32}
33
34pub trait Corr<T> {
35    type OutputEle;
36    fn e(&self) -> Vec<Self::OutputEle>;
37    fn corr(&self) -> Array2<Self::OutputEle>;
38    fn cov(&self) -> Array2<Self::OutputEle>;
39    fn delta(&self) -> Vec<Vec<Self::OutputEle>>;
40}
41
42impl<T: FromPrimitive + Num + Default + Copy + Float + From<i8> + 'static> Corr<u16> for [&Vec<T>]
43{
44    type OutputEle = T;
45    fn e(&self) -> Vec<Self::OutputEle> {
46        self.as_ref()
47            .iter()
48            .map(|x| x.to_array().mean().unwrap())
49            .collect_vec()
50    }
51
52    fn corr(&self) -> Array2<Self::OutputEle> {
53        self.as_ref()
54            .to_array()
55            .pearson_correlation()
56            .unwrap()
57    }
58
59    fn cov(&self) -> Array2<Self::OutputEle> {
60        self.as_ref()
61            .to_array()
62            .cov(<T as From<i8>>::from(1i8))
63            .unwrap()
64    }
65
66    fn delta(&self) -> Vec<Vec<Self::OutputEle>> {
67        let k = self.cov();
68        k.dot(&k)
69            .axis_iter(Axis(0))
70            .map(|x| x.to_vec())
71            .collect_vec()
72    }
73}