primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Correlation and covariance functions
//!
//! # Functions
//!
//! - `pearson_correlation`: Pearson product-moment correlation coefficient
//! - `covariance`: Sample covariance between two variables
//! - `correlation_matrix`: Pairwise correlations for multiple variables
//! - `covariance_matrix`: Pairwise covariances for multiple variables
//!
//! # Notes
//!
//! All functions use sample statistics (dividing by n-1 for covariance).

use crate::error::{BarracudaError, Result};

/// Compute Pearson correlation coefficient between two vectors.
///
/// r = Σ(xᵢ - x̄)(yᵢ - ȳ) / √[Σ(xᵢ - x̄)² Σ(yᵢ - ȳ)²]
///
/// # Arguments
///
/// * `x` - First variable
/// * `y` - Second variable (must have same length as x)
///
/// # Returns
///
/// Correlation coefficient in [-1, 1], or NaN if either variance is zero.
///
/// # Errors
///
/// Returns [`Err`] if `x` and `y` have different lengths, or if there are fewer than 2 data points.
///
/// # Examples
///
/// ```
/// use barracuda::stats::pearson_correlation;
///
/// let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
/// let y = vec![2.0, 4.0, 6.0, 8.0, 10.0];
/// let r = pearson_correlation(&x, &y).unwrap();
/// assert!((r - 1.0).abs() < 1e-10);  // Perfect positive correlation
/// ```
pub fn pearson_correlation(x: &[f64], y: &[f64]) -> Result<f64> {
    if x.len() != y.len() {
        return Err(BarracudaError::InvalidInput {
            message: format!("Vectors must have same length: {} vs {}", x.len(), y.len()),
        });
    }

    if x.len() < 2 {
        return Err(BarracudaError::InvalidInput {
            message: "Need at least 2 data points for correlation".to_string(),
        });
    }

    let n = x.len() as f64;

    // Compute means
    let mean_x: f64 = x.iter().sum::<f64>() / n;
    let mean_y: f64 = y.iter().sum::<f64>() / n;

    // Compute covariance and variances in one pass
    let mut cov = 0.0;
    let mut var_x = 0.0;
    let mut var_y = 0.0;

    for (&xi, &yi) in x.iter().zip(y) {
        let dx = xi - mean_x;
        let dy = yi - mean_y;
        cov = dx.mul_add(dy, cov);
        var_x = dx.mul_add(dx, var_x);
        var_y = dy.mul_add(dy, var_y);
    }

    let denom = (var_x * var_y).sqrt();
    if denom == 0.0 {
        // One or both variables have zero variance
        return Ok(f64::NAN);
    }

    Ok(cov / denom)
}

/// Compute sample covariance between two vectors.
///
/// Cov(X,Y) = Σ(xᵢ - x̄)(yᵢ - ȳ) / (n-1)
///
/// # Arguments
///
/// * `x` - First variable
/// * `y` - Second variable (must have same length as x)
///
/// # Errors
///
/// Returns [`Err`] if `x` and `y` have different lengths, or if there are fewer than 2 data points.
///
/// # Examples
///
/// ```
/// use barracuda::stats::covariance;
///
/// let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
/// let y = vec![2.0, 4.0, 6.0, 8.0, 10.0];
/// let cov = covariance(&x, &y).unwrap();
/// assert!((cov - 5.0).abs() < 1e-10);
/// ```
pub fn covariance(x: &[f64], y: &[f64]) -> Result<f64> {
    if x.len() != y.len() {
        return Err(BarracudaError::InvalidInput {
            message: format!("Vectors must have same length: {} vs {}", x.len(), y.len()),
        });
    }

    if x.len() < 2 {
        return Err(BarracudaError::InvalidInput {
            message: "Need at least 2 data points for covariance".to_string(),
        });
    }

    let n = x.len() as f64;

    let mean_x: f64 = x.iter().sum::<f64>() / n;
    let mean_y: f64 = y.iter().sum::<f64>() / n;

    let cov: f64 = x
        .iter()
        .zip(y.iter())
        .map(|(&xi, &yi)| (xi - mean_x) * (yi - mean_y))
        .sum();

    // Sample covariance: divide by n-1
    Ok(cov / (n - 1.0))
}

