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
// 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/>.
//! Restarted, right-preconditioned GMRES — GMRES(m).
//!
//! The generalised minimal residual method (Saad & Schultz, 1986) for
//! **nonsymmetric** `A x = b`. Each outer cycle builds an `m`-dimensional Krylov
//! subspace by Arnoldi (modified Gram-Schmidt) and minimises the residual 2-norm
//! over that subspace via incremental Givens rotations on the Hessenberg factor;
//! the cycle then **restarts** from the current iterate to bound storage at `m`
//! basis vectors. Total inner iterations are capped at `settings.max_iter`.
//!
//! # Right preconditioning
//!
//! This solver uses **right** preconditioning: it applies GMRES to
//! `A M^{-1} u = b` with `x = M^{-1} u`. The chief practical advantage is that the
//! Krylov residual `b − A M^{-1} u_k` *equals* the true residual `b − A x_k`, so
//! the cheap Givens-rotation residual estimate tracks the genuine residual and the
//! stopping test `||r||₂ / ||b||₂ ≤ tol` needs no correction. The preconditioner
//! is applied once per basis vector inside Arnoldi and once to the accumulated
//! correction at the end of each cycle. All vectors are dimensionless `f64` of
//! length `n_cells`.
//!
//! # Execution backend
//!
//! There is **one** implementation, [`gmres_prepared`](crate::krylov::gmres_prepared()), with the backend as a
//! parameter; [`gmres`](crate::krylov::gmres()) is the convenience adapter for a caller holding a bare
//! [`LduMatrix`](crate::ldu_matrix::LduMatrix), which builds the cell-gather index and runs on
//! [`ComputeBackend::Serial`](crate::compute::ComputeBackend::Serial). The control flow — Arnoldi, the Givens rotations,
//! the `k x k` back substitution — stays on the host exactly as bead
//! `op-yvj.4.4` requires; only the `O(n)` and `O(n_faces)` kernels are
//! dispatched. See [`crate::krylov::bicgstab`]'s module documentation for the
//! determinism contract, which is identical here.
//!
//! # Where GMRES's cost sits, and why that matters for threading
//!
//! GMRES(m) does **one** sparse product per inner iteration but `j + 1` inner
//! products and `j + 1` `axpy`s at Arnoldi step `j`, so by the end of a cycle the
//! vector operations dominate — the opposite balance to BiCGStab, which is two
//! products against a fixed four inner products. Since the vector operations have
//! a size floor 64x higher than the product's
//! ([`VECOP_MIN_ELEMENTS`](crate::ldu_matrix::parallel::VECOP_MIN_ELEMENTS) =
//! 262 144 against
//! [`SPMV_MIN_CELLS`](crate::ldu_matrix::parallel::SPMV_MIN_CELLS) = 4 096),
//! GMRES has **less** to gain than BiCGStab from `CpuMulti` on a mid-sized mesh,
//! and more to gain on a very large one.
//!
//! That is a prediction of the dispatch policy, and it was measured rather than
//! left as a claim. On an asymmetric 7-point-stencil system with Jacobi
//! preconditioning, 4 logical cores, release, `--features parallel`, 2026-08-13
//! (`gmres_end_to_end_speedup_benchmark`, best of 3 solves — taken under heavy
//! load, so these are lower bounds):
//!
//! | Cells | GMRES(30) speed-up | BiCGStab speed-up, same system |
//! |---|---|---|
//! | 4 096 | 0.62-0.75x (a loss) | 0.62-0.81x (a loss) |
//! | 32 768 | 0.99-1.21x | 1.57-1.82x |
//! | 110 592 | 1.26-1.30x | 1.78-1.89x |
//! | 262 144 | 1.68-1.99x | 2.19-2.51x |
//!
//! Ranges span three independent runs of the benchmark (2026-08-13); the third,
//! at load `1.75 1.56 0.89`, measured 0.68x / 1.05x / 1.27x / 1.68x.
//!
//! GMRES is behind BiCGStab at every size and catches up only as the mesh grows
//! past the vector-operation floor, exactly as predicted. Full methodology,
//! repeat runs and limitations are on the benchmark in
//! `crate::krylov::hybrid_tests`.
use Arc;
use ;
use crateComputeBackend;
use crate;
use crateLduMatrix;
/// Below this the Arnoldi vector norm is treated as a "happy breakdown" (the
/// Krylov space is exhausted / the solution lies exactly in the current space).
///
/// `pub(super)` so the flat-reduction reference implementation in
/// [`crate::krylov::hybrid_tests`] shares this exact constant: that reference
/// exists to isolate the *summation order*, so every other constant it uses must
/// provably be the same one, not a copy that could drift.
pub const HAPPY_TOL: f64 = 1.0e-300;
/// Solve `A x = b` with restarted right-preconditioned GMRES(m), serially, from
/// a bare [`LduMatrix`](crate::ldu_matrix::LduMatrix).
///
/// The convenience adapter over [`gmres_prepared`]: it builds the cell-gather
/// index and runs on [`ComputeBackend::Serial`](crate::compute::ComputeBackend::Serial). In a solver loop prefer
/// [`gmres_prepared`](crate::krylov::gmres_prepared()), which reuses a caller-owned index and accepts a backend —
/// see [`crate::krylov::bicgstab`] for the same note in full.
///
/// # Arguments
/// - `a` — sparse system matrix (LDU). May be asymmetric.
/// - `b` — right-hand side, length `n_cells`.
/// - `x0` — optional initial guess; `None` means the zero vector.
/// - `precond` — preconditioner `M^{-1}` applied on the **right**.
/// - `settings` — `tolerance` (relative, on `||r||₂ / ||b||₂`), `max_iter` (total
/// inner-iteration cap), and `restart` = the subspace dimension `m`. A `restart`
/// of `0` is treated as `m = max_iter` (unrestarted up to the cap).
///
/// # Returns
/// `(x, result)` with the final iterate, its **true** relative residual
/// `||b − A x||₂ / ||b||₂`, and whether the tolerance was met. If `b` is exactly
/// zero, returns `x = 0`, `converged = true`, `0` iterations.
/// Solve `A x = b` with restarted right-preconditioned GMRES(m) on a chosen
/// [`ComputeBackend`](crate::compute::ComputeBackend).
///
/// **This is the implementation**; [`gmres`](crate::krylov::gmres()) is a thin adapter onto it.
///
/// # Determinism
///
/// Bitwise identical on [`ComputeBackend::Serial`](crate::compute::ComputeBackend::Serial) and
/// [`ComputeBackend::CpuMulti`] at any thread count — identical iterates,
/// identical Givens residual estimates, identical iteration count. Every kernel
/// it uses carries that guarantee individually.
///
/// # Arguments
///
/// As [`gmres`](crate::krylov::gmres()), plus:
/// - `ldu` — the prepared sparse system, replacing `a`.
/// - `backend` — requested execution backend; degrades rather than failing when
/// unavailable.
///
/// # Storage
///
/// `O(m · n_cells)` for the Arnoldi basis, unchanged by the backend: this
/// function threads the kernels, it does not change the algorithm.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::ldu_matrix::LduMatrix;
/// use outram_foam_basic_lib::ldu_matrix::parallel::HybridLdu;
/// use outram_foam_basic_lib::krylov::{gmres_prepared, KrylovSettings, Preconditioner};
///
/// let mut a = LduMatrix::new(4, vec![0, 1, 2], vec![1, 2, 3]);
/// a.diag = vec![4.0; 4];
/// a.lower = vec![-1.0; 3];
/// a.upper = vec![-2.0; 3];
/// let precond = Preconditioner::ilu0(&a);
/// let ldu = HybridLdu::new(Arc::new(a));
/// let b = vec![1.0, 2.0, 3.0, 4.0];
/// let settings = KrylovSettings::default();
///
/// let (x_ser, r_ser) =
/// gmres_prepared(&ldu, &b, None, &precond, &settings, ComputeBackend::Serial);
/// let (x_par, r_par) =
/// gmres_prepared(&ldu, &b, None, &precond, &settings, ComputeBackend::CpuMulti);
///
/// assert!(r_ser.converged);
/// assert_eq!(x_ser, x_par);
/// assert_eq!(r_ser.n_iterations, r_par.n_iterations);
/// ```
/// [`gmres_prepared`](crate::krylov::gmres_prepared()) with the relative-residual history captured.
///
/// `history` is cleared and then receives the Givens residual estimate
/// `|g[j + 1]| / ||b||₂` after every completed inner iteration — which, because
/// this solver is right-preconditioned, is the *true* relative residual rather
/// than an estimate of it. Crate-internal, for the backend-parity V&V in
/// `crate::krylov::hybrid_tests`; see
/// [`crate::krylov::bicgstab_impl`](super::bicgstab::bicgstab_impl) for why the
/// history is what a parity gate must compare.
pub
/// Compute the Givens rotation `(c, s)` that zeroes `b` in `[a; b]`.
///
/// Returns `(c, s)` such that `[c s; -s c] · [a; b] = [r; 0]` with
/// `r = sqrt(a² + b²)`. Uses a scaling-free direct form (inputs here are already
/// well scaled). For `a = b = 0` returns `(1, 0)` (identity).
///
/// `pub(super)` for the same reason as [`HAPPY_TOL`]: the flat-reduction GMRES
/// reference in [`crate::krylov::hybrid_tests`] calls this very function, so the
/// only difference between it and [`gmres_impl`] is how inner products are summed.
pub