oxiblas 0.2.1

OxiBLAS - Pure Rust BLAS/LAPACK implementation for the scirs2 ecosystem
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Automatic algorithm selection for OxiBLAS.
//!
//! This module provides intelligent algorithm selection based on matrix
//! properties such as size, structure, and conditioning.
//!
//! # Examples
//!
//! ```
//! use oxiblas::prelude::*;
//! use oxiblas::auto::*;
//!
//! // Automatic matrix multiply - picks best algorithm based on size
//! let a = MatBuilder::<f64>::random(100, 100, 42);
//! let b = MatBuilder::<f64>::random(100, 100, 43);
//! let c = auto_matmul(a.as_ref(), b.as_ref());
//! ```

use oxiblas_blas::level3;
use oxiblas_blas::level3::GemmKernel;
use oxiblas_core::scalar::{Field, Scalar};
use oxiblas_matrix::{Mat, MatMut, MatRef};

/// Helper to convert MatRef to owned Mat.
fn matref_to_mat<T: Scalar>(r: MatRef<'_, T>) -> Mat<T>
where
    T: bytemuck::Zeroable,
{
    let mut m = Mat::zeros(r.nrows(), r.ncols());
    m.copy_from(&r);
    m
}

/// Threshold for switching to parallel algorithms.
#[cfg(feature = "parallel")]
const PARALLEL_THRESHOLD: usize = 256;

/// Matrix structure hint for algorithm selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatrixStructure {
    /// General matrix with no special structure.
    General,
    /// Symmetric matrix (A = A^T).
    Symmetric,
    /// Hermitian matrix (A = A^H).
    Hermitian,
    /// Positive definite matrix.
    PositiveDefinite,
    /// Upper triangular matrix.
    UpperTriangular,
    /// Lower triangular matrix.
    LowerTriangular,
    /// Diagonal matrix.
    Diagonal,
}

/// Automatic matrix multiplication.
///
/// Selects the best algorithm based on matrix dimensions:
/// - Medium matrices: Use standard blocked GEMM
/// - Large matrices: Use parallel GEMM (with `parallel` feature)
///
/// # Arguments
///
/// * `a` - Left matrix (m × k)
/// * `b` - Right matrix (k × n)
///
/// # Returns
///
/// The result matrix C = A × B (m × n).
///
/// # Examples
///
/// ```
/// use oxiblas::prelude::*;
/// use oxiblas::auto::auto_matmul;
///
/// let a = MatBuilder::<f64>::identity(50);
/// let b = MatBuilder::<f64>::hilbert(50);
/// let c = auto_matmul(a.as_ref(), b.as_ref());
/// ```
pub fn auto_matmul<T>(a: MatRef<'_, T>, b: MatRef<'_, T>) -> Mat<T>
where
    T: Scalar + Field + GemmKernel + bytemuck::Zeroable,
{
    let m = a.nrows();
    let n = b.ncols();
    let k = a.ncols();

    assert_eq!(k, b.nrows(), "Inner dimensions must match");

    let mut c = Mat::zeros(m, n);
    auto_gemm(T::one(), a, b, T::zero(), c.as_mut());
    c
}

