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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
use super::EvdError;
use crate::internal_prelude::*;
use crate::perm::swap_cols_idx;
use crate::utils::thread::join_raw;
use linalg::householder::*;
use linalg::jacobi::JacobiRotation;
use linalg::matmul::{dot, matmul};
use linalg::svd::bidiag_svd::secular_eq_root_finder;
/// Scales `(diag, offdiag)` into the range where the algorithm's squares and
/// reciprocals stay finite, and returns the factor that takes the computed
/// eigenvalues back to the input scale. LAPACK's `dsteqr` rescales `anorm` the
/// same way: a spectrum that is finite can still overflow a shift or underflow
/// a reciprocal.
fn normalize_range<T: RealField>(
	diag: &mut ColMut<'_, T, usize, ContiguousFwd>,
	offdiag: &mut ColMut<'_, T, usize, ContiguousFwd>,
) -> T {
	let ref anorm = diag.rb().norm_max().fmax(offdiag.rb().norm_max());
	// below `lo` the square of an entry of size `eps * anorm` underflows, above
	// `hi` an entry squared overflows
	let ref lo = min_positive::<T>().sqrt() / eps::<T>();
	let ref hi = max_positive::<T>().sqrt();
	if *anorm == zero() || (*anorm > *lo && *anorm < *hi) {
		return one();
	}
	// dividing by `anorm` also works where its reciprocal has no finite value,
	// which is what a subnormal norm would ask for
	for x in diag.rb_mut().iter_mut() {
		*x = x.copy() / anorm;
	}
	for x in offdiag.rb_mut().iter_mut() {
		*x = x.copy() / anorm;
	}
	anorm.copy()
}
pub(crate) fn qr_algorithm<T: RealField>(
	diag: ColMut<'_, T, usize, ContiguousFwd>,
	offdiag: ColMut<'_, T, usize, ContiguousFwd>,
	u: Option<MatMut<'_, T, usize, usize>>,
) -> Result<(), EvdError> {
	let n = diag.nrows();
	let mut u = u;
	let mut diag = diag;
	let mut offdiag = offdiag;
	if let Some(mut u) = u.rb_mut() {
		u.fill(zero());
		u.diagonal_mut().fill(one());
	}
	if n <= 1 {
		return Ok(());
	}
	let ref eps = eps::<T>();
	let ref sml = min_positive::<T>();
	let ref scale = normalize_range(&mut diag, &mut offdiag);
	if n == 2 {
		let ref a = diag[0].copy();
		let ref d = diag[1].copy();
		let ref b = offdiag[0].copy();
		let ref half = from_f64::<T>(0.5);
		let ref t0 =
			(a - d).hypot(b.mul_pow2(from_f64::<T>(2.0))).mul_pow2(half);
		let ref sum = a + d;
		// halve before summing only when the trace overflows: halving a
		// subnormal is not exact, so the direct form is kept where it works
		let ref t1 = if sum.is_finite() {
			sum.mul_pow2(half)
		} else {
			a.mul_pow2(half) + d.mul_pow2(half)
		};
		let ref r0 = t1 - t0;
		let ref r1 = t1 + t0;
		let ref tol = r0.abs().fmax(r1.abs()) * eps;
		if let Some(mut u) = u.rb_mut() {
			if r1 - r0 <= *tol {
				u[(0, 0)] = one();
				u[(1, 0)] = zero();
				u[(0, 1)] = zero();
				u[(1, 1)] = one();
			} else if b.abs() <= *tol {
				if diag[0] < diag[1] {
					u[(0, 0)] = one();
					u[(1, 0)] = zero();
					u[(0, 1)] = zero();
					u[(1, 1)] = one();
				} else {
					u[(0, 0)] = zero();
					u[(1, 0)] = one();
					u[(0, 1)] = one();
					u[(1, 1)] = zero();
				}
			} else {
				let tau = ((d - a) / b).mul_pow2(half);
				let mut t = (tau.abs() + tau.hypot(one::<T>())).recip();
				if tau < zero() {
					t = -t;
				}
				let ref c = t.hypot(one::<T>());
				let ref s = c * t;
				let ref r = c.hypot(s);
				let ref c = c / r;
				let ref s = s / r;
				let ref r0_r = (c * a - s * b) / c;
				if (r0 - r0_r).abs() < r1 - r0_r {
					u[(0, 0)] = c.copy();
					u[(1, 0)] = -s;
					u[(0, 1)] = s.copy();
					u[(1, 1)] = c.copy();
				} else {
					u[(0, 1)] = c.copy();
					u[(1, 1)] = -s;
					u[(0, 0)] = s.copy();
					u[(1, 0)] = c.copy();
				}
			}
		}
		diag[0] = r0 * scale;
		diag[1] = r1 * scale;
		return Ok(());
	}
	let mut end = n - 1;
	let mut start = 0;
	let max_iters = Ord::max(30, nbits::<T>() / 2)
		.saturating_mul(n)
		.saturating_mul(n);
	for iter in 0..max_iters {
		for i in start..end {
			if offdiag[i].abs() < *sml
				|| offdiag[i].abs() < eps * &diag[i].hypot(&diag[i + 1])
			{
				offdiag[i] = zero();
			}
		}
		while end > 0 && (offdiag[end - 1] == zero()) {
			end -= 1;
		}
		if end == 0 {
			break;
		}
		if iter + 1 == max_iters {
			for x in diag.rb_mut().iter_mut() {
				*x *= scale;
			}
			for x in offdiag.rb_mut().iter_mut() {
				*x *= scale;
			}
			return Err(EvdError::NoConvergence);
		}
		start = end - 1;
		while start > 0 && !(offdiag[start - 1] == zero()) {
			start -= 1;
		}
		{
			// The shift and the implicit QR step below translate the QR branch
			// (labels 90-140) of DSTEQR, `SRC/dsteqr.f` of Reference-LAPACK
			// release v3.12.1, commit 6ec7f2bc4ecf4c4a93496aa2fa519575bc0e39ca
			// (https://github.com/Reference-LAPACK/lapack). Material changes:
			// faer's block splitting, deflation test, ordering and eigenvector
			// update are kept, and `make_givens` replaces DLARTG. LAPACK's
			// copyright notice and license terms are in
			// `faer/COPYING.LAPACK.BSD` (see `NOTICE`).
			//
			// Shift `g = diag[start] - mu`, where `mu` is the eigenvalue of the
			// trailing 2x2 block that is nearest to `diag[end]`.
			let p0 = diag[end].copy();
			let ref e = offdiag[end - 1].copy();
			let g0 = (&diag[end - 1] - &p0) / (e + e);
			let r0 = g0.hypot(one::<T>());
			let ref sgn = if g0 >= zero() { r0.copy() } else { -r0 };
			// implicit QR step, chased from `start` to `end`. `p` carries the
			// correction that the previous rotation applied to the entry being
			// visited, so a diagonal is updated as `g + p` instead of being
			// re-rounded as `c^2 d - 2 c s e + s^2 d'` on every rotation (#76).
			let ref two = from_f64::<T>(2.0);
			let mut g = &diag[start] - &p0 + e / (g0 + sgn);
			let mut c = one::<T>();
			let mut s = one::<T>();
			let mut p = zero::<T>();
			for k in start..end {
				let ref ek = offdiag[k].copy();
				let ref f = &s * ek;
				let ref b = &c * ek;
				let rot = JacobiRotation::make_givens(g.copy(), f.copy());
				if k > start {
					offdiag[k - 1] = &rot.c * &g - &rot.s * f;
				}
				// `make_givens` and `dlartg` describe the same rotation but
				// carry opposite signs for its sine; the update below is the
				// `dlartg` one.
				s = -&rot.s;
				c = rot.c.copy();
				g = &diag[k] - &p;
				let ref r = (&diag[k + 1] - &g) * &s + (&c * b).mul_pow2(two);
				p = &s * r;
				diag[k] = &g + &p;
				g = &c * r - b;
				if let Some(u) = u.rb_mut() {
					rot.apply_on_the_right_in_place(u.two_cols_mut(k + 1, k));
				}
			}
			diag[end] = &diag[end] - &p;
			offdiag[end - 1] = g;
		}
	}
	for i in 0..n - 1 {
		let mut idx = i;
		let mut min = diag[i].copy();
		for k in i + 1..n {
			if diag[k] < min {
				idx = k;
				min = diag[k].copy();
			}
		}
		if idx != i {
			let (a, b) = (diag[i].copy(), diag[idx].copy());
			diag[i] = b;
			diag[idx] = a;
			if let Some(mut u) = u.rb_mut() {
				swap_cols_idx(u.rb_mut(), i, idx);
			}
		}
	}
	for x in diag.rb_mut().iter_mut() {
		*x *= scale;
	}
	Ok(())
}
fn secular_eq<T: RealField>(
	ref shift: T,
	ref mu: T,
	d: ColRef<'_, T, usize, ContiguousFwd>,
	z: ColRef<'_, T, usize, ContiguousFwd>,
	rho_recip: T,
) -> T {
	with_dim!(n, d.nrows());
	let d = d.as_row_shape(n);
	let z = z.as_row_shape(n);
	let mut res = rho_recip;
	for i in n.indices() {
		let ref d = d[i].copy();
		let ref z = z[i].copy();
		res += z * (z / ((d - shift) - mu));
	}
	res
}
fn batch_secular_eq<const N: usize, T: RealField>(
	ref shift: &[T; N],
	ref mu: &[T; N],
	d: ColRef<'_, T, usize, ContiguousFwd>,
	z: ColRef<'_, T, usize, ContiguousFwd>,
	ref rho_recip: T,
) -> [T; N] {
	with_dim!(n, d.nrows());
	let d = d.as_row_shape(n);
	let z = z.as_row_shape(n);
	let mut res = [(); N].map(|_| rho_recip.copy());
	for i in n.indices() {
		let ref d = d[i].copy();
		let ref z = z[i].copy();
		for ((res, mu), shift) in
			res.iter_mut().zip(mu.iter()).zip(shift.iter())
		{
			*res += z * (z / ((d - shift) - mu));
		}
	}
	res
}
/// The width the root loop of a merge with `k` non deflated poles runs at on `par` (1:
/// serial): the widest width that pays for the loop's estimated serial time, `k^2` units of
/// [`secular_roots`](crate::utils::cost::rate::secular_roots), one section, never more than `k`.
///
/// It is a function of `k`, the degree of `par` and the host's cost table only, never of
/// scheduling. A `Par::Seq` or a one-thread team gives 1.
fn secular_width<T: RealField>(par: &Par, k: usize) -> usize {
	crate::utils::cost::par_width_upto::<T>(
		par,
		k.saturating_mul(k),
		crate::utils::cost::rate::secular_roots(),
		1,
		k,
	)
}

