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
//! Iterative Refinement for improving linear system solutions
//!
//! This module provides iterative refinement techniques that can improve
//! the accuracy of solutions obtained from direct or iterative solvers.

use crate::array::Array;
use crate::error::{NumRs2Error, Result};
use num_traits::{Float, Zero};

use super::bicgstab::bicgstab;
use super::cg::conjugate_gradient;
use super::core::matvec;

/// Configuration for iterative refinement
#[derive(Debug, Clone)]
pub struct RefinementConfig<T: Float> {
    /// Maximum number of refinement iterations
    pub max_iter: usize,
    /// Convergence tolerance (relative residual)
    pub tol: T,
    /// Minimum improvement ratio to continue (0.5 means residual must reduce by half)
    pub min_improvement: T,
}

impl<T: Float> Default for RefinementConfig<T> {
    fn default() -> Self {
        Self {
            max_iter: 10,
            tol: T::from(1e-12).unwrap_or(T::epsilon()),
            min_improvement: T::from(0.5).unwrap_or(T::one() / (T::one() + T::one())),
        }
    }
}

/// Result of iterative refinement
#[derive(Debug, Clone)]
pub struct RefinementResult<T: Clone> {
    /// Refined solution vector
    pub solution: Array<T>,
    /// Number of refinement iterations performed
    pub iterations: usize,
    /// Initial residual norm (before refinement)
    pub initial_residual: T,
    /// Final residual norm (after refinement)
    pub final_residual: T,
    /// Improvement factor (initial/final residual ratio)
    pub improvement_factor: T,
    /// Whether refinement converged to tolerance
    pub converged: bool,
}

/// Iterative refinement for improving linear system solutions
///
/// Given an initial solution x0 to Ax = b, iteratively improves accuracy by:
/// 1. Computing residual r = b - Ax
/// 2. Solving Ay = r for correction y
/// 3. Updating x = x + y
/// 4. Repeating until convergence
///
/// This is particularly useful for ill-conditioned systems where direct
/// solvers may lose accuracy due to numerical errors.
///
/// # Arguments
///
/// * `a` - Coefficient matrix (n x n)
/// * `b` - Right-hand side vector (n)
/// * `x0` - Initial solution (from a direct solver)
/// * `solver` - Function to solve Ay = r for correction y
/// * `config` - Optional refinement configuration
///
/// # Returns
///
/// A `RefinementResult` containing the refined solution and diagnostics
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::iterative_solvers::*;
///
/// // Create a system Ax = b
/// let a = Array::from_vec(vec![
///     4.0, 1.0,
///     1.0, 3.0,
/// ]).reshape(&[2, 2]);
/// let b = Array::from_vec(vec![1.0, 2.0]);
///
/// // Get initial solution (could be from LU decomposition)
/// let x0 = Array::from_vec(vec![0.0909, 0.6363]); // Approximate solution
///
/// // Refine using CG as the correction solver
/// let result = iterative_refinement(&a, &b, &x0, |mat, rhs| {
///     conjugate_gradient(mat, rhs, None, Some(1e-12), Some(100))
///         .map(|r| r.solution)
/// }, None).expect("iterative refinement should succeed");
///
/// assert!(result.improvement_factor > 1.0); // Solution improved
/// ```
pub fn iterative_refinement<T, F>(
    a: &Array<T>,
    b: &Array<T>,
    x0: &Array<T>,
    solver: F,
    config: Option<RefinementConfig<T>>,
) -> Result<RefinementResult<T>>
where
    T: Float + Clone + Zero + std::fmt::Debug + std::ops::AddAssign,
    F: Fn(&Array<T>, &Array<T>) -> Result<Array<T>>,
{
    let shape = a.shape();
    if shape.len() != 2 || shape[0] != shape[1] {
        return Err(NumRs2Error::InvalidOperation(
            "Matrix must be square".to_string(),
        ));
    }

    let n = shape[0];
    if b.shape() != [n] || x0.shape() != [n] {
        return Err(NumRs2Error::ShapeMismatch {
            expected: vec![n],
            actual: b.shape(),
        });
    }

    let config = config.unwrap_or_default();
    let mut x = x0.clone();

    // Compute initial residual r = b - Ax
    let ax = matvec(a, &x)?;
    let mut residual = compute_residual(b, &ax)?;
    let initial_norm = vector_norm(&residual)?;

    if initial_norm < config.tol {
        // Already converged
        return Ok(RefinementResult {
            solution: x,
            iterations: 0,
            initial_residual: initial_norm,
            final_residual: initial_norm,
            improvement_factor: T::one(),
            converged: true,
        });
    }

    let b_norm = vector_norm(b)?;
    let mut prev_norm = initial_norm;
    let mut iterations = 0;

    for iter in 0..config.max_iter {
        iterations = iter + 1;

        // Solve Ay = r for the correction
        let correction = solver(a, &residual)?;

        // Update solution: x = x + y
        x = array_add(&x, &correction)?;

        // Compute new residual: r = b - Ax
        let ax = matvec(a, &x)?;
        residual = compute_residual(b, &ax)?;
        let current_norm = vector_norm(&residual)?;

        // Check convergence
        let relative_residual = current_norm / b_norm;
        if relative_residual < config.tol {
            return Ok(RefinementResult {
                solution: x,
                iterations,
                initial_residual: initial_norm,
                final_residual: current_norm,
                improvement_factor: initial_norm / current_norm,
                converged: true,
            });
        }

        // Check if improvement is sufficient
        let improvement = prev_norm / current_norm;
        if improvement < config.min_improvement {
            // Stagnating, stop refinement
            return Ok(RefinementResult {
                solution: x,
                iterations,
                initial_residual: initial_norm,
                final_residual: current_norm,
                improvement_factor: initial_norm / current_norm,
                converged: false,
            });
        }

        prev_norm = current_norm;
    }

    let final_norm = vector_norm(&residual)?;
    Ok(RefinementResult {
        solution: x,
        iterations,
        initial_residual: initial_norm,
        final_residual: final_norm,
        improvement_factor: initial_norm / final_norm,
        converged: false,
    })
}