/// Automatic GEMM with alpha/beta scaling.
///
/// Computes C = α × A × B + β × C with automatic algorithm selection.
///
/// # Arguments
///
/// * `alpha` - Scalar multiplier for A × B
/// * `a` - Left matrix
/// * `b` - Right matrix
/// * `beta` - Scalar multiplier for C
/// * `c` - Output matrix (modified in place)
///
/// # Examples
///
/// ```
/// use oxiblas::prelude::*;
/// use oxiblas::auto::auto_gemm;
///
/// let a = MatBuilder::<f64>::random(100, 100, 42);
/// let b = MatBuilder::<f64>::random(100, 100, 43);
/// let mut c = MatBuilder::<f64>::zeros(100, 100);
///
/// auto_gemm(1.0, a.as_ref(), b.as_ref(), 0.0, c.as_mut());
/// ```
pub fn auto_gemm<T>(alpha: T, a: MatRef<'_, T>, b: MatRef<'_, T>, beta: T, c: MatMut<'_, T>)
where
    T: Scalar + Field + GemmKernel + bytemuck::Zeroable,
{
    // Select algorithm based on dimensions
    #[cfg(feature = "parallel")]
    {
        let m = a.nrows();
        let n = b.ncols();
        let k = a.ncols();
        let max_dim = m.max(n).max(k);
        if max_dim >= PARALLEL_THRESHOLD {
            // Use parallel GEMM for large matrices
            level3::gemm_with_par(alpha, a, b, beta, c, oxiblas_core::Par::Rayon);
            return;
        }
    }

    // Use standard GEMM for smaller matrices
    level3::gemm(alpha, a, b, beta, c);
}

/// Result type for solve operations.
pub type SolveResult<T> = Result<Mat<T>, SolveError>;

/// Error type for solve operations.
#[derive(Debug, Clone)]
pub enum SolveError {
    /// Matrix is singular or nearly singular.
    Singular,
    /// Matrix is not positive definite.
    NotPositiveDefinite,
    /// Dimension mismatch.
    DimensionMismatch {
        /// Expected dimension.
        expected: usize,
        /// Actual dimension.
        got: usize,
    },
    /// Generic error.
    Other(String),
}

impl std::fmt::Display for SolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SolveError::Singular => write!(f, "Matrix is singular"),
            SolveError::NotPositiveDefinite => write!(f, "Matrix is not positive definite"),
            SolveError::DimensionMismatch { expected, got } => {
                write!(f, "Dimension mismatch: expected {expected}, got {got}")
            }
            SolveError::Other(msg) => write!(f, "{msg}"),
        }
    }
}

impl std::error::Error for SolveError {}

/// Automatic linear system solve for f64.
///
/// Solves A × x = b using the most appropriate algorithm:
/// - First tries Cholesky (if matrix appears SPD)
/// - Falls back to LU with partial pivoting
///
/// # Arguments
///
/// * `a` - Coefficient matrix (n × n)
/// * `b` - Right-hand side (n × m)
///
/// # Returns
///
/// The solution matrix x (n × m), or an error if the solve fails.
///
/// # Examples
///
/// ```
/// use oxiblas::prelude::*;
/// use oxiblas::auto::auto_solve_f64;
///
/// let a = MatBuilder::<f64>::random_spd(10, 42);
/// let b = MatBuilder::<f64>::random(10, 1, 43);
///
/// let x = auto_solve_f64(a.as_ref(), b.as_ref()).expect("Solve failed");
/// ```
pub fn auto_solve_f64(a: MatRef<'_, f64>, b: MatRef<'_, f64>) -> SolveResult<f64> {
    use oxiblas_lapack::cholesky::Cholesky;
    use oxiblas_lapack::lu::Lu;

    let n = a.nrows();

    if a.ncols() != n {
        return Err(SolveError::DimensionMismatch {
            expected: n,
            got: a.ncols(),
        });
    }

    if b.nrows() != n {
        return Err(SolveError::DimensionMismatch {
            expected: n,
            got: b.nrows(),
        });
    }

    // Try Cholesky first if matrix looks SPD
    if is_likely_spd_f64(&a) {
        if let Ok(chol) = Cholesky::compute_auto(a) {
            if let Ok(x) = chol.solve(b) {
                return Ok(x);
            }
        }
    }

    // Fall back to LU
    match Lu::compute_auto(a) {
        Ok(lu) => match lu.solve(b) {
            Ok(x) => Ok(x),
            Err(_) => Err(SolveError::Singular),
        },
        Err(_) => Err(SolveError::Singular),
    }
}

/// Automatic linear system solve for f32.
pub fn auto_solve_f32(a: MatRef<'_, f32>, b: MatRef<'_, f32>) -> SolveResult<f32> {
    use oxiblas_lapack::cholesky::Cholesky;
    use oxiblas_lapack::lu::Lu;

    let n = a.nrows();

    if a.ncols() != n {
        return Err(SolveError::DimensionMismatch {
            expected: n,
            got: a.ncols(),
        });
    }

    if b.nrows() != n {
        return Err(SolveError::DimensionMismatch {
            expected: n,
            got: b.nrows(),
        });
    }

    // Try Cholesky first if matrix looks SPD
    if is_likely_spd_f32(&a) {
        if let Ok(chol) = Cholesky::compute_auto(a) {
            if let Ok(x) = chol.solve(b) {
                return Ok(x);
            }
        }
    }

    // Fall back to LU
    match Lu::compute_auto(a) {
        Ok(lu) => match lu.solve(b) {
            Ok(x) => Ok(x),
            Err(_) => Err(SolveError::Singular),
        },
        Err(_) => Err(SolveError::Singular),
    }
}

