From a037fc48d68539d86874640ca6cc61064b348451 Mon Sep 17 00:00:00 2001 From: Dan Munckton Date: Mon, 6 May 2019 08:42:17 +0100 Subject: [PATCH] deviation: Implement peak_signal_to_noise_ratio --- src/deviation.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/deviation.rs b/src/deviation.rs index 34e963a3..3ecdf5d7 100644 --- a/src/deviation.rs +++ b/src/deviation.rs @@ -52,6 +52,10 @@ where fn root_mean_sq_dev(&self, other: &ArrayBase) -> A where A: AddAssign + Clone + FromPrimitive + Signed + Float; + + fn peak_signal_to_noise_ratio(&self, other: &ArrayBase, maxv: A) -> A + where + A: AddAssign + Clone + FromPrimitive + Signed + Float; } impl DeviationExt for ArrayBase @@ -176,6 +180,14 @@ where { self.mean_sq_dev(other).sqrt() } + + fn peak_signal_to_noise_ratio(&self, other: &ArrayBase, maxv: A) -> A + where + A: AddAssign + Clone + FromPrimitive + Signed + Float, + { + let ten = A::from(10.).unwrap(); + ten * Float::log10((maxv * maxv) / self.mean_sq_dev(&other)) + } } #[cfg(test)] @@ -327,4 +339,19 @@ mod tests { assert_abs_diff_eq!(a.root_mean_sq_dev(&b), 10.0.sqrt(), epsilon = f64::EPSILON); assert_abs_diff_eq!(b.root_mean_sq_dev(&a), 10.0.sqrt(), epsilon = f64::EPSILON); } + + #[test] + fn test_peak_signal_to_noise_ratio() { + let a = array![1., 1.]; + assert!(a.peak_signal_to_noise_ratio(&a, 1.).is_infinite()); + + let a = array![1., 2., 3., 4., 5., 6., 7.]; + let b = array![1., 3., 3., 4., 6., 7., 8.]; + let maxv = 2.; + + let expected = maxv * 10. * Float::log10(maxv) - 10. * Float::log10(a.mean_sq_dev(&b)); + let actual = a.peak_signal_to_noise_ratio(&b, maxv); + + assert_abs_diff_eq!(actual, expected, epsilon = f64::EPSILON * 8.); + } }