Skip to main content

tenferro_linalg/
eig_normalize.rs

1//! The public gauge of `eig` eigenvector columns.
2//!
3//! `eig` promises unit 2-norm columns, which the numeric library does not deliver, so the
4//! backend seam normalizes them. A caller that drives `tlinalg` eig itself - a kernel that
5//! batches square blocks on a lane token, say - has to produce the same values and the same
6//! typed failure as `eig`; publishing the routine is what makes that possible without a copy
7//! of the arithmetic (#2387).
8
9use num_complex::Complex;
10use num_traits::cast::AsPrimitive;
11use num_traits::{Float, NumAssign};
12
13use crate::error::into_tensor_error;
14use crate::Error;
15
16/// Normalize the eigenvector columns of a batch of `n x n` column-major blocks in place.
17///
18/// `vectors` holds `n * n` complex elements per batch item, blocks back to back, and only
19/// the first `batch_count` blocks are read and written. Each block is normalized column by
20/// column to unit 2-norm, the gauge `eig` documents.
21///
22/// The arithmetic is the one `eig` uses: each column is scaled by its largest component
23/// before the squares are summed, so a finite column of large magnitude does not square to
24/// infinity and one of tiny magnitude does not square to zero. A column that cannot be
25/// normalized - every component zero, or a non-finite sum - is reported as
26/// `Error::NonFinite` with `op: "eig"` and `role: "eigenvector column"`, the failure `eig`
27/// raises.
28///
29/// The whole slice is validated before anything is written, so an `Err` leaves `vectors`
30/// untouched.
31///
32/// # Errors
33///
34/// A [`tenferro_tensor::Error`] with a validation source when `n` is zero, when
35/// `n * n * batch_count` overflows `usize`, or when `vectors` is shorter than that product;
36/// and a numerical failure carrying [`Error::NonFinite`] for a column with no unit gauge.
37///
38/// # Examples
39///
40/// ```
41/// use num_complex::Complex64;
42/// use tenferro_linalg::normalize_eig_vectors;
43///
44/// // One 2x2 column-major block: columns (2, 0) and (0, 3i).
45/// let mut vectors = [
46///     Complex64::new(2.0, 0.0),
47///     Complex64::new(0.0, 0.0),
48///     Complex64::new(0.0, 0.0),
49///     Complex64::new(0.0, 3.0),
50/// ];
51/// normalize_eig_vectors(&mut vectors, 2, 1)?;
52/// assert_eq!(vectors[0], Complex64::new(1.0, 0.0));
53/// assert_eq!(vectors[3], Complex64::new(0.0, 1.0));
54/// # Ok::<(), tenferro_tensor::Error>(())
55/// ```
56pub fn normalize_eig_vectors<R>(
57    vectors: &mut [Complex<R>],
58    n: usize,
59    batch_count: usize,
60) -> tenferro_tensor::Result<()>
61where
62    R: Float + NumAssign + AsPrimitive<f64> + 'static,
63    f64: AsPrimitive<R>,
64{
65    let block = n.checked_mul(n).filter(|_| n > 0).ok_or_else(|| {
66        tenferro_tensor::Error::invalid_argument(
67            "eig",
68            "vectors",
69            "n must be non-zero to name a column",
70        )
71    })?;
72    let needed = block.checked_mul(batch_count).ok_or_else(|| {
73        tenferro_tensor::Error::invalid_argument(
74            "eig",
75            "vectors",
76            "the eigenvector element count overflows usize",
77        )
78    })?;
79    if vectors.len() < needed {
80        return Err(tenferro_tensor::Error::invalid_argument(
81            "eig",
82            "vectors",
83            format!(
84                "{} elements hold {batch_count} blocks of {n}x{n}, {needed} needed",
85                vectors.len()
86            ),
87        ));
88    }
89
90    for block in vectors[..needed].chunks_exact_mut(block) {
91        for column in block.chunks_exact_mut(n) {
92            // Scale before summing squares. The operand dtype squares its own components,
93            // so a finite column of large magnitude squares to `inf` and one of tiny
94            // magnitude squares to `0`, and both would be rejected as `NonFinite` even
95            // though the column is normalizable. Scaling by the largest component first
96            // keeps every squared term in [0, 1], and the scaling itself is done in f64 so
97            // it cannot overflow.
98            let magnitude = column
99                .iter()
100                .map(|value| {
101                    let largest: f64 = value.re.abs().max(value.im.abs()).as_();
102                    largest
103                })
104                .fold(0.0_f64, f64::max);
105            if magnitude == 0.0 {
106                return Err(non_finite_column());
107            }
108            let norm = magnitude
109                * column
110                    .iter()
111                    .map(|value| {
112                        let re: f64 = value.re.as_() / magnitude;
113                        let im: f64 = value.im.as_() / magnitude;
114                        re * re + im * im
115                    })
116                    .sum::<f64>()
117                    .sqrt();
118            let scale: R = norm.as_();
119            if !norm.is_finite() || !scale.is_finite() || scale == R::zero() {
120                return Err(non_finite_column());
121            }
122            for value in column.iter_mut() {
123                *value /= scale;
124            }
125        }
126    }
127    Ok(())
128}
129
130/// The failure `eig` raises for an eigenvector column with no unit gauge.
131fn non_finite_column() -> tenferro_tensor::Error {
132    into_tensor_error(
133        "eig",
134        Error::NonFinite {
135            op: "eig",
136            role: "eigenvector column",
137        },
138    )
139}
140
141#[cfg(test)]
142mod tests {
143    use num_complex::{Complex32, Complex64};
144
145    use super::normalize_eig_vectors;
146
147    fn norm64(column: &[Complex64]) -> f64 {
148        column.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt()
149    }
150
151    #[test]
152    fn every_column_of_every_block_is_unit() {
153        let mut vectors = [
154            Complex64::new(3.0, 4.0),
155            Complex64::new(0.0, 0.0),
156            Complex64::new(1.0, 0.0),
157            Complex64::new(-2.0, 2.0),
158            Complex64::new(0.5, 0.0),
159            Complex64::new(0.0, -6.0),
160            Complex64::new(1.0, 1.0),
161            Complex64::new(1.0, 1.0),
162        ];
163        normalize_eig_vectors(&mut vectors, 2, 2).unwrap();
164        for block in [&vectors[..4], &vectors[4..]] {
165            for column in [&block[..2], &block[2..]] {
166                assert!((norm64(column) - 1.0).abs() < 1e-12);
167            }
168        }
169    }
170
171    #[test]
172    fn a_huge_f32_column_does_not_square_to_infinity() {
173        // 1e30 squared is inf in f32; the scaled sum keeps both terms in [0, 1].
174        let mut vectors = [
175            Complex32::new(1e30, 0.0),
176            Complex32::new(1e30, 0.0),
177            Complex32::new(0.0, 0.0),
178            Complex32::new(0.0, -1e30),
179        ];
180        normalize_eig_vectors(&mut vectors, 2, 1).unwrap();
181        let scale = 1.0 / 2.0_f32.sqrt();
182        assert!((vectors[0].re - scale).abs() < 1e-6);
183        assert!((vectors[1].re - scale).abs() < 1e-6);
184        assert_eq!(vectors[3], Complex32::new(0.0, -1.0));
185    }
186
187    #[test]
188    fn a_tiny_f64_column_does_not_square_to_zero() {
189        let mut vectors = [
190            Complex64::new(1e-200, 0.0),
191            Complex64::new(0.0, 1e-200),
192            Complex64::new(0.0, 0.0),
193            Complex64::new(1e-200, 0.0),
194        ];
195        normalize_eig_vectors(&mut vectors, 2, 1).unwrap();
196        let scale = 1.0 / 2.0_f64.sqrt();
197        assert!((vectors[0].re - scale).abs() < 1e-12);
198        assert!((vectors[1].im - scale).abs() < 1e-12);
199        assert_eq!(vectors[3], Complex64::new(1.0, 0.0));
200    }
201
202    #[test]
203    fn a_zero_column_is_the_typed_non_finite_failure() {
204        let mut vectors = [Complex64::new(0.0, 0.0); 4];
205        let error = normalize_eig_vectors(&mut vectors, 2, 1).unwrap_err();
206        assert!(format!("{error:?}").contains("NumericalFailure"));
207        assert!(format!("{error:?}").contains("eigenvector column"));
208    }
209
210    #[test]
211    fn a_short_slice_is_rejected_before_anything_is_written() {
212        let mut vectors = [Complex64::new(2.0, 0.0), Complex64::new(0.0, 0.0)];
213        let error = normalize_eig_vectors(&mut vectors, 2, 2).unwrap_err();
214        assert!(format!("{error:?}").contains("8 needed"));
215        assert_eq!(vectors[0], Complex64::new(2.0, 0.0));
216    }
217
218    #[test]
219    fn a_zero_column_count_is_rejected() {
220        let mut vectors = [Complex64::new(1.0, 0.0)];
221        assert!(normalize_eig_vectors(&mut vectors, 0, 1).is_err());
222    }
223}