Signal

Struct Signal 

pub struct Signal<T: SignalType> { /* private fields */ }
Expand description

A generic signal container supporting both f32 and f64

§Examples

use ferro_wave::Signal;

// Create a signal from a vector
let signal = Signal::<f64>::new(vec![1.0, 2.0, 3.0, 4.0]);
assert_eq!(signal.len(), 4);

// Create a signal with sample rate
let mut signal = Signal::<f32>::with_sample_rate(vec![0.0; 100], 44100.0);
assert_eq!(signal.sample_rate(), Some(44100.0));

Implementations§

§

impl<T: SignalType> Signal<T>

pub fn new(data: Vec<T>) -> Self

Create a new signal from a vector of data

pub fn with_sample_rate(data: Vec<T>, sample_rate: f64) -> Self

Create a new signal with a specified sample rate

pub fn from_slice(data: &[T]) -> Self

Create a signal from a slice

pub fn zeros(length: usize) -> Self

Create a zero signal of specified length

pub fn ones(length: usize) -> Self

Create a signal filled with ones

pub fn len(&self) -> usize

Get the length of the signal

pub fn is_empty(&self) -> bool

Check if the signal is empty

pub fn data(&self) -> &[T]

Get a reference to the underlying data

pub fn data_mut(&mut self) -> &mut [T]

Get a mutable reference to the underlying data

pub fn to_vec(self) -> Vec<T>

Convert to a vector

pub fn sample_rate(&self) -> Option<f64>

Get the sample rate if available

pub fn set_sample_rate(&mut self, rate: f64)

Set the sample rate

pub fn metadata(&self) -> &SignalMetadata

Get metadata

pub fn metadata_mut(&mut self) -> &mut SignalMetadata

Get mutable metadata

pub fn map<F>(&self, f: F) -> Self
where F: Fn(T) -> T,

Apply a function to each element

pub fn mean(&self) -> T

Compute the mean of the signal

pub fn std(&self) -> T

Compute the sample standard deviation using Welford’s numerically stable algorithm

This calculates the sample standard deviation using Bessel’s correction (n-1 denominator) for unbiased estimation, not the population standard deviation (n denominator).

Formula: σ = sqrt(Σ(xi - μ)² / (n-1))

Where:

  • xi: individual sample values
  • μ: sample mean
  • n: number of samples
§Why Sample Standard Deviation?

We use the sample standard deviation (with n-1) because:

  • It provides an unbiased estimate when working with samples from a larger population
  • It’s the standard choice in signal processing and statistics
  • It prevents underestimation of variance in finite samples
§Returns

Returns 0 if the signal has fewer than 2 samples.

§Example
use ferro_wave::Signal;

let signal = Signal::<f64>::new(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
let std = signal.std();  // Sample standard deviation
assert!((std - 1.5811388300841898).abs() < 1e-10);

pub fn std_population(&self) -> T

Compute the population standard deviation

This calculates the population standard deviation using n as the denominator, suitable when you have the complete population rather than a sample.

Formula: σ = sqrt(Σ(xi - μ)² / n)

§Comparison with std()
  • Use std() (sample) when working with a sample from a larger population
  • Use std_population() when you have the entire population
  • For large n, the difference becomes negligible
§Example
use ferro_wave::Signal;

let signal = Signal::<f64>::new(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
let std_sample = signal.std();             // Uses n-1
let std_pop = signal.std_population();     // Uses n
assert!(std_sample > std_pop);  // Sample std is always larger

pub fn normalize(&self) -> Self

Normalize the signal to have zero mean and unit variance

Uses the sample standard deviation (with Bessel’s correction) for normalization. This is the standard approach in signal processing as it provides unbiased estimation.

The transformation applied is: x’ = (x - μ) / σ

Where:

  • x: original sample value
  • μ: sample mean
  • σ: sample standard deviation (using n-1)
  • x’: normalized value
§Returns

Returns a new signal with mean ≈ 0 and standard deviation ≈ 1. If the standard deviation is zero (constant signal), returns a clone of the original.

§Examples
use ferro_wave::Signal;

let signal = Signal::<f64>::new(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
let normalized = signal.normalize();

assert!((normalized.mean()).abs() < 1e-10);
assert!((normalized.std() - 1.0).abs() < 1e-10);  // Sample std = 1

pub fn energy(&self) -> T

Compute the energy of the signal (sum of squared values)

Energy = Σ(xi²) where xi are the signal samples

pub fn rms(&self) -> T

Compute the RMS (Root Mean Square) value of the signal

RMS = sqrt(Σ(xi²) / n) where xi are the signal samples and n is the length

pub fn peak_to_peak(&self) -> T

Compute the peak-to-peak amplitude

pub fn snr_db(&self, noise: &Signal<T>) -> Option<f64>

Compute the signal-to-noise ratio in dB

Returns None if signals have different lengths or noise has zero power

pub fn resample(&self, new_length: usize) -> Self

Resample the signal to a new length using linear interpolation

§

impl Signal<f64>

pub fn mean_fast(&self) -> f64

Optimized mean calculation for f64 signals

pub fn energy_fast(&self) -> f64

Optimized energy calculation for f64 signals

pub fn rms_fast(&self) -> f64

Optimized RMS calculation for f64 signals

pub fn normalize_inplace(&mut self)

In-place normalization for f64 signals

pub fn add_scalar_inplace(&mut self, scalar: f64)

Add a scalar value to all elements (in-place)

pub fn scale_inplace(&mut self, scalar: f64)

Multiply all elements by a scalar (in-place)

§

impl Signal<f32>

pub fn mean_fast(&self) -> f32

Optimized mean calculation for f32 signals

pub fn energy_fast(&self) -> f32

Optimized energy calculation for f32 signals

pub fn rms_fast(&self) -> f32

Optimized RMS calculation for f32 signals

Trait Implementations§

§

impl<T: Clone + SignalType> Clone for Signal<T>

§

fn clone(&self) -> Signal<T>

Returns a duplicate of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T: Debug + SignalType> Debug for Signal<T>

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
§

impl<T: SignalType> From<&[T]> for Signal<T>

§

fn from(data: &[T]) -> Self

Converts to this type from the input type.
§

impl<T: SignalType> From<Vec<T>> for Signal<T>

§

fn from(data: Vec<T>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<T> Freeze for Signal<T>

§

impl<T> RefUnwindSafe for Signal<T>
where T: RefUnwindSafe,

§

impl<T> Send for Signal<T>

§

impl<T> Sync for Signal<T>

§

impl<T> Unpin for Signal<T>
where T: Unpin,

§

impl<T> UnwindSafe for Signal<T>
where T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CloneToUninit for T
where T: Clone,

§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> IntoEither for T

§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,