/// Compute sample variance of a vector.
///
/// Var(X) = Σ(xᵢ - x̄)² / (n-1)
///
/// # Errors
///
/// Returns [`Err`] if there are fewer than 2 data points.
pub fn variance(x: &[f64]) -> Result<f64> {
    if x.len() < 2 {
        return Err(BarracudaError::InvalidInput {
            message: "Need at least 2 data points for variance".to_string(),
        });
    }

    let n = x.len() as f64;
    let mean: f64 = x.iter().sum::<f64>() / n;

    let var: f64 = x.iter().map(|&xi| (xi - mean).powi(2)).sum();

    Ok(var / (n - 1.0))
}

/// Compute standard deviation of a vector.
///
/// # Errors
///
/// Returns [`Err`] if [`variance`] fails (fewer than 2 data points).
pub fn std_dev(x: &[f64]) -> Result<f64> {
    Ok(variance(x)?.sqrt())
}

/// Compute correlation matrix for multiple variables.
///
/// Given data matrix with n observations (rows) and p variables (columns),
/// returns a p×p symmetric matrix where element (i,j) is the correlation
/// between variable i and variable j.
///
/// # Arguments
///
/// * `data` - Data matrix as row-major Vec of rows, each row is one observation
///
/// # Returns
///
/// p×p correlation matrix (flattened row-major)
///
/// # Errors
///
/// Returns [`Err`] if the data matrix is empty, has fewer than 2 observations, has no variables,
/// rows have inconsistent lengths, or [`pearson_correlation`] fails for any pair.
///
/// # Examples
///
/// ```
/// use barracuda::stats::correlation_matrix;
///
/// // 5 observations, 2 variables
/// let data = vec![
///     vec![1.0, 2.0],
///     vec![2.0, 4.0],
///     vec![3.0, 6.0],
///     vec![4.0, 8.0],
///     vec![5.0, 10.0],
/// ];
/// let corr = correlation_matrix(&data).unwrap();
/// // corr is 2x2: [[1, r], [r, 1]] where r ≈ 1.0
/// assert!((corr[0] - 1.0).abs() < 1e-10);  // var1 with var1
/// assert!((corr[1] - 1.0).abs() < 1e-10);  // var1 with var2 (perfect correlation)
/// ```
pub fn correlation_matrix(data: &[Vec<f64>]) -> Result<Vec<f64>> {
    if data.is_empty() {
        return Err(BarracudaError::InvalidInput {
            message: "Data matrix is empty".to_string(),
        });
    }

    let n = data.len();
    if n < 2 {
        return Err(BarracudaError::InvalidInput {
            message: "Need at least 2 observations".to_string(),
        });
    }

    let p = data[0].len();
    if p == 0 {
        return Err(BarracudaError::InvalidInput {
            message: "Data has no variables".to_string(),
        });
    }

    // Verify all rows have same length
    for (i, row) in data.iter().enumerate() {
        if row.len() != p {
            return Err(BarracudaError::InvalidInput {
                message: format!("Row {} has {} elements, expected {}", i, row.len(), p),
            });
        }
    }

    // Extract columns
    let columns: Vec<Vec<f64>> = (0..p)
        .map(|j| data.iter().map(|row| row[j]).collect())
        .collect();

    // Compute correlation matrix
    let mut corr = vec![0.0; p * p];
    for i in 0..p {
        corr[i * p + i] = 1.0; // Diagonal is always 1
        for j in (i + 1)..p {
            let r = pearson_correlation(&columns[i], &columns[j])?;
            corr[i * p + j] = r;
            corr[j * p + i] = r; // Symmetric
        }
    }

    Ok(corr)
}

