From 98ac1e33d67f893d286355df0eb4a6ca90dc010b Mon Sep 17 00:00:00 2001 From: Mohit0928 Date: Thu, 21 Oct 2021 18:00:55 +0530 Subject: [PATCH] edited label block; ran cargo fmt on all blocks --- audio_float_conversion/src/lib.rs | 6 +- fft/src/lib.rs | 8 ++- image-normalization/src/lib.rs | 2 +- label/Cargo.toml | 5 +- label/src/into_index_macro.rs | 85 ++++++++++++++++++++++++++ label/src/lib.rs | 69 +++++++++++---------- modulo/src/lib.rs | 10 ++- most_confident_indices/src/lib.rs | 10 ++- noise-filtering/src/lib.rs | 4 +- noise-filtering/src/noise_reduction.rs | 4 +- normalize/src/lib.rs | 4 +- 11 files changed, 155 insertions(+), 52 deletions(-) create mode 100644 label/src/into_index_macro.rs diff --git a/audio_float_conversion/src/lib.rs b/audio_float_conversion/src/lib.rs index 99fc5189e22..720ecfaaa62 100644 --- a/audio_float_conversion/src/lib.rs +++ b/audio_float_conversion/src/lib.rs @@ -6,7 +6,7 @@ extern crate alloc; #[macro_use] extern crate std; -use hotg_rune_proc_blocks::{ProcBlock, Transform, Tensor}; +use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; // TODO: Add Generics @@ -36,7 +36,9 @@ impl AudioFloatConversion { } impl Default for AudioFloatConversion { - fn default() -> Self { AudioFloatConversion::new() } + fn default() -> Self { + AudioFloatConversion::new() + } } impl Transform> for AudioFloatConversion { diff --git a/fft/src/lib.rs b/fft/src/lib.rs index 0d7d2dfa345..487a9dd38ca 100644 --- a/fft/src/lib.rs +++ b/fft/src/lib.rs @@ -14,9 +14,9 @@ extern crate pretty_assertions; pub type Fft = ShortTimeFourierTransform; use alloc::{sync::Arc, vec::Vec}; -use hotg_rune_proc_blocks::{ProcBlock, Transform, Tensor}; -use sonogram::SpecOptionsBuilder; +use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; use nalgebra::DMatrix; +use sonogram::SpecOptionsBuilder; #[derive(Debug, Clone, PartialEq, ProcBlock)] pub struct ShortTimeFourierTransform { @@ -107,7 +107,9 @@ impl ShortTimeFourierTransform { } impl Default for ShortTimeFourierTransform { - fn default() -> Self { ShortTimeFourierTransform::new() } + fn default() -> Self { + ShortTimeFourierTransform::new() + } } impl Transform> for ShortTimeFourierTransform { diff --git a/image-normalization/src/lib.rs b/image-normalization/src/lib.rs index 5a7c1268004..5d246159c1d 100644 --- a/image-normalization/src/lib.rs +++ b/image-normalization/src/lib.rs @@ -4,8 +4,8 @@ #[macro_use] extern crate alloc; +use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; use num_traits::{Bounded, ToPrimitive}; -use hotg_rune_proc_blocks::{ProcBlock, Transform, Tensor}; /// A normalization routine which takes some tensor of integers and fits their /// values to the range `[0, 1]` as `f32`'s. diff --git a/label/Cargo.toml b/label/Cargo.toml index 1660fd1adea..5d657bc8f77 100644 --- a/label/Cargo.toml +++ b/label/Cargo.toml @@ -1,10 +1,11 @@ [package] name = "label" -version = "0.0.0" +version = "0.8.0" edition = "2018" publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -hotg-rune-proc-blocks = "^0.9.0" +libm = {version = "0.2.1", default-features = false} +hotg-rune-proc-blocks = "^0.9.2" diff --git a/label/src/into_index_macro.rs b/label/src/into_index_macro.rs new file mode 100644 index 00000000000..65229c69248 --- /dev/null +++ b/label/src/into_index_macro.rs @@ -0,0 +1,85 @@ +use core::convert::TryInto; +use libm::floorf; + +pub trait IntoIndex: Sized { + fn try_into_index(self) -> usize; +} + +macro_rules! float_into_index { + ($($float:ty),*$(,)?) => {$( + impl IntoIndex for $float { + fn try_into_index(self) -> usize { + // Integers are exactly representable at or below this value + const MAX_VALUE: $float = (1u64 << <$float>::MANTISSA_DIGITS) as $float; + + assert!(!self.is_nan(),"The index can't be NAN"); + assert!(!self.is_infinite(), "The index can't be infinite"); + assert!(self >= 0.0, "The index must be a positive number"); + assert!(self <= MAX_VALUE, "The index is larger than the largest number that can safely represent an integer"); + assert_eq!(self - floorf(self), 0.0, "The index wasn't an integer"); + + (self as u32).try_into().expect("UNSUPPORTED: Can't be converted to usize. It only supports u8, u16, u32, u64, i32, i64 ( with positive numbers) f32 (with their fractional part zero E.g. 2.0, 4.0, etc)") + } + } + )*} +} + +float_into_index!(f32); + +macro_rules! integer_into_index { + ($($int:ty),*$(,)?) => {$( + impl IntoIndex for $int { + fn try_into_index(self) -> usize { + self.try_into().ok().expect("UNSUPPORTED: Can't be converted to usize. It only supports u8, u16, u32, u64, i32, i64 ( with positive numbers) f32 (with their fractional part zero E.g. 2.0, 4.0, etc)") + } + } + )*} +} + +integer_into_index!( + i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, isize, usize +); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_f32_floats() { + assert_eq!(1, 1.0f32.try_into_index()) + } + + #[test] + fn test_u32_inetger() { + assert_eq!(1, 1u32.try_into_index()) + } + + #[test] + #[should_panic = "UNSUPPORTED: Can't be converted to usize. It only supports u8, u16, u32, u64, i32, i64 ( with positive numbers) f32 (with their fractional part zero E.g. 2.0, 4.0, etc)"] + fn test_negative_integer() { + (-1).try_into_index(); + } + + #[test] + #[should_panic = "The index can't be infinite"] + fn test_infinite() { + (1.0 / 0.0).try_into_index(); + } + + #[test] + #[should_panic = "The index must be a positive number"] + fn test_negative_float() { + (-3.0).try_into_index(); + } + #[test] + #[should_panic = "The index wasn't an intege"] + fn test_float_with_fraction() { + (4.3).try_into_index(); + } + + #[test] + #[should_panic = "The index is larger than the largest number that can safely represent an integer"] + fn test_float_out_of_bound() { + (16_777_216_456_673_784.0).try_into_index(); + } +} diff --git a/label/src/lib.rs b/label/src/lib.rs index 7984dd85fd8..9d635c8da6b 100644 --- a/label/src/lib.rs +++ b/label/src/lib.rs @@ -1,10 +1,12 @@ #![no_std] -extern crate alloc; +pub mod into_index_macro; +pub use into_index_macro::IntoIndex; -use core::{convert::TryInto, fmt::Debug}; +extern crate alloc; use alloc::{borrow::Cow, vec::Vec}; +use core::fmt::Debug; use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; /// A proc block which, when given a set of indices, will return their @@ -22,37 +24,37 @@ use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; /// let got = proc_block.transform(input); /// /// assert_eq!(got.elements(), &["three", "one", "two"]); -/// ``` + #[derive(Debug, Default, Clone, PartialEq, ProcBlock)] pub struct Label { labels: Vec<&'static str>, } +impl Label { + fn get_by_index(&mut self, ix: usize) -> Cow<'static, str> { + // Note: We use a more cumbersome match statement instead of unwrap() + // to provide the user with more useful error messages + match self.labels.get(ix) { + Some(&label) => label.into(), + None => panic!("Index out of bounds: there are {} labels but label {} was requested", self.labels.len(), ix) + } + } +} + impl Transform> for Label where - T: Copy + TryInto, - >::Error: Debug, + T: Copy + IntoIndex, { type Output = Tensor>; fn transform(&mut self, input: Tensor) -> Self::Output { - let view = input - .view::<1>() - .expect("This proc block only supports 1D inputs"); - - let indices = view.elements().iter().copied().map(|ix| { - ix.try_into() - .expect("Unable to convert the index to a usize") - }); + let indices = input + .elements() + .iter() + .copied() + .map(IntoIndex::try_into_index); - // Note: We use a more cumbersome match statement instead of unwrap() - // to provide the user with more useful error messages - indices - .map(|ix| match self.labels.get(ix) { - Some(&label) => Cow::Borrowed(label), - None => panic!("Index out of bounds: there are {} labels but label {} was requested", self.labels.len(), ix) - }) - .collect() + indices.map(|ix| self.get_by_index(ix)).collect() } } @@ -61,12 +63,17 @@ mod tests { use super::*; #[test] - #[should_panic] - fn only_works_with_1d_inputs() { + fn get_the_correct_labels() { let mut proc_block = Label::default(); - let input: Tensor = Tensor::zeroed(alloc::vec![1, 2, 3]); + proc_block.set_labels(["zero", "one", "two", "three"]); + let input = Tensor::new_vector(alloc::vec![2, 0, 1]); + let should_be = Tensor::new_vector( + ["two", "zero", "one"].iter().copied().map(Cow::Borrowed), + ); - let _ = proc_block.transform(input); + let got = proc_block.transform(input); + + assert_eq!(got, should_be); } #[test] @@ -80,16 +87,12 @@ mod tests { } #[test] - fn get_the_correct_labels() { + #[should_panic = "UNSUPPORTED: Can't be converted to usize. It only supports u8, u16, u32, u64, i32, i64 ( with positive numbers) f32 (with their fractional part zero E.g. 2.0, 4.0, etc)"] + fn get_the_correct_labels_panic() { let mut proc_block = Label::default(); proc_block.set_labels(["zero", "one", "two", "three"]); - let input = Tensor::new_vector(alloc::vec![3, 1, 2]); - let should_be = Tensor::new_vector( - ["three", "one", "two"].iter().copied().map(Cow::Borrowed), - ); + let input = Tensor::new_vector(alloc::vec![-3, -1, -2]); - let got = proc_block.transform(input); - - assert_eq!(got, should_be); + let _got = proc_block.transform(input); } } diff --git a/modulo/src/lib.rs b/modulo/src/lib.rs index 9871e517306..fd3b6cd9bbe 100644 --- a/modulo/src/lib.rs +++ b/modulo/src/lib.rs @@ -1,7 +1,7 @@ #![no_std] +use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; use num_traits::{FromPrimitive, ToPrimitive}; -use hotg_rune_proc_blocks::{Tensor, Transform, ProcBlock}; pub fn modulo(modulus: f32, values: &mut [T]) where @@ -19,11 +19,15 @@ pub struct Modulo { } impl Modulo { - pub fn new() -> Self { Modulo { modulus: 1.0 } } + pub fn new() -> Self { + Modulo { modulus: 1.0 } + } } impl Default for Modulo { - fn default() -> Self { Modulo::new() } + fn default() -> Self { + Modulo::new() + } } impl<'a, T> Transform> for Modulo diff --git a/most_confident_indices/src/lib.rs b/most_confident_indices/src/lib.rs index 701bd5c9d02..2ca8816aa7c 100644 --- a/most_confident_indices/src/lib.rs +++ b/most_confident_indices/src/lib.rs @@ -5,7 +5,7 @@ extern crate alloc; use core::{convert::TryInto, fmt::Debug}; use alloc::vec::Vec; -use hotg_rune_proc_blocks::{ProcBlock, Transform, Tensor}; +use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; /// A proc block which, when given a list of confidences, will return the /// indices of the top N most confident values. @@ -18,7 +18,9 @@ pub struct MostConfidentIndices { } impl MostConfidentIndices { - pub fn new(count: usize) -> Self { MostConfidentIndices { count } } + pub fn new(count: usize) -> Self { + MostConfidentIndices { count } + } fn check_input_dimensions(&self, dimensions: &[usize]) { match simplify_dimensions(dimensions) { @@ -37,7 +39,9 @@ impl MostConfidentIndices { } impl Default for MostConfidentIndices { - fn default() -> Self { MostConfidentIndices::new(1) } + fn default() -> Self { + MostConfidentIndices::new(1) + } } impl Transform> for MostConfidentIndices { diff --git a/noise-filtering/src/lib.rs b/noise-filtering/src/lib.rs index 9e80bfa7f6c..060ce295a39 100644 --- a/noise-filtering/src/lib.rs +++ b/noise-filtering/src/lib.rs @@ -8,10 +8,10 @@ mod macros; mod gain_control; mod noise_reduction; -pub use noise_reduction::NoiseReduction; pub use gain_control::GainControl; +pub use noise_reduction::NoiseReduction; -use hotg_rune_proc_blocks::{ProcBlock, Transform, Tensor}; +use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; #[derive(Debug, Default, Clone, PartialEq, ProcBlock)] pub struct NoiseFiltering { diff --git a/noise-filtering/src/noise_reduction.rs b/noise-filtering/src/noise_reduction.rs index a032e94cbeb..9dec34c6031 100644 --- a/noise-filtering/src/noise_reduction.rs +++ b/noise-filtering/src/noise_reduction.rs @@ -56,7 +56,9 @@ impl NoiseReduction { min_signal_remaining: f32, ); - pub fn noise_estimate(&self) -> &[u32] { &self.estimate } + pub fn noise_estimate(&self) -> &[u32] { + &self.estimate + } pub fn transform(&mut self, mut input: Tensor) -> Tensor { // make sure we have the right estimate buffer size and panic if we diff --git a/normalize/src/lib.rs b/normalize/src/lib.rs index e775d15e92f..fea156a475d 100644 --- a/normalize/src/lib.rs +++ b/normalize/src/lib.rs @@ -7,7 +7,7 @@ use core::{ fmt::Debug, ops::{Div, Sub}, }; -use hotg_rune_proc_blocks::{Transform, Tensor}; +use hotg_rune_proc_blocks::{Tensor, Transform}; pub fn normalize(input: &mut [T]) where @@ -70,7 +70,7 @@ where let min = if item < min { item } else { min }; let max = if max < item { item } else { max }; Some((min, max)) - }, + } None => Some((item, item)), }) }