RustedSciThe 0.4.22

Rust framework for symbolic and numerical computing:BVP ( Newton-Raphson frozen/damped/with collocations ), IVP( BDF, Radau, Backward Euler, LSODE, LSODA, RK45, DoPri), nonlinear equations ( Levenberg, Gavin) and more
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
//! Backend-neutral linear-system boundary.
//!
//! The collocation core sees one contract.  Backend implementations assemble
//! directly into their native storage and own factorization/workspace reuse;
//! dense-to-sparse and sparse-to-banded conversions are not part of the new
//! design.

use super::{
    backends::{BandedBackend, DenseBackend, ReusableSparseExperimentalBackend, SparseBackend},
    config::{BvpSciMatrixLayout, BvpSciSparseFactorization},
    error::BvpSciNewError,
    telemetry::BvpSciTelemetry,
};
use crate::somelinalg::bvp_sparse_lu::ReusableSparseLuStrategy;
use std::collections::HashSet;
use std::sync::{Mutex, OnceLock};

static SUPERLU_FALLBACK_WARNINGS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();

pub trait LinearSystemBackend {
    /// Return the immutable layout selected for this backend instance.
    fn layout(&self) -> BvpSciMatrixLayout;
    /// Return the global collocation system dimension.
    fn dimension(&self) -> usize;
    /// Assemble numeric entries directly into native backend storage.
    fn assemble(&mut self, entries: &[(usize, usize, f64)]) -> Result<(), BvpSciNewError>;
    /// Factor the most recently assembled matrix.
    fn factor(&mut self) -> Result<(), BvpSciNewError>;
    /// Solve in place without allocating a result vector per Newton step.
    fn solve_in_place(&mut self, rhs: &mut [f64]) -> Result<(), BvpSciNewError>;
}

/// Backend selected once for one global collocation system.
///
/// The enum keeps dispatch outside the Newton scalar loops.  Each variant
/// assembles directly into its native matrix representation.
pub enum NativeLinearBackend {
    /// Nalgebra dense matrix/LU path for compact fully coupled systems.
    Dense(DenseBackend),
    /// Faer sparse path; no intermediate dense global matrix is formed.
    Sparse(SparseBackend),
    /// Native band storage selected with explicit lower/upper widths.
    Banded(BandedBackend),
}

impl NativeLinearBackend {
    pub fn new(
        layout: BvpSciMatrixLayout,
        dimension: usize,
        pattern_nnz: usize,
    ) -> Result<Self, BvpSciNewError> {
        if dimension == 0 {
            return Err(BvpSciNewError::InvalidConfiguration(
                "linear system dimension must be positive".into(),
            ));
        }
        // Layout is resolved once per mesh. The Newton loop later calls the
        // enum through one fixed variant, so it never performs conversions or
        // re-evaluates the user's layout policy for individual entries.
        Ok(match layout {
            BvpSciMatrixLayout::Dense => Self::Dense(DenseBackend::new(dimension)),
            BvpSciMatrixLayout::Sparse => Self::Sparse(SparseBackend::new_with_telemetry(
                dimension,
                pattern_nnz,
                BvpSciTelemetry::disabled(),
            )),
            BvpSciMatrixLayout::Banded { lower, upper } => {
                Self::Banded(BandedBackend::new(dimension, lower, upper)?)
            }
        })
    }

    /// Construct a backend with collocation dimensions available to the
    /// bordered-banded route. Dense and Sparse retain the same native paths;
    /// Banded receives the node/state partition and writes directly into
    /// `[T U; V D]` storage.
    pub fn new_for_collocation(
        layout: BvpSciMatrixLayout,
        dimension: usize,
        pattern_nnz: usize,
        state_dimension: usize,
        node_count: usize,
        parameter_dimension: usize,
        telemetry: BvpSciTelemetry,
    ) -> Result<Self, BvpSciNewError> {
        if dimension == 0 {
            return Err(BvpSciNewError::InvalidConfiguration(
                "linear system dimension must be positive".into(),
            ));
        }
        Ok(match layout {
            BvpSciMatrixLayout::Dense => Self::Dense(DenseBackend::new(dimension)),
            BvpSciMatrixLayout::Sparse => Self::Sparse(SparseBackend::new_with_telemetry(
                dimension,
                pattern_nnz,
                telemetry,
            )),
            BvpSciMatrixLayout::Banded { lower, upper } => {
                Self::Banded(BandedBackend::new_for_collocation(
                    dimension,
                    lower,
                    upper,
                    state_dimension,
                    node_count,
                    parameter_dimension,
                    telemetry,
                )?)
            }
        })
    }

