numrs2 0.3.1

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Matrix decomposition functions
//!
//! This module contains matrix decomposition functions extracted from the main linalg module
//! for better organization and modularity. Includes:
//!
//! - QR decomposition (`qr`)
//! - Cholesky decomposition (`cholesky`)
//! - Eigenvalue decomposition (`eig`)
//! - Singular value decomposition (`svd`)
//! - Matrix rank computation (`matrix_rank`)
//!
//! All functions support both feature-gated (with `matrix_decomp`) and non-feature-gated versions
//! to maintain compatibility across different build configurations.

#[allow(unused_imports)] // Used conditionally based on features
use crate::array::Array;
#[allow(unused_imports)] // Used conditionally based on features
use crate::error::{NumRs2Error, Result};
#[allow(unused_imports)] // Used conditionally based on features
use num_traits::Float;
#[allow(unused_imports)] // Used conditionally based on features
use std::fmt::Debug;

/// Compute the rank of a matrix
///
/// Computes the rank of a matrix using singular value decomposition.
/// The rank is determined by counting the number of singular values
/// that are greater than a specified tolerance.
///
/// # Arguments
///
/// * `a` - Input 2D matrix
/// * `tol` - Tolerance for determining rank. If None, uses default tolerance
///   based on machine precision and matrix size
///
/// # Returns
///
/// The rank of the matrix as a usize
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::matrix_rank;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
/// let rank = matrix_rank(&a, None).expect("matrix_rank should succeed");
/// assert_eq!(rank, 2);
/// ```
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub fn matrix_rank<T: Float + Clone + Debug>(a: &Array<T>, tol: Option<T>) -> Result<usize> {
    // Check that the matrix is 2D
    let shape = a.shape();
    if shape.len() != 2 {
        return Err(NumRs2Error::DimensionMismatch(
            "matrix_rank requires a 2D matrix".to_string(),
        ));
    }

    // Compute SVD to get singular values using the proper implementation
    let (_, s, _) = crate::new_modules::matrix_decomp::svd(a)?;

    // Get the tolerance
    let tol_val = match tol {
        Some(t) => t,
        None => {
            // Default is max(M, N) * eps * max(S)
            let m = shape[0];
            let n = shape[1];
            let max_dim = std::cmp::max(m, n);
            let eps = T::epsilon();
            let s_data = s.to_vec();
            let max_s = s_data
                .iter()
                .fold(T::zero(), |max, &val| if val > max { val } else { max });

            T::from(max_dim).unwrap_or_else(|| T::one()) * eps * max_s
        }
    };

    // Count singular values larger than tolerance
    let s_data = s.to_vec();
    let rank = s_data.iter().filter(|&&val| val > tol_val).count();

    Ok(rank)
}

/// Compute the QR decomposition of a matrix
///
/// Performs QR decomposition of a matrix A such that A = Q * R, where
/// Q is an orthogonal matrix and R is an upper triangular matrix.
///
/// # Arguments
///
/// * `a` - Input matrix to decompose
///
/// # Returns
///
/// A tuple (Q, R) where Q is orthogonal and R is upper triangular
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::qr;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
/// let (q, r) = qr(&a).expect("qr should succeed");
/// ```
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub fn qr<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::DivAssign
        + std::ops::SubAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
) -> Result<(Array<T>, Array<T>)> {
    // Use the proper implementation from new_modules
    crate::new_modules::matrix_decomp::qr(a)
}

/// Compute the QR decomposition of a matrix
///
/// Performs QR decomposition of a matrix A such that A = Q * R, where
/// Q is an orthogonal matrix and R is an upper triangular matrix.
///
/// # Arguments
///
/// * `a` - Input matrix to decompose
///
/// # Returns
///
/// A tuple (Q, R) where Q is orthogonal and R is upper triangular
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::qr;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
/// let (q, r) = qr(&a).expect("qr should succeed");
/// ```
#[cfg(not(feature = "matrix_decomp"))]
pub fn qr<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::SubAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
) -> Result<(Array<T>, Array<T>)> {
    a.qr()
}

