From 1bb2f52839b75b9c2ee9aa08a11d7d3823dbe647 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 26 Apr 2022 14:56:53 +0300 Subject: modularize code and tests --- src/correlations.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) (limited to 'src/correlations.rs') diff --git a/src/correlations.rs b/src/correlations.rs index f84bb65..596240e 100644 --- a/src/correlations.rs +++ b/src/correlations.rs @@ -5,7 +5,8 @@ use rgsl::{ pub trait Correlation { - fn correlate(&self,x:&[f64],y:&[f64]) ->(f64,f64); + fn correlate(&self,x:&[f64],y:&[f64]) ->(f64,f64); + } #[derive(PartialEq, Debug)] @@ -29,6 +30,16 @@ impl Pearson { } } } + +impl Spearman { + pub fn new(n:usize) -> Self { + + Self { + n, + degrees_of_freedom:(n - 2) as f64, + } + } +} impl Correlation for Pearson { fn correlate(&self,x:&[f64],y:&[f64]) ->(f64,f64){ @@ -72,3 +83,47 @@ impl Correlation for Spearman { return (rho,p_val); } } + + +#[cfg(test)] + +mod test{ + use assert_approx_eq::assert_approx_eq; + use super::*; + + + + #[test] + fn test_pearson_obj(){ + let new_pearson = Pearson::new(5); + assert_eq!(new_pearson,Pearson{n:5, degrees_of_freedom:3.0}); + } + #[test] + fn test_pearson_correlation(){ + let new_pearson = Pearson::new(3); + let (corr_coeff,p_val) = new_pearson.correlate(&[1.,2.,3.,4.,5.] ,&[1.,2.,3.,4.,5.]); + + assert_eq!(format!("{:.2}", corr_coeff),"1.00"); + assert_approx_eq!(p_val,1.341575855,2f64); + } + + #[test] + fn test_spearman_obj(){ + let new_spearman = Spearman::new(5); + + assert_eq!(new_spearman,Spearman{n:5, degrees_of_freedom:3.0}); + + } + #[test] + fn test_spearman_correlation(){ + let new_spearman = Spearman::new(5); + + let (s_rho,p_val) = new_spearman.correlate(&[1.,2.,3.,4.,5.], &[5.,6.,7.,8.,7.]); + + + assert_approx_eq!(s_rho,0.079603960396039,2f64); + assert_approx_eq!(p_val,0.43111687,2f64) + + } + +} \ No newline at end of file -- cgit 1.4.1