Skip to content

Commit

Permalink
edited label block; ran cargo fmt on all blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohit0928 committed Oct 21, 2021
1 parent e683d5a commit 98ac1e3
Show file tree
Hide file tree
Showing 11 changed files with 155 additions and 52 deletions.
6 changes: 4 additions & 2 deletions audio_float_conversion/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -36,7 +36,9 @@ impl AudioFloatConversion {
}

impl Default for AudioFloatConversion {
fn default() -> Self { AudioFloatConversion::new() }
fn default() -> Self {
AudioFloatConversion::new()
}
}

impl Transform<Tensor<i16>> for AudioFloatConversion {
Expand Down
8 changes: 5 additions & 3 deletions fft/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -107,7 +107,9 @@ impl ShortTimeFourierTransform {
}

impl Default for ShortTimeFourierTransform {
fn default() -> Self { ShortTimeFourierTransform::new() }
fn default() -> Self {
ShortTimeFourierTransform::new()
}
}

impl Transform<Tensor<i16>> for ShortTimeFourierTransform {
Expand Down
2 changes: 1 addition & 1 deletion image-normalization/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions label/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
85 changes: 85 additions & 0 deletions label/src/into_index_macro.rs
Original file line number Diff line number Diff line change
@@ -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();
}
}
69 changes: 36 additions & 33 deletions label/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<T> Transform<Tensor<T>> for Label
where
T: Copy + TryInto<usize>,
<T as TryInto<usize>>::Error: Debug,
T: Copy + IntoIndex,
{
type Output = Tensor<Cow<'static, str>>;

fn transform(&mut self, input: Tensor<T>) -> 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()
}
}

Expand All @@ -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<i32> = 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]
Expand All @@ -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);
}
}
10 changes: 7 additions & 3 deletions modulo/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<T>(modulus: f32, values: &mut [T])
where
Expand All @@ -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<Tensor<T>> for Modulo
Expand Down
10 changes: 7 additions & 3 deletions most_confident_indices/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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) {
Expand All @@ -37,7 +39,9 @@ impl MostConfidentIndices {
}

impl Default for MostConfidentIndices {
fn default() -> Self { MostConfidentIndices::new(1) }
fn default() -> Self {
MostConfidentIndices::new(1)
}
}

impl<T: PartialOrd + Copy> Transform<Tensor<T>> for MostConfidentIndices {
Expand Down
4 changes: 2 additions & 2 deletions noise-filtering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion noise-filtering/src/noise_reduction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>) -> Tensor<u32> {
// make sure we have the right estimate buffer size and panic if we
Expand Down
4 changes: 2 additions & 2 deletions normalize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(input: &mut [T])
where
Expand Down Expand Up @@ -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)),
})
}
Expand Down

0 comments on commit 98ac1e3

Please sign in to comment.