1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// pub mod tests;
pub mod i64impls;
pub mod f64impls;
pub mod vimpls;
pub mod tests;

use std::cmp::Ordering::Equal;
use anyhow::Result;
/// Median and quartiles
#[derive(Default)]
pub struct Med {
    pub lquartile: f64,
    pub median: f64,
    pub uquartile: f64
}
impl std::fmt::Display for Med {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "(LQ: {}, M: {}, UQ: {})", self.lquartile, self.median, self.uquartile)
    }
}
/// Mean and standard deviation (or std ratio for geometric mean)
#[derive(Default)]
pub struct MStats {
    pub mean: f64,
    pub std: f64
}
impl std::fmt::Display for MStats {
   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
      write!(f, "Mean:\t{}\nStd:\t{}", self.mean, self.std)
   }
}
/// Set of n dimensional points (vectors) as one flat `&[f64]` (buff field);  
/// n is therefore the length of each vector and is stored as dims field.
/// The number of points held by instance s is `s.buff.len()/s.dims`
#[derive(Default)]
pub struct  NDPoints<'a> {
   pub dims: usize,
   pub buff: &'a [f64]
}
impl std::fmt::Display for NDPoints<'_> {
   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
      write!(f, "Points: {} Dimensions: {}", self.buff.len()/self.dims, self.dims)
   }
}

pub trait GMedian {

   fn medoid(&self) -> usize;

}

pub trait RStats { 

   fn amean(&self) -> Result<f64>;
   fn ameanstd(&self) -> Result<MStats>;
   fn awmean(&self) -> Result<f64>;
   fn awmeanstd(&self) -> Result<MStats>;
   fn hmean(&self) -> Result<f64>;
   fn hwmean(&self) -> Result<f64>;
   fn gmean(&self) -> Result<f64>;
   fn gwmean(&self) -> Result<f64>;
   fn gmeanstd(&self) -> Result<MStats>;
   fn gwmeanstd(&self) -> Result<MStats>;
   fn median(&self) -> Result<Med>;
   fn icorrelation(&self, other:&[i64]) -> Result<f64>;
   fn correlation(&self, other:&[f64]) -> Result<f64>;
   fn autocorr(&self) -> Result<f64>;
  
}

pub trait Vectors {

   fn dotp(&self, other:&[f64]) -> f64;
   fn vsub(&self, other:&[f64]) -> Vec<f64>;
   fn vmag(&self) -> f64;
   fn vdist(&self, other:&[f64]) -> f64;
   fn smult(&self, s:f64) -> Vec<f64>;

}

/// Private helper function for formatting error messages
fn emsg(file:&'static str, line:u32, msg:&'static str)-> String {
   format!("{}:{} rstats {}",file,line,msg)
}

/// Private sum of linear weights 
fn wsum(n: usize) -> f64 { (n*(n+1)) as f64/2. }

/// Sorts a mutable Vec<f64> in place.  
/// It is the responsibility of the user to ensure that there are no NaNs etc.
pub fn sortf(v: &mut [f64]) { 
   v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Equal))
}