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
use *;
use crateassert;
use crate;
/// Balancing failed because the input contains a nonfinite entry.
///
/// # Examples
/// ```
/// use dyn_stack::{MemBuffer, MemStack};
/// use colmat::Par;
/// use colmat::linalg::evd::*;
/// let mut a = colmat::mat![[f64::NAN]];
/// let mut mem = MemBuffer::new(balance_scratch());
/// assert_eq!(
/// balance_in_place(
/// a.as_mut(),
/// &mut [0],
/// &mut [1.0],
/// Par::Seq,
/// MemStack::new(&mut mem)
/// ),
/// Err(BalanceError::NonFiniteInput)
/// );
/// ```
/// Which parts of the balancing to run, like the `job` argument of LAPACK's `xGEBAL`.
///
/// # Examples
/// ```
/// use dyn_stack::{MemBuffer, MemStack};
/// use colmat::Par;
/// use colmat::linalg::evd::*;
/// let a = colmat::mat![[1.0f64, 1024.0], [1.0 / 1024.0, 2.0]];
/// // scaling alone leaves the permutation at the identity
/// let (mut perm, mut scale) = ([0; 2], [0.0; 2]);
/// let mut mem = MemBuffer::new(balance_scratch());
/// balance_in_place_with(
/// a.cloned().as_mut(),
/// &mut perm,
/// &mut scale,
/// BalanceJob::Scale,
/// Par::Seq,
/// MemStack::new(&mut mem),
/// )
/// .unwrap();
/// assert_eq!(perm, [0, 1]);
/// assert_ne!(scale, [1.0, 1.0]);
/// ```
/// Workspace for [`balance_in_place`]; all metadata is supplied by the caller.
///
/// # Examples
/// ```
/// assert_eq!(colmat::linalg::evd::balance_scratch().size_bytes(), 0);
/// ```
/// Permutes and balances a square matrix in place, like `xGEBAL(job=B)`.
/// Returns the zero-based, half-open active range `ilo..ihi`. Outside this
/// range the permutation isolates eigenvalues in triangular blocks.
///
/// On return `b[i,j] = a[perm[i],perm[j]] * scale[j] / scale[i]`:
/// `perm[i]` is the original index now at row/column `i`, and `scale` holds
/// positive powers of two (one outside the active range). Scaling is accepted
/// only if it reduces the sum of the active row/column 2-norms (including the
/// diagonal) by at least 5%, subject to safe-range guards. This is the LAPACK
/// 3.5+ criterion, rather than the older 1-norm rule.
///
/// Use [`balance_eigenvectors_in_place`] for right eigenvectors. For a matrix
/// function such as `exp`, undo by `f(a)[perm[i],perm[j]] =
/// scale[i] * f(b)[i,j] / scale[j]`. Powers of two introduce no rounding when
/// the scaled values stay normal; underflow can prevent bit-for-bit recovery.
///
/// # Panics
/// Panics unless `a` is square and both metadata slices have length `n`.
///
/// # Errors
/// Returns [`BalanceError::NonFiniteInput`] before modifying any output if an
/// entry is NaN or infinite.
///
/// # Examples
/// ```
/// use dyn_stack::{MemBuffer, MemStack};
/// use colmat::Par;
/// use colmat::linalg::evd::*;
/// let mut a = colmat::mat![[1.0f64, 1024.0], [1.0 / 1024.0, 2.0]];
/// let (mut perm, mut scale) = ([0; 2], [0.0; 2]);
/// let mut mem = MemBuffer::new(balance_scratch());
/// let active = balance_in_place(
/// a.as_mut(),
/// &mut perm,
/// &mut scale,
/// Par::Seq,
/// MemStack::new(&mut mem),
/// )
/// .unwrap();
/// assert_eq!(active, 0..2);
/// let row = a.row(0).norm_l2();
/// let col = a.col(0).norm_l2();
/// assert!(row <= 2.0 * col && col <= 2.0 * row);
/// assert_eq!(a[(0, 1)] * scale[0] / scale[1], 1024.0);
/// ```
/// Permutes and/or scales a square matrix in place, like `xGEBAL` with the job `job`.
/// Returns the zero-based, half-open active range `ilo..ihi`. Outside this range the
/// permutation (when `job` includes it) isolates eigenvalues in triangular blocks.
///
/// [`BalanceJob::None`] returns `0..n`, leaves the matrix alone and sets the metadata to
/// the identity; [`BalanceJob::Scale`] scales without permuting (the metadata keeps the
/// identity permutation) and also returns `0..n`; [`BalanceJob::Permute`] and
/// [`BalanceJob::Both`] return the isolated range.
///
/// On return `b[i,j] = a[perm[i],perm[j]] * scale[j] / scale[i]`:
/// `perm[i]` is the original index now at row/column `i`, and `scale` holds
/// positive powers of two (one outside the active range). Scaling is accepted
/// only if it reduces the sum of the active row/column 2-norms (including the
/// diagonal) by at least 5%, subject to safe-range guards. This is the LAPACK
/// 3.5+ criterion, rather than the older 1-norm rule.
///
/// Use [`balance_eigenvectors_in_place`] for right eigenvectors. For a matrix
/// function such as `exp`, undo by `f(a)[perm[i],perm[j]] =
/// scale[i] * f(b)[i,j] / scale[j]`. Powers of two introduce no rounding when
/// the scaled values stay normal; underflow can prevent bit-for-bit recovery.
///
/// # Panics
/// Panics unless `a` is square and both metadata slices have length `n`.
///
/// # Errors
/// Returns [`BalanceError::NonFiniteInput`] before modifying any output if an
/// entry is NaN or infinite, whatever `job` is.
///
/// # Examples
/// ```
/// use dyn_stack::{MemBuffer, MemStack};
/// use colmat::Par;
/// use colmat::linalg::evd::*;
/// let mut a = colmat::mat![[1.0f64, 1024.0], [1.0 / 1024.0, 2.0]];
/// let original = a.clone();
/// let (mut perm, mut scale) = ([0; 2], [0.0; 2]);
/// let mut mem = MemBuffer::new(balance_scratch());
/// // permute only: the entries move, the scales stay one
/// let active = balance_in_place_with(
/// a.as_mut(),
/// &mut perm,
/// &mut scale,
/// BalanceJob::Permute,
/// Par::Seq,
/// MemStack::new(&mut mem),
/// )
/// .unwrap();
/// assert_eq!(active, 0..2);
/// assert_eq!(scale, [1.0, 1.0]);
/// for i in 0..2 {
/// for j in 0..2 {
/// assert_eq!(a[(i, j)], original[(perm[i], perm[j])]);
/// }
/// }
/// ```
/// Workspace for [`balance_eigenvectors_in_place`].
///
/// # Examples
/// ```
/// let _buffer = dyn_stack::MemBuffer::new(
/// colmat::linalg::evd::balance_eigenvectors_scratch::<f64>(3),
/// );
/// ```
/// Back-transforms columns of right eigenvectors: `x_original = P D
/// x_balanced`. Accepts any number of columns, including the real/imaginary
/// pair encoding. The columns are not renormalized. `perm` and `scale` are the
/// metadata from [`balance_in_place`].
///
/// # Panics
/// Panics on incompatible lengths, a non-permutation, a nonpositive/nonfinite
/// scale, or insufficient scratch. Metadata must describe the balanced input.
///
/// # Examples
/// ```
/// use dyn_stack::{MemBuffer, MemStack};
/// use colmat::Par;
/// use colmat::linalg::evd::*;
/// let mut x = colmat::mat![[1.0f64], [2.0]];
/// let mut mem = MemBuffer::new(balance_eigenvectors_scratch::<f64>(2));
/// balance_eigenvectors_in_place(
/// x.as_mut(),
/// &[1, 0],
/// &[2.0, 0.5],
/// Par::Seq,
/// MemStack::new(&mut mem),
/// );
/// assert_eq!(x, colmat::mat![[1.0], [2.0]]);
/// ```