rosa 0.1.0

Audio feature extraction library matching librosa output
Documentation
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::Matrix;

/// Which axis to operate along.
#[derive(Clone, Copy)]
pub enum Axis {
    /// Axis 0: reduce across rows → result has `cols` elements.
    Row,
    /// Axis 1: reduce across columns → result has `rows` elements.
    Col,
}

// --- Axis reductions (Step 4) ---

impl Matrix {
    /// Sum along axis.
    pub fn sum_axis(&self, axis: Axis) -> Vec<f64> {
        match axis {
            Axis::Col => {
                // Reduce across columns → one value per row
                (0..self.rows()).map(|r| self.row(r).iter().sum()).collect()
            }
            Axis::Row => {
                // Reduce across rows → one value per column
                let mut result = vec![0.0; self.cols()];
                for r in 0..self.rows() {
                    let row = self.row(r);
                    for (c, val) in row.iter().enumerate() {
                        result[c] += val;
                    }
                }
                result
            }
        }
    }

    /// Mean along axis.
    pub fn mean_axis(&self, axis: Axis) -> Vec<f64> {
        let sums = self.sum_axis(axis);
        let divisor = match axis {
            Axis::Col => self.cols() as f64,
            Axis::Row => self.rows() as f64,
        };
        sums.into_iter().map(|s| s / divisor).collect()
    }

    /// Max along axis.
    pub fn max_axis(&self, axis: Axis) -> Vec<f64> {
        match axis {
            Axis::Col => (0..self.rows())
                .map(|r| {
                    self.row(r)
                        .iter()
                        .copied()
                        .fold(f64::NEG_INFINITY, f64::max)
                })
                .collect(),
            Axis::Row => {
                let mut result = vec![f64::NEG_INFINITY; self.cols()];
                for r in 0..self.rows() {
                    let row = self.row(r);
                    for (c, &val) in row.iter().enumerate() {
                        result[c] = result[c].max(val);
                    }
                }
                result
            }
        }
    }

    /// Min along axis.
    pub fn min_axis(&self, axis: Axis) -> Vec<f64> {
        match axis {
            Axis::Col => (0..self.rows())
                .map(|r| self.row(r).iter().copied().fold(f64::INFINITY, f64::min))
                .collect(),
            Axis::Row => {
                let mut result = vec![f64::INFINITY; self.cols()];
                for r in 0..self.rows() {
                    let row = self.row(r);
                    for (c, &val) in row.iter().enumerate() {
                        result[c] = result[c].min(val);
                    }
                }
                result
            }
        }
    }

    /// Argmin along axis. Returns indices of minimum values.
    /// First occurrence wins (matches numpy behavior).
    pub fn argmin_axis(&self, axis: Axis) -> Vec<usize> {
        match axis {
            Axis::Col => (0..self.rows())
                .map(|r| {
                    let row = self.row(r);
                    let mut min_idx = 0;
                    let mut min_val = row[0];
                    for (i, &val) in row.iter().enumerate().skip(1) {
                        if val < min_val {
                            min_val = val;
                            min_idx = i;
                        }
                    }
                    min_idx
                })
                .collect(),
            Axis::Row => {
                let mut result = vec![0usize; self.cols()];
                let mut min_vals: Vec<f64> = self.row(0).to_vec();
                for r in 1..self.rows() {
                    let row = self.row(r);
                    for (c, &val) in row.iter().enumerate() {
                        if val < min_vals[c] {
                            min_vals[c] = val;
                            result[c] = r;
                        }
                    }
                }
                result
            }
        }
    }

    /// Argmax along axis. Returns indices of maximum values.
    /// First occurrence wins (matches numpy behavior).
    pub fn argmax_axis(&self, axis: Axis) -> Vec<usize> {
        match axis {
            Axis::Col => (0..self.rows())
                .map(|r| {
                    let row = self.row(r);
                    let mut max_idx = 0;
                    let mut max_val = row[0];
                    for (i, &val) in row.iter().enumerate().skip(1) {
                        if val > max_val {
                            max_val = val;
                            max_idx = i;
                        }
                    }
                    max_idx
                })
                .collect(),
            Axis::Row => {
                let mut result = vec![0usize; self.cols()];
                let mut max_vals: Vec<f64> = self.row(0).to_vec();
                for r in 1..self.rows() {
                    let row = self.row(r);
                    for (c, &val) in row.iter().enumerate() {
                        if val > max_vals[c] {
                            max_vals[c] = val;
                            result[c] = r;
                        }
                    }
                }
                result
            }
        }
    }