/// Compute the Cholesky decomposition of a matrix
///
/// Performs Cholesky decomposition of a positive definite matrix A such that
/// A = L * L^T, where L is a lower triangular matrix.
///
/// # Arguments
///
/// * `a` - Input positive definite matrix
///
/// # Returns
///
/// The lower triangular matrix L
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::cholesky;
///
/// // Create a positive definite matrix
/// let a = Array::from_vec(vec![4.0, 2.0, 2.0, 5.0]).reshape(&[2, 2]);
/// let l = cholesky(&a).expect("cholesky should succeed");
/// ```
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub fn cholesky<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::DivAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
) -> Result<Array<T>> {
    // Use the proper implementation from new_modules
    crate::new_modules::matrix_decomp::cholesky(a)
}

/// Compute the Cholesky decomposition of a matrix
///
/// Performs Cholesky decomposition of a positive definite matrix A such that
/// A = L * L^T, where L is a lower triangular matrix.
///
/// # Arguments
///
/// * `a` - Input positive definite matrix
///
/// # Returns
///
/// The lower triangular matrix L
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::cholesky;
///
/// // Create a positive definite matrix
/// let a = Array::from_vec(vec![4.0, 2.0, 2.0, 5.0]).reshape(&[2, 2]);
/// let l = cholesky(&a).expect("cholesky should succeed");
/// ```
#[cfg(not(feature = "matrix_decomp"))]
pub fn cholesky<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::SubAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
) -> Result<Array<T>> {
    a.cholesky()
}

/// Compute the eigenvalues and eigenvectors of a square matrix
///
/// Computes the eigenvalues and eigenvectors of a square matrix.
/// Optionally sorts the results by eigenvalue magnitude.
///
/// # Parameters
///
/// * `a` - The input square matrix
/// * `sort` - Sort eigenvalues and eigenvectors by eigenvalue magnitude.
///   Options: "asc" (ascending), "desc" (descending), or None (no sorting)
///
/// # Returns
///
/// A tuple of (eigenvalues, eigenvectors) where eigenvalues is a 1D array
/// and eigenvectors is a 2D array with eigenvectors as columns
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::eig;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 2.0, 1.0]).reshape(&[2, 2]);
/// let (eigenvals, eigenvecs) = eig(&a, None).expect("eig should succeed");
/// ```
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub fn eig<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::DivAssign
        + std::ops::SubAssign
        + std::fmt::Display
        + 'static,
>(
    a: &Array<T>,
    sort: Option<&str>,
) -> Result<(Array<T>, Array<T>)> {
    // Get the eigenvalues and eigenvectors
    let (eigenvalues, eigenvectors) = a.eig()?;

    // Return if no sorting is requested
    if sort.is_none() {
        return Ok((eigenvalues, eigenvectors));
    }

    let sort_option = sort.expect("sort option already checked for None");

    if sort_option != "asc" && sort_option != "desc" {
        return Err(NumRs2Error::InvalidOperation(format!(
            "Invalid sort option: {}. Must be 'asc', 'desc', or None",
            sort_option
        )));
    }

    // Get the shape of the eigenvectors matrix
    let evec_shape = eigenvectors.shape();

    // Convert eigenvalues to vector for sorting
    let evals_data = eigenvalues.to_vec();
    let n = evals_data.len();

    // Create indices for sorting
    let mut indices: Vec<usize> = (0..n).collect();

    // Sort indices by eigenvalue magnitude
    indices.sort_by(|&i, &j| {
        let a_abs = num_traits::Float::abs(evals_data[i]);
        let b_abs = num_traits::Float::abs(evals_data[j]);

        if sort_option == "asc" {
            a_abs
                .partial_cmp(&b_abs)
                .unwrap_or(std::cmp::Ordering::Equal)
        } else {
            b_abs
                .partial_cmp(&a_abs)
                .unwrap_or(std::cmp::Ordering::Equal)
        }
    });

    // Create sorted eigenvalues array
    let mut sorted_evals = Vec::with_capacity(n);
    for &idx in &indices {
        sorted_evals.push(evals_data[idx]);
    }

    // Create sorted eigenvectors array
    let evecs_data = eigenvectors.to_vec();
    let eigvec_size = evec_shape[0];
    let mut sorted_evecs = Vec::with_capacity(evecs_data.len());

    for &idx in &indices {
        // Extract the eigenvector column
        for i in 0..eigvec_size {
            let evec_idx = i * n + idx;
            sorted_evecs.push(evecs_data[evec_idx]);
        }
    }

    // Convert to Array objects
    let sorted_eigenvalues = Array::from_vec(sorted_evals);
    let sorted_eigenvectors = Array::from_vec(sorted_evecs).reshape(&evec_shape);

    Ok((sorted_eigenvalues, sorted_eigenvectors))
}

