1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use core::fmt::Display;
use core::str::FromStr;
use std::{
num::NonZeroUsize,
sync::{Arc, OnceLock},
};
use non_empty_slice::NonEmptyVec;
use crate::{SpectrogramError, make_window};
/// Window functions for spectral analysis and filtering.
///
/// Different window types provide different trade-offs between frequency resolution
/// and spectral leakage in FFT-based analysis.
#[derive(Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive] // Allow adding new window types in future versions
pub enum WindowType {
/// Rectangular window (no windowing) - best frequency resolution but high leakage.
Rectangular,
/// Hanning window - good general-purpose window with moderate leakage.
#[default]
Hanning,
/// Hamming window - similar to Hanning but slightly different coefficients.
Hamming,
/// Blackman window - low leakage but wider main lobe.
Blackman,
/// Kaiser window - parameterizable trade-off between resolution and leakage.
Kaiser {
/// Beta parameter controlling the trade-off between main lobe width and side lobe level
beta: f64,
},
/// Gaussian window - smooth roll-off with parameterizable width.
Gaussian {
/// Standard deviation parameter controlling the window width
std: f64,
},
/// Custom pre-computed window coefficients.
///
/// The length must match the FFT size used in `make_window`.
/// Use `WindowType::custom()` to create a custom window from a vector of coefficients.
Custom {
/// Pre-computed window coefficients
#[cfg_attr(feature = "serde", serde(with = "arc_vec_serde"))]
coefficients: Arc<Vec<f64>>,
/// Size of the window (must match n_fft)
size: NonZeroUsize,
},
}
#[cfg(feature = "serde")]
mod arc_vec_serde {
use super::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S>(arc: &Arc<Vec<f64>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
arc.as_ref().serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Arc<Vec<f64>>, D::Error>
where
D: Deserializer<'de>,
{
Vec::<f64>::deserialize(deserializer).map(Arc::new)
}
}
impl WindowType {
/// Create a custom window from pre-computed coefficients.
///
/// # Arguments
///
/// * `coefficients` - Pre-computed window coefficients. The length must match
/// the FFT size that will be used with this window.
///
/// # Errors
///
/// Returns error if:
/// - Coefficients are empty
/// - Any coefficient is non-finite (NaN or infinity)
///
/// # Examples
///
/// ```
/// use spectrograms::WindowType;
///
/// // Create a simple triangular window
/// let coeffs = vec![0.0, 0.5, 1.0, 0.5, 0.0];
/// let window = WindowType::custom(coeffs).unwrap();
/// ```
#[inline]
pub fn custom(coefficients: Vec<f64>) -> Result<Self, SpectrogramError> {
Self::custom_with_normalization(coefficients, None)
}
/// Create a custom window from pre-computed coefficients with optional normalization.
///
/// # Arguments
///
/// * `coefficients` - Pre-computed window coefficients. The length must match
/// the FFT size that will be used with this window.
/// * `normalize` - Optional normalization mode:
/// - `None`: No normalization (use coefficients as-is)
/// - `Some("sum")`: Normalize so sum equals 1.0
/// - `Some("peak")`: Normalize so maximum value equals 1.0
/// - `Some("energy")`: Normalize so sum of squares equals 1.0
///
/// # Errors
///
/// Returns error if:
/// - Coefficients are empty
/// - Any coefficient is non-finite (NaN or infinity)
/// - Unknown normalization mode is specified
/// - Normalization would divide by zero (e.g., all-zero window)
///
/// # Examples
///
/// ```
/// use spectrograms::WindowType;
///
/// // Create a window normalized to unit sum
/// let coeffs = vec![1.0, 2.0, 3.0, 2.0, 1.0];
/// let window = WindowType::custom_with_normalization(coeffs, Some("sum")).unwrap();
///
/// // Create a window normalized to unit peak
/// let coeffs = vec![0.0, 0.5, 1.0, 0.5, 0.0];
/// let window = WindowType::custom_with_normalization(coeffs, Some("peak")).unwrap();
/// ```
#[inline]
pub fn custom_with_normalization(
mut coefficients: Vec<f64>,
normalize: Option<&str>,
) -> Result<Self, SpectrogramError> {
let size = NonZeroUsize::new(coefficients.len()).ok_or_else(|| {
SpectrogramError::invalid_input("Custom window coefficients cannot be empty")
})?;
// Validate all coefficients are finite
for (i, &coef) in coefficients.iter().enumerate() {
if !coef.is_finite() {
return Err(SpectrogramError::invalid_input(format!(
"Window coefficient at index {i} is not finite: {coef}"
)));
}
}
// Apply normalization if requested
if let Some(norm_mode) = normalize {
match norm_mode {
"sum" => {
let sum: f64 = coefficients.iter().sum();
if sum == 0.0 {
return Err(SpectrogramError::invalid_input(
"Cannot normalize window by sum: sum is zero",
));
}
for coef in &mut coefficients {
*coef /= sum;
}
}
"peak" | "max" => {
let max = coefficients
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max);
if max == 0.0 {
return Err(SpectrogramError::invalid_input(
"Cannot normalize window by peak: maximum is zero",
));
}
for coef in &mut coefficients {
*coef /= max;
}
}
"energy" | "rms" => {
let energy: f64 = coefficients.iter().map(|x| x * x).sum();
if energy == 0.0 {
return Err(SpectrogramError::invalid_input(
"Cannot normalize window by energy: energy is zero",
));
}
let norm = energy.sqrt();
for coef in &mut coefficients {
*coef /= norm;
}
}
_ => {
return Err(SpectrogramError::invalid_input(format!(
"Unknown normalization mode '{norm_mode}'. Valid modes: 'sum', 'peak', 'energy'"
)));
}
}
}
Ok(Self::Custom {
coefficients: Arc::new(coefficients),
size,
})
}
#[must_use]
#[inline]
pub const fn is_parameterized(&self) -> bool {
matches!(self, Self::Kaiser { .. } | Self::Gaussian { .. })
}
#[must_use]
#[inline]
pub const fn parameter_value(&self) -> Option<f64> {
match self {
Self::Kaiser { beta } => Some(*beta),
Self::Gaussian { std } => Some(*std),
_ => None,
}
}
}
#[must_use]
#[inline]
pub fn hanning_window(n: NonZeroUsize) -> NonEmptyVec<f64> {
make_window(WindowType::Hanning, n)
}
#[must_use]
#[inline]
pub fn hamming_window(n: NonZeroUsize) -> NonEmptyVec<f64> {
make_window(WindowType::Hamming, n)
}
#[must_use]
#[inline]
pub fn blackman_window(n: NonZeroUsize) -> NonEmptyVec<f64> {
make_window(WindowType::Blackman, n)
}
#[must_use]
#[inline]
pub fn rectangular_window(n: NonZeroUsize) -> NonEmptyVec<f64> {
make_window(WindowType::Rectangular, n)
}
#[must_use]
#[inline]
pub fn kaiser_window(n: NonZeroUsize, beta: f64) -> NonEmptyVec<f64> {
make_window(WindowType::Kaiser { beta }, n)
}
#[must_use]
#[inline]
pub fn gaussian_window(n: NonZeroUsize, std: f64) -> NonEmptyVec<f64> {
make_window(WindowType::Gaussian { std }, n)
}
impl Display for WindowType {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Rectangular => write!(f, "Rectangular"),
Self::Hanning => write!(f, "Hanning"),
Self::Hamming => write!(f, "Hamming"),
Self::Blackman => write!(f, "Blackman"),
Self::Kaiser { beta } => write!(f, "Kaiser(beta={beta})"),
Self::Gaussian { std } => write!(f, "Gaussian(std={std})"),
Self::Custom { size, .. } => write!(f, "Custom(n={size})"),
}
}
}
// Cache the compiled regex for window type parsing
static WINDOW_REGEX: OnceLock<regex::Regex> = OnceLock::new();
impl FromStr for WindowType {
type Err = SpectrogramError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
return Err(SpectrogramError::invalid_input(
"Input must not be empty. Must be one of ['rectangular', 'hanning', 'hamming', 'blackman', 'gaussian', 'kaiser']",
));
}
let reg = WINDOW_REGEX.get_or_init(|| {
let pattern = r"^(?:(?P<name>rect|rectangle|hann|hanning|hamm|hamming|blackman)|(?P<param_name>kaiser|gaussian)=(?P<param>\d+(\.\d+)?))$";
regex::RegexBuilder::new(pattern)
.case_insensitive(true)
.build()
.expect("hardcoded window regex should compile")
});
let normalised = s.trim();
match reg.captures(normalised) {
Some(caps) => {
if let Some(name) = caps.name("name") {
match name.as_str().to_ascii_lowercase().as_str() {
"rect" | "rectangle" => Ok(Self::Rectangular),
"hann" | "hanning" => Ok(Self::Hanning),
"hamm" | "hamming" => Ok(Self::Hamming),
"blackman" => Ok(Self::Blackman),
_ => Err(SpectrogramError::invalid_input(format!(
"Unrecognized window name: {}",
name.as_str()
))),
}
} else if let (Some(param_name), Some(param)) =
(caps.name("param_name"), caps.name("param"))
{
let value: f64 = param.as_str().parse().map_err(|_| {
SpectrogramError::invalid_input(format!(
"Invalid numeric parameter '{}'",
param.as_str()
))
})?;
match param_name.as_str().to_ascii_lowercase().as_str() {
"kaiser" => Ok(Self::Kaiser { beta: value }),
"gaussian" => Ok(Self::Gaussian { std: value }),
_ => Err(SpectrogramError::invalid_input(format!(
"Unrecognized parameterized window: {}",
param_name.as_str()
))),
}
} else {
Err(SpectrogramError::invalid_input(
"Invalid window specification: regex matched but no valid capture group found",
))
}
}
None => Err(SpectrogramError::invalid_input(format!(
"Invalid window specification '{s}'"
))),
}
}
}