    pub fn layout(&self) -> BvpSciMatrixLayout {
        match self {
            Self::Dense(backend) => backend.layout(),
            Self::Sparse(backend) => backend.layout(),
            Self::Banded(backend) => backend.layout(),
        }
    }

    pub fn dimension(&self) -> usize {
        match self {
            Self::Dense(backend) => backend.dimension(),
            Self::Sparse(backend) => backend.dimension(),
            Self::Banded(backend) => backend.dimension(),
        }
    }

    pub fn assemble(&mut self, entries: &[(usize, usize, f64)]) -> Result<(), BvpSciNewError> {
        // `entries` is the only backend-neutral boundary. Implementations
        // validate and write directly into their native storage.
        match self {
            Self::Dense(backend) => backend.assemble(entries),
            Self::Sparse(backend) => backend.assemble(entries),
            Self::Banded(backend) => backend.assemble(entries),
        }
    }

    pub fn factor(&mut self) -> Result<(), BvpSciNewError> {
        match self {
            Self::Dense(backend) => backend.factor(),
            Self::Sparse(backend) => backend.factor(),
            Self::Banded(backend) => backend.factor(),
        }
    }

    pub fn solve_in_place(&mut self, rhs: &mut [f64]) -> Result<(), BvpSciNewError> {
        // All backends mutate the caller-owned Newton RHS. This avoids a
        // result vector allocation on every modified-Newton iteration.
        match self {
            Self::Dense(backend) => backend.solve_in_place(rhs),
            Self::Sparse(backend) => backend.solve_in_place(rhs),
            Self::Banded(backend) => backend.solve_in_place(rhs),
        }
    }
}

/// Private solver dispatch that preserves the public `NativeLinearBackend`
/// variants while supporting optional Sparse factorization policies.
pub(crate) enum BvpSciLinearBackend {
    Standard(NativeLinearBackend),
    ReusableSparseExperimental(ReusableSparseExperimentalBackend),
    #[cfg(feature = "superlu")]
    SuperLu(super::backends::SuperLuBackend),
}

impl BvpSciLinearBackend {
    #[allow(deprecated)]
    pub(crate) fn new_for_collocation(
        layout: BvpSciMatrixLayout,
        dimension: usize,
        pattern_nnz: usize,
        state_dimension: usize,
        node_count: usize,
        parameter_dimension: usize,
        telemetry: BvpSciTelemetry,
        sparse_factorization: BvpSciSparseFactorization,
    ) -> Result<Self, BvpSciNewError> {
        #[allow(deprecated)]
        let wants_superlu = matches!(
            sparse_factorization,
            BvpSciSparseFactorization::SuperLu | BvpSciSparseFactorization::SuperLuExperimental
        );
        if wants_superlu {
            if layout != BvpSciMatrixLayout::Sparse {
                return Err(BvpSciNewError::UnsupportedRoute(
                    "SuperLU factorization requires Sparse matrix layout".into(),
                ));
            }
            #[cfg(feature = "superlu")]
            {
                match super::backends::SuperLuBackend::new(dimension, telemetry.clone()) {
                    Ok(backend) => return Ok(Self::SuperLu(backend)),
                    Err(error) => {
                        return Self::superlu_fallback(
                            layout,
                            dimension,
                            pattern_nnz,
                            state_dimension,
                            node_count,
                            parameter_dimension,
                            telemetry,
                            error.to_string(),
                        );
                    }
                }
            }
            #[cfg(not(feature = "superlu"))]
            {
                return Self::superlu_fallback(
                    layout,
                    dimension,
                    pattern_nnz,
                    state_dimension,
                    node_count,
                    parameter_dimension,
                    telemetry,
                    "crate was compiled without Cargo feature `superlu`".into(),
                );
            }
        }

        let reusable_strategy = match sparse_factorization {
            BvpSciSparseFactorization::ReusableFaerExperimental => {
                Some(ReusableSparseLuStrategy::Auto)
            }
            BvpSciSparseFactorization::ReusableFaerSimplicialExperimental => {
                Some(ReusableSparseLuStrategy::Simplicial)
            }
            BvpSciSparseFactorization::StandardFaer
            | BvpSciSparseFactorization::SuperLu
            | BvpSciSparseFactorization::SuperLuExperimental => None,
        };
        if layout == BvpSciMatrixLayout::Sparse {
            if let Some(reusable_strategy) = reusable_strategy {
                if dimension == 0 {
                    return Err(BvpSciNewError::InvalidConfiguration(
                        "linear system dimension must be positive".into(),
                    ));
                }
                return Ok(Self::ReusableSparseExperimental(
                    ReusableSparseExperimentalBackend::new(
                        dimension,
                        pattern_nnz,
                        telemetry,
                        reusable_strategy,
                    ),
                ));
            }
        }
        Ok(Self::Standard(NativeLinearBackend::new_for_collocation(
            layout,
            dimension,
            pattern_nnz,
            state_dimension,
            node_count,
            parameter_dimension,
            telemetry,
        )?))
    }