/// Compute the eigenvalues and eigenvectors of a square matrix
///
/// Computes the eigenvalues and eigenvectors of a square matrix.
/// Optionally sorts the results by eigenvalue magnitude.
///
/// # Parameters
///
/// * `a` - The input square matrix
/// * `sort` - Sort eigenvalues and eigenvectors by eigenvalue magnitude.
///   Options: "asc" (ascending), "desc" (descending), or None (no sorting)
///
/// # Returns
///
/// A tuple of (eigenvalues, eigenvectors) where eigenvalues is a 1D array
/// and eigenvectors is a 2D array with eigenvectors as columns
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::eig;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 2.0, 1.0]).reshape(&[2, 2]);
/// let (eigenvals, eigenvecs) = eig(&a, None).expect("eig should succeed");
/// ```
#[cfg(not(feature = "matrix_decomp"))]
pub fn eig<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::SubAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
    sort: Option<&str>,
) -> Result<(Array<T>, Array<T>)> {
    // Get the eigenvalues and eigenvectors
    let (eigenvalues, eigenvectors) = a.eig()?;

    // Return if no sorting is requested
    if sort.is_none() {
        return Ok((eigenvalues, eigenvectors));
    }

    let sort_option = sort.expect("sort option already checked for None");

    if sort_option != "asc" && sort_option != "desc" {
        return Err(NumRs2Error::InvalidOperation(format!(
            "Invalid sort option: {}. Must be 'asc', 'desc', or None",
            sort_option
        )));
    }

    // Get the shape of the eigenvectors matrix
    let evec_shape = eigenvectors.shape();

    // Convert eigenvalues to vector for sorting
    let evals_data = eigenvalues.to_vec();
    let n = evals_data.len();

    // Create indices for sorting
    let mut indices: Vec<usize> = (0..n).collect();

    // Sort indices by eigenvalue magnitude
    indices.sort_by(|&i, &j| {
        let a_abs = num_traits::Float::abs(evals_data[i]);
        let b_abs = num_traits::Float::abs(evals_data[j]);

        if sort_option == "asc" {
            a_abs
                .partial_cmp(&b_abs)
                .unwrap_or(std::cmp::Ordering::Equal)
        } else {
            b_abs
                .partial_cmp(&a_abs)
                .unwrap_or(std::cmp::Ordering::Equal)
        }
    });

    // Create sorted eigenvalues array
    let mut sorted_evals = Vec::with_capacity(n);
    for &idx in &indices {
        sorted_evals.push(evals_data[idx]);
    }

    // Create sorted eigenvectors array
    let evecs_data = eigenvectors.to_vec();
    let eigvec_size = evec_shape[0];
    let mut sorted_evecs = Vec::with_capacity(evecs_data.len());

    for &idx in &indices {
        // Extract the eigenvector column
        for i in 0..eigvec_size {
            let evec_idx = i * n + idx;
            sorted_evecs.push(evecs_data[evec_idx]);
        }
    }

    // Convert to Array objects
    let sorted_eigenvalues = Array::from_vec(sorted_evals);
    let sorted_eigenvectors = Array::from_vec(sorted_evecs).reshape(&evec_shape);

    Ok((sorted_eigenvalues, sorted_eigenvectors))
}

