scirs2-linalg 0.4.0

Linear algebra module for SciRS2 (scirs2-linalg)
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
//! Parameter validation utilities for linear algebra operations
//!
//! This module provides consistent parameter validation functions that are used
//! throughout the linear algebra library to ensure robust error handling and
//! user-friendly error messages.

use crate::error::{LinalgError, LinalgResult};
use scirs2_core::ndarray::{ArrayView1, ArrayView2};
use scirs2_core::numeric::Float;

/// Validates that a matrix is not empty
///
/// # Arguments
///
/// * `matrix` - The matrix to validate
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if the matrix is not empty
/// * `Err(LinalgError)` if the matrix is empty
#[allow(dead_code)]
pub fn validate_not_emptymatrix<F>(matrix: &ArrayView2<F>, operation: &str) -> LinalgResult<()>
where
    F: Float,
{
    if matrix.is_empty() {
        return Err(LinalgError::ShapeError(format!(
            "{operation} failed: Input matrix cannot be empty"
        )));
    }
    Ok(())
}

/// Validates that a vector is not empty
///
/// # Arguments
///
/// * `vector` - The vector to validate
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if the vector is not empty
/// * `Err(LinalgError)` if the vector is empty
#[allow(dead_code)]
pub fn validate_not_empty_vector<F>(vector: &ArrayView1<F>, operation: &str) -> LinalgResult<()>
where
    F: Float,
{
    if vector.is_empty() {
        return Err(LinalgError::ShapeError(format!(
            "{operation} failed: Input _vector cannot be empty"
        )));
    }
    Ok(())
}

/// Validates that a matrix is square
///
/// # Arguments
///
/// * `matrix` - The matrix to validate
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if the matrix is square
/// * `Err(LinalgError)` if the matrix is not square
#[allow(dead_code)]
pub fn validate_squarematrix<F>(matrix: &ArrayView2<F>, operation: &str) -> LinalgResult<()>
where
    F: Float,
{
    if matrix.nrows() != matrix.ncols() {
        let rows = matrix.nrows();
        let cols = matrix.ncols();
        return Err(LinalgError::ShapeError(format!(
            "{operation} failed: Matrix must be square\\nMatrix shape: {rows}×{cols}\\nExpected: Square matrix (n×n)"
        )));
    }
    Ok(())
}

/// Validates that matrix dimensions are compatible for matrix-vector operations
///
/// # Arguments
///
/// * `matrix` - The matrix
/// * `vector` - The vector
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if dimensions are compatible
/// * `Err(LinalgError)` if dimensions are incompatible
#[allow(dead_code)]
pub fn validatematrix_vector_dimensions<F>(
    matrix: &ArrayView2<F>,
    vector: &ArrayView1<F>,
    operation: &str,
) -> LinalgResult<()>
where
    F: Float,
{
    if matrix.nrows() != vector.len() {
        let matrix_rows = matrix.nrows();
        let matrix_cols = matrix.ncols();
        let vector_len = vector.len();
        return Err(LinalgError::ShapeError(format!(
            "{operation} failed: Matrix and vector dimensions must match\\nMatrix shape: {matrix_rows}×{matrix_cols}\\nVector shape: {vector_len}\\nExpected: Vector length = {matrix_rows}"
        )));
    }
    Ok(())
}

/// Validates that matrix dimensions are compatible for matrix-matrix operations
///
/// # Arguments
///
/// * `matrix_a` - The first matrix
/// * `matrix_b` - The second matrix
/// * `operation` - Name of the operation being performed (for error messages)
/// * `require_same_rows` - Whether the matrices must have the same number of rows
///
/// # Returns
///
/// * `Ok(())` if dimensions are compatible
/// * `Err(LinalgError)` if dimensions are incompatible
#[allow(dead_code)]
pub fn validatematrixmatrix_dimensions<F>(
    matrix_a: &ArrayView2<F>,
    matrix_b: &ArrayView2<F>,
    operation: &str,
    require_same_rows: bool,
) -> LinalgResult<()>
where
    F: Float,
{
    if require_same_rows && matrix_a.nrows() != matrix_b.nrows() {
        let a_rows = matrix_a.nrows();
        let a_cols = matrix_a.ncols();
        let b_rows = matrix_b.nrows();
        let b_cols = matrix_b.ncols();
        return Err(LinalgError::ShapeError(format!(
            "{operation} failed: Matrix _rows must match\\nFirst matrix shape: {a_rows}×{a_cols}\\nSecond matrix shape: {b_rows}×{b_cols}\\nExpected: Same number of _rows"
        )));
    }
    Ok(())
}

/// Validates that all values in a matrix are finite
///
/// # Arguments
///
/// * `matrix` - The matrix to validate
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all values are finite
/// * `Err(LinalgError)` if any value is non-finite
#[allow(dead_code)]
pub fn validate_finitematrix<F>(matrix: &ArrayView2<F>, operation: &str) -> LinalgResult<()>
where
    F: Float,
{
    for &val in matrix.iter() {
        if !val.is_finite() {
            return Err(LinalgError::InvalidInputError(format!(
                "{operation} failed: Matrix contains non-finite values"
            )));
        }
    }
    Ok(())
}

