Skip to main content

tenferro_linalg/
rank_revealing_qr.rs

1use tenferro_tensor::Error;
2
3use crate::QrGauge;
4
5/// Four fixed-shape outputs of a rank-revealing QR factorization.
6///
7/// `Q` and `R` use `T`; the column permutation and numerical rank use `M`.
8/// For dynamic, eager, and traced tensors, `T` and `M` are the same tensor
9/// type. For typed tensors `LinalgOps::rank_revealing_qr` returns
10/// `RankRevealingQrResult<TypedTensor<T>, TypedTensor<i64>>`.
11///
12/// # Examples
13///
14/// ```rust
15/// use tenferro_linalg::RankRevealingQrResult;
16///
17/// let result = RankRevealingQrResult {
18///     q: "q",
19///     r: "r",
20///     column_permutation: vec![1_i64, 0],
21///     rank: vec![2_i64],
22/// };
23/// assert_eq!(result.column_permutation, [1, 0]);
24/// assert_eq!(result.rank, [2]);
25/// ```
26#[derive(Clone, Debug)]
27pub struct RankRevealingQrResult<T, M = T> {
28    /// Thin orthonormal factor with shape `[m, min(m, n), batch...]`.
29    pub q: T,
30    /// Upper-trapezoidal factor with shape `[min(m, n), n, batch...]`.
31    pub r: T,
32    /// Zero-based original column at each factor column, shaped `[n, batch...]`.
33    pub column_permutation: M,
34    /// Leading-prefix numerical rank, shaped `[batch...]`.
35    pub rank: M,
36}
37
38/// Options for column-pivoted rank-revealing QR.
39///
40/// Rank is the length of the leading diagonal prefix satisfying
41/// `abs(R[i,i]) > max(atol, rtol * abs(R[0,0]))`. Both tolerances must be
42/// finite and non-negative. The default uses zero tolerances so callers choose
43/// an application-specific numerical threshold explicitly.
44///
45/// # Examples
46///
47/// ```rust
48/// use tenferro_linalg::{QrGauge, RankRevealingQrOptions};
49///
50/// let options = RankRevealingQrOptions::default()
51///     .gauge(QrGauge::PositiveDiagonal)
52///     .rtol(1.0e-10)
53///     .atol(1.0e-14);
54/// assert_eq!(options.rtol, 1.0e-10);
55/// assert_eq!(options.atol, 1.0e-14);
56/// ```
57#[derive(Clone, Copy, Debug, PartialEq)]
58#[non_exhaustive]
59pub struct RankRevealingQrOptions {
60    /// QR sign or phase convention. The default is [`QrGauge::Raw`].
61    pub gauge: QrGauge,
62    /// Relative diagonal threshold. The default is `0.0`.
63    pub rtol: f64,
64    /// Absolute diagonal threshold. The default is `0.0`.
65    pub atol: f64,
66}
67
68impl Default for RankRevealingQrOptions {
69    fn default() -> Self {
70        Self {
71            gauge: QrGauge::Raw,
72            rtol: 0.0,
73            atol: 0.0,
74        }
75    }
76}
77
78impl RankRevealingQrOptions {
79    /// Return options with the requested QR gauge.
80    ///
81    /// # Examples
82    ///
83    /// ```rust
84    /// use tenferro_linalg::{QrGauge, RankRevealingQrOptions};
85    ///
86    /// let options = RankRevealingQrOptions::default().gauge(QrGauge::PositiveDiagonal);
87    /// assert_eq!(options.gauge, QrGauge::PositiveDiagonal);
88    /// ```
89    pub fn gauge(mut self, gauge: QrGauge) -> Self {
90        self.gauge = gauge;
91        self
92    }
93
94    /// Return options with the requested relative rank tolerance.
95    ///
96    /// # Examples
97    ///
98    /// ```rust
99    /// use tenferro_linalg::RankRevealingQrOptions;
100    ///
101    /// let options = RankRevealingQrOptions::default().rtol(1.0e-8);
102    /// assert_eq!(options.rtol, 1.0e-8);
103    /// ```
104    pub fn rtol(mut self, rtol: f64) -> Self {
105        self.rtol = rtol;
106        self
107    }
108
109    /// Return options with the requested absolute rank tolerance.
110    ///
111    /// # Examples
112    ///
113    /// ```rust
114    /// use tenferro_linalg::RankRevealingQrOptions;
115    ///
116    /// let options = RankRevealingQrOptions::default().atol(1.0e-12);
117    /// assert_eq!(options.atol, 1.0e-12);
118    /// ```
119    pub fn atol(mut self, atol: f64) -> Self {
120        self.atol = atol;
121        self
122    }
123}
124
125pub(crate) fn validate_rank_revealing_qr_options(
126    op: &'static str,
127    options: RankRevealingQrOptions,
128) -> tenferro_tensor::Result<()> {
129    for (name, value) in [("rtol", options.rtol), ("atol", options.atol)] {
130        if !value.is_finite() || value < 0.0 {
131            return Err(Error::invalid_argument(
132                op,
133                name,
134                format!("must be finite and non-negative, got {value}"),
135            ));
136        }
137    }
138    Ok(())
139}