From cc4a44718aecf0021994b13bb407eee964181263 Mon Sep 17 00:00:00 2001 From: Alexander_Kabui Date: Thu, 13 Nov 2025 15:19:58 +0300 Subject: feat: Add unittests for checking if negative correlations are handled correctly. --- src/correlations.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/correlations.rs b/src/correlations.rs index 29b9064..c3b4202 100644 --- a/src/correlations.rs +++ b/src/correlations.rs @@ -149,11 +149,11 @@ impl<'a> Compute<'a> { .split(self.file_delimiter) .collect::>(), ); - if ty.x_vals.len() < 4 || ty.y_vals.len() < 4 { - // minimum number of acceptable trait values for - // computing the correlations - continue; - } + if ty.x_vals.len() < 4 || ty.y_vals.len() < 4 { + // minimum number of acceptable trait values for + // computing the correlations + continue; + } let (key_name, parsed_x_val, parsed_y_val) = (ty.row_name, ty.x_vals, ty.y_vals); @@ -215,6 +215,51 @@ mod tests { assert_approx_eq!(p_val, 1.341575855, 2f64); } + #[test] + fn test_pearson_negative_rho() { + let new_pearson = Pearson::new(3); + let (corr_coeff, p_val) = + new_pearson.correlate(&[1., 2., 3., 4., 5.], &[5., 4., 3., 2., 1.]); + + assert_eq!(format!("{:.2}", corr_coeff), "-1.00"); + } + + #[test] + fn test_pearson_negative_rho_signs() { + // let new_pearson = Pearson::new(3); + + // Each pair should produce a negative correlation + let test_cases = vec![ + (vec![1., 2., 3., 4., 5.], vec![5., 4., 3., 2., 1.]), // perfect -1.0 + (vec![1., 2., 3., 4., 5.], vec![5., 4.5, 3.5, 3.0, 2.5]), // roughly -0.9 + (vec![1., 2., 3., 4., 5.], vec![4.5, 4.0, 3.8, 3.5, 3.0]), // small negative ~ -0.3 + ]; + + for (x, y) in test_cases { + let new_pearson = Pearson::new(3); + let new_spearman = Spearman::new(3); + let (corr_coeff, _p_val) = new_pearson.correlate(&x, &y); // pearson correlation + let (s_rho, p_val) = new_spearman.correlate(&x, &y); + let formatted = format!("{:.2}", corr_coeff); + let s_formatted = format!("{:.2}", s_rho); + + // Assert the sign is actually negative in the formatted string + assert!( + formatted.starts_with('-'), + "Expected negative correlation, got formatted value `{}` (raw {})", + formatted, + corr_coeff + ); + + assert!( + formatted.starts_with('-'), + "Expected negative correlation, got formatted value `{}` (raw {})", + s_formatted, + s_rho + ); + } + } + #[test] fn test_spearman_obj() { let new_spearman = Spearman::new(5); @@ -302,9 +347,20 @@ mod tests { assert!(corr_results.is_ok()) } - #[test] + fn test_negative_compute() { + let compute_obj = Compute::new( + ',', + "pearson", + "tests/data/mock_negative_dataset.txt", + &[12.0, 15.0, 11.0, 16.0, 11.0, 8.0, 7.0], + "./output_negative.txt", + ); + let corr_results = compute_obj.compute(); + assert!(corr_results.is_ok()) + } + #[test] fn test_parse_f64() { let data = "9. ,5. ,0. ,7. ,6. ,1. ,5. ,0.\n"; -- cgit 1.4.1