/// Compute the singular value decomposition of a matrix
///
/// Performs singular value decomposition of a matrix A such that
/// A = U * S * V^T, where U and V are orthogonal matrices and S is
/// a diagonal matrix containing the singular values.
///
/// # Arguments
///
/// * `a` - Input matrix to decompose
///
/// # Returns
///
/// A tuple (U, S, V^T) where:
/// - U: Left singular vectors (orthogonal matrix)
/// - S: Singular values (1D array)
/// - V^T: Right singular vectors transposed (orthogonal matrix)
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::svd;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
/// let (u, s, vt) = svd(&a).expect("svd should succeed");
/// ```
#[cfg(all(feature = "matrix_decomp", feature = "lapack"))]
pub fn svd<T: Float + Clone + Debug>(a: &Array<T>) -> Result<(Array<T>, Array<T>, Array<T>)> {
    // Use the proper implementation from new_modules
    let (u, s_vec, vt) = crate::new_modules::matrix_decomp::svd(a)?;

    // Convert singular values vector to diagonal matrix
    let m = u.shape()[0];
    let n = vt.shape()[0];
    let k = s_vec.len();
    let mut s = Array::zeros(&[m, n]);
    for i in 0..k.min(m).min(n) {
        let val = s_vec.get(&[i])?;
        // Convert Real to T using NumCast which works for f32/f64
        if let Some(t_val) = num_traits::NumCast::from(val) {
            s.set(&[i, i], t_val)?;
        }
    }

    Ok((u, s, vt))
}

/// Compute the singular value decomposition of a matrix
///
/// Performs singular value decomposition of a matrix A such that
/// A = U * S * V^T, where U and V are orthogonal matrices and S is
/// a diagonal matrix containing the singular values.
///
/// # Arguments
///
/// * `a` - Input matrix to decompose
///
/// # Returns
///
/// A tuple (U, S, V^T) where:
/// - U: Left singular vectors (orthogonal matrix)
/// - S: Singular values (1D array)
/// - V^T: Right singular vectors transposed (orthogonal matrix)
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::svd;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
/// let (u, s, vt) = svd(&a).expect("svd should succeed");
/// ```
#[cfg(not(feature = "matrix_decomp"))]
pub fn svd<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::SubAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
) -> Result<(Array<T>, Array<T>, Array<T>)> {
    a.svd()
}

/// Compute the rank of a matrix
///
/// Computes the rank of a matrix using singular value decomposition.
/// The rank is determined by counting the number of singular values
/// that are greater than a specified tolerance.
///
/// # Arguments
///
/// * `a` - Input 2D matrix
/// * `tol` - Tolerance for determining rank. If None, uses default tolerance
///   based on machine precision and matrix size
///
/// # Returns
///
/// The rank of the matrix as a usize
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::decomposition::matrix_rank;
///
/// let a = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]).reshape(&[2, 2]);
/// let rank = matrix_rank(&a, None).expect("matrix_rank should succeed");
/// assert_eq!(rank, 2);
/// ```
#[cfg(not(feature = "matrix_decomp"))]
pub fn matrix_rank<
    T: Float
        + Clone
        + Debug
        + std::ops::AddAssign
        + std::ops::MulAssign
        + std::ops::SubAssign
        + std::fmt::Display,
>(
    a: &Array<T>,
    tol: Option<T>,
) -> Result<usize> {
    // Check that the matrix is 2D
    let shape = a.shape();
    if shape.len() != 2 {
        return Err(NumRs2Error::DimensionMismatch(
            "matrix_rank requires a 2D matrix".to_string(),
        ));
    }

    // Compute SVD to get singular values using the non-feature-gated implementation
    let (_, s, _) = svd(a)?;

    // Get the tolerance
    let tol_val = match tol {
        Some(t) => t,
        None => {
            // Default is max(M, N) * eps * max(S)
            let m = shape[0];
            let n = shape[1];
            let max_dim = if m > n { m } else { n };
            let eps = T::epsilon();

            // Find max singular value
            let s_data = s.to_vec();
            let max_s = s_data
                .iter()
                .fold(T::zero(), |max, &val| if val > max { val } else { max });

            T::from(max_dim).unwrap_or_else(|| T::one()) * eps * max_s
        }
    };

    // Count singular values larger than tolerance
    let s_data = s.to_vec();
    let rank = s_data.iter().filter(|&&val| val > tol_val).count();

    Ok(rank)
}