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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 OUTRAM PARK contributors
//
// This file is part of OUTRAM PARK.
//
// OUTRAM PARK is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// OUTRAM PARK is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with OUTRAM PARK. If not, see <https://www.gnu.org/licenses/>.
//! Bridge from the finite-volume solver settings to the asymmetric Krylov
//! solvers in [`crate::krylov`].
//!
//! [`crate::krylov`] holds solver *kernels* (BiCGStab, restarted GMRES) that
//! speak plain `LduMatrix` + `&[f64]`. The finite-volume layer
//! ([`FvMatrix`](crate::ldu_matrix::FvMatrix),
//! [`FvVectorMatrix`](crate::ldu_matrix::FvVectorMatrix)) speaks
//! [`SolverSettings`] / [`SolverPerformance`]. This module is the thin adapter
//! between the two, plus the two small selection enums that let a caller choose
//! the method and the preconditioner **by value, never by trait object**
//! (workspace design rule).
//!
//! # Why this matters physically
//!
//! Any equation carrying a convection term — momentum, energy, or a transported
//! scalar — assembles an **asymmetric** matrix (`lower[f] != upper[f]`), because
//! upwinding puts the flux on the donor side only. The crate's symmetric
//! machinery (DIC-PCG, GAMG) is therefore inapplicable to those systems, and
//! before this module the only fallback was plain Gauss-Seidel, whose iteration
//! count grows like the condition number `O(kappa)`. BiCGStab/GMRES with an
//! ILU(0) preconditioner is the direct analogue of OpenFOAM's `PBiCGStab` with
//! `DILU`, and converges far faster on the same systems. See
//! `tests/krylov_convection_diffusion.rs` for measured iteration counts.
//!
//! # Units
//!
//! The linear algebra is dimensionless. `A`, `b` and `x` carry whatever units the
//! assembling operator gave them (e.g. for `fvm::laplacian(gamma, T)` the source
//! is `[gamma]·[T]·m`); the solver only ever forms ratios, so no `uom` typing is
//! applied here. Apply units at the field/equation layer.
use Arc;
use crateComputeBackend;
use crate;
use crate;
use crateLduMatrix;
use crateHybridLdu;
/// Which preconditioner `M^{-1} ~ A^{-1}` a Krylov solve should build from the
/// matrix.
///
/// This is a *selection* enum: it carries no data, so it is `Copy` and can sit
/// in a settings struct. The built preconditioner itself is
/// [`crate::krylov::Preconditioner`]. Dispatch is by enum, never a trait object.
/// Which asymmetric Krylov method to run.
///
/// Both handle `lower[f] != upper[f]`; neither requires symmetry or positive
/// definiteness.
/// Extra controls a Krylov solve needs beyond [`SolverSettings`].
///
/// Kept separate from `SolverSettings` deliberately: `SolverSettings` is shared
/// with Gauss-Seidel, PCG and GAMG, and adding fields to it would break every
/// existing struct-literal construction.
///
/// All fields are dimensionless.
/// Solve `A·x = b` with an asymmetric Krylov method, reporting in the
/// finite-volume layer's [`SolverPerformance`] form.
///
/// This is the single entry point that
/// [`FvMatrix::solve_krylov`](crate::ldu_matrix::FvMatrix::solve_krylov) and
/// [`FvVectorMatrix::solve_krylov`](crate::ldu_matrix::FvVectorMatrix::solve_krylov)
/// call; use it directly when you already hold a raw [`LduMatrix`].
///
/// # Arguments
/// - `a` — the sparse system matrix. May be asymmetric (`lower != upper`);
/// symmetric matrices also work but PCG/GAMG are cheaper for those.
/// - `b` — right-hand side, length `a.n_cells`.
/// - `x0` — optional initial guess (e.g. the previous time step's field);
/// `None` starts from zero.
/// - `method` — BiCGStab or GMRES(m).
/// - `options` — preconditioner choice and GMRES restart length.
/// - `settings` — `tolerance` and `max_iter`, shared with the other solvers.
///
/// # Convergence measure
///
/// `SolverPerformance::final_residual` is the **true relative 2-norm residual**
/// `||b − A·x||₂ / ||b||₂` of the returned iterate, recomputed from `a` and `b`
/// — the same measure
/// [`conjugate_gradient`](crate::ldu_matrix::solvers::conjugate_gradient()) reports, and
/// **not** the L1-scaled [`LduMatrix::normalised_residual`] that
/// [`gauss_seidel`](crate::ldu_matrix::solvers::gauss_seidel()) reports. When comparing
/// against Gauss-Seidel, recompute one common measure rather than comparing the
/// two reported numbers directly.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::ldu_matrix::LduMatrix;
/// use outram_foam_basic_lib::ldu_matrix::{
/// krylov_solve, KrylovMethod, KrylovOptions, PreconditionerKind, SolverSettings,
/// };
///
/// // Asymmetric 3-cell chain: upper != lower (an upwinded convection stencil).
/// let mut a = LduMatrix::new(3, vec![0, 1], vec![1, 2]);
/// a.diag = vec![4.0, 4.0, 4.0];
/// a.lower = vec![-2.0, -2.0];
/// a.upper = vec![-1.0, -1.0];
/// let b = vec![1.0, 2.0, 3.0];
///
/// let (x, perf) = krylov_solve(
/// &a,
/// &b,
/// None,
/// KrylovMethod::BiCGStab,
/// KrylovOptions::with_preconditioner(PreconditionerKind::Ilu0),
/// &SolverSettings::default(),
/// );
/// assert!(perf.converged);
///
/// let ax = a.multiply(&x);
/// for i in 0..3 {
/// assert!((ax[i] - b[i]).abs() < 1e-6);
/// }
/// ```
/// Solve `A·x = b` with an asymmetric Krylov method, reusing a caller-owned
/// cell-gather index and a caller-owned preconditioner.
///
/// The form [`krylov_solve`] delegates to, and the one a solver loop should call.
/// It differs only in **what the caller has already prepared**, not in where it
/// runs — the backend is [`KrylovOptions::backend`] in both cases, so this is not
/// a parallel sibling of a serial function.
///
/// # Why prepare anything
///
/// [`krylov_solve`] pays two costs on every call that a repeated solve should not:
///
/// - it clones `a` into an [`Arc`] and rebuilds the
/// `O(n_cells + n_internal_faces)` cell-gather index
/// ([`LduTopology`](crate::ldu_matrix::parallel::LduTopology)), and
/// - it rebuilds the preconditioner, which for
/// [`PreconditionerKind::Ilu0`] is a full incomplete factorisation.
///
/// A finite-volume solver reassembles coefficients every outer iteration while
/// the **mesh addressing never changes**, so it should build the index once and
/// refresh it with [`HybridLdu::with_matrix`], which is an addressing check
/// rather than a rebuild. The preconditioner does have to be rebuilt whenever the
/// coefficients change — ILU(0) factorises them — so it is passed in explicitly
/// rather than silently reused, which would degrade convergence without any
/// visible symptom.
///
/// # Arguments
///
/// - `ldu` — the prepared sparse system.
/// - `b` — right-hand side, length `n_cells`.
/// - `x0` — optional initial guess.
/// - `method` — BiCGStab or GMRES(m).
/// - `precond` — preconditioner built from **these** coefficients.
/// - `options` — GMRES restart length and the execution backend.
/// [`KrylovOptions::preconditioner`] is **ignored** here, because the
/// preconditioner is supplied directly.
/// - `settings` — `tolerance` and `max_iter`.
///
/// # Returns
///
/// As [`krylov_solve`].
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::krylov::Preconditioner;
/// use outram_foam_basic_lib::ldu_matrix::parallel::HybridLdu;
/// use outram_foam_basic_lib::ldu_matrix::{
/// krylov_solve_prepared, KrylovMethod, KrylovOptions, LduMatrix, SolverSettings,
/// };
///
/// let mut a = LduMatrix::new(3, vec![0, 1], vec![1, 2]);
/// a.diag = vec![4.0, 4.0, 4.0];
/// a.lower = vec![-2.0, -2.0];
/// a.upper = vec![-1.0, -1.0];
/// let b = vec![1.0, 2.0, 3.0];
///
/// let precond = Preconditioner::ilu0(&a);
/// let ldu = HybridLdu::new(Arc::new(a));
///
/// let (x, perf) = krylov_solve_prepared(
/// &ldu,
/// &b,
/// None,
/// KrylovMethod::BiCGStab,
/// &precond,
/// KrylovOptions::on_backend(ComputeBackend::CpuMulti),
/// &SolverSettings::default(),
/// );
/// assert!(perf.converged);
///
/// let ax = ldu.spmv(&x, ComputeBackend::Serial);
/// for i in 0..3 {
/// assert!((ax[i] - b[i]).abs() < 1e-6);
/// }
/// ```
// ── Tests ─────────────────────────────────────────────────────────────────────