colmat 0.34.0

Dense and sparse linear algebra for HPC applications with caller owned thread teams.
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
use super::*;
use crate::assert;
/// computes the layout of required workspace for executing the bicgstab
/// algorithm
pub fn bicgstab_scratch<T: ComplexField>(
	left_precond: impl Precond<T>,
	right_precond: impl Precond<T>,
	mat: impl LinOp<T>,
	rhs_ncols: usize,
	par: ParShape,
) -> StackReq {
	fn implementation<T: ComplexField>(
		K1: &dyn Precond<T>,
		K2: &dyn Precond<T>,
		A: &dyn LinOp<T>,
		rhs_ncols: usize,
		par: ParShape,
	) -> StackReq {
		let n = A.nrows();
		let k = rhs_ncols;
		let nk = temp_mat_scratch::<T>(n, k);
		let kk = temp_mat_scratch::<T>(k, k);
		let k_usize = StackReq::new::<usize>(k);
		let lu = crate::linalg::lu::full_pivoting::factor::lu_in_place_scratch::<
			usize,
			T,
		>(k, k, par, Default::default());
		StackReq::all_of(&[
			k_usize,
			k_usize,
			k_usize,
			k_usize,
			kk,
			nk,
			nk,
			nk,
			nk,
			nk,
			nk,
			nk,
			nk,
			StackReq::any_of(&[
				lu,
				A.apply_scratch(k, par),
				StackReq::all_of(&[
					nk,
					K1.apply_scratch(k, par),
					K2.apply_scratch(k, par),
				]),
				StackReq::all_of(&[kk, kk]),
				kk,
			]),
		])
	}
	implementation(&left_precond, &right_precond, &mat, rhs_ncols, par)
}
/// algorithm parameters
#[derive(Copy, Clone, Debug)]
pub struct BicgParams<T> {
	/// whether the initial guess is implicitly zero or not
	pub initial_guess: InitialGuessStatus,
	/// absolute tolerance for convergence testing
	pub abs_tolerance: T,
	/// relative tolerance for convergence testing
	pub rel_tolerance: T,
	/// maximum number of iterations
	pub max_iters: usize,
	#[doc(hidden)]
	pub non_exhaustive: NonExhaustive,
}
impl<T: RealField> Default for BicgParams<T> {
	#[inline]
	fn default() -> Self {
		Self {
			initial_guess: InitialGuessStatus::MaybeNonZero,
			abs_tolerance: zero(),
			rel_tolerance: eps::<T>() * from_f64::<T>(128.0),
			max_iters: usize::MAX,
			non_exhaustive: NonExhaustive(()),
		}
	}
}
/// algorithm result
#[derive(Copy, Clone, Debug)]
pub struct BicgInfo<T> {
	/// absolute residual at the final step
	pub abs_residual: T,
	/// relative residual at the final step
	pub rel_residual: T,
	/// number of iterations executed by the algorithm
	pub iter_count: usize,
	/// whether the callback requested an early stop (not a convergence claim)
	pub stopped: bool,
	#[doc(hidden)]
	pub non_exhaustive: NonExhaustive,
}
/// algorithm error
///
/// Both variants carry the residual of the last finite iterate, so a caller can restart
/// from the returned `out`. A [`Breakdown`](BicgError::Breakdown) is a numerical
/// breakdown (a vanishing direction, `rho`/`alpha`/`omega` in the scalar recurrences);
/// [`NoConvergence`](BicgError::NoConvergence) means `max_iters` was reached.
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub enum BicgError<T> {
	/// convergence failure: `max_iters` was reached
	NoConvergence {
		/// absolute residual at the final step
		abs_residual: T,
		/// relative residual at the final step
		rel_residual: T,
	},
	/// numerical breakdown: a direction or a step vanished
	///
	/// In the scalar recurrences this is `rho = 0`, `alpha = 0` or `omega = 0`; in this
	/// block implementation it is the equivalent rank test on `r̃ᵀ v`, a half step that is
	/// not finite, or a new residual that is not finite. The last finite iterate stays in
	/// `out`, and one usually restarts from it rather than raising `max_iters`.
	Breakdown {
		/// absolute residual at the last finite iterate
		abs_residual: T,
		/// relative residual at the last finite iterate
		rel_residual: T,
		/// number of iterations executed, the breakdown included
		iter_count: usize,
	},
}
/// executes bicgstab using the provided preconditioners
///
/// # note
/// this function is also optimized for a rhs with multiple columns
///
/// The callback runs after an update and may return `()` to continue or
/// `core::ops::ControlFlow<()>` to request a stop. A stopped iterate remains in
/// `out`; the returned info has `stopped = true` and does not imply convergence.
/// Initial convergence needs no update and does not call the callback, and a
/// numerical breakdown does not call it either: the last finite iterate (a kept
/// half step included) remains in `out` and the error carries its residual.
///
/// # Errors
/// Returns [`BicgError::Breakdown`] when the iteration breaks down -- the rank test on
/// `r̃ᵀ v` reports no direction left, the half step is not finite, or the new residual is
/// not finite -- and [`BicgError::NoConvergence`] when `max_iters` is reached first. Both
/// carry the residual of the last finite iterate.
#[track_caller]
pub fn bicgstab<T: ComplexField, C: IterationControl>(
	out: MatMut<'_, T>,
	left_precond: impl Precond<T>,
	right_precond: impl Precond<T>,
	mat: impl LinOp<T>,
	rhs: MatRef<'_, T>,
	params: BicgParams<T::Real>,
	mut callback: impl FnMut(MatRef<'_, T>) -> C,
	par: Par,
	stack: &mut MemStack,
) -> Result<BicgInfo<T::Real>, BicgError<T::Real>> {
	#[track_caller]
	fn implementation<T: ComplexField>(
		out: MatMut<'_, T>,
		left_precond: &dyn Precond<T>,
		right_precond: &dyn Precond<T>,
		mat: &dyn LinOp<T>,
		rhs: MatRef<'_, T>,
		params: BicgParams<T::Real>,
		callback: &mut dyn FnMut(MatRef<'_, T>) -> bool,
		mut par: Par,
		stack: &mut MemStack,
	) -> Result<BicgInfo<T::Real>, BicgError<T::Real>> {
		let mut x = out;
		let A = mat;
		let K1 = left_precond;
		let K2 = right_precond;
		let b = rhs;
		assert!(A.nrows() == A.ncols());
		let n = A.nrows();
		let k = x.ncols();
		let ref b_norm = b.norm_l2();
		if *b_norm == zero::<T::Real>() {
			x.fill(zero());
			return Ok(BicgInfo {
				abs_residual: zero::<T::Real>(),
				rel_residual: zero::<T::Real>(),
				iter_count: 0,
				stopped: false,
				non_exhaustive: NonExhaustive(()),
			});
		}
		if params.initial_guess == InitialGuessStatus::Zero {
			// every exit returns `x`, so an implicit zero is written out once
			// here
			x.fill(zero());
		}
		let rel_threshold = params.rel_tolerance * b_norm;
		let abs_threshold = params.abs_tolerance;
		let threshold = if abs_threshold > rel_threshold {
			abs_threshold
		} else {
			rel_threshold
		};
		let (row_perm, stack) = unsafe { stack.make_raw::<usize>(k) };
		let (row_perm_inv, stack) = unsafe { stack.make_raw::<usize>(k) };
		let (col_perm, stack) = unsafe { stack.make_raw::<usize>(k) };
		let (col_perm_inv, stack) = unsafe { stack.make_raw::<usize>(k) };
		let (mut rtv, stack) =
			unsafe { temp_mat_uninit::<T, _, _>(k, k, stack) };
		let mut rtv = rtv.as_mat_mut();
		let (mut r, stack) = unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
		let mut r = r.as_mat_mut();
		let (mut p, stack) = unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
		let mut p = p.as_mat_mut();
		let (mut r_tilde, stack) =
			unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
		let mut r_tilde = r_tilde.as_mat_mut();
		let mut abs_residual =
			if params.initial_guess == InitialGuessStatus::MaybeNonZero {
				A.apply(r.rb_mut(), x.rb(), par.reborrow(), stack);
				z!(&mut r, &b).for_each(|uz!(r, b)| *r = b - &*r);
				r.norm_l2()
			} else {
				r.copy_from(&b);
				b_norm.copy()
			};
		if abs_residual < threshold {
			return Ok(BicgInfo {
				rel_residual: &abs_residual / b_norm,
				abs_residual,
				iter_count: 0,
				stopped: false,
				non_exhaustive: NonExhaustive(()),
			});
		}
		p.copy_from(&r);
		r_tilde.copy_from(&r);
		// the iteration a numerical breakdown stopped at, if one did: it is what tells
		// the two error variants apart (`max_iters` exhaustion is the other one)
		let mut breakdown = None;
		for iter in 0..params.max_iters {
			let (mut v, stack) =
				unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
			let mut v = v.as_mat_mut();
			let (mut y, stack) =
				unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
			let mut y = y.as_mat_mut();
			{
				let (mut y0, stack) =
					unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
				let mut y0 = y0.as_mat_mut();
				K1.apply(y0.rb_mut(), p.rb(), par.reborrow(), stack);
				K2.apply(y.rb_mut(), y0.rb(), par.reborrow(), stack);
			}
			A.apply(v.rb_mut(), y.rb(), par.reborrow(), stack);
			crate::linalg::matmul::matmul(
				rtv.rb_mut(),
				Accum::Replace,
				r_tilde.rb().transpose(),
				v.rb(),
				one::<T>(),
				par.reborrow(),
			);
			let (_, row_perm, col_perm) =
				crate::linalg::lu::full_pivoting::factor::lu_in_place(
					rtv.rb_mut(),
					row_perm,
					row_perm_inv,
					col_perm,
					col_perm_inv,
					par.reborrow(),
					stack,
					Default::default(),
				);
			// the tolerance is relative to what an entry of `r̃ᵀ v` could be,
			// not to its own largest pivot: otherwise a zero first pivot
			// passes and the step divides by zero
			let max_col_norm = |m: MatRef<'_, T>| {
				let mut max = zero::<T::Real>();
				for j in 0..k {
					let norm = m.col(j).norm_l2();
					if norm > max {
						max = norm;
					}
				}
				max
			};
			let mut rank = k;
			let tol = eps::<T::Real>()
				* from_f64::<T::Real>(k as f64)
				* max_col_norm(r_tilde.rb())
				* max_col_norm(v.rb());
			for i in 0..k {
				if !(rtv[(i, i)].abs() > tol) {
					rank = i;
					break;
				}
			}
			if rank == 0 {
				// breakdown: no direction left; `x` is the last iterate and `r`
				// its residual
				breakdown = Some(iter + 1);
				break;
			}
			let s_norm;
			let (mut s, stack) =
				unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
			let mut s = s.as_mat_mut();
			{
				let (mut rtr, stack) =
					unsafe { temp_mat_uninit::<T, _, _>(k, k, stack) };
				let mut rtr = rtr.as_mat_mut();
				crate::linalg::matmul::matmul(
					rtr.rb_mut(),
					Accum::Replace,
					r_tilde.rb().transpose(),
					r.rb(),
					one::<T>(),
					par.reborrow(),
				);
				let (mut temp, _) =
					unsafe { temp_mat_uninit::<T, _, _>(k, k, stack) };
				let mut temp = temp.as_mat_mut();
				crate::perm::permute_rows(temp.rb_mut(), rtr.rb(), row_perm);
				crate::linalg::triangular_solve::solve_unit_lower_triangular_in_place(
					rtv.rb().get(..rank, ..rank),
					temp.rb_mut().get_mut(..rank, ..),
					par.reborrow(),
				);
				crate::linalg::triangular_solve::solve_upper_triangular_in_place(
					rtv.rb().get(..rank, ..rank),
					temp.rb_mut().get_mut(..rank, ..),
					par.reborrow(),
				);
				temp.rb_mut().get_mut(rank.., ..).fill(zero());
				crate::perm::permute_rows(
					rtr.rb_mut(),
					temp.rb(),
					col_perm.inverse(),
				);
				let alpha = rtr.rb();
				s.copy_from(&r);
				crate::linalg::matmul::matmul(
					s.rb_mut(),
					Accum::Add,
					v.rb(),
					alpha.rb(),
					-one::<T>(),
					par.reborrow(),
				);
				s_norm = s.norm_l2();
				if !s_norm.is_finite() {
					// the step is not usable: keep `x` and `r` as they are
					breakdown = Some(iter + 1);
					break;
				}
				crate::linalg::matmul::matmul(
					x.rb_mut(),
					if iter == 0
						&& params.initial_guess == InitialGuessStatus::Zero
					{
						Accum::Replace
					} else {
						Accum::Add
					},
					y.rb(),
					alpha.rb(),
					one::<T>(),
					par.reborrow(),
				);
			}
			if s_norm < threshold {
				return Ok(BicgInfo {
					rel_residual: &s_norm / b_norm,
					abs_residual: s_norm,
					iter_count: iter + 1,
					stopped: callback(x.rb()),
					non_exhaustive: NonExhaustive(()),
				});
			}
			let (mut t, stack) =
				unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
			let mut t = t.as_mat_mut();
			let (mut z, stack) =
				unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
			let mut z = z.as_mat_mut();
			{
				let (mut z0, stack) =
					unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
				let mut z0 = z0.as_mat_mut();
				K1.apply(z0.rb_mut(), s.rb(), par.reborrow(), stack);
				K2.apply(z.rb_mut(), z0.rb(), par.reborrow(), stack);
			}
			A.apply(t.rb_mut(), z.rb(), par.reborrow(), stack);
			let compute_w = |kt: MatRef<'_, T>, ks: MatRef<'_, T>| {
				let mut wt = zero::<T>();
				let mut ws = zero::<T>();
				for j in 0..k {
					let kt = kt.rb().col(j);
					let ks = ks.rb().col(j);
					ws = ws + kt.transpose() * ks;
					wt = wt + kt.transpose() * kt;
				}
				wt.recip() * ws
			};
			let ref w = {
				let mut kt = y;
				let (mut ks, stack) =
					unsafe { temp_mat_uninit::<T, _, _>(n, k, stack) };
				let mut ks = ks.as_mat_mut();
				K1.apply(kt.rb_mut(), t.rb(), par.reborrow(), stack);
				K1.apply(ks.rb_mut(), s.rb(), par.reborrow(), stack);
				compute_w(kt.rb(), ks.rb())
			};
			z!(&mut r, &s, &t).for_each(|uz!(r, s, t)| *r = s - w * t);
			let norm = r.norm_l2();
			if !norm.is_finite() {
				// `x` keeps the first half step, whose residual is `s`
				abs_residual = s_norm;
				breakdown = Some(iter + 1);
				break;
			}
			z!(&mut x, &z).for_each(|uz!(x, z)| *x += w * z);
			z!(&mut p, &v).for_each(|uz!(p, v)| *p -= w * v);
			if callback(x.rb()) {
				return Ok(BicgInfo {
					rel_residual: &norm / b_norm,
					abs_residual: norm,
					iter_count: iter + 1,
					stopped: true,
					non_exhaustive: NonExhaustive(()),
				});
			}
			abs_residual = norm.copy();
			if norm < threshold {
				return Ok(BicgInfo {
					rel_residual: &norm / b_norm,
					abs_residual: norm,
					iter_count: iter + 1,
					stopped: false,
					non_exhaustive: NonExhaustive(()),
				});
			}
			let (mut rtt, stack) =
				unsafe { temp_mat_uninit::<T, _, _>(k, k, stack) };
			let mut rtt = rtt.as_mat_mut();
			{
				crate::linalg::matmul::matmul(
					rtt.rb_mut(),
					Accum::Replace,
					r_tilde.rb().transpose(),
					t.rb(),
					one::<T>(),
					par.reborrow(),
				);
				let (mut temp, _) =
					unsafe { temp_mat_uninit::<T, _, _>(k, k, stack) };
				let mut temp = temp.as_mat_mut();
				crate::perm::permute_rows(temp.rb_mut(), rtt.rb(), row_perm);
				crate::linalg::triangular_solve::solve_unit_lower_triangular_in_place(
					rtv.rb().get(..rank, ..rank),
					temp.rb_mut().get_mut(..rank, ..),
					par.reborrow(),
				);
				crate::linalg::triangular_solve::solve_upper_triangular_in_place(
					rtv.rb().get(..rank, ..rank),
					temp.rb_mut().get_mut(..rank, ..),
					par.reborrow(),
				);
				temp.rb_mut().get_mut(rank.., ..).fill(zero());
				crate::perm::permute_rows(
					rtt.rb_mut(),
					temp.rb(),
					col_perm.inverse(),
				);
			}
			let beta = rtt.rb();
			let mut tmp = v;
			crate::linalg::matmul::matmul(
				tmp.rb_mut(),
				Accum::Replace,
				p.rb(),
				beta.rb(),
				one::<T>(),
				par.reborrow(),
			);
			z!(&mut p, &r, &tmp).for_each(|uz!(p, r, tmp)| *p = r - tmp);
		}
		if let Some(iter_count) = breakdown {
			return Err(BicgError::Breakdown {
				rel_residual: &abs_residual / b_norm,
				abs_residual,
				iter_count,
			});
		}
		Err(BicgError::NoConvergence {
			rel_residual: &abs_residual / b_norm,
			abs_residual,
		})
	}
	implementation(
		out,
		&left_precond,
		&right_precond,
		&mat,
		rhs,
		params,
		&mut |x| callback(x).should_stop(),
		par,
		stack,
	)
}
#[cfg(test)]
mod tests {
	use super::*;
	use crate::stats::prelude::*;
	use dyn_stack::MemBuffer;
	use equator::assert;
	#[test]
	fn test_bicgstab() {
		let ref mut rng = StdRng::seed_from_u64(0);
		let ref A = mat![[2.5, -1.0], [1.0, 3.1]];
		let ref sol = mat![[2.1, 2.1], [4.1, 3.2]];
		let ref rhs = A * sol;
		let ref mut diag = Mat::<f64>::identity(2, 2);
		for i in 0..2 {
			diag[(i, i)] = f64::exp(StandardUniform.sample(rng));
		}
		let ref diag = *diag;
		let ref mut out = Mat::<f64>::zeros(2, sol.ncols());
		let mut params = BicgParams::default();
		params.max_iters = 10;
		let result = bicgstab(
			out.as_mut(),
			diag.as_ref(),
			diag.as_ref(),
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				diag.as_ref(),
				diag.as_ref(),
				A.as_ref(),
				sol.ncols(),
				ParShape::Seq,
			))),
		);
		let ref out = *out;
		assert!(result.is_ok());
		assert!(
			(A * out - rhs).norm_l2() <= params.rel_tolerance * rhs.norm_l2()
		);
	}
	#[test]
	fn codeberg_326() {
		let ref A = mat![[2.0]];
		let ref rhs = mat![[2.0]];
		let precond = IdentityPrecond { dim: 1 };
		let params = BicgParams {
			initial_guess: InitialGuessStatus::Zero,
			max_iters: 10, // unfixed code looped infinitely
			..BicgParams::default()
		};
		let req = bicgstab_scratch(precond, precond, A.as_ref(), 1, ParShape::Seq);
		for fill in [0x00u8, 0x3F, 0xFF] {
			// the workspace is uninitialized memory: any byte pattern must work
			let mut buffer = alloc::vec![
				core::mem::MaybeUninit::new(fill);
				req.unaligned_bytes_required()
			];
			let ref mut out = Mat::<f64>::zeros(1, 1);
			let result = bicgstab(
				out.as_mut(),
				precond,
				precond,
				A.as_ref(),
				rhs.as_ref(),
				params,
				|_| {},
				Par::Seq,
				MemStack::new(&mut buffer),
			);
			let _info = result.unwrap();
			assert!((out[(0, 0)] - 1.0).abs() < 1e-10);
		}
	}
	#[test]
	fn codeberg_328() {
		// one step does not converge: the error carries the residual of the
		// returned `x`
		let ref A = mat![[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]];
		let ref rhs = mat![[1.0], [1.0], [1.0]];
		let precond = IdentityPrecond { dim: 3 };
		let params = BicgParams {
			max_iters: 1,
			..BicgParams::default()
		};
		let ref mut out = Mat::<f64>::zeros(3, 1);
		let result = bicgstab(
			out.as_mut(),
			precond,
			precond,
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				precond,
				precond,
				A.as_ref(),
				1,
				ParShape::Seq,
			))),
		);
		let err = result.unwrap_err();
		let BicgError::NoConvergence {
			abs_residual,
			rel_residual,
		} = err
		else {
			panic!("expected NoConvergence, got {err:?}");
		};
		let true_residual = (rhs - A * &*out).norm_l2();
		assert!((abs_residual - true_residual).abs() < 1e-12);
		assert!((rel_residual - true_residual / rhs.norm_l2()).abs() < 1e-12);
		assert!(abs_residual < 0.5);
	}
	#[test]
	fn codeberg_327() {
		// after one step `r̃ᵀ r = 0`, so the next `r̃ᵀ v` is zero: a breakdown
		let ref A = mat![[1.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, -1.0, 1.0]];
		let ref rhs = mat![[1.0], [0.0], [0.0]];
		let precond = IdentityPrecond { dim: 3 };
		for initial_guess in
			[InitialGuessStatus::MaybeNonZero, InitialGuessStatus::Zero]
		{
			let params = BicgParams {
				initial_guess,
				max_iters: 10,
				..BicgParams::default()
			};
			let ref mut out = Mat::<f64>::zeros(3, 1);
			let result = bicgstab(
				out.as_mut(),
				precond,
				precond,
				A.as_ref(),
				rhs.as_ref(),
				params,
				|_| {},
				Par::Seq,
				MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
					precond,
					precond,
					A.as_ref(),
					1,
					ParShape::Seq,
				))),
			);
			let err = result.unwrap_err();
			let BicgError::Breakdown {
				abs_residual,
				iter_count,
				..
			} = err
			else {
				panic!("expected Breakdown, got {err:?}");
			};
			assert!(iter_count >= 1);
			assert!(out.norm_l2().is_finite());
			let true_residual = (rhs - A * &*out).norm_l2();
			assert!((abs_residual - true_residual).abs() < 1e-12);
		}
	}
	#[test]
	fn breakdown_when_the_operator_maps_the_direction_to_zero() {
		// `A r̃ = 0`, so `v = 0` and the tolerance is zero: still a breakdown
		let ref A = mat![[0.0, 0.0], [0.0, 1.0]];
		let ref rhs = mat![[1.0], [0.0]];
		let precond = IdentityPrecond { dim: 2 };
		let params = BicgParams {
			max_iters: 10,
			..BicgParams::default()
		};
		let ref mut out = Mat::<f64>::zeros(2, 1);
		let result = bicgstab(
			out.as_mut(),
			precond,
			precond,
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				precond,
				precond,
				A.as_ref(),
				1,
				ParShape::Seq,
			))),
		);
		let err = result.unwrap_err();
		let BicgError::Breakdown { abs_residual, .. } = err else {
			panic!("expected Breakdown, got {err:?}");
		};
		assert!(out.norm_l2() == 0.0);
		assert!(abs_residual == 1.0);
	}
	#[test]
	fn breakdown_on_the_first_step_with_a_zero_guess() {
		// `r̃ᵀ A r̃ = 0` at once; a zero initial guess must come back as zeros,
		// not as the caller's buffer
		let ref A = mat![[0.0, 1.0], [-1.0, 0.0]];
		let ref rhs = mat![[1.0], [0.0]];
		let precond = IdentityPrecond { dim: 2 };
		let params = BicgParams {
			initial_guess: InitialGuessStatus::Zero,
			max_iters: 10,
			..BicgParams::default()
		};
		let ref mut out = Mat::<f64>::full(2, 1, f64::NAN);
		let result = bicgstab(
			out.as_mut(),
			precond,
			precond,
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				precond,
				precond,
				A.as_ref(),
				1,
				ParShape::Seq,
			))),
		);
		let err = result.unwrap_err();
		let BicgError::Breakdown { abs_residual, .. } = err else {
			panic!("expected Breakdown, got {err:?}");
		};
		assert!(out.norm_l2() == 0.0);
		assert!(abs_residual == 1.0);
	}
	#[test]
	fn nonfinite_second_half_step_keeps_the_first() {
		// `A s = 0`, so `w` is 0 / 0: `x` keeps the alpha step, whose residual
		// is `s`
		let ref A = mat![[2.0, 0.0], [1.0, 0.0]];
		let ref rhs = mat![[1.0], [0.0]];
		let precond = IdentityPrecond { dim: 2 };
		let params = BicgParams {
			max_iters: 10,
			..BicgParams::default()
		};
		let ref mut out = Mat::<f64>::zeros(2, 1);
		let result = bicgstab(
			out.as_mut(),
			precond,
			precond,
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				precond,
				precond,
				A.as_ref(),
				1,
				ParShape::Seq,
			))),
		);
		let err = result.unwrap_err();
		let BicgError::Breakdown { abs_residual, .. } = err else {
			panic!("expected Breakdown, got {err:?}");
		};
		assert!(out.norm_l2().is_finite());
		assert!((abs_residual - (rhs - A * &*out).norm_l2()).abs() < 1e-12);
		assert!((abs_residual - 0.5).abs() < 1e-12);
	}
	#[test]
	fn zero_guess_is_written_out_without_an_iteration() {
		let ref A = mat![[1.0]];
		let ref rhs = mat![[1.0]];
		let precond = IdentityPrecond { dim: 1 };
		let params = BicgParams {
			initial_guess: InitialGuessStatus::Zero,
			max_iters: 0,
			..BicgParams::default()
		};
		let ref mut out = Mat::<f64>::full(1, 1, 7.0);
		let result = bicgstab(
			out.as_mut(),
			precond,
			precond,
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				precond,
				precond,
				A.as_ref(),
				1,
				ParShape::Seq,
			))),
		);
		let err = result.unwrap_err();
		let BicgError::NoConvergence { abs_residual, .. } = err else {
			panic!("expected NoConvergence, got {err:?}");
		};
		assert!(out[(0, 0)] == 0.0);
		assert!(abs_residual == 1.0);
	}
	#[test]
	fn block_rhs_with_identity_is_not_a_breakdown() {
		// `r̃ᵀ v` is the identity: its pivots are 1, whatever the block width
		let k = 64;
		let ref A = Mat::<f32>::identity(k, k);
		let ref rhs = Mat::<f32>::identity(k, k);
		let precond = IdentityPrecond { dim: k };
		let params = BicgParams {
			initial_guess: InitialGuessStatus::Zero,
			max_iters: 1,
			..BicgParams::default()
		};
		let ref mut out = Mat::<f32>::zeros(k, k);
		let result = bicgstab(
			out.as_mut(),
			precond,
			precond,
			A.as_ref(),
			rhs.as_ref(),
			params,
			|_| {},
			Par::Seq,
			MemStack::new(&mut MemBuffer::new(bicgstab_scratch(
				precond,
				precond,
				A.as_ref(),
				k,
				ParShape::Seq,
			))),
		);
		assert!(result.is_ok());
		assert!((A * &*out - rhs).norm_l2() < 1e-5);
	}
}