/// Heuristic to check if a matrix is likely symmetric positive definite (f64).
fn is_likely_spd_f64(a: &MatRef<'_, f64>) -> bool {
    let n = a.nrows();
    if n != a.ncols() {
        return false;
    }

    // Check if diagonal elements are positive
    for i in 0..n {
        let diag = a[(i, i)];
        if diag <= f64::EPSILON {
            return false;
        }
    }

    // Check if approximately symmetric (sample a few off-diagonal elements)
    let samples = n.min(5);
    for i in 0..samples {
        for j in (i + 1)..n.min(i + samples) {
            let diff = (a[(i, j)] - a[(j, i)]).abs();
            let scale = a[(i, j)].abs() + a[(j, i)].abs() + f64::EPSILON;
            if diff / scale > 1e-6 {
                return false;
            }
        }
    }

    true
}

/// Heuristic to check if a matrix is likely symmetric positive definite (f32).
fn is_likely_spd_f32(a: &MatRef<'_, f32>) -> bool {
    let n = a.nrows();
    if n != a.ncols() {
        return false;
    }

    for i in 0..n {
        let diag = a[(i, i)];
        if diag <= f32::EPSILON {
            return false;
        }
    }

    let samples = n.min(5);
    for i in 0..samples {
        for j in (i + 1)..n.min(i + samples) {
            let diff = (a[(i, j)] - a[(j, i)]).abs();
            let scale = a[(i, j)].abs() + a[(j, i)].abs() + f32::EPSILON;
            if diff / scale > 1e-4 {
                return false;
            }
        }
    }

    true
}

/// Algorithm selection hint for SVD.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SvdAlgorithm {
    /// Automatically select the best algorithm.
    #[default]
    Auto,
    /// Standard bidiagonal SVD (more accurate).
    Standard,
    /// Divide and conquer (faster for large matrices).
    DivideConquer,
}

/// Compute SVD with automatic algorithm selection (f64).
///
/// Selects the best SVD algorithm based on matrix size:
/// - Small matrices (< 100): Use standard bidiagonal SVD
/// - Large matrices (>= 100): Use divide and conquer
///
/// # Arguments
///
/// * `a` - Input matrix
///
/// # Returns
///
/// Tuple of (U, S, Vt) where A ≈ U × diag(S) × Vt.
///
/// # Examples
///
/// ```
/// use oxiblas::prelude::*;
/// use oxiblas::auto::auto_svd_f64;
///
/// let a = MatBuilder::<f64>::random(50, 30, 42);
/// let (u, s, vt) = auto_svd_f64(a.as_ref());
/// ```
pub fn auto_svd_f64(a: MatRef<'_, f64>) -> (Mat<f64>, Vec<f64>, Mat<f64>) {
    auto_svd_f64_with_algorithm(a, SvdAlgorithm::Auto)
}

/// Compute SVD with specified algorithm (f64).
pub fn auto_svd_f64_with_algorithm(
    a: MatRef<'_, f64>,
    algorithm: SvdAlgorithm,
) -> (Mat<f64>, Vec<f64>, Mat<f64>) {
    let m = a.nrows();
    let n = a.ncols();
    let min_dim = m.min(n);

    let algo = match algorithm {
        SvdAlgorithm::Auto => {
            if min_dim < 100 {
                SvdAlgorithm::Standard
            } else {
                SvdAlgorithm::DivideConquer
            }
        }
        other => other,
    };

    match algo {
        SvdAlgorithm::Standard | SvdAlgorithm::Auto => {
            use oxiblas_lapack::svd::Svd;
            let svd = Svd::compute(a.to_owned()).expect("SVD failed");
            (
                matref_to_mat(svd.u()),
                svd.singular_values().to_vec(),
                matref_to_mat(svd.vt()),
            )
        }
        SvdAlgorithm::DivideConquer => {
            use oxiblas_lapack::svd::SvdDc;
            let svd = SvdDc::compute(a.to_owned()).expect("SVD DC failed");
            (
                matref_to_mat(svd.u()),
                svd.singular_values().to_vec(),
                matref_to_mat(svd.vt()),
            )
        }
    }
}