/// Iterative refinement using Conjugate Gradient as the correction solver
///
/// Convenience function that uses CG for the correction step.
/// Best suited for symmetric positive definite systems.
///
/// # Arguments
///
/// * `a` - SPD coefficient matrix (n x n)
/// * `b` - Right-hand side vector (n)
/// * `x0` - Initial solution
/// * `tol` - Convergence tolerance (optional, default 1e-12)
/// * `max_iter` - Maximum refinement iterations (optional, default 10)
///
/// # Examples
///
/// ```
/// use numrs2::prelude::*;
/// use numrs2::linalg::iterative_solvers::*;
///
/// let a = Array::from_vec(vec![4.0, 1.0, 1.0, 3.0]).reshape(&[2, 2]);
/// let b = Array::from_vec(vec![1.0, 2.0]);
/// let x0 = Array::from_vec(vec![0.09, 0.64]); // Approximate
///
/// let result = iterative_refinement_cg(&a, &b, &x0, Some(1e-12), Some(5)).expect("iterative refinement should succeed");
/// assert!(result.improvement_factor >= 1.0);
/// ```
pub fn iterative_refinement_cg<T>(
    a: &Array<T>,
    b: &Array<T>,
    x0: &Array<T>,
    tol: Option<T>,
    max_iter: Option<usize>,
) -> Result<RefinementResult<T>>
where
    T: Float + Clone + Zero + std::fmt::Debug + std::ops::AddAssign,
{
    let config = RefinementConfig {
        max_iter: max_iter.unwrap_or(10),
        tol: tol.unwrap_or(T::from(1e-12).unwrap_or(T::epsilon())),
        min_improvement: T::from(0.5).unwrap_or(T::one() / (T::one() + T::one())),
    };

    iterative_refinement(
        a,
        b,
        x0,
        |mat, rhs| {
            conjugate_gradient(
                mat,
                rhs,
                None,
                Some(T::from(1e-14).unwrap_or(T::epsilon())),
                Some(500),
            )
            .map(|r| r.solution)
        },
        Some(config),
    )
}

