1use crate::infer::GraphExt as _;
28use crate::op::Activation;
29use crate::{DType, Graph, NodeId, fft::FftNorm};
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum WindowKind {
34 Rectangular,
36 Hann,
38 Hamming,
40 Blackman,
42}
43
44impl WindowKind {
45 fn coeffs(self, n: usize) -> Vec<f32> {
46 use std::f32::consts::PI;
47 if n == 1 {
48 return vec![1.0];
49 }
50 let d = (n - 1) as f32;
51 (0..n)
52 .map(|i| {
53 let t = i as f32 / d;
54 match self {
55 WindowKind::Rectangular => 1.0,
56 WindowKind::Hann => 0.5 - 0.5 * (2.0 * PI * t).cos(),
57 WindowKind::Hamming => 0.54 - 0.46 * (2.0 * PI * t).cos(),
58 WindowKind::Blackman => {
59 0.42 - 0.5 * (2.0 * PI * t).cos() + 0.08 * (4.0 * PI * t).cos()
60 }
61 }
62 })
63 .collect()
64 }
65}
66
67impl Graph {
68 pub fn spectrogram(
76 &mut self,
77 x: NodeId,
78 frame_len: usize,
79 hop: usize,
80 window: WindowKind,
81 power: bool,
82 log: bool,
83 ) -> NodeId {
84 assert!(frame_len > 0 && hop > 0, "spectrogram: frame_len/hop > 0");
85 let shape = self.shape(x).clone();
86 let last = shape.rank() - 1;
87 let t = shape.dim(last).unwrap_static();
88 assert!(t >= frame_len, "spectrogram: T {t} < frame_len {frame_len}");
89 let n_frames = 1 + (t - frame_len) / hop;
90
91 let mut rows = Vec::with_capacity(n_frames);
93 for f in 0..n_frames {
94 let start = f * hop;
95 let frame = self.narrow_(x, last, start, frame_len);
96 let mut dims: Vec<i64> = self
97 .shape(frame)
98 .dims()
99 .iter()
100 .map(|d| d.unwrap_static() as i64)
101 .collect();
102 dims.insert(0, 1);
103 rows.push(self.reshape_(frame, dims));
104 }
105 let framed = if rows.len() == 1 {
106 rows.pop().unwrap()
107 } else {
108 self.concat_(rows, 0)
109 };
110
111 let framed = if window == WindowKind::Rectangular {
113 framed
114 } else {
115 let w = self.const_f32_tensor(window.coeffs(frame_len), &[frame_len]);
116 self.mul(framed, w)
117 };
118
119 let (re, im) = self.rfft(framed, FftNorm::Backward);
120 let re2 = self.mul(re, re);
121 let im2 = self.mul(im, im);
122 let mag2 = self.add(re2, im2);
123 let out = if power { mag2 } else { self.sqrt(mag2) };
124 if log { self.log_eps(out, 1e-8) } else { out }
125 }
126
127 pub fn band_power(&mut self, x: NodeId, sample_rate: f32, bands: &[(f32, f32)]) -> NodeId {
133 assert!(!bands.is_empty(), "band_power: need ≥1 band");
134 let shape = self.shape(x).clone();
135 let last = shape.rank() - 1;
136 let t = shape.dim(last).unwrap_static();
137 let n_pad = crate::fft::next_pow2(t);
138 let n_bins = n_pad / 2 + 1;
139
140 let (re, im) = self.rfft(x, FftNorm::Backward);
141 let re2 = self.mul(re, re);
142 let im2 = self.mul(im, im);
143 let power = self.add(re2, im2); let plast = self.shape(power).rank() - 1;
145
146 let hz_per_bin = sample_rate / n_pad as f32;
147 let mut cols = Vec::with_capacity(bands.len());
148 for &(lo, hi) in bands {
149 let mut b0 = (lo / hz_per_bin).ceil() as isize;
150 let mut b1 = (hi / hz_per_bin).floor() as isize;
151 b0 = b0.clamp(0, n_bins as isize - 1);
152 b1 = b1.clamp(0, n_bins as isize - 1);
153 let (b0, b1) = if b1 < b0 { (b0, b0) } else { (b0, b1) };
154 let seg = self.narrow_(power, plast, b0 as usize, (b1 - b0 + 1) as usize);
155 cols.push(self.sum(seg, vec![plast], true)); }
157 if cols.len() == 1 {
158 cols.pop().unwrap()
159 } else {
160 self.concat_(cols, plast)
161 }
162 }
163
164 pub fn differential_entropy(
170 &mut self,
171 x: NodeId,
172 sample_rate: f32,
173 bands: &[(f32, f32)],
174 ) -> NodeId {
175 let bp = self.band_power(x, sample_rate, bands);
176 let c = self.constant(2.0 * std::f64::consts::PI * std::f64::consts::E, DType::F32);
178 let scaled = self.mul(bp, c);
179 let logv = self.log_eps(scaled, 1e-8);
180 let half = self.constant(0.5, DType::F32);
181 self.mul(logv, half)
182 }
183
184 fn log_eps(&mut self, x: NodeId, eps: f32) -> NodeId {
185 let e = self.constant(eps as f64, DType::F32);
186 let shifted = self.add(x, e);
187 let s = crate::shape::unary_shape(self.shape(shifted));
188 self.activation(Activation::Log, shifted, s)
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195 use crate::Shape;
196
197 fn dims(g: &Graph, id: NodeId) -> Vec<usize> {
198 g.shape(id)
199 .dims()
200 .iter()
201 .map(|d| d.unwrap_static())
202 .collect()
203 }
204 fn input(g: &mut Graph, shape: &[usize]) -> NodeId {
205 g.input("x", Shape::new(shape, DType::F32))
206 }
207
208 #[test]
209 fn spectrogram_shape() {
210 let mut g = Graph::new("spec");
211 let x = input(&mut g, &[2, 256]); let y = g.spectrogram(x, 64, 32, WindowKind::Hann, true, true);
214 assert_eq!(dims(&g, y), vec![7, 2, 33]);
215 }
216
217 #[test]
218 fn band_power_shape() {
219 let mut g = Graph::new("bp");
220 let x = input(&mut g, &[4, 512]); let bands = [
222 (0.5, 4.0),
223 (4.0, 8.0),
224 (8.0, 13.0),
225 (13.0, 30.0),
226 (30.0, 45.0),
227 ];
228 let y = g.band_power(x, 128.0, &bands);
229 assert_eq!(dims(&g, y), vec![4, 5]);
230 }
231
232 #[test]
233 fn differential_entropy_shape() {
234 let mut g = Graph::new("de");
235 let x = input(&mut g, &[4, 512]);
236 let bands = [(1.0, 4.0), (4.0, 8.0), (8.0, 14.0)];
237 let y = g.differential_entropy(x, 200.0, &bands);
238 assert_eq!(dims(&g, y), vec![4, 3]);
239 }
240}