/// Validates that all values in a vector are finite
///
/// # Arguments
///
/// * `vector` - The vector to validate
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all values are finite
/// * `Err(LinalgError)` if any value is non-finite
#[allow(dead_code)]
pub fn validate_finite_vector<F>(vector: &ArrayView1<F>, operation: &str) -> LinalgResult<()>
where
    F: Float,
{
    for &val in vector.iter() {
        if !val.is_finite() {
            return Err(LinalgError::InvalidInputError(format!(
                "{operation} failed: Vector contains non-finite values"
            )));
        }
    }
    Ok(())
}

/// Comprehensive validation for linear system operations (Ax = b)
///
/// Performs all necessary validations for solving linear systems:
/// - Matrix and vector are not empty
/// - Matrix is square
/// - Matrix and vector dimensions are compatible
/// - All values are finite
///
/// # Arguments
///
/// * `matrix` - The coefficient matrix A
/// * `vector` - The right-hand side vector b
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validate_linear_system<F>(
    matrix: &ArrayView2<F>,
    vector: &ArrayView1<F>,
    operation: &str,
) -> LinalgResult<()>
where
    F: Float,
{
    validate_not_emptymatrix(matrix, operation)?;
    validate_not_empty_vector(vector, operation)?;
    validate_squarematrix(matrix, operation)?;
    validatematrix_vector_dimensions(matrix, vector, operation)?;
    validate_finitematrix(matrix, operation)?;
    validate_finite_vector(vector, operation)?;
    Ok(())
}

/// Comprehensive validation for least squares operations (Ax = b with A not necessarily square)
///
/// Performs all necessary validations for least squares problems:
/// - Matrix and vector are not empty
/// - Matrix rows and vector length are compatible
/// - All values are finite
///
/// # Arguments
///
/// * `matrix` - The coefficient matrix A
/// * `vector` - The right-hand side vector b
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validate_least_squares<F>(
    matrix: &ArrayView2<F>,
    vector: &ArrayView1<F>,
    operation: &str,
) -> LinalgResult<()>
where
    F: Float,
{
    validate_not_emptymatrix(matrix, operation)?;
    validate_not_empty_vector(vector, operation)?;
    validatematrix_vector_dimensions(matrix, vector, operation)?;
    validate_finitematrix(matrix, operation)?;
    validate_finite_vector(vector, operation)?;
    Ok(())
}

/// Comprehensive validation for matrix decomposition operations
///
/// Performs all necessary validations for matrix decompositions:
/// - Matrix is not empty
/// - Matrix is square (for decompositions that require it)
/// - All values are finite
///
/// # Arguments
///
/// * `matrix` - The matrix to decompose
/// * `operation` - Name of the operation being performed (for error messages)
/// * `require_square` - Whether the decomposition requires a square matrix
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validate_decomposition<F>(
    matrix: &ArrayView2<F>,
    operation: &str,
    require_square: bool,
) -> LinalgResult<()>
where
    F: Float,
{
    validate_not_emptymatrix(matrix, operation)?;
    if require_square {
        validate_squarematrix(matrix, operation)?;
    }
    validate_finitematrix(matrix, operation)?;
    Ok(())
}

/// Comprehensive validation for multiple linear systems (AX = B)
///
/// Performs all necessary validations for solving multiple linear systems:
/// - Both matrices are not empty
/// - Coefficient matrix is square
/// - Matrix dimensions are compatible
/// - All values are finite
///
/// # Arguments
///
/// * `coeffmatrix` - The coefficient matrix A
/// * `rhsmatrix` - The right-hand sides matrix B
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validate_multiple_linear_systems<F>(
    coeffmatrix: &ArrayView2<F>,
    rhsmatrix: &ArrayView2<F>,
    operation: &str,
) -> LinalgResult<()>
where
    F: Float,
{
    validate_not_emptymatrix(coeffmatrix, operation)?;
    validate_not_emptymatrix(rhsmatrix, operation)?;
    validate_squarematrix(coeffmatrix, operation)?;
    validatematrixmatrix_dimensions(coeffmatrix, rhsmatrix, operation, true)?;
    validate_finitematrix(coeffmatrix, operation)?;
    validate_finitematrix(rhsmatrix, operation)?;
    Ok(())
}