/// One root of the secular equation of a merge: the root in `(d[i], d[i + 1])`, or above
/// `d[n - 1]` for the last one, as `(shift, mu)` with the root equal to `shift + mu`. Reads only
/// `d`, `z` and `rho`, so every root is independent of every other.
#[inline(always)]
fn secular_root<T: RealField>(
	i: usize,
	d: ColRef<'_, T, usize, ContiguousFwd>,
	z: ColRef<'_, T, usize, ContiguousFwd>,
	rho: &T,
	rho_recip: &T,
	n: usize,
) -> (T, T) {
	let left = d[i].copy();
	let last = i == n - 1;
	let right = if last {
		&d[i] + rho * z.squared_norm_l2()
	} else {
		d[i + 1].copy()
	};
	let d = d.subrows(0, n);
	let z = z.subrows(0, n);
	secular_eq_root_finder(
		&|shift, mu| secular_eq(shift, mu, d, z, rho_recip.copy()),
		&|shift, mu| batch_secular_eq(shift, mu, d, z, rho_recip.copy()),
		left,
		right,
		last,
	)
}

/// Solves the `non_deflated` roots of the secular equation into `(shifts, mus)` and writes the
/// deflated entries as `(0, d[i])`.
///
/// With a team, the roots are dealt out in contiguous blocks over [`secular_width`]
/// participants (tensor4all/faer#391). Each root is computed by [`secular_root`] alone, with no
/// arithmetic shared between roots, so its bits do not depend on which participant computes it
/// or on how the roots are split: the output is bitwise identical to the serial loop for every
/// width and every thread count. Without a team, or when the split does not pay, the loop is
/// the serial one.
fn compute_eigenvalues<T: RealField>(
	mut mus: ColMut<'_, T, usize, ContiguousFwd>,
	mut shifts: ColMut<'_, T, usize, ContiguousFwd>,
	d: ColRef<'_, T, usize, ContiguousFwd>,
	z: ColRef<'_, T, usize, ContiguousFwd>,
	rho: T,
	non_deflated: usize,
	par: Par,
) {
	let n = non_deflated;
	let full_n = d.nrows();
	let ref rho = rho;
	let ref rho_recip = rho.recip();
	let width = secular_width::<T>(&par, n);
	if width < 2 {
		for i in 0..n {
			let (shift, mu) = secular_root(i, d, z, rho, rho_recip, n);
			shifts[i] = shift;
			mus[i] = mu;
		}
	} else {
		#[cfg(feature = "rayon")]
		{
			use rayon::prelude::*;
			let mus = mus.rb_mut().subrows_mut(0, n).as_slice_mut();
			let shifts = shifts.rb_mut().subrows_mut(0, n).as_slice_mut();
			crate::utils::thread::with_width(par, width, |par| {
				crate::utils::thread::for_each(
					par,
					width,
					mus.par_iter_mut().zip(shifts.par_iter_mut()).enumerate(),
					|(i, (mu, shift))| {
						let (s, m) = secular_root(i, d, z, rho, rho_recip, n);
						*shift = s;
						*mu = m;
					},
				)
			});
		}
		#[cfg(not(feature = "rayon"))]
		unreachable!("a width of two or more needs a team");
	}
	for i in n..full_n {
		shifts[i] = zero();
		mus[i] = d[i].copy();
	}
}
fn divide_and_conquer_recurse<T: RealField>(
	mut diag: ColMut<'_, T, usize, ContiguousFwd>,
	mut offdiag: ColMut<'_, T, usize, ContiguousFwd>,
	mut u: MatMut<'_, T, usize, usize>,
	mut par: Par,
	pl_before: &mut [usize],
	pl_after: &mut [usize],
	pr: &mut [usize],
	run_info: &mut [usize],
	mut z: ColMut<'_, T, usize, ContiguousFwd>,
	mut permuted_diag: ColMut<'_, T, usize, ContiguousFwd>,
	mut permuted_z: ColMut<'_, T, usize, ContiguousFwd>,
	mut householder: ColMut<'_, T, usize, ContiguousFwd>,
	mut mus: ColMut<'_, T, usize, ContiguousFwd>,
	mut shifts: ColMut<'_, T, usize, ContiguousFwd>,
	mut repaired_u: MatMut<'_, T, usize, usize, ContiguousFwd>,
	mut tmp: MatMut<'_, T, usize, usize, ContiguousFwd>,
	qr_fallback_threshold: usize,
) -> Result<(), EvdError> {
	let n = diag.nrows();
	let qr_fallback_threshold = Ord::max(qr_fallback_threshold, 4);
	if n <= qr_fallback_threshold {
		return qr_algorithm(diag, offdiag, Some(u));
	}
	let n1 = n / 2;
	let mut rho = offdiag[n1 - 1].copy();
	let (mut diag0, mut diag1) = diag.rb_mut().split_at_row_mut(n1);
	let (offdiag0, offdiag1) = offdiag.rb_mut().split_at_row_mut(n1 - 1);
	let offdiag1 = offdiag1.split_at_row_mut(1).1;
	diag0[n1 - 1] -= rho.abs();
	diag1[0] -= rho.abs();
	let (mut u0, _, _, mut u1) = u.rb_mut().split_at_mut(n1, n1);
	{
		let (pl_before0, pl_before1) = pl_before.split_at_mut(n1);
		let (pl_after0, pl_after1) = pl_after.split_at_mut(n1);
		let (pr0, pr1) = pr.split_at_mut(n1);
		let (run_info0, run_info1) = run_info.split_at_mut(n1);
		let (z0, z1) = z.rb_mut().split_at_row_mut(n1);
		let (permuted_diag0, permuted_diag1) =
			permuted_diag.rb_mut().split_at_row_mut(n1);
		let (permuted_z0, permuted_z1) =
			permuted_z.rb_mut().split_at_row_mut(n1);
		let (householder0, householder1) =
			householder.rb_mut().split_at_row_mut(n1);
		let (mus0, mus1) = mus.rb_mut().split_at_row_mut(n1);
		let (shift0, shift1) = shifts.rb_mut().split_at_row_mut(n1);
		let (repaired_u0, _, _, repaired_u1) =
			repaired_u.rb_mut().split_at_mut(n1, n1);
		let (tmp0, _, _, tmp1) = tmp.rb_mut().split_at_mut(n1, n1);
		let mut r0 = Ok(());
		let mut r1 = Ok(());
		// one section for the join of the two halves, each a whole solve of size `n / 2`
		let join_par = if crate::utils::cost::halves_pays::<T>(
			&par,
			n,
			crate::utils::cost::rate::tridiag_evd_dc(),
			2,
		) {
			par.reborrow()
		} else {
			Par::Seq
		};
		join_raw(
			|par| {
				r0 = divide_and_conquer_recurse(
					diag0,
					offdiag0,
					u0.rb_mut(),
					par,
					pl_before0,
					pl_after0,
					pr0,
					run_info0,
					z0,
					permuted_diag0,
					permuted_z0,
					householder0,
					mus0,
					shift0,
					repaired_u0,
					tmp0,
					qr_fallback_threshold,
				);
			},
			|par| {
				r1 = divide_and_conquer_recurse(
					diag1,
					offdiag1,
					u1.rb_mut(),
					par,
					pl_before1,
					pl_after1,
					pr1,
					run_info1,
					z1,
					permuted_diag1,
					permuted_z1,
					householder1,
					mus1,
					shift1,
					repaired_u1,
					tmp1,
					qr_fallback_threshold,
				);
			},
			join_par,
		);
		r0?;
		r1?;
	}
	let mut repaired_u = repaired_u.subrows_mut(0, n);
	let mut tmp = tmp.subrows_mut(0, n);
	let (mut z0, mut z1) = z.rb_mut().split_at_row_mut(n1);
	z0.copy_from(u0.rb().row(n1 - 1).transpose());
	if rho < zero() {
		z!(z1.rb_mut(), u1.rb().row(0).transpose())
			.for_each(|uz!(z, u)| *z = -u);
	} else {
		z1.copy_from(u1.rb().row(0).transpose());
	}
	let ref inv_sqrt2 = from_f64::<T>(0.5).sqrt();
	z!(z.rb_mut()).for_each(|uz!(x)| *x *= inv_sqrt2);
	rho = rho.abs().mul_pow2(from_f64::<T>(2.0));
	{
		let mut i = 0usize;
		let mut j = 0usize;
		for p in &mut *pl_before {
			if i == n1 {
				*p = n1 + j;
				j += 1;
			} else if (j == n - n1) || diag[i] < diag[n1 + j] {
				*p = i;
				i += 1;
			} else {
				*p = n1 + j;
				j += 1;
			}
		}
	}
	for (i, &pl_before) in pl_before.iter().enumerate() {
		permuted_diag[i] = diag[pl_before].copy();
	}
	for (i, &pl_before) in pl_before.iter().enumerate() {
		permuted_z[i] = z[pl_before].copy();
	}
	let ref dmax = permuted_diag.norm_max();
	let ref zmax = permuted_z.norm_max();
	let ref eps = eps::<T>();
	let ref tol = from_f64::<T>(8.0) * eps * dmax;
	if &rho * zmax <= *tol {
		let (mut tmp_tl, mut tmp_tr, mut tmp_bl, mut tmp_br) =
			tmp.rb_mut().split_at_mut(n1, n1);
		tmp_tl.copy_from(u0.rb());
		tmp_br.copy_from(u1.rb());
		tmp_tr.fill(zero());
		tmp_bl.fill(zero());
		for (j, &pl_before) in pl_before.iter().enumerate() {
			u.rb_mut().col_mut(j).copy_from(tmp.rb().col(pl_before));
		}
		for (j, diag) in diag.iter_mut().enumerate() {
			*diag = permuted_diag[j].copy();
		}
		return Ok(());
	}
	for i in 0..n {
		let ref zi = permuted_z[i].copy();
		if (&rho * zi).abs() <= *tol {
			permuted_z[i] = zero();
		}
	}
	let mut applied_householder = false;
	let mut idx = 0;
	while idx < n {
		let mut run_len = 1;
		let ref d_prev = permuted_diag[idx].copy();
		while idx + run_len < n {
			if &permuted_diag[idx + run_len] - d_prev <= *tol {
				permuted_diag[idx + run_len] = d_prev.copy();
				run_len += 1;
			} else {
				break;
			}
		}
		run_info[idx..][..run_len].fill(run_len);
		if run_len > 1 {
			applied_householder = true;
			let mut householder =
				householder.rb_mut().subrows_mut(idx, run_len);
			let mut permuted_z = permuted_z.rb_mut().subrows_mut(idx, run_len);
			householder.copy_from(permuted_z.rb());
			let (tail, head) =
				householder.rb_mut().split_at_row_mut(run_len - 1);
			let head = head.at_mut(0);
			let HouseholderInfo { tau, .. } = make_householder_in_place(
				head,
				tail.as_dyn_stride_mut().reverse_rows_mut(),
			);
			permuted_z.fill(zero());
			permuted_z[run_len - 1] = head.copy();
			*head = tau;
		}
		idx += run_len;
	}
	let mut writer_deflated = 0;
	let mut writer_non_deflated = 0;
	for reader in 0..n {
		let z = permuted_z[reader].copy();
		let d = permuted_diag[reader].copy();
		if z == zero() {
			diag[writer_deflated] = d;
			pr[writer_deflated] = reader;
			writer_deflated += 1;
		} else {
			permuted_z[writer_non_deflated] = z;
			permuted_diag[writer_non_deflated] = d;
			pl_after[writer_non_deflated] = reader;
			writer_non_deflated += 1;
		}
	}
	let non_deflated = writer_non_deflated;
	let deflated = writer_deflated;
	for i in 0..deflated {
		permuted_diag[non_deflated + i] = diag[i].copy();
		pl_after[non_deflated + i] = pr[i];
	}
	compute_eigenvalues(
		mus.rb_mut(),
		shifts.rb_mut(),
		permuted_diag.rb(),
		permuted_z.rb(),
		rho.copy(),
		non_deflated,
		par.reborrow(),
	);
	for i in 0..non_deflated {
		let ref di = permuted_diag[i].copy();
		let ref mu_i = mus[i].copy();
		let ref shift_i = shifts[i].copy();
		let mut prod = mu_i + (shift_i - di);
		(0..i).chain(i + 1..non_deflated).for_each(|k| {
			let ref dk = permuted_diag[k].copy();
			let ref mu_k = mus[k].copy();
			let ref shift_k = shifts[k].copy();
			let ref numerator = mu_k + (shift_k - di);
			let ref denominator = dk - di;
			prod *= numerator / denominator;
		});
		let prod = prod.abs().sqrt();
		let zi = permuted_z.rb_mut().at_mut(i);
		let new_zi = if *zi < zero() { -prod } else { prod };
		*zi = new_zi;
	}
	let mut eigenvals = z;
	for i in 0..n {
		eigenvals[i] = &mus[i] + &shifts[i];
	}
	for (i, p) in pr.iter_mut().enumerate() {
		*p = i;
	}
	pr.sort_unstable_by(|&i, &j| {
		match PartialOrd::partial_cmp(&eigenvals[i], &eigenvals[j]) {
			Some(ord) => ord,
			None => {
				if eigenvals[i].is_nan() && eigenvals[j].is_nan() {
					core::cmp::Ordering::Equal
				} else if eigenvals[i].is_nan() {
					core::cmp::Ordering::Greater
				} else {
					core::cmp::Ordering::Less
				}
			},
		}
	});
	if !applied_householder {
		for p in pl_after.iter_mut() {
			*p = pl_before[*p];
		}
	}
	for (j, &pj) in pr.iter().enumerate() {
		if pj >= non_deflated {
			repaired_u.rb_mut().col_mut(j).fill(zero());
			repaired_u[(pl_after[pj], j)] = one();
		} else {
			let ref mu_j = mus[pj].copy();
			let ref shift_j = shifts[pj].copy();
			for (i, &pl_after) in pl_after[..non_deflated].iter().enumerate() {
				let ref zi = permuted_z[i].copy();
				let ref di = permuted_diag[i].copy();
				repaired_u[(pl_after, j)] = zi / ((di - shift_j) - mu_j);
			}
			for &pl_after in &pl_after[non_deflated..non_deflated + deflated] {
				repaired_u[(pl_after, j)] = zero();
			}
			let ref inv_norm = repaired_u.rb().col(j).norm_l2().recip();
			z!(repaired_u.rb_mut().col_mut(j))
				.for_each(|unzip!(x)| *x *= inv_norm);
		}
	}
	if applied_householder {
		let mut idx = 0;
		while idx < n {
			let run_len = run_info[idx];
			if run_len > 1 {
				let mut householder =
					householder.rb_mut().subrows_mut(idx, run_len);
				let tau = householder[run_len - 1].copy();
				householder[run_len - 1] = one();
				let householder = householder.rb();
				let mut repaired_u =
					repaired_u.rb_mut().subrows_mut(idx, run_len);
				let ref tau_inv = tau.recip();
				for j in 0..n {
					let mut col = repaired_u.rb_mut().col_mut(j);
					let ref dot = tau_inv
						* dot::inner_prod(
							householder.as_dyn_stride().transpose(),
							Conj::No,
							col.rb().as_dyn_stride(),
							Conj::No,
						);
					z!(col.rb_mut(), householder)
						.for_each(|uz!(u, h)| *u -= dot * h);
				}
			}
			idx += run_len;
		}
		for j in 0..n {
			for (i, &pl_before) in pl_before.iter().enumerate() {
				tmp[(pl_before, j)] = repaired_u[(i, j)].copy();
			}
		}
		core::mem::swap(&mut repaired_u, &mut tmp);
	}
	let (repaired_u_top, repaired_u_bot) = repaired_u.rb().split_at_row(n1);
	let (tmp_top, tmp_bot) = tmp.rb_mut().split_at_row_mut(n1);
	// one section; the two products `n1 x n1` and `(n - n1) x (n - n1)` against `n` columns
	let join_par = if crate::utils::cost::join_pays::<T>(
		&par,
		(n1 * n1 + (n - n1) * (n - n1)).saturating_mul(n),
		crate::utils::cost::rate::gemm_mac(),
		1,
	) {
		par
	} else {
		Par::Seq
	};
	crate::utils::thread::join_raw(
		|par| {
			matmul(tmp_top, Accum::Replace, u0.rb(), repaired_u_top, one(), par)
		},
		|par| {
			matmul(tmp_bot, Accum::Replace, u1.rb(), repaired_u_bot, one(), par)
		},
		join_par,
	);
	u.copy_from(tmp.rb());
	for i in 0..n {
		diag[i] = &mus[pr[i]] + &shifts[pr[i]];
	}
	Ok(())
}
pub(crate) fn divide_and_conquer<T: RealField>(
	mut diag: ColMut<'_, T, usize, ContiguousFwd>,
	mut offdiag: ColMut<'_, T, usize, ContiguousFwd>,
	u: MatMut<'_, T, usize, usize>,
	par: Par,
	stack: &mut MemStack,
	qr_fallback_threshold: usize,
) -> Result<(), EvdError> {
	let n = diag.nrows();
	let ref scale = normalize_range(&mut diag, &mut offdiag);
	let (mut pl_before, stack) = stack.make_with(n, |_| 0usize);
	let (mut pl_after, stack) = stack.make_with(n, |_| 0usize);
	let (mut pr, stack) = stack.make_with(n, |_| 0usize);
	let (mut run_info, stack) = stack.make_with(n, |_| 0usize);
	let (mut z, stack) = unsafe { temp_mat_uninit(n, 1, stack) };
	let (mut permuted_diag, stack) = unsafe { temp_mat_uninit(n, 1, stack) };
	let (mut permuted_z, stack) = unsafe { temp_mat_uninit(n, 1, stack) };
	let (mut householder, stack) = unsafe { temp_mat_uninit(n, 1, stack) };
	let (mut mus, stack) = unsafe { temp_mat_uninit(n, 1, stack) };
	let (mut shifts, stack) = unsafe { temp_mat_uninit(n, 1, stack) };
	let (mut repaired_u, stack) = unsafe { temp_mat_uninit(n, n, stack) };
	let (mut tmp, _) = unsafe { temp_mat_uninit(n, n, stack) };
	let res = divide_and_conquer_recurse(
		diag.rb_mut(),
		offdiag.rb_mut(),
		u,
		par,
		&mut pl_before,
		&mut pl_after,
		&mut pr,
		&mut run_info,
		z.as_mat_mut().col_mut(0).try_as_col_major_mut().unwrap(),
		permuted_diag
			.as_mat_mut()
			.col_mut(0)
			.try_as_col_major_mut()
			.unwrap(),
		permuted_z
			.as_mat_mut()
			.col_mut(0)
			.try_as_col_major_mut()
			.unwrap(),
		householder
			.as_mat_mut()
			.col_mut(0)
			.try_as_col_major_mut()
			.unwrap(),
		mus.as_mat_mut().col_mut(0).try_as_col_major_mut().unwrap(),
		shifts
			.as_mat_mut()
			.col_mut(0)
			.try_as_col_major_mut()
			.unwrap(),
		repaired_u.as_mat_mut().try_as_col_major_mut().unwrap(),
		tmp.as_mat_mut().try_as_col_major_mut().unwrap(),
		qr_fallback_threshold,
	);
	for x in diag.iter_mut() {
		*x *= scale;
	}
	res
}
pub(crate) fn divide_and_conquer_scratch<T: ComplexField>(
	n: usize,
	par: ParShape,
) -> StackReq {
	let _ = par;
	StackReq::all_of(&[
		StackReq::new::<usize>(n).array(4),
		temp_mat_scratch::<T>(n, 1).array(6),
		temp_mat_scratch::<T>(n, n).array(2),
	])
}
#[cfg(test)]
mod evd_qr_tests {
	use super::*;
	use crate::utils::approx::*;
	use crate::{ColMut, Mat, assert};
	use dyn_stack::MemBuffer;
	#[track_caller]
	fn test_qr(diag: &[f64], offdiag: &[f64]) {
		let n = diag.len();
		let mut u = Mat::full(n, n, f64::NAN);
		let s = {
			let mut diag = diag.to_vec();
			let mut offdiag = offdiag.to_vec();
			qr_algorithm(
				ColMut::from_slice_mut(&mut diag)
					.try_as_col_major_mut()
					.unwrap(),
				ColMut::from_slice_mut(&mut offdiag)
					.try_as_col_major_mut()
					.unwrap(),
				Some(u.as_mut()),
			)
			.unwrap();
			Mat::from_fn(n, n, |i, j| if i == j { diag[i] } else { 0.0 })
		};
		let reconstructed = &u * &s * u.transpose();
		for j in 0..n {
			for i in 0..n {
				let target = if i == j {
					diag[j]
				} else if i == j + 1 {
					offdiag[j]
				} else if j == i + 1 {
					offdiag[i]
				} else {
					0.0
				};
				let approx_eq = ApproxEq::<f64>::eps();
				assert!(reconstructed[(i, j)] ~ target);
			}
		}
	}
	#[track_caller]
	fn test_dc(diag: &[f64], offdiag: &[f64]) {
		let n = diag.len();
		let mut u = Mat::full(n, n, f64::NAN);
		let s = {
			let mut diag = diag.to_vec();
			let mut offdiag = offdiag.to_vec();
			divide_and_conquer(
				ColMut::from_slice_mut(&mut diag)
					.try_as_col_major_mut()
					.unwrap(),
				ColMut::from_slice_mut(&mut offdiag)
					.try_as_col_major_mut()
					.unwrap(),
				u.as_mut(),
				Par::Seq,
				MemStack::new(&mut MemBuffer::new(
					divide_and_conquer_scratch::<f64>(n, ParShape::Seq),
				)),
				4,
			)
			.unwrap();
			Mat::from_fn(n, n, |i, j| if i == j { diag[i] } else { 0.0 })
		};
		let reconstructed = &u * &s * u.transpose();
		for j in 0..n {
			for i in 0..n {
				let target = if i == j {
					diag[j]
				} else if i == j + 1 {
					offdiag[j]
				} else if j == i + 1 {
					offdiag[i]
				} else {
					0.0
				};
				let approx_eq = ApproxEq::<f64>::eps();
				assert!(reconstructed[(i, j)] ~ target);
			}
		}
	}
	#[test]
	fn test_evd_2_0() {
		let diag = [1.0, 1.0];
		let offdiag = [0.0];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_evd_2_1() {
		let diag = [1.0, 1.0];
		let offdiag = [0.5213289];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_evd_3() {
		let diag = [1.79069356, 1.20930644, 1.0];
		let offdiag = [-4.06813537e-01, 0.0];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_evd_5() {
		let diag = [1.95069537, 2.44845332, 2.56957029, 3.03128102, 1.0];
		let offdiag = [-7.02200909e-01, -1.11661820e+00, -6.81418803e-01, 0.0];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_evd_wilkinson() {
		let diag = [3.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0];
		let offdiag = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_glued_wilkinson() {
		let diag = [
			3.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 0.0, 1.0, 2.0,
			3.0,
		];
		let x = 1e-6;
		let offdiag = [
			1.0, 1.0, 1.0, 1.0, 1.0, 1.0, x, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
		];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_gh_82() {
		let diag = [
			0.0,
			0.0,
			1.0769230769230773,
			-0.4290761869709236,
			-0.8278050499098524,
			0.07994922044020283,
			-0.35579623371016944,
			0.6487378508167678,
			-0.9347442346214521,
			-0.08624745233962683,
			-0.4999243909534632,
			1.3708277457481026,
			-0.2592167303689501,
			-0.5929351972647323,
			-0.5863220906879729,
			0.15069873027683844,
			0.2449309426221532,
			0.5599151389028441,
			0.440084861097156,
			9.811634162559901e-17,
		];
		let offdiag = [
			1.7320508075688772,
			2.081665999466133,
			2.0303418353670932,
			1.2463948607107287,
			1.5895840148470526,
			1.3810057029812097,
			1.265168346300635,
			0.8941431038915991,
			1.007512301091709,
			0.5877505835309086,
			1.0370970338888965,
			0.8628932798233644,
			1.1935059937001073,
			1.1614143449715744,
			0.41040224297074174,
			0.561318309959268,
			3.1807090401145072e-15,
			0.4963971959331084,
			1.942890293094024e-16,
		];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
	#[test]
	fn test_gh_82_mini() {
		let diag = [1.0000000000000002, 1.0000000000000002];
		let offdiag = [7.216449660063518e-16];
		test_qr(&diag, &offdiag);
		test_dc(&diag, &offdiag);
	}
}
#[cfg(test)]
mod secular_split_tests {
	//! tensor4all/faer#391: the root loop of a merge split across a team.
	//!
	//! What is claimed: every root is computed by the same serial code from read-only inputs, so
	//! the `(shifts, mus)` of a merge are bitwise identical for any split, and therefore for any
	//! thread count, `Par::Seq` included. This is narrower than the public routine: the rest of
	//! the merge (the two `matmul`s) is not claimed to be identical across thread counts
	//! (`docs/reproducibility.md`), only at a fixed one, which the last test pins.
	use super::*;
	use crate::{ColMut, Mat, assert};
	use dyn_stack::MemBuffer;

	fn lcg(st: &mut u64) -> f64 {
		*st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
		((*st >> 11) as f64) / ((1u64 << 53) as f64)
	}

	/// The inputs of one merge: `full` sorted poles of which the first `k` are not deflated,
	/// and a unit `z`.
	fn merge_input(full: usize, k: usize, seed: u64) -> (Vec<f64>, Vec<f64>, f64) {
		let mut st = seed;
		let mut d: Vec<f64> = (0..full).map(|_| 4.0 * lcg(&mut st) - 2.0).collect();
		d[..k].sort_by(f64::total_cmp);
		let mut z: Vec<f64> = (0..full).map(|_| lcg(&mut st) + 0.05).collect();
		let norm = z[..k].iter().map(|x| x * x).sum::<f64>().sqrt();
		z.iter_mut().for_each(|x| *x /= norm);
		(d, z, 0.75)
	}

	/// `(shifts, mus)` as bits.
	fn roots(par: Par, d: &[f64], z: &[f64], rho: f64, k: usize) -> Vec<(u64, u64)> {
		let full = d.len();
		let mut mus = vec![f64::NAN; full];
		let mut shifts = vec![f64::NAN; full];
		compute_eigenvalues(
			ColMut::from_slice_mut(&mut mus).try_as_col_major_mut().unwrap(),
			ColMut::from_slice_mut(&mut shifts).try_as_col_major_mut().unwrap(),
			ColRef::from_slice(d).try_as_col_major().unwrap(),
			ColRef::from_slice(z).try_as_col_major().unwrap(),
			rho,
			k,
			par,
		);
		shifts.iter().zip(&mus).map(|(s, m)| (s.to_bits(), m.to_bits())).collect()
	}

	#[test]
	fn serial_without_a_team() {
		assert!(secular_width::<f64>(&Par::Seq, 128) == 1);
		assert!(secular_width::<f64>(&Par::Seq, 0) == 1);
	}

	/// The roots are solved, i.e. every one lies in its interval and is finite.
	#[test]
	fn serial_roots_interlace() {
		let (d, z, rho) = merge_input(70, 64, 0x391);
		let r = roots(Par::Seq, &d, &z, rho, 64);
		for i in 0..64 {
			let lambda = f64::from_bits(r[i].0) + f64::from_bits(r[i].1);
			assert!(lambda.is_finite());
			assert!(lambda >= d[i]);
			if i + 1 < 64 {
				assert!(lambda <= d[i + 1]);
			}
		}
		// the deflated tail is `(0, d[i])`
		for i in 64..70 {
			assert!(r[i] == (0.0f64.to_bits(), d[i].to_bits()));
		}
	}

	#[cfg(feature = "threadteam")]
	#[test]
	fn split_roots_are_bitwise_identical_at_every_width() {
		for (full, k) in [(128, 128), (100, 96), (70, 64), (33, 32)] {
			let (d, z, rho) = merge_input(full, k, 0x391 + k as u64);
			let seq = roots(Par::Seq, &d, &z, rho, k);
			for threads in [2usize, 3, 8] {
				let (first, second, width) = crate::team::with_team(threads, |mut par| {
					(
						roots(par.reborrow(), &d, &z, rho, k),
						roots(par.reborrow(), &d, &z, rho, k),
						secular_width::<f64>(&par, k),
					)
				});
				// same thread count, same split: same bits
				assert!(first == second, "k = {k}, {threads} threads");
				// the split changes nothing, so a different thread count, or none, does not either
				assert!(first == seq, "k = {k}, {threads} threads against Par::Seq");
				// the gate is the cost model's, at most `k` participants and at most the team
				assert!(width <= Ord::min(k, threads));
			}
		}
		// the loop of the top merge at the record's sizes is split on a team of 8 (the work is
		// `k^2` at the host's `secular_roots` rate against one width-8 section)
		crate::team::with_team(8, |par| {
			assert!(secular_width::<f64>(&par, 128) >= 2);
		});
	}

	/// The whole divide and conquer on a team, run twice at the same thread count: same bits
	/// (`docs/reproducibility.md`). Against `Par::Seq` it is compared by its residual only.
	#[cfg(feature = "threadteam")]
	#[test]
	fn divide_and_conquer_on_a_team_is_reproducible() {
		let n = 128;
		let mut st = 0x391u64;
		let diag: Vec<f64> = (0..n).map(|_| 2.0 * lcg(&mut st) - 1.0).collect();
		let offdiag: Vec<f64> = (0..n - 1).map(|_| 2.0 * lcg(&mut st) - 1.0).collect();
		let run = |par: Par| {
			let mut d = diag.clone();
			let mut e = offdiag.clone();
			let mut u = Mat::<f64>::zeros(n, n);
			divide_and_conquer(
				ColMut::from_slice_mut(&mut d).try_as_col_major_mut().unwrap(),
				ColMut::from_slice_mut(&mut e).try_as_col_major_mut().unwrap(),
				u.as_mut(),
				par,
				MemStack::new(&mut MemBuffer::new(divide_and_conquer_scratch::<f64>(
					n,
					ParShape::Seq,
				))),
				16,
			)
			.unwrap();
			(d, u)
		};
		let bits = |(d, u): &(Vec<f64>, Mat<f64>)| {
			let mut v: Vec<u64> = d.iter().map(|x| x.to_bits()).collect();
			for j in 0..n {
				for i in 0..n {
					v.push(u[(i, j)].to_bits());
				}
			}
			v
		};
		let (a, b) = crate::team::with_team(8, |mut par| (run(par.reborrow()), run(par.reborrow())));
		assert!(bits(&a) == bits(&b));
		// residual and orthogonality of the team result
		let (s, u) = &a;
		let t = Mat::from_fn(n, n, |i, j| {
			if i == j {
				diag[i]
			} else if i == j + 1 {
				offdiag[j]
			} else if j == i + 1 {
				offdiag[i]
			} else {
				0.0
			}
		});
		let lam = Mat::from_fn(n, n, |i, j| if i == j { s[i] } else { 0.0 });
		let tol = n as f64 * f64::EPSILON;
		let res = (&t * u - u * &lam).norm_max() / t.norm_max();
		let orth = (u.transpose() * u - Mat::<f64>::identity(n, n)).norm_max();
		assert!(res < tol, "{res}");
		assert!(orth < tol, "{orth}");
		let seq = run(Par::Seq);
		for i in 0..n {
			assert!((seq.0[i] - s[i]).abs() <= tol * t.norm_max());
		}
	}
}