/// Compute SVD with automatic algorithm selection (f32).
pub fn auto_svd_f32(a: MatRef<'_, f32>) -> (Mat<f32>, Vec<f32>, Mat<f32>) {
    let m = a.nrows();
    let n = a.ncols();
    let min_dim = m.min(n);

    if min_dim < 100 {
        use oxiblas_lapack::svd::Svd;
        let svd = Svd::compute(a.to_owned()).expect("SVD failed");
        (
            matref_to_mat(svd.u()),
            svd.singular_values().to_vec(),
            matref_to_mat(svd.vt()),
        )
    } else {
        use oxiblas_lapack::svd::SvdDc;
        let svd = SvdDc::compute(a.to_owned()).expect("SVD DC failed");
        (
            matref_to_mat(svd.u()),
            svd.singular_values().to_vec(),
            matref_to_mat(svd.vt()),
        )
    }
}

/// Compute eigenvalues with automatic algorithm selection (f64).
///
/// For symmetric matrices, uses efficient symmetric EVD (real eigenvalues only).
/// For general matrices, uses Schur decomposition and returns real parts.
///
/// # Arguments
///
/// * `a` - Square input matrix
/// * `symmetric` - Hint if the matrix is symmetric
///
/// # Returns
///
/// Vector of eigenvalues (real parts for general matrices).
///
/// # Examples
///
/// ```
/// use oxiblas::prelude::*;
/// use oxiblas::auto::auto_eigenvalues_f64;
///
/// let a = MatBuilder::<f64>::random_spd(20, 42);
/// let eigvals = auto_eigenvalues_f64(a.as_ref(), true);
/// ```
pub fn auto_eigenvalues_f64(a: MatRef<'_, f64>, symmetric: bool) -> Vec<f64> {
    let n = a.nrows();
    assert_eq!(n, a.ncols(), "Matrix must be square");

    if symmetric {
        use oxiblas_lapack::evd::SymmetricEvd;
        let evd = SymmetricEvd::compute(a).expect("EVD failed");
        evd.eigenvalues().to_vec()
    } else {
        use oxiblas_lapack::evd::GeneralEvd;
        let evd = GeneralEvd::compute(a).expect("EVD failed");
        // For general matrices, eigenvalues may be complex. Return real parts.
        evd.eigenvalues().iter().map(|e| e.real).collect()
    }
}

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

    #[test]
    fn test_auto_matmul() {
        let a = MatBuilder::<f64>::identity(10);
        let b = MatBuilder::<f64>::hilbert(10);
        let c = auto_matmul(a.as_ref(), b.as_ref());

        // Identity * Hilbert = Hilbert
        for i in 0..10 {
            for j in 0..10 {
                let expected = 1.0 / ((i + j + 1) as f64);
                assert!((c[(i, j)] - expected).abs() < 1e-10);
            }
        }
    }

    #[test]
    fn test_auto_solve_spd() {
        let a = MatBuilder::<f64>::random_spd(10, 42);
        let b = MatBuilder::<f64>::random(10, 1, 43);

        let x = auto_solve_f64(a.as_ref(), b.as_ref()).expect("Solve failed");

        // Verify: A * x ≈ b
        let mut ax = MatBuilder::<f64>::zeros(10, 1);
        auto_gemm(1.0, a.as_ref(), x.as_ref(), 0.0, ax.as_mut());

        for i in 0..10 {
            assert!((ax[(i, 0)] - b[(i, 0)]).abs() < 1e-8);
        }
    }

    #[test]
    fn test_auto_svd() {
        let a = MatBuilder::<f64>::random(20, 10, 42);
        let (u, s, vt) = auto_svd_f64(a.as_ref());

        // Full SVD: U is m×m, Vt is n×n
        assert_eq!(u.nrows(), 20);
        assert_eq!(u.ncols(), 20);
        assert_eq!(s.len(), 10);
        assert_eq!(vt.nrows(), 10);
        assert_eq!(vt.ncols(), 10);

        // Singular values should be non-negative and sorted descending
        for i in 1..s.len() {
            assert!(s[i - 1] >= s[i]);
            assert!(s[i] >= 0.0);
        }
    }

    #[test]
    fn test_auto_eigenvalues_symmetric() {
        let a = MatBuilder::<f64>::random_spd(10, 42);
        let eigvals = auto_eigenvalues_f64(a.as_ref(), true);

        assert_eq!(eigvals.len(), 10);

        // Eigenvalues of SPD should be positive
        for &e in &eigvals {
            assert!(e > 0.0);
        }
    }

    #[test]
    fn test_is_likely_spd() {
        let spd = MatBuilder::<f64>::random_spd(10, 42);
        assert!(is_likely_spd_f64(&spd.as_ref()));
    }
}