    fn superlu_fallback(
        layout: BvpSciMatrixLayout,
        dimension: usize,
        pattern_nnz: usize,
        state_dimension: usize,
        node_count: usize,
        parameter_dimension: usize,
        telemetry: BvpSciTelemetry,
        reason: String,
    ) -> Result<Self, BvpSciNewError> {
        telemetry.record_superlu_fallback();
        let warned = SUPERLU_FALLBACK_WARNINGS.get_or_init(|| Mutex::new(HashSet::new()));
        if let Ok(mut warned) = warned.lock() {
            if warned.insert(reason.clone()) {
                eprintln!(
                    "[BVP_sci] SuperLU was requested but unavailable ({reason}); falling back to StandardFaer Sparse. Enable Cargo feature `superlu` and set SUPERLU_LIBRARY to use SuperLU."
                );
            }
        }
        Ok(Self::Standard(NativeLinearBackend::new_for_collocation(
            layout,
            dimension,
            pattern_nnz,
            state_dimension,
            node_count,
            parameter_dimension,
            telemetry,
        )?))
    }

    pub(crate) fn layout(&self) -> BvpSciMatrixLayout {
        match self {
            Self::Standard(backend) => backend.layout(),
            Self::ReusableSparseExperimental(backend) => backend.layout(),
            #[cfg(feature = "superlu")]
            Self::SuperLu(backend) => backend.layout(),
        }
    }

    pub(crate) fn assemble(
        &mut self,
        entries: &[(usize, usize, f64)],
    ) -> Result<(), BvpSciNewError> {
        match self {
            Self::Standard(backend) => backend.assemble(entries),
            Self::ReusableSparseExperimental(backend) => backend.assemble(entries),
            #[cfg(feature = "superlu")]
            Self::SuperLu(backend) => backend.assemble(entries),
        }
    }

    pub(crate) fn factor(&mut self) -> Result<(), BvpSciNewError> {
        match self {
            Self::Standard(backend) => backend.factor(),
            Self::ReusableSparseExperimental(backend) => backend.factor(),
            #[cfg(feature = "superlu")]
            Self::SuperLu(backend) => backend.factor(),
        }
    }

    pub(crate) fn solve_in_place(&mut self, rhs: &mut [f64]) -> Result<(), BvpSciNewError> {
        match self {
            Self::Standard(backend) => backend.solve_in_place(rhs),
            Self::ReusableSparseExperimental(backend) => backend.solve_in_place(rhs),
            #[cfg(feature = "superlu")]
            Self::SuperLu(backend) => backend.solve_in_place(rhs),
        }
    }
}

impl LinearSystemBackend for NativeLinearBackend {
    fn layout(&self) -> BvpSciMatrixLayout {
        NativeLinearBackend::layout(self)
    }

    fn dimension(&self) -> usize {
        NativeLinearBackend::dimension(self)
    }

    fn assemble(&mut self, entries: &[(usize, usize, f64)]) -> Result<(), BvpSciNewError> {
        NativeLinearBackend::assemble(self, entries)
    }

    fn factor(&mut self) -> Result<(), BvpSciNewError> {
        NativeLinearBackend::factor(self)
    }