    /// Cumulative sum along axis. Returns Matrix of same shape.
    pub fn cumsum_axis(&self, axis: Axis) -> Matrix {
        let mut result = self.clone();
        match axis {
            Axis::Col => {
                // Cumsum across columns within each row
                for r in 0..self.rows() {
                    let row = result.row_mut(r);
                    for c in 1..self.cols() {
                        row[c] += row[c - 1];
                    }
                }
            }
            Axis::Row => {
                // Cumsum across rows within each column
                for r in 1..self.rows() {
                    for c in 0..self.cols() {
                        let prev = result.get(r - 1, c);
                        *result.get_mut(r, c) += prev;
                    }
                }
            }
        }
        result
    }
}

// --- Normalize (Step 5) ---

impl Matrix {
    /// Lp-normalize along axis.
    /// - `norm == 1.0`: L1 (divide by sum of abs values)
    /// - `norm == 2.0`: L2 (divide by sqrt of sum of squares)
    /// - `norm == f64::INFINITY`: max-norm (divide by max abs value)
    ///
    /// If the norm is zero for a row/col, leave it as zeros.
    pub fn normalize_axis(&self, axis: Axis, norm: f64) -> Matrix {
        let mut result = self.clone();

        match axis {
            Axis::Col => {
                // Normalize each row
                for r in 0..self.rows() {
                    let row = self.row(r);
                    let divisor = compute_norm(row.iter().copied(), norm);
                    if divisor > 0.0 {
                        let out_row = result.row_mut(r);
                        for val in out_row.iter_mut() {
                            *val /= divisor;
                        }
                    }
                }
            }
            Axis::Row => {
                // Normalize each column
                for c in 0..self.cols() {
                    let col_vals: Vec<f64> = self.col(c).copied().collect();
                    let divisor = compute_norm(col_vals.iter().copied(), norm);
                    if divisor > 0.0 {
                        for r in 0..self.rows() {
                            *result.get_mut(r, c) /= divisor;
                        }
                    }
                }
            }
        }
        result
    }
}