/// Compute covariance matrix for multiple variables.
///
/// Given data matrix with n observations (rows) and p variables (columns),
/// returns a p×p symmetric matrix where element (i,j) is the covariance
/// between variable i and variable j.
///
/// # Arguments
///
/// * `data` - Data matrix as row-major Vec of rows
///
/// # Returns
///
/// p×p covariance matrix (flattened row-major)
///
/// # Errors
///
/// Returns [`Err`] if the data matrix is empty, has fewer than 2 observations, has no variables,
/// rows have inconsistent lengths, or [`covariance`] fails for any pair.
pub fn covariance_matrix(data: &[Vec<f64>]) -> Result<Vec<f64>> {
    if data.is_empty() {
        return Err(BarracudaError::InvalidInput {
            message: "Data matrix is empty".to_string(),
        });
    }

    let n = data.len();
    if n < 2 {
        return Err(BarracudaError::InvalidInput {
            message: "Need at least 2 observations".to_string(),
        });
    }

    let p = data[0].len();
    if p == 0 {
        return Err(BarracudaError::InvalidInput {
            message: "Data has no variables".to_string(),
        });
    }

    // Verify all rows have same length
    for (i, row) in data.iter().enumerate() {
        if row.len() != p {
            return Err(BarracudaError::InvalidInput {
                message: format!("Row {} has {} elements, expected {}", i, row.len(), p),
            });
        }
    }

    // Extract columns
    let columns: Vec<Vec<f64>> = (0..p)
        .map(|j| data.iter().map(|row| row[j]).collect())
        .collect();

    // Compute covariance matrix
    let mut cov_mat = vec![0.0; p * p];
    for i in 0..p {
        for j in i..p {
            let c = covariance(&columns[i], &columns[j])?;
            cov_mat[i * p + j] = c;
            cov_mat[j * p + i] = c; // Symmetric
        }
    }

    Ok(cov_mat)
}

/// Compute Spearman rank correlation coefficient.
///
/// Measures monotonic relationship (not just linear).
///
/// # Errors
///
/// Returns [`Err`] if `x` and `y` have different lengths, have fewer than 2 data points,
/// or if [`pearson_correlation`] fails on the ranks.
pub fn spearman_correlation(x: &[f64], y: &[f64]) -> Result<f64> {
    if x.len() != y.len() {
        return Err(BarracudaError::InvalidInput {
            message: format!("Vectors must have same length: {} vs {}", x.len(), y.len()),
        });
    }

    if x.len() < 2 {
        return Err(BarracudaError::InvalidInput {
            message: "Need at least 2 data points".to_string(),
        });
    }

    // Compute ranks
    let rank_x = compute_ranks(x);
    let rank_y = compute_ranks(y);

    // Pearson correlation of ranks
    pearson_correlation(&rank_x, &rank_y)
}