    fn solve_in_place(&mut self, rhs: &mut [f64]) -> Result<(), BvpSciNewError> {
        NativeLinearBackend::solve_in_place(self, rhs)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::numerical::BVP_sci::new::BvpSciStatus;

    #[test]
    fn invalid_banded_dimensions_return_typed_configuration_error() {
        let result = NativeLinearBackend::new(
            BvpSciMatrixLayout::Banded {
                lower: usize::MAX,
                upper: 0,
            },
            1,
            0,
        );
        assert!(matches!(
            result,
            Err(BvpSciNewError::InvalidConfiguration(_))
        ));
    }

    #[cfg(not(feature = "superlu"))]
    #[test]
    fn superlu_policy_without_feature_falls_back_to_standard_faer() {
        let telemetry = BvpSciTelemetry::timings();
        let result = BvpSciLinearBackend::new_for_collocation(
            BvpSciMatrixLayout::Sparse,
            2,
            2,
            1,
            2,
            0,
            telemetry.clone(),
            BvpSciSparseFactorization::SuperLu,
        )
        .expect("missing optional SuperLU feature should use StandardFaer");
        assert!(matches!(result, BvpSciLinearBackend::Standard(_)));
        assert_eq!(telemetry.snapshot().superlu_fallbacks, 1);
    }

    #[test]
    fn superlu_fallback_is_sparse_and_observable() {
        let telemetry = BvpSciTelemetry::timings();
        let backend = BvpSciLinearBackend::superlu_fallback(
            BvpSciMatrixLayout::Sparse,
            3,
            3,
            1,
            3,
            0,
            telemetry.clone(),
            "simulated bridge load failure".into(),
        )
        .expect("fallback should construct the StandardFaer sparse route");
        assert!(matches!(&backend, BvpSciLinearBackend::Standard(_)));
        assert_eq!(backend.layout(), BvpSciMatrixLayout::Sparse);
        assert_eq!(telemetry.snapshot().superlu_fallbacks, 1);
    }

    #[test]
    fn singular_banded_factorization_keeps_scipy_status_two() {
        let mut backend =
            NativeLinearBackend::new(BvpSciMatrixLayout::Banded { lower: 2, upper: 2 }, 3, 3)
                .expect("banded backend should construct");
        backend
            .assemble(&[(0, 0, 0.0), (1, 1, 0.0), (2, 2, 0.0)])
            .expect("singular test matrix should assemble");
        let error = backend.factor().expect_err("zero matrix must be singular");
        assert_eq!(error.status(), Some(BvpSciStatus::SingularJacobian));
    }

    #[test]
    fn singular_dense_solve_uses_typed_scipy_status_two() {
        let mut backend = NativeLinearBackend::new(BvpSciMatrixLayout::Dense, 2, 0)
            .expect("dense backend should construct");
        backend
            .assemble(&[(0, 0, 0.0), (1, 1, 0.0)])
            .expect("singular dense matrix should assemble");
        backend
            .factor()
            .expect("dense factorization should be created");
        let error = backend
            .solve_in_place(&mut [1.0, 1.0])
            .expect_err("singular dense solve must fail");
        assert!(matches!(error, BvpSciNewError::SingularJacobian));
        assert_eq!(error.status(), Some(BvpSciStatus::SingularJacobian));
    }

    #[test]
    fn reusable_sparse_backend_refactors_same_pattern_and_solves_in_place() {
        let telemetry = BvpSciTelemetry::timings();
        let mut backend = BvpSciLinearBackend::new_for_collocation(
            BvpSciMatrixLayout::Sparse,
            3,
            5,
            3,
            1,
            0,
            telemetry.clone(),
            BvpSciSparseFactorization::ReusableFaerExperimental,
        )
        .expect("experimental sparse route should construct");

        for scale in [1.0, 2.0] {
            backend
                .assemble(&[
                    (0, 0, 4.0 * scale),
                    (1, 0, 1.0 * scale),
                    (1, 1, 5.0 * scale),
                    (2, 1, 1.0 * scale),
                    (2, 2, 6.0 * scale),
                ])
                .expect("same-pattern sparse matrix should assemble");
            backend
                .factor()
                .expect("numeric factorization should succeed");
            let mut rhs = [1.0 * scale, 2.0 * scale, 3.0 * scale];
            backend
                .solve_in_place(&mut rhs)
                .expect("in-place sparse solve should succeed");
            assert!((rhs[0] - 0.25).abs() < 1e-12);
            assert!((rhs[1] - 0.35).abs() < 1e-12);
            assert!((rhs[2] - 0.44166666666666665).abs() < 1e-12);
        }

        let snapshot = telemetry.snapshot();
        assert_eq!(snapshot.sparse_symbolic_analyses, 1);
        assert_eq!(snapshot.sparse_symbolic_reuses, 1);
        assert_eq!(snapshot.sparse_numeric_factorizations, 2);
        assert_eq!(snapshot.sparse_csc_assemblies, 2);
        assert!(snapshot.validate_contract().is_ok());
    }
}