fn compute_norm(values: impl Iterator<Item = f64>, norm: f64) -> f64 {
    if norm == 1.0 {
        values.map(|x| x.abs()).sum()
    } else if norm == 2.0 {
        values.map(|x| x * x).sum::<f64>().sqrt()
    } else if norm.is_infinite() {
        values.map(|x| x.abs()).fold(0.0_f64, f64::max)
    } else {
        values
            .map(|x| x.abs().powf(norm))
            .sum::<f64>()
            .powf(1.0 / norm)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;

    // --- Step 4 tests: Axis reductions ---

    fn test_matrix() -> Matrix {
        // 3×4 matrix with known values:
        // [ 1  2  3  4 ]
        // [ 5  6  7  8 ]
        // [ 9 10 11 12 ]
        Matrix::from_fn(3, 4, |r, c| (r * 4 + c + 1) as f64)
    }

    #[test]
    fn test_sum_axis_col() {
        let m = test_matrix();
        let sums = m.sum_axis(Axis::Col);
        assert_eq!(sums, vec![10.0, 26.0, 42.0]);
    }

    #[test]
    fn test_sum_axis_row() {
        let m = test_matrix();
        let sums = m.sum_axis(Axis::Row);
        assert_eq!(sums, vec![15.0, 18.0, 21.0, 24.0]);
    }

    #[test]
    fn test_mean_axis_col() {
        let m = test_matrix();
        let means = m.mean_axis(Axis::Col);
        assert_eq!(means, vec![2.5, 6.5, 10.5]);
    }

    #[test]
    fn test_mean_axis_row() {
        let m = test_matrix();
        let means = m.mean_axis(Axis::Row);
        assert_eq!(means, vec![5.0, 6.0, 7.0, 8.0]);
    }

    #[test]
    fn test_max_axis_col() {
        let m = test_matrix();
        assert_eq!(m.max_axis(Axis::Col), vec![4.0, 8.0, 12.0]);
    }

    #[test]
    fn test_max_axis_row() {
        let m = test_matrix();
        assert_eq!(m.max_axis(Axis::Row), vec![9.0, 10.0, 11.0, 12.0]);
    }

    #[test]
    fn test_min_axis_col() {
        let m = test_matrix();
        assert_eq!(m.min_axis(Axis::Col), vec![1.0, 5.0, 9.0]);
    }

    #[test]
    fn test_min_axis_row() {
        let m = test_matrix();
        assert_eq!(m.min_axis(Axis::Row), vec![1.0, 2.0, 3.0, 4.0]);
    }

    #[test]
    fn test_argmax_axis_col() {
        let m = test_matrix();
        assert_eq!(m.argmax_axis(Axis::Col), vec![3, 3, 3]); // max at last col
    }

    #[test]
    fn test_argmax_axis_row() {
        let m = test_matrix();
        assert_eq!(m.argmax_axis(Axis::Row), vec![2, 2, 2, 2]); // max at last row
    }

    #[test]
    fn test_argmin_axis_col() {
        let m = test_matrix();
        assert_eq!(m.argmin_axis(Axis::Col), vec![0, 0, 0]); // min at first col
    }

    #[test]
    fn test_argmin_axis_row() {
        let m = test_matrix();
        assert_eq!(m.argmin_axis(Axis::Row), vec![0, 0, 0, 0]); // min at first row
    }

    #[test]
    fn test_argmax_ties_first_wins() {
        let m = Matrix::from_rows(&[&[1.0, 3.0, 3.0, 2.0]]);
        assert_eq!(m.argmax_axis(Axis::Col), vec![1]); // first occurrence of 3.0
    }

    #[test]
    fn test_cumsum_axis_col() {
        let m = Matrix::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0]]);
        let cs = m.cumsum_axis(Axis::Col);
        assert_eq!(cs.row(0), &[1.0, 3.0, 6.0]);
        assert_eq!(cs.row(1), &[4.0, 9.0, 15.0]);
    }

    #[test]
    fn test_cumsum_axis_row() {
        let m = Matrix::from_rows(&[&[1.0, 2.0], &[3.0, 4.0], &[5.0, 6.0]]);
        let cs = m.cumsum_axis(Axis::Row);
        assert_eq!(cs.row(0), &[1.0, 2.0]);
        assert_eq!(cs.row(1), &[4.0, 6.0]);
        assert_eq!(cs.row(2), &[9.0, 12.0]);
    }

    #[test]
    fn test_reductions_1x1() {
        let m = Matrix::from_vec(vec![42.0], 1, 1);
        assert_eq!(m.sum_axis(Axis::Col), vec![42.0]);
        assert_eq!(m.sum_axis(Axis::Row), vec![42.0]);
        assert_eq!(m.mean_axis(Axis::Col), vec![42.0]);
        assert_eq!(m.max_axis(Axis::Col), vec![42.0]);
        assert_eq!(m.min_axis(Axis::Row), vec![42.0]);
        assert_eq!(m.argmax_axis(Axis::Col), vec![0]);
        assert_eq!(m.argmin_axis(Axis::Row), vec![0]);
    }

    // --- Step 5 tests: normalize_axis ---

    #[test]
    fn test_normalize_l1_col() {
        let m = Matrix::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0]]);
        let n = m.normalize_axis(Axis::Col, 1.0);
        // Each row should sum to 1.0
        for r in 0..n.rows() {
            let sum: f64 = n.row(r).iter().sum();
            assert_relative_eq!(sum, 1.0, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_normalize_l1_row() {
        let m = Matrix::from_rows(&[&[1.0, 2.0], &[3.0, 4.0], &[5.0, 6.0]]);
        let n = m.normalize_axis(Axis::Row, 1.0);
        // Each column should sum to 1.0
        for c in 0..n.cols() {
            let sum: f64 = n.col(c).sum();
            assert_relative_eq!(sum, 1.0, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_normalize_l2_col() {
        let m = Matrix::from_rows(&[&[3.0, 4.0]]);
        let n = m.normalize_axis(Axis::Col, 2.0);
        // L2 norm of [3, 4] = 5, so [0.6, 0.8]
        assert_relative_eq!(n.get(0, 0), 0.6, epsilon = 1e-10);
        assert_relative_eq!(n.get(0, 1), 0.8, epsilon = 1e-10);
        let norm: f64 = n.row(0).iter().map(|x| x * x).sum::<f64>().sqrt();
        assert_relative_eq!(norm, 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_normalize_linf_col() {
        let m = Matrix::from_rows(&[&[1.0, -5.0, 3.0]]);
        let n = m.normalize_axis(Axis::Col, f64::INFINITY);
        // Max abs value is 5, so divide by 5
        assert_relative_eq!(n.get(0, 0), 0.2, epsilon = 1e-10);
        assert_relative_eq!(n.get(0, 1), -1.0, epsilon = 1e-10);
        assert_relative_eq!(n.get(0, 2), 0.6, epsilon = 1e-10);
    }

    #[test]
    fn test_normalize_zero_row() {
        let m = Matrix::from_rows(&[&[0.0, 0.0, 0.0], &[1.0, 2.0, 3.0]]);
        let n = m.normalize_axis(Axis::Col, 1.0);
        // All-zero row stays zero
        assert_eq!(n.row(0), &[0.0, 0.0, 0.0]);
        // Non-zero row normalizes
        let sum: f64 = n.row(1).iter().sum();
        assert_relative_eq!(sum, 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_normalize_zero_col() {
        let m = Matrix::from_rows(&[&[0.0, 1.0], &[0.0, 2.0]]);
        let n = m.normalize_axis(Axis::Row, 2.0);
        // First column is all zeros → stays zero
        assert_eq!(n.get(0, 0), 0.0);
        assert_eq!(n.get(1, 0), 0.0);
        // Second column normalizes
        let norm: f64 = n.col(1).map(|x| x * x).sum::<f64>().sqrt();
        assert_relative_eq!(norm, 1.0, epsilon = 1e-10);
    }
}