/// Enhanced validation for parameter ranges and values
///
/// This function provides validation for common parameter constraints
/// that appear frequently in linear algebra operations.
///
/// # Arguments
///
/// * `value` - The value to validate
/// * `min` - Minimum allowed value (inclusive, None = no minimum)
/// * `max` - Maximum allowed value (inclusive, None = no maximum)
/// * `operation` - Name of the operation being performed (for error messages)
/// * `parameter_name` - Name of the parameter being validated
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validate_parameter_range<F>(
    value: F,
    min: Option<F>,
    max: Option<F>,
    operation: &str,
    parameter_name: &str,
) -> LinalgResult<()>
where
    F: Float + PartialOrd + std::fmt::Debug,
{
    if !value.is_finite() {
        return Err(LinalgError::InvalidInputError(format!(
            "{operation} failed: Parameter '{parameter_name}' must be finite, got {value:?}"
        )));
    }

    if let Some(min_val) = min {
        if value < min_val {
            return Err(LinalgError::InvalidInputError(format!(
                "{operation} failed: Parameter '{parameter_name}' must be >= {min_val:?}, got {value:?}"
            )));
        }
    }

    if let Some(max_val) = max {
        if value > max_val {
            return Err(LinalgError::InvalidInputError(format!(
                "{operation} failed: Parameter '{parameter_name}' must be <= {max_val:?}, got {value:?}"
            )));
        }
    }

    Ok(())
}

/// Validate iteration parameters commonly used in iterative algorithms
///
/// This function validates parameters that appear frequently in iterative
/// algorithms like solvers and eigenvalue methods.
///
/// # Arguments
///
/// * `max_iterations` - Maximum number of iterations (must be > 0)
/// * `tolerance` - Convergence tolerance (must be > 0)
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validate_iteration_parameters<F>(
    max_iterations: usize,
    tolerance: F,
    operation: &str,
) -> LinalgResult<()>
where
    F: Float + std::fmt::Debug,
{
    if max_iterations == 0 {
        return Err(LinalgError::InvalidInputError(format!(
            "{operation} failed: Maximum _iterations must be > 0, got {max_iterations}"
        )));
    }

    validate_parameter_range(tolerance, Some(F::zero()), None, operation, "tolerance")?;

    if tolerance == F::zero() {
        return Err(LinalgError::InvalidInputError(format!(
            "{operation} failed: Tolerance must be > 0 for convergence, got {tolerance:?}"
        )));
    }

    Ok(())
}

/// Validate matrix dimensions for specific algorithm requirements
///
/// This function provides enhanced validation for matrices that need
/// to meet specific size requirements for certain algorithms.
///
/// # Arguments
///
/// * `matrix` - The matrix to validate
/// * `minsize` - Minimum required size (None = no minimum)
/// * `maxsize` - Maximum allowed size (None = no maximum)  
/// * `required_square` - Whether the matrix must be square
/// * `operation` - Name of the operation being performed (for error messages)
///
/// # Returns
///
/// * `Ok(())` if all validations pass
/// * `Err(LinalgError)` if any validation fails
#[allow(dead_code)]
pub fn validatematrixsize_requirements<F>(
    matrix: &ArrayView2<F>,
    minsize: Option<usize>,
    maxsize: Option<usize>,
    required_square: bool,
    operation: &str,
) -> LinalgResult<()>
where
    F: Float,
{
    validate_not_emptymatrix(matrix, operation)?;

    if required_square {
        validate_squarematrix(matrix, operation)?;
    }

    let (rows, cols) = matrix.dim();
    let size = if required_square {
        rows
    } else {
        std::cmp::max(rows, cols)
    };

    if let Some(min) = minsize {
        if size < min {
            return Err(LinalgError::InvalidInputError(format!(
                "{operation} failed: Matrix size {size} is below minimum required size {min}"
            )));
        }
    }

    if let Some(max) = maxsize {
        if size > max {
            return Err(LinalgError::InvalidInputError(format!(
                "{operation} failed: Matrix size {size} exceeds maximum allowed size {max}"
            )));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::{array, Array2};

    #[test]
    fn test_validate_not_emptymatrix() {
        let emptymatrix = Array2::<f64>::zeros((0, 0));
        let result = validate_not_emptymatrix(&emptymatrix.view(), "test operation");
        assert!(result.is_err());

        let validmatrix = array![[1.0, 2.0], [3.0, 4.0]];
        let result = validate_not_emptymatrix(&validmatrix.view(), "test operation");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_squarematrix() {
        let non_square = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];
        let result = validate_squarematrix(&non_square.view(), "test operation");
        assert!(result.is_err());

        let square = array![[1.0, 2.0], [3.0, 4.0]];
        let result = validate_squarematrix(&square.view(), "test operation");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_finitematrix() {
        let invalidmatrix = array![[1.0, f64::NAN], [3.0, 4.0]];
        let result = validate_finitematrix(&invalidmatrix.view(), "test operation");
        assert!(result.is_err());

        let validmatrix = array![[1.0, 2.0], [3.0, 4.0]];
        let result = validate_finitematrix(&validmatrix.view(), "test operation");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_linear_system() {
        let matrix = array![[1.0, 2.0], [3.0, 4.0]];
        let vector = array![5.0, 6.0];
        let result = validate_linear_system(&matrix.view(), &vector.view(), "test solve");
        assert!(result.is_ok());

        // Test dimension mismatch
        let wrong_vector = array![5.0, 6.0, 7.0];
        let result = validate_linear_system(&matrix.view(), &wrong_vector.view(), "test solve");
        assert!(result.is_err());
    }
}