/// Iterative refinement using BiCGSTAB as the correction solver
///
/// Convenience function that uses BiCGSTAB for the correction step.
/// Suitable for non-symmetric systems.
///
/// # Arguments
///
/// * `a` - Coefficient matrix (n x n)
/// * `b` - Right-hand side vector (n)
/// * `x0` - Initial solution
/// * `tol` - Convergence tolerance (optional, default 1e-12)
/// * `max_iter` - Maximum refinement iterations (optional, default 10)
pub fn iterative_refinement_bicgstab<T>(
    a: &Array<T>,
    b: &Array<T>,
    x0: &Array<T>,
    tol: Option<T>,
    max_iter: Option<usize>,
) -> Result<RefinementResult<T>>
where
    T: Float + Clone + Zero + std::fmt::Debug + std::ops::AddAssign,
{
    let config = RefinementConfig {
        max_iter: max_iter.unwrap_or(10),
        tol: tol.unwrap_or(T::from(1e-12).unwrap_or(T::epsilon())),
        min_improvement: T::from(0.5).unwrap_or(T::one() / (T::one() + T::one())),
    };

    iterative_refinement(
        a,
        b,
        x0,
        |mat, rhs| {
            bicgstab(
                mat,
                rhs,
                None,
                Some(T::from(1e-14).unwrap_or(T::epsilon())),
                Some(500),
            )
            .map(|r| r.solution)
        },
        Some(config),
    )
}

/// Compute residual vector r = b - ax
fn compute_residual<T>(b: &Array<T>, ax: &Array<T>) -> Result<Array<T>>
where
    T: Float + Clone + Zero,
{
    let n = b.size();
    let mut r = Array::zeros(&[n]);
    for i in 0..n {
        let bi = b.get(&[i])?;
        let axi = ax.get(&[i])?;
        r.set(&[i], bi - axi)?;
    }
    Ok(r)
}

/// Compute 2-norm of a vector
fn vector_norm<T>(v: &Array<T>) -> Result<T>
where
    T: Float + Clone + Zero,
{
    let n = v.size();
    let mut sum = T::zero();
    for i in 0..n {
        let vi = v.get(&[i])?;
        sum = sum + vi * vi;
    }
    Ok(sum.sqrt())
}