/// Helper: compute ranks of values (1-based, average for ties).
fn compute_ranks(x: &[f64]) -> Vec<f64> {
    let n = x.len();
    let mut indexed: Vec<(usize, f64)> = x.iter().copied().enumerate().collect();
    indexed.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

    let mut ranks = vec![0.0; n];
    let mut i = 0;
    while i < n {
        let mut j = i;
        // Find all tied values
        while j < n - 1 && indexed[j].1 == indexed[j + 1].1 {
            j += 1;
        }
        // Average rank for tied values
        let avg_rank = (i + j) as f64 / 2.0 + 1.0;
        for k in i..=j {
            ranks[indexed[k].0] = avg_rank;
        }
        i = j + 1;
    }

    ranks
}

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

    #[test]
    fn test_pearson_perfect_positive() {
        let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let y = vec![2.0, 4.0, 6.0, 8.0, 10.0];
        let r = pearson_correlation(&x, &y).unwrap();
        assert!((r - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_pearson_perfect_negative() {
        let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let y = vec![10.0, 8.0, 6.0, 4.0, 2.0];
        let r = pearson_correlation(&x, &y).unwrap();
        assert!((r + 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_pearson_zero() {
        // Orthogonal data
        let x = vec![1.0, -1.0, 1.0, -1.0];
        let y = vec![1.0, 1.0, -1.0, -1.0];
        let r = pearson_correlation(&x, &y).unwrap();
        assert!(r.abs() < 1e-10);
    }

    #[test]
    fn test_pearson_length_mismatch() {
        let x = vec![1.0, 2.0, 3.0];
        let y = vec![1.0, 2.0];
        assert!(pearson_correlation(&x, &y).is_err());
    }

    #[test]
    fn test_covariance_perfect() {
        let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let y = vec![2.0, 4.0, 6.0, 8.0, 10.0]; // y = 2x
        let cov = covariance(&x, &y).unwrap();
        // Cov(X, 2X) = 2 Var(X) = 2 * 2.5 = 5.0
        assert!((cov - 5.0).abs() < 1e-10);
    }

    #[test]
    fn test_variance() {
        let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let v = variance(&x).unwrap();
        // Var = 2.5 (sample variance)
        assert!((v - 2.5).abs() < 1e-10);
    }

    #[test]
    fn test_correlation_matrix() {
        // 5 observations, 2 perfectly correlated variables
        let data = vec![
            vec![1.0, 2.0],
            vec![2.0, 4.0],
            vec![3.0, 6.0],
            vec![4.0, 8.0],
            vec![5.0, 10.0],
        ];
        let corr = correlation_matrix(&data).unwrap();

        // 2x2 matrix, flattened
        assert_eq!(corr.len(), 4);
        assert!((corr[0] - 1.0).abs() < 1e-10); // [0,0]
        assert!((corr[1] - 1.0).abs() < 1e-10); // [0,1]
        assert!((corr[2] - 1.0).abs() < 1e-10); // [1,0]
        assert!((corr[3] - 1.0).abs() < 1e-10); // [1,1]
    }

    #[test]
    fn test_covariance_matrix() {
        let data = vec![
            vec![1.0, 2.0],
            vec![2.0, 4.0],
            vec![3.0, 6.0],
            vec![4.0, 8.0],
            vec![5.0, 10.0],
        ];
        let cov = covariance_matrix(&data).unwrap();

        // Var(X) = 2.5, Var(Y) = 10.0, Cov(X,Y) = 5.0
        assert!((cov[0] - 2.5).abs() < 1e-10); // [0,0]
        assert!((cov[1] - 5.0).abs() < 1e-10); // [0,1]
        assert!((cov[2] - 5.0).abs() < 1e-10); // [1,0]
        assert!((cov[3] - 10.0).abs() < 1e-10); // [1,1]
    }

    #[test]
    fn test_spearman_monotonic() {
        let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let y = vec![1.0, 4.0, 9.0, 16.0, 25.0]; // y = x², monotonic
        let r = spearman_correlation(&x, &y).unwrap();
        assert!((r - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_spearman_with_ties() {
        let x = vec![1.0, 2.0, 2.0, 4.0];
        let y = vec![1.0, 3.0, 2.0, 4.0];
        let r = spearman_correlation(&x, &y).unwrap();
        // Should still work with ties
        assert!(r > 0.5);
    }

    #[test]
    fn test_compute_ranks() {
        let x = vec![3.0, 1.0, 2.0];
        let ranks = compute_ranks(&x);
        assert!((ranks[0] - 3.0).abs() < 1e-10); // 3.0 is largest
        assert!((ranks[1] - 1.0).abs() < 1e-10); // 1.0 is smallest
        assert!((ranks[2] - 2.0).abs() < 1e-10); // 2.0 is middle
    }

    #[test]
    fn test_compute_ranks_with_ties() {
        let x = vec![1.0, 2.0, 2.0, 4.0];
        let ranks = compute_ranks(&x);
        assert!((ranks[0] - 1.0).abs() < 1e-10);
        assert!((ranks[1] - 2.5).abs() < 1e-10); // Tied values get average rank
        assert!((ranks[2] - 2.5).abs() < 1e-10);
        assert!((ranks[3] - 4.0).abs() < 1e-10);
    }
}