/// Add two arrays element-wise
fn array_add<T>(a: &Array<T>, b: &Array<T>) -> Result<Array<T>>
where
    T: Float + Clone + Zero,
{
    let n = a.size();
    let mut result = Array::zeros(&[n]);
    for i in 0..n {
        let ai = a.get(&[i])?;
        let bi = b.get(&[i])?;
        result.set(&[i], ai + bi)?;
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::linalg::iterative_solvers::core::matvec;
    use approx::assert_relative_eq;

    #[test]
    fn test_iterative_refinement_basic() {
        // Well-conditioned SPD system
        let a = Array::from_vec(vec![4.0, 1.0, 1.0, 3.0]).reshape(&[2, 2]);
        let b = Array::from_vec(vec![1.0, 2.0]);

        // True solution is approximately [0.0909, 0.6363]
        // Start with a slightly inaccurate initial guess
        let x0 = Array::from_vec(vec![0.09, 0.64]);

        let result =
            iterative_refinement_cg(&a, &b, &x0, Some(1e-10), Some(5)).expect("Should refine");

        // Refinement should improve the solution
        assert!(result.improvement_factor >= 1.0);

        // Verify refined solution
        let ax = matvec(&a, &result.solution).expect("matvec should work");
        for i in 0..2 {
            assert_relative_eq!(
                ax.get(&[i]).expect("valid"),
                b.get(&[i]).expect("valid"),
                epsilon = 1e-8
            );
        }
    }

    #[test]
    fn test_iterative_refinement_already_converged() {
        let a = Array::from_vec(vec![4.0, 1.0, 1.0, 3.0]).reshape(&[2, 2]);
        let b = Array::from_vec(vec![1.0, 2.0]);

        // Get exact solution using CG first
        let cg_result =
            conjugate_gradient(&a, &b, None, Some(1e-14), Some(100)).expect("Should solve");
        let x0 = cg_result.solution;

        // Refinement should detect already converged
        let result =
            iterative_refinement_cg(&a, &b, &x0, Some(1e-10), Some(5)).expect("Should refine");

        // Should converge immediately or in 1 iteration
        assert!(result.iterations <= 1);
        assert!(result.converged);
    }

    #[test]
    fn test_iterative_refinement_larger_system() {
        // 4x4 SPD system (tridiagonal)
        let a = Array::from_vec(vec![
            4.0, 1.0, 0.0, 0.0, 1.0, 4.0, 1.0, 0.0, 0.0, 1.0, 4.0, 1.0, 0.0, 0.0, 1.0, 4.0,
        ])
        .reshape(&[4, 4]);
        let b = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0]);

        // Poor initial guess
        let x0 = Array::from_vec(vec![0.0, 0.0, 0.0, 0.0]);

        let result =
            iterative_refinement_cg(&a, &b, &x0, Some(1e-10), Some(10)).expect("Should refine");

        // Should converge with improved solution
        assert!(result.improvement_factor > 1.0);

        // Verify solution accuracy
        let ax = matvec(&a, &result.solution).expect("matvec should work");
        for i in 0..4 {
            assert_relative_eq!(
                ax.get(&[i]).expect("valid"),
                b.get(&[i]).expect("valid"),
                epsilon = 1e-8
            );
        }
    }

    #[test]
    fn test_iterative_refinement_bicgstab() {
        // Non-symmetric system
        let a = Array::from_vec(vec![
            4.0, 1.0, 2.0, 3.0, // Not symmetric: a[1,0] != a[0,1]
        ])
        .reshape(&[2, 2]);
        let b = Array::from_vec(vec![1.0, 2.0]);

        // Get initial solution with BiCGSTAB
        let initial = bicgstab(&a, &b, None, Some(1e-4), Some(50)).expect("Should solve");

        // Refine with BiCGSTAB
        let result = iterative_refinement_bicgstab(&a, &b, &initial.solution, Some(1e-10), Some(5))
            .expect("Should refine");

        // Should improve or maintain accuracy
        assert!(result.improvement_factor >= 1.0 || result.final_residual < 1e-8);
    }

    #[test]
    fn test_iterative_refinement_custom_solver() {
        let a = Array::from_vec(vec![4.0, 1.0, 1.0, 3.0]).reshape(&[2, 2]);
        let b = Array::from_vec(vec![1.0, 2.0]);
        let x0 = Array::from_vec(vec![0.0, 0.0]);

        // Use custom solver function
        let result = iterative_refinement(
            &a,
            &b,
            &x0,
            |mat, rhs| {
                // Use CG with high precision
                conjugate_gradient(mat, rhs, None, Some(1e-14), Some(200)).map(|r| r.solution)
            },
            None,
        )
        .expect("Should refine");

        assert!(result.improvement_factor > 1.0);
    }

    #[test]
    fn test_refinement_config() {
        let config: RefinementConfig<f64> = RefinementConfig::default();
        assert_eq!(config.max_iter, 10);
        assert_relative_eq!(config.tol, 1e-12, epsilon = 1e-15);
        assert_relative_eq!(config.min_improvement, 0.5, epsilon = 1e-10);

        // Custom config
        let custom_config = RefinementConfig {
            max_iter: 20,
            tol: 1e-8,
            min_improvement: 0.1,
        };
        assert_eq!(custom_config.max_iter, 20);
    }

    #[test]
    fn test_refinement_result_fields() {
        let a = Array::from_vec(vec![4.0, 1.0, 1.0, 3.0]).reshape(&[2, 2]);
        let b = Array::from_vec(vec![1.0, 2.0]);
        let x0 = Array::from_vec(vec![0.0, 0.0]);

        let result =
            iterative_refinement_cg(&a, &b, &x0, Some(1e-10), Some(5)).expect("Should refine");

        // Check result fields are populated
        assert_eq!(result.solution.size(), 2);
        assert!(result.iterations > 0);
        assert!(result.initial_residual > 0.0);
        assert!(result.final_residual >= 0.0);
        assert!(result.improvement_factor > 0.0);
    }
}