Skip to main content

tensor4all_tensorbackend/
backend.rs

1//! Backend dispatch helpers for linear algebra operations.
2//!
3//! This module keeps tensor4all's typed factorization entry points thin while
4//! routing the actual work through the shared tenferro CPU backend.
5
6use anyhow::{anyhow, Result};
7use num_complex::{Complex32, Complex64, ComplexFloat};
8use tenferro::{DType, Tensor, TensorScalar, TensorSessionOpsExt, TypedTensor};
9use tenferro_linalg::TensorLinalgExt;
10
11use crate::context::{with_default_session, CpuExecutionContext};
12use crate::matrix::Matrix;
13
14/// Result of SVD decomposition `A = U * diag(S) * Vt`.
15/// The singular values are stored in a real-valued typed tensor, even when the
16/// input matrix is complex.
17/// # Examples
18/// ```
19/// use tensor4all_tensorbackend::svd_backend;
20/// use tenferro::TypedTensor;
21/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
22/// let a = TypedTensor::<f64>::from_vec_col_major(vec![2, 2], vec![1.0, 0.0, 0.0, 2.0])?;
23/// let result = svd_backend(&a)?;
24/// assert_eq!(result.u().shape(), &[2, 2]);
25/// assert_eq!(result.s().shape(), &[2]);
26/// assert_eq!(result.vt().shape(), &[2, 2]);
27/// # Ok(())
28/// # }
29/// ```
30#[derive(Debug)]
31pub struct SvdResult<T: TensorScalar> {
32    u: TypedTensor<T>,
33    s: TypedTensor<T::Real>,
34    vt: TypedTensor<T>,
35}
36
37/// Result of complete-pivoting LU decomposition `P A Q^T = L U`.
38/// The parity output from tenferro is intentionally omitted because current
39/// tensor4all callers only need the permutation matrices and the upper
40/// triangular factor for pivot selection.
41#[derive(Debug)]
42pub struct FullPivLuResult<T: TensorScalar> {
43    p: TypedTensor<T>,
44    l: TypedTensor<T>,
45    u: TypedTensor<T>,
46    q: TypedTensor<T>,
47}
48
49fn clone_linalg_tensor<T: TensorScalar>(tensor: &TypedTensor<T>) -> TypedTensor<T> {
50    tensor.duplicate().unwrap_or_else(|error| {
51        crate::invariant_violated("linalg result duplication failed", error)
52    })
53}
54
55impl<T: TensorScalar> SvdResult<T> {
56    /// Borrow the left singular vectors.
57    pub fn u(&self) -> &TypedTensor<T> {
58        &self.u
59    }
60
61    /// Borrow the singular values.
62    pub fn s(&self) -> &TypedTensor<T::Real> {
63        &self.s
64    }
65
66    /// Borrow the transposed right singular vectors.
67    pub fn vt(&self) -> &TypedTensor<T> {
68        &self.vt
69    }
70
71    /// Consume the decomposition into `(U, S, Vt)`.
72    pub fn into_parts(self) -> (TypedTensor<T>, TypedTensor<T::Real>, TypedTensor<T>) {
73        (self.u, self.s, self.vt)
74    }
75}
76
77impl<T: TensorScalar> FullPivLuResult<T> {
78    /// Borrow the left permutation matrix.
79    pub fn p(&self) -> &TypedTensor<T> {
80        &self.p
81    }
82
83    /// Borrow the lower triangular factor.
84    pub fn l(&self) -> &TypedTensor<T> {
85        &self.l
86    }
87
88    /// Borrow the upper triangular factor.
89    pub fn u(&self) -> &TypedTensor<T> {
90        &self.u
91    }
92
93    /// Borrow the right permutation matrix.
94    pub fn q(&self) -> &TypedTensor<T> {
95        &self.q
96    }
97
98    /// Consume the decomposition into `(P, L, U, Q)`.
99    pub fn into_parts(
100        self,
101    ) -> (
102        TypedTensor<T>,
103        TypedTensor<T>,
104        TypedTensor<T>,
105        TypedTensor<T>,
106    ) {
107        (self.p, self.l, self.u, self.q)
108    }
109}
110
111impl<T: TensorScalar> Clone for SvdResult<T> {
112    fn clone(&self) -> Self {
113        Self {
114            u: clone_linalg_tensor(&self.u),
115            s: clone_linalg_tensor(&self.s),
116            vt: clone_linalg_tensor(&self.vt),
117        }
118    }
119}
120
121impl<T: TensorScalar> Clone for FullPivLuResult<T> {
122    fn clone(&self) -> Self {
123        Self {
124            p: clone_linalg_tensor(&self.p),
125            l: clone_linalg_tensor(&self.l),
126            u: clone_linalg_tensor(&self.u),
127            q: clone_linalg_tensor(&self.q),
128        }
129    }
130}
131
132/// Result of complete-pivoting LU decomposition on [`Matrix`] values.
133/// This is the matrix-shaped counterpart of [`FullPivLuResult`]. It exists so
134/// downstream crates can use backend linalg without hand-writing
135/// `TypedTensor` conversion code.
136/// # Examples
137/// ```
138/// use tensor4all_tensorbackend::{from_vec2d, full_piv_lu_matrix};
139/// let matrix = from_vec2d(vec![vec![0.0_f64, 1.0], vec![2.0, 3.0]]);
140/// let factors = full_piv_lu_matrix(&matrix).unwrap();
141/// assert_eq!(factors.u.nrows(), 2);
142/// assert_eq!(factors.u.ncols(), 2);
143/// ```
144#[derive(Debug, Clone)]
145pub struct FullPivLuMatrixResult<T> {
146    /// Left permutation matrix.
147    pub p: Matrix<T>,
148    /// Lower triangular factor.
149    pub l: Matrix<T>,
150    /// Upper triangular factor.
151    pub u: Matrix<T>,
152    /// Right permutation matrix.
153    pub q: Matrix<T>,
154}
155
156/// Scalar bound accepted by tensor4all's typed linalg wrappers.
157pub trait BackendLinalgScalar: TensorScalar {}
158
159/// Scalar types that can solve `T * P = Pi1` via a right full-pivoting LU
160/// solve on the tenferro backend.
161///
162/// This is the foundational seam for matrix cross-interpolation (CI)
163/// materialization: it lets an algorithm layer ask for the backend's
164/// full-pivot LU solve without depending on any higher crate. The four
165/// supported scalar types (f32, f64, Complex32, Complex64) are implemented
166/// here; the backend solves each in its own scalar type along its own kernel
167/// route, and this trait adds no promotion of its own.
168///
169/// # Errors
170///
171/// Returns an error when the pivot matrix is not square, the shapes are
172/// incompatible, or the backend solve fails.
173pub trait FullPivLuScalar: BackendLinalgScalar {
174    /// Solve `T * P = Pi1` for `T`, where `P` is the pivot matrix (column-major).
175    ///
176    /// # Errors
177    ///
178    /// Returns a [`BackendLinalgError`] when the pivot matrix is not square
179    /// (a shape mismatch), when the shapes are incompatible (`lhs_cols !=
180    /// pivot_rows`, a shape mismatch), or when the backend full-pivot LU solve
181    /// fails (a backend failure).
182    fn solve_right_full_piv_lu(
183        lhs_values: &[Self],
184        lhs_rows: usize,
185        lhs_cols: usize,
186        pivot_values: &[Self],
187        pivot_rows: usize,
188        pivot_cols: usize,
189    ) -> std::result::Result<Vec<Self>, BackendLinalgError>;
190
191    /// Same solve, in a caller-owned execution context.
192    ///
193    /// The shapes and values are interpreted exactly as in
194    /// [`Self::solve_right_full_piv_lu`]; only the engine that performs the
195    /// solve is the caller's, so the work runs on the caller's backend instead
196    /// of the process-global one. The context is entered after the operands are
197    /// prepared and validated; a caller that must avoid an entry for a
198    /// degenerate input decides that before calling this method (the
199    /// materialization layer's all-zero pivot shortcut is one such caller).
200    ///
201    /// # Errors
202    ///
203    /// Returns a [`BackendLinalgError`] when the pivot matrix is not square
204    /// (a shape mismatch), when the shapes are incompatible (`lhs_cols !=
205    /// pivot_rows`, a shape mismatch), when the context rejects the entry (a
206    /// nested session on this thread, with the original entry error kept as the
207    /// source), or when the backend full-pivot LU solve fails (a backend
208    /// failure).
209    fn solve_right_full_piv_lu_in(
210        context: &CpuExecutionContext,
211        lhs_values: &[Self],
212        lhs_rows: usize,
213        lhs_cols: usize,
214        pivot_values: &[Self],
215        pivot_rows: usize,
216        pivot_cols: usize,
217    ) -> std::result::Result<Vec<Self>, BackendLinalgError>;
218
219    /// Same solve, on an engine the caller already holds.
220    ///
221    /// Neither this method nor the backend enters a context, and nothing
222    /// consults the process-global one. The shapes and values are interpreted
223    /// exactly as in [`Self::solve_right_full_piv_lu`], and they are validated
224    /// before the engine is used.
225    ///
226    /// # Errors
227    ///
228    /// Returns a [`BackendLinalgError`] when the pivot matrix is not square
229    /// (a shape mismatch), when the shapes are incompatible (`lhs_cols !=
230    /// pivot_rows`, a shape mismatch), or when the backend full-pivot LU solve
231    /// fails on the supplied engine (a backend failure).
232    fn solve_right_full_piv_lu_on_session(
233        session: &mut dyn tenferro_tensor::Engine,
234        lhs_values: &[Self],
235        lhs_rows: usize,
236        lhs_cols: usize,
237        pivot_values: &[Self],
238        pivot_rows: usize,
239        pivot_cols: usize,
240    ) -> std::result::Result<Vec<Self>, BackendLinalgError>;
241}
242
243macro_rules! impl_full_piv_lu_scalar {
244    ($t:ty) => {
245        impl FullPivLuScalar for $t {
246            fn solve_right_full_piv_lu(
247                lhs_values: &[Self],
248                lhs_rows: usize,
249                lhs_cols: usize,
250                pivot_values: &[Self],
251                pivot_rows: usize,
252                pivot_cols: usize,
253            ) -> std::result::Result<Vec<Self>, BackendLinalgError> {
254                let inputs = FullPivLuSolveInputs::new(
255                    lhs_values,
256                    lhs_rows,
257                    lhs_cols,
258                    pivot_values,
259                    pivot_rows,
260                    pivot_cols,
261                )?;
262                let solved_t =
263                    with_default_session(|session| inputs.solve(session)).map_err(|e| {
264                        BackendLinalgError::from(anyhow::anyhow!("full_piv_lu_solve failed: {e}"))
265                    })?;
266                inputs.finish::<Self>(solved_t)
267            }
268
269            fn solve_right_full_piv_lu_in(
270                context: &CpuExecutionContext,
271                lhs_values: &[Self],
272                lhs_rows: usize,
273                lhs_cols: usize,
274                pivot_values: &[Self],
275                pivot_rows: usize,
276                pivot_cols: usize,
277            ) -> std::result::Result<Vec<Self>, BackendLinalgError> {
278                let inputs = FullPivLuSolveInputs::new(
279                    lhs_values,
280                    lhs_rows,
281                    lhs_cols,
282                    pivot_values,
283                    pivot_rows,
284                    pivot_cols,
285                )?;
286                // A rejected entry keeps its own error as the source: the
287                // caller asked for its context, so a worker refusal must stay
288                // visible as a refusal rather than as text. Validation stays
289                // before the entry: a malformed operand must fail without
290                // waiting for the caller's engine.
291                let solved_t = context
292                    .with_concrete_session(|session| inputs.solve(session.engine()))
293                    .map_err(|error| BackendLinalgError::from(anyhow::Error::new(error)))?
294                    .map_err(|error| {
295                        BackendLinalgError::from(anyhow::anyhow!(
296                            "full_piv_lu_solve failed: {error}"
297                        ))
298                    })?;
299                inputs.finish::<Self>(solved_t)
300            }
301
302            fn solve_right_full_piv_lu_on_session(
303                session: &mut dyn tenferro_tensor::Engine,
304                lhs_values: &[Self],
305                lhs_rows: usize,
306                lhs_cols: usize,
307                pivot_values: &[Self],
308                pivot_rows: usize,
309                pivot_cols: usize,
310            ) -> std::result::Result<Vec<Self>, BackendLinalgError> {
311                let inputs = FullPivLuSolveInputs::new(
312                    lhs_values,
313                    lhs_rows,
314                    lhs_cols,
315                    pivot_values,
316                    pivot_rows,
317                    pivot_cols,
318                )?;
319                let solved_t = inputs.solve(session).map_err(|error| {
320                    BackendLinalgError::from(anyhow::anyhow!("full_piv_lu_solve failed: {error}"))
321                })?;
322                inputs.finish::<Self>(solved_t)
323            }
324        }
325    };
326}
327
328/// Validated, transposed operands for a right full-pivot LU solve.
329///
330/// Preparing them is engine-free on purpose: an invalid shape must fail
331/// before any context is entered.
332struct FullPivLuSolveInputs {
333    pivot_tensor: tenferro_tensor::Tensor,
334    lhs_tensor: tenferro_tensor::Tensor,
335    lhs_cols: usize,
336    lhs_rows: usize,
337}
338
339impl FullPivLuSolveInputs {
340    fn new<T: BackendLinalgScalar + num_traits::Zero>(
341        lhs_values: &[T],
342        lhs_rows: usize,
343        lhs_cols: usize,
344        pivot_values: &[T],
345        pivot_rows: usize,
346        pivot_cols: usize,
347    ) -> std::result::Result<Self, BackendLinalgError> {
348        if pivot_rows != pivot_cols {
349            return Err(BackendLinalgError::from(anyhow::anyhow!(
350                "full-pivot solve requires a square pivot matrix, got {}x{}",
351                pivot_rows,
352                pivot_cols
353            )));
354        }
355        if lhs_cols != pivot_rows {
356            return Err(BackendLinalgError::from(anyhow::anyhow!(
357                "cannot solve T * P = Pi1 with Pi1 shape {}x{} and P shape {}x{}",
358                lhs_rows,
359                lhs_cols,
360                pivot_rows,
361                pivot_cols
362            )));
363        }
364
365        let lhs_t = transpose_column_major(lhs_values, lhs_rows, lhs_cols);
366        let pivot_t = transpose_column_major(pivot_values, pivot_rows, pivot_cols);
367        let pivot_tensor =
368            tenferro_tensor::Tensor::from_vec_col_major(vec![pivot_cols, pivot_rows], pivot_t)
369                .map_err(|e| BackendLinalgError::from(anyhow::Error::new(e)))?;
370        let lhs_tensor =
371            tenferro_tensor::Tensor::from_vec_col_major(vec![lhs_cols, lhs_rows], lhs_t)
372                .map_err(|e| BackendLinalgError::from(anyhow::Error::new(e)))?;
373        Ok(Self {
374            pivot_tensor,
375            lhs_tensor,
376            lhs_cols,
377            lhs_rows,
378        })
379    }
380
381    fn solve(
382        &self,
383        session: &mut dyn tenferro_tensor::Engine,
384    ) -> tenferro_tensor::Result<tenferro_tensor::Tensor> {
385        self.pivot_tensor
386            .full_piv_lu_solve(&self.lhs_tensor, session)
387    }
388
389    fn finish<T: BackendLinalgScalar + num_traits::Zero>(
390        &self,
391        solved_t: tenferro_tensor::Tensor,
392    ) -> std::result::Result<Vec<T>, BackendLinalgError> {
393        let solved_t_values = solved_t.as_slice::<T>().map_err(|e| {
394            BackendLinalgError::from(anyhow::anyhow!(
395                "full_piv_lu_solve returned unexpected dtype: {e}"
396            ))
397        })?;
398        Ok(transpose_column_major(
399            solved_t_values,
400            self.lhs_cols,
401            self.lhs_rows,
402        ))
403    }
404}
405
406impl_full_piv_lu_scalar!(f32);
407impl_full_piv_lu_scalar!(f64);
408impl_full_piv_lu_scalar!(num_complex::Complex32);
409impl_full_piv_lu_scalar!(num_complex::Complex64);
410
411/// Transpose a column-major flat buffer.
412fn transpose_column_major<T: Copy + num_traits::Zero>(
413    values: &[T],
414    nrows: usize,
415    ncols: usize,
416) -> Vec<T> {
417    let mut out = vec![T::zero(); nrows * ncols];
418    for col in 0..ncols {
419        for row in 0..nrows {
420            out[col + ncols * row] = values[row + nrows * col];
421        }
422    }
423    out
424}
425
426impl<T: TensorScalar> BackendLinalgScalar for T {}
427
428/// Scalar types supported by [`solve_matrix`].
429/// `f64` and `Complex64` are solved directly. `f32` and `Complex32` are
430/// promoted to the corresponding 64-bit dtype for the backend solve and then
431/// converted back, because the current tenferro CPU LU solve is double
432/// precision only.
433/// # Examples
434/// ```
435/// use tensor4all_tensorbackend::{from_vec2d, solve_matrix};
436/// let a = from_vec2d(vec![vec![2.0_f32, 1.0], vec![1.0, 2.0]]);
437/// let b = from_vec2d(vec![vec![1.0_f32], vec![0.0]]);
438/// let x = solve_matrix(&a, &b).unwrap();
439/// assert!((x[[0, 0]] - 2.0 / 3.0).abs() < 1.0e-6);
440/// ```
441pub trait MatrixSolveScalar: BackendLinalgScalar + crate::matrix::MatrixScalar {
442    #[doc(hidden)]
443    fn solve_matrix_impl(a: &Matrix<Self>, b: &Matrix<Self>) -> Result<Matrix<Self>>;
444
445    #[doc(hidden)]
446    fn solve_matrix_owned_impl(a: Matrix<Self>, b: Matrix<Self>) -> Result<Matrix<Self>> {
447        Self::solve_matrix_impl(&a, &b)
448    }
449
450    /// Solve `a * x = b` on an engine the caller already holds.
451    ///
452    /// The engine-taking counterpart of [`Self::solve_matrix_impl`], for
453    /// callers that own their execution domain rather than a context they may
454    /// enter themselves.
455    ///
456    /// # Errors
457    ///
458    /// Returns the backend's solve failure: a non-square factor, an
459    /// incompatible right-hand side, a singular factor, or an engine-level
460    /// execution failure.
461    #[doc(hidden)]
462    fn solve_matrix_in_impl(
463        session: &mut dyn tenferro_tensor::Engine,
464        a: &Matrix<Self>,
465        b: &Matrix<Self>,
466    ) -> Result<Matrix<Self>>;
467}
468
469/// Error returned by the CPU backend linear-algebra dispatch helpers.
470///
471/// Wraps the underlying tenferro or shape diagnostic, preserving its source
472/// chain.
473///
474/// # Remedies
475/// - Shape/dtype mismatch: verify matrix dims and scalar dtypes against the
476///   operation contract before calling.
477/// - Singular or invalid input: check matrix conditioning and finite values
478///   before solve/factorization operations.
479/// - Backend failure: the wrapped source chain identifies the failing stage.
480#[derive(Debug, thiserror::Error)]
481#[error("backend linear algebra failed: {source}")]
482pub struct BackendLinalgError {
483    /// Original backend or shape diagnostic.
484    #[source]
485    pub source: anyhow::Error,
486}
487
488impl From<anyhow::Error> for BackendLinalgError {
489    fn from(source: anyhow::Error) -> Self {
490        Self { source }
491    }
492}
493
494/// Scalar types supported by [`triangular_solve_matrix`] and
495/// [`triangular_solve_matrix_in`].
496/// `f64` and `Complex64` are solved directly. `f32` and `Complex32` are
497/// promoted to the corresponding 64-bit dtype for the backend solve and then
498/// converted back, because the current tenferro CPU triangular solve is double
499/// precision only. The process-global and the session route apply the same
500/// promotion, so they return bitwise identical results for every scalar type.
501/// # Examples
502/// ```
503/// use tensor4all_tensorbackend::{from_vec2d, triangular_solve_matrix};
504/// let a = from_vec2d(vec![vec![2.0_f64, 0.0], vec![1.0, 3.0]]);
505/// let b = from_vec2d(vec![vec![2.0_f64], vec![7.0]]);
506/// let x = triangular_solve_matrix(&a, &b, true, true, false, false).unwrap();
507/// assert!((x[[0, 0]] - 1.0).abs() < 1.0e-12);
508/// assert!((x[[1, 0]] - 2.0).abs() < 1.0e-12);
509/// ```
510pub trait MatrixTriangularSolveScalar: BackendLinalgScalar + crate::matrix::MatrixScalar {
511    #[doc(hidden)]
512    fn triangular_solve_matrix_impl(
513        a: &Matrix<Self>,
514        b: &Matrix<Self>,
515        left_side: bool,
516        lower: bool,
517        transpose_a: bool,
518        unit_diagonal: bool,
519    ) -> Result<Matrix<Self>>;
520
521    #[doc(hidden)]
522    fn triangular_solve_matrix_owned_impl(
523        a: Matrix<Self>,
524        b: Matrix<Self>,
525        left_side: bool,
526        lower: bool,
527        transpose_a: bool,
528        unit_diagonal: bool,
529    ) -> Result<Matrix<Self>> {
530        Self::triangular_solve_matrix_impl(&a, &b, left_side, lower, transpose_a, unit_diagonal)
531    }
532
533    /// Solve a triangular system on an engine the caller already holds.
534    ///
535    /// The engine-taking counterpart of [`Self::triangular_solve_matrix_impl`],
536    /// with the same scalar promotion, so both routes agree bit for bit.
537    ///
538    /// # Errors
539    ///
540    /// Returns the backend's triangular-solve failure: incompatible shapes,
541    /// inconsistent triangular flags, or an engine-level execution failure.
542    #[doc(hidden)]
543    #[allow(clippy::too_many_arguments)]
544    fn triangular_solve_matrix_in_impl(
545        session: &mut dyn tenferro_tensor::Engine,
546        a: &Matrix<Self>,
547        b: &Matrix<Self>,
548        left_side: bool,
549        lower: bool,
550        transpose_a: bool,
551        unit_diagonal: bool,
552    ) -> Result<Matrix<Self>>;
553}
554
555/// Small-matrix diagnostics produced by the successive randomized compression
556/// stopping estimator.
557///
558/// `error` is the Appendix C randomized residual estimate and `norm` is the
559/// corresponding Frobenius norm estimate. Both values use the sketch width as
560/// their normalization factor.
561///
562/// # Examples
563///
564/// ```
565/// use tensor4all_tensorbackend::{src_error_estimate, Matrix};
566///
567/// let r = Matrix::from_col_major_vec(1, 1, vec![2.0_f64]);
568/// let estimate = src_error_estimate(&r).unwrap();
569/// assert!((estimate.error - 2.0).abs() < 1.0e-12);
570/// assert!((estimate.norm - 2.0).abs() < 1.0e-12);
571/// ```
572#[derive(Debug, Clone, Copy, PartialEq)]
573pub struct SrcErrorEstimate {
574    /// Estimated residual magnitude from the inverse-adjoint QR factor.
575    pub error: f64,
576    /// Estimated norm of the sketched tensor from the QR factor.
577    pub norm: f64,
578}
579
580/// Compute the Appendix C SRC error and norm estimates from an upper-triangular
581/// QR factor `R`.
582///
583/// Provenance: the formulas are Eq. (err-est) and Eq. (norm-est) in Appendix C
584/// of Camaño--Epperly--Tropp, [arXiv:2504.06475](https://arxiv.org/abs/2504.06475),
585/// cross-checked against `chriscamano/RandomMPOMPS/code/tensornetwork/incrementalqr.cpp::get_error_estimate`
586/// (lines 106--119). The use of actual `R` plus an `R†` solve is an equivalent
587/// representation derived in the audit; it is not a literal port of the
588/// author's inverse-`R` storage.
589///
590/// The helper explicitly builds `R†` before solving `R† G = I`, so complex
591/// inputs use the Hermitian adjoint rather than a plain transpose. The solve is
592/// delegated to the configured tensor4all backend and is restricted to the
593/// small sketch matrix; no general dense inverse routine is used.
594///
595/// # Errors
596///
597/// Returns [`BackendLinalgError`] when `r` is empty, non-square,
598/// non-triangular, singular, or contains non-finite values, or when the backend
599/// triangular solve fails.
600///
601/// # Examples
602///
603/// ```
604/// use tensor4all_tensorbackend::{src_error_estimate, Matrix};
605///
606/// let r = Matrix::from_col_major_vec(2, 2, vec![2.0_f64, 0.0, 1.0, 3.0]);
607/// let estimate = src_error_estimate(&r).unwrap();
608/// assert!(estimate.error.is_finite());
609/// assert!(estimate.norm.is_finite());
610/// ```
611pub fn src_error_estimate<T>(
612    r: &Matrix<T>,
613) -> std::result::Result<SrcErrorEstimate, BackendLinalgError>
614where
615    T: MatrixTriangularSolveScalar + ComplexFloat,
616{
617    let inverse_adjoint = src_inverse_adjoint(r)?;
618    src_error_estimate_from_inverse_adjoint(r, &inverse_adjoint)
619}
620
621/// Compute the Appendix C SRC estimates from a general square sketch factor.
622///
623/// This variant is equivalent to [`src_error_estimate`] but uses a general
624/// solve for factors whose columns have been restored from pivoted QR order.
625/// The matrix is a small SRC sketch factor, not a full tensor materialization.
626///
627/// # Errors
628///
629/// Returns [`BackendLinalgError`] when `factor` is empty, non-square, singular,
630/// contains non-finite values, or when the configured general solve fails.
631///
632/// # Examples
633///
634/// ```
635/// use tensor4all_tensorbackend::{src_error_estimate_general, Matrix};
636///
637/// let factor = Matrix::from_col_major_vec(2, 2, vec![0.0_f64, 3.0, 2.0, 1.0]);
638/// let estimate = src_error_estimate_general(&factor).unwrap();
639/// assert!(estimate.error.is_finite());
640/// assert!((estimate.norm - (14.0_f64 / 2.0).sqrt()).abs() < 1.0e-12);
641/// ```
642pub fn src_error_estimate_general<T>(
643    factor: &Matrix<T>,
644) -> std::result::Result<SrcErrorEstimate, BackendLinalgError>
645where
646    T: MatrixSolveScalar + ComplexFloat,
647{
648    let nrows = factor.nrows();
649    let ncols = factor.ncols();
650    if nrows != ncols {
651        return Err(BackendLinalgError::from(anyhow!(
652            "SRC estimator requires a square factor, got {nrows}x{ncols}"
653        )));
654    }
655    if nrows == 0 {
656        return Err(BackendLinalgError::from(anyhow!(
657            "SRC estimator requires a non-empty factor"
658        )));
659    }
660    if factor
661        .as_col_major_slice()
662        .iter()
663        .any(|value| !value.matrix_abs_sq().is_finite())
664    {
665        return Err(BackendLinalgError::from(anyhow!(
666            "SRC estimator requires finite entries in its factor"
667        )));
668    }
669    let mut adjoint = Matrix::zeros(nrows, ncols);
670    let mut identity = Matrix::zeros(nrows, ncols);
671    for col in 0..ncols {
672        for row in 0..nrows {
673            adjoint[[row, col]] = factor[[col, row]].conj();
674        }
675        identity[[col, col]] = T::one();
676    }
677    let inverse_adjoint = solve_matrix(&adjoint, &identity).map_err(|error| {
678        BackendLinalgError::from(anyhow!("SRC inverse-adjoint general solve failed: {error}"))
679    })?;
680    src_error_estimate_from_inverse_adjoint(factor, &inverse_adjoint)
681}
682
683/// Compute the inverse adjoint `R^{-†}` used by the Appendix C estimator.
684///
685/// This is crate-visible so incremental QR can initialize the stored
686/// estimator state once and then update it with the block formula from
687/// Appendix C.3 instead of solving the same triangular system after every
688/// appended sketch block.
689pub(crate) fn src_inverse_adjoint<T>(
690    r: &Matrix<T>,
691) -> std::result::Result<Matrix<T>, BackendLinalgError>
692where
693    T: MatrixTriangularSolveScalar + ComplexFloat,
694{
695    let nrows = r.nrows();
696    let ncols = r.ncols();
697    if nrows != ncols {
698        return Err(BackendLinalgError::from(anyhow!(
699            "SRC estimator requires a square R, got {nrows}x{ncols}"
700        )));
701    }
702    if nrows == 0 {
703        return Err(BackendLinalgError::from(anyhow!(
704            "SRC estimator requires a non-empty R"
705        )));
706    }
707
708    // Only the diagonal is checked here; the full-R Frobenius-norm
709    // finiteness check lives solely in `src_error_estimate_from_inverse_adjoint`,
710    // which every `src_error_estimate` call already runs immediately after
711    // this function returns. Duplicating that O(rank^2) accumulation here
712    // would recompute the identical sum for nothing on SRC's adaptive
713    // stopping-test hot path.
714    for col in 0..ncols {
715        let diagonal_sq = r[[col, col]].matrix_abs_sq();
716        if !diagonal_sq.is_finite() || diagonal_sq == 0.0 {
717            return Err(BackendLinalgError::from(anyhow!(
718                "SRC estimator requires a finite, nonzero diagonal in R at ({col}, {col})"
719            )));
720        }
721        for row in col + 1..nrows {
722            if r[[row, col]].matrix_abs_sq() != 0.0 {
723                return Err(BackendLinalgError::from(anyhow!(
724                    "SRC triangular estimator requires upper-triangular R; entry ({row}, {col}) is nonzero"
725                )));
726            }
727        }
728    }
729
730    let mut adjoint = Matrix::zeros(nrows, ncols);
731    for col in 0..ncols {
732        for row in 0..nrows {
733            adjoint[[row, col]] = r[[col, row]].conj();
734        }
735    }
736    let mut identity = Matrix::zeros(nrows, ncols);
737    for diagonal in 0..nrows {
738        identity[[diagonal, diagonal]] = T::one();
739    }
740
741    let inverse_adjoint = triangular_solve_matrix(&adjoint, &identity, true, true, false, false)
742        .map_err(|error| {
743            BackendLinalgError::from(anyhow!(
744                "SRC inverse-adjoint triangular solve failed: {error}"
745            ))
746        })?;
747    Ok(inverse_adjoint)
748}
749
750/// Evaluate the Appendix C estimator from a previously computed `R^{-†}`.
751///
752/// The inverse-adjoint argument is intentionally separate from
753/// [`src_error_estimate`] so incremental QR can reuse its updated triangular
754/// solve state. This helper performs only norm accumulation and validation.
755pub(crate) fn src_error_estimate_from_inverse_adjoint<T>(
756    r: &Matrix<T>,
757    inverse_adjoint: &Matrix<T>,
758) -> std::result::Result<SrcErrorEstimate, BackendLinalgError>
759where
760    T: crate::matrix::MatrixScalar + ComplexFloat,
761{
762    let nrows = r.nrows();
763    let ncols = r.ncols();
764    if nrows != ncols || inverse_adjoint.nrows() != nrows || inverse_adjoint.ncols() != ncols {
765        return Err(BackendLinalgError::from(anyhow!(
766            "SRC estimator requires matching square R and inverse-adjoint factors"
767        )));
768    }
769    if nrows == 0 {
770        return Err(BackendLinalgError::from(anyhow!(
771            "SRC estimator requires a non-empty R"
772        )));
773    }
774
775    let mut norm_sq = 0.0_f64;
776    for value in r.as_col_major_slice() {
777        norm_sq += value.matrix_abs_sq();
778    }
779    if !norm_sq.is_finite() {
780        return Err(BackendLinalgError::from(anyhow!(
781            "SRC estimator requires finite entries in R"
782        )));
783    }
784    let mut inverse_column_error_sq = 0.0_f64;
785    for col in 0..ncols {
786        let column_norm_sq = (0..nrows)
787            .map(|row| inverse_adjoint[[row, col]].matrix_abs_sq())
788            .sum::<f64>();
789        if !column_norm_sq.is_finite() || column_norm_sq == 0.0 {
790            return Err(BackendLinalgError::from(anyhow!(
791                "SRC inverse-adjoint solve returned an invalid column norm at column {col}"
792            )));
793        }
794        inverse_column_error_sq += 1.0 / column_norm_sq;
795    }
796
797    let sketch_width = ncols as f64;
798    let error_sq = inverse_column_error_sq / sketch_width;
799    let norm_estimate_sq = norm_sq / sketch_width;
800    if !error_sq.is_finite() || !norm_estimate_sq.is_finite() {
801        return Err(BackendLinalgError::from(anyhow!(
802            "SRC estimator produced a non-finite estimate"
803        )));
804    }
805    Ok(SrcErrorEstimate {
806        error: error_sq.sqrt(),
807        norm: norm_estimate_sq.sqrt(),
808    })
809}
810
811fn solve_matrix_direct<T>(a: &Matrix<T>, b: &Matrix<T>) -> Result<Matrix<T>>
812where
813    T: BackendLinalgScalar + Copy,
814    Tensor: From<TypedTensor<T>>,
815{
816    with_default_session(|session| Ok(solve_matrix_direct_in(session, a, b)))
817        .map_err(|e| anyhow!("linear solve failed via tenferro-tensor: {e}"))?
818}
819
820fn solve_matrix_direct_in<T>(
821    session: &mut dyn tenferro_tensor::Engine,
822    a: &Matrix<T>,
823    b: &Matrix<T>,
824) -> Result<Matrix<T>>
825where
826    T: BackendLinalgScalar + Copy,
827    Tensor: From<TypedTensor<T>>,
828{
829    solve_matrix_direct_owned_in(session, a.clone(), b.clone())
830}
831
832fn solve_matrix_direct_owned<T>(a: Matrix<T>, b: Matrix<T>) -> Result<Matrix<T>>
833where
834    T: BackendLinalgScalar + Copy,
835    Tensor: From<TypedTensor<T>>,
836{
837    with_default_session(|session| Ok(solve_matrix_direct_owned_in(session, a, b)))
838        .map_err(|e| anyhow!("linear solve failed via tenferro-tensor: {e}"))?
839}
840
841fn solve_matrix_direct_owned_in<T>(
842    session: &mut dyn tenferro_tensor::Engine,
843    a: Matrix<T>,
844    b: Matrix<T>,
845) -> Result<Matrix<T>>
846where
847    T: BackendLinalgScalar + Copy,
848    Tensor: From<TypedTensor<T>>,
849{
850    use tenferro_linalg::TensorLinalgExt;
851
852    let a_tensor: Tensor = a.into_typed_tensor().into();
853    let b_tensor: Tensor = b.into_typed_tensor().into();
854    let result = a_tensor
855        .solve(&b_tensor, session)
856        .map_err(|e| anyhow!("linear solve failed via tenferro-tensor: {e}"))?;
857    let x = try_into_typed_result::<T>("solve", result)?;
858    typed_tensor_to_matrix("solve", x)
859}
860
861/// Solve `A X = B` on a caller-held engine.
862///
863/// Same kernel and validation as [`solve_matrix`], entered through the given session
864/// instead of the process-global one. The scalar conversion differs for the narrow
865/// types: `f64` and `Complex64` are solved directly on both routes, so the results
866/// agree bit for bit, but this entry solves `f32` and `Complex32` in their own
867/// precision, while [`solve_matrix`] promotes them to `f64` / `Complex64` and narrows
868/// the result. For the narrow types the two routes can therefore differ in the last
869/// bits; [`MatrixSolveScalar`]'s session hook applies the global route's promotion.
870///
871/// # Errors
872///
873/// Returns [`BackendLinalgError`] under the same conditions as [`solve_matrix`].
874pub fn solve_matrix_in<T>(
875    session: &mut dyn tenferro_tensor::Engine,
876    a: &Matrix<T>,
877    b: &Matrix<T>,
878) -> std::result::Result<Matrix<T>, BackendLinalgError>
879where
880    T: BackendLinalgScalar + Copy,
881    Tensor: From<TypedTensor<T>>,
882{
883    solve_matrix_direct_in(session, a, b).map_err(BackendLinalgError::from)
884}
885
886fn triangular_solve_matrix_direct<T>(
887    a: &Matrix<T>,
888    b: &Matrix<T>,
889    left_side: bool,
890    lower: bool,
891    transpose_a: bool,
892    unit_diagonal: bool,
893) -> Result<Matrix<T>>
894where
895    T: BackendLinalgScalar + Copy,
896    Tensor: From<TypedTensor<T>>,
897{
898    with_default_session(|session| {
899        Ok(triangular_solve_matrix_direct_in(
900            session,
901            a,
902            b,
903            left_side,
904            lower,
905            transpose_a,
906            unit_diagonal,
907        ))
908    })
909    .map_err(|e| anyhow!("triangular solve failed via tenferro-tensor: {e}"))?
910}
911
912#[allow(clippy::too_many_arguments)]
913fn triangular_solve_matrix_direct_in<T>(
914    session: &mut dyn tenferro_tensor::Engine,
915    a: &Matrix<T>,
916    b: &Matrix<T>,
917    left_side: bool,
918    lower: bool,
919    transpose_a: bool,
920    unit_diagonal: bool,
921) -> Result<Matrix<T>>
922where
923    T: BackendLinalgScalar + Copy,
924    Tensor: From<TypedTensor<T>>,
925{
926    triangular_solve_matrix_direct_owned_in(
927        session,
928        a.clone(),
929        b.clone(),
930        left_side,
931        lower,
932        transpose_a,
933        unit_diagonal,
934    )
935}
936
937fn triangular_solve_matrix_direct_owned<T>(
938    a: Matrix<T>,
939    b: Matrix<T>,
940    left_side: bool,
941    lower: bool,
942    transpose_a: bool,
943    unit_diagonal: bool,
944) -> Result<Matrix<T>>
945where
946    T: BackendLinalgScalar + Copy,
947    Tensor: From<TypedTensor<T>>,
948{
949    with_default_session(|session| {
950        Ok(triangular_solve_matrix_direct_owned_in(
951            session,
952            a,
953            b,
954            left_side,
955            lower,
956            transpose_a,
957            unit_diagonal,
958        ))
959    })
960    .map_err(|e| anyhow!("triangular solve failed via tenferro-tensor: {e}"))?
961}
962
963#[allow(clippy::too_many_arguments)]
964fn triangular_solve_matrix_direct_owned_in<T>(
965    session: &mut dyn tenferro_tensor::Engine,
966    a: Matrix<T>,
967    b: Matrix<T>,
968    left_side: bool,
969    lower: bool,
970    transpose_a: bool,
971    unit_diagonal: bool,
972) -> Result<Matrix<T>>
973where
974    T: BackendLinalgScalar + Copy,
975    Tensor: From<TypedTensor<T>>,
976{
977    use tenferro_linalg::TensorLinalgExt;
978
979    let a_tensor: Tensor = a.into_typed_tensor().into();
980    let b_tensor: Tensor = b.into_typed_tensor().into();
981    let result = a_tensor
982        .triangular_solve(
983            &b_tensor,
984            left_side,
985            lower,
986            transpose_a,
987            unit_diagonal,
988            session,
989        )
990        .map_err(|e| anyhow!("triangular solve failed via tenferro-tensor: {e}"))?;
991    let x = try_into_typed_result::<T>("triangular_solve", result)?;
992    typed_tensor_to_matrix("triangular_solve", x)
993}
994
995/// Solve a triangular system on a caller-held engine.
996///
997/// Same kernel, conversion and validation as [`triangular_solve_matrix`], entered
998/// through the given engine instead of the process-global context. Per scalar type:
999/// `f64` and `Complex64` are solved directly; `f32` and `Complex32` are promoted to
1000/// `f64` / `Complex64`, solved, and narrowed back, exactly as on the global route.
1001/// The two routes therefore return bitwise identical results for all four types.
1002///
1003/// # Errors
1004///
1005/// Returns [`BackendLinalgError`] under the same conditions as
1006/// [`triangular_solve_matrix`].
1007#[allow(clippy::too_many_arguments)]
1008pub fn triangular_solve_matrix_in<T>(
1009    session: &mut dyn tenferro_tensor::Engine,
1010    a: &Matrix<T>,
1011    b: &Matrix<T>,
1012    left_side: bool,
1013    lower: bool,
1014    transpose_a: bool,
1015    unit_diagonal: bool,
1016) -> std::result::Result<Matrix<T>, BackendLinalgError>
1017where
1018    T: MatrixTriangularSolveScalar,
1019{
1020    T::triangular_solve_matrix_in_impl(session, a, b, left_side, lower, transpose_a, unit_diagonal)
1021        .map_err(BackendLinalgError::from)
1022}
1023
1024/// Narrow scalar whose triangular solve runs in its 64-bit counterpart.
1025trait WidenedTriangularSolveScalar: Copy + Send + Sync {
1026    type Wide: BackendLinalgScalar + Copy;
1027
1028    fn widen(self) -> Self::Wide;
1029
1030    fn narrow(wide: Self::Wide) -> Self;
1031}
1032
1033impl WidenedTriangularSolveScalar for f32 {
1034    type Wide = f64;
1035
1036    fn widen(self) -> f64 {
1037        f64::from(self)
1038    }
1039
1040    fn narrow(wide: f64) -> Self {
1041        wide as f32
1042    }
1043}
1044
1045impl WidenedTriangularSolveScalar for Complex32 {
1046    type Wide = Complex64;
1047
1048    fn widen(self) -> Complex64 {
1049        Complex64::new(f64::from(self.re), f64::from(self.im))
1050    }
1051
1052    fn narrow(wide: Complex64) -> Self {
1053        Complex32::new(wide.re as f32, wide.im as f32)
1054    }
1055}
1056
1057/// The one triangular solve for `f32` / `Complex32`: promote both operands, solve
1058/// on `session`, narrow the result. The process-global route enters it through
1059/// [`triangular_solve_matrix_widened`], the session route directly.
1060#[allow(clippy::too_many_arguments)]
1061fn triangular_solve_matrix_widened_in<T>(
1062    session: &mut dyn tenferro_tensor::Engine,
1063    a: &Matrix<T>,
1064    b: &Matrix<T>,
1065    left_side: bool,
1066    lower: bool,
1067    transpose_a: bool,
1068    unit_diagonal: bool,
1069) -> Result<Matrix<T>>
1070where
1071    T: WidenedTriangularSolveScalar,
1072    Tensor: From<TypedTensor<T::Wide>>,
1073{
1074    let widen = |m: &Matrix<T>| {
1075        Matrix::from_col_major_vec(
1076            m.nrows(),
1077            m.ncols(),
1078            m.as_col_major_slice().iter().map(|&v| v.widen()).collect(),
1079        )
1080    };
1081    let x = triangular_solve_matrix_direct_in(
1082        session,
1083        &widen(a),
1084        &widen(b),
1085        left_side,
1086        lower,
1087        transpose_a,
1088        unit_diagonal,
1089    )?;
1090    Ok(Matrix::from_col_major_vec(
1091        x.nrows(),
1092        x.ncols(),
1093        x.as_col_major_slice()
1094            .iter()
1095            .map(|&v| T::narrow(v))
1096            .collect(),
1097    ))
1098}
1099
1100/// [`triangular_solve_matrix_widened_in`] on the process-global session.
1101fn triangular_solve_matrix_widened<T>(
1102    a: &Matrix<T>,
1103    b: &Matrix<T>,
1104    left_side: bool,
1105    lower: bool,
1106    transpose_a: bool,
1107    unit_diagonal: bool,
1108) -> Result<Matrix<T>>
1109where
1110    T: WidenedTriangularSolveScalar,
1111    Tensor: From<TypedTensor<T::Wide>>,
1112{
1113    with_default_session(|session| {
1114        Ok(triangular_solve_matrix_widened_in(
1115            session,
1116            a,
1117            b,
1118            left_side,
1119            lower,
1120            transpose_a,
1121            unit_diagonal,
1122        ))
1123    })
1124    .map_err(|e| anyhow!("triangular solve failed via tenferro-tensor: {e}"))?
1125}
1126
1127impl MatrixSolveScalar for f64 {
1128    fn solve_matrix_impl(a: &Matrix<Self>, b: &Matrix<Self>) -> Result<Matrix<Self>> {
1129        solve_matrix_direct(a, b)
1130    }
1131
1132    fn solve_matrix_in_impl(
1133        session: &mut dyn tenferro_tensor::Engine,
1134        a: &Matrix<Self>,
1135        b: &Matrix<Self>,
1136    ) -> Result<Matrix<Self>> {
1137        solve_matrix_direct_in(session, a, b)
1138    }
1139
1140    fn solve_matrix_owned_impl(a: Matrix<Self>, b: Matrix<Self>) -> Result<Matrix<Self>> {
1141        solve_matrix_direct_owned(a, b)
1142    }
1143}
1144
1145impl MatrixTriangularSolveScalar for f64 {
1146    fn triangular_solve_matrix_impl(
1147        a: &Matrix<Self>,
1148        b: &Matrix<Self>,
1149        left_side: bool,
1150        lower: bool,
1151        transpose_a: bool,
1152        unit_diagonal: bool,
1153    ) -> Result<Matrix<Self>> {
1154        triangular_solve_matrix_direct(a, b, left_side, lower, transpose_a, unit_diagonal)
1155    }
1156
1157    fn triangular_solve_matrix_owned_impl(
1158        a: Matrix<Self>,
1159        b: Matrix<Self>,
1160        left_side: bool,
1161        lower: bool,
1162        transpose_a: bool,
1163        unit_diagonal: bool,
1164    ) -> Result<Matrix<Self>> {
1165        triangular_solve_matrix_direct_owned(a, b, left_side, lower, transpose_a, unit_diagonal)
1166    }
1167
1168    fn triangular_solve_matrix_in_impl(
1169        session: &mut dyn tenferro_tensor::Engine,
1170        a: &Matrix<Self>,
1171        b: &Matrix<Self>,
1172        left_side: bool,
1173        lower: bool,
1174        transpose_a: bool,
1175        unit_diagonal: bool,
1176    ) -> Result<Matrix<Self>> {
1177        triangular_solve_matrix_direct_in(
1178            session,
1179            a,
1180            b,
1181            left_side,
1182            lower,
1183            transpose_a,
1184            unit_diagonal,
1185        )
1186    }
1187}
1188
1189impl MatrixSolveScalar for Complex64 {
1190    fn solve_matrix_impl(a: &Matrix<Self>, b: &Matrix<Self>) -> Result<Matrix<Self>> {
1191        solve_matrix_direct(a, b)
1192    }
1193
1194    fn solve_matrix_in_impl(
1195        session: &mut dyn tenferro_tensor::Engine,
1196        a: &Matrix<Self>,
1197        b: &Matrix<Self>,
1198    ) -> Result<Matrix<Self>> {
1199        solve_matrix_direct_in(session, a, b)
1200    }
1201
1202    fn solve_matrix_owned_impl(a: Matrix<Self>, b: Matrix<Self>) -> Result<Matrix<Self>> {
1203        solve_matrix_direct_owned(a, b)
1204    }
1205}
1206
1207impl MatrixTriangularSolveScalar for Complex64 {
1208    fn triangular_solve_matrix_impl(
1209        a: &Matrix<Self>,
1210        b: &Matrix<Self>,
1211        left_side: bool,
1212        lower: bool,
1213        transpose_a: bool,
1214        unit_diagonal: bool,
1215    ) -> Result<Matrix<Self>> {
1216        triangular_solve_matrix_direct(a, b, left_side, lower, transpose_a, unit_diagonal)
1217    }
1218
1219    fn triangular_solve_matrix_owned_impl(
1220        a: Matrix<Self>,
1221        b: Matrix<Self>,
1222        left_side: bool,
1223        lower: bool,
1224        transpose_a: bool,
1225        unit_diagonal: bool,
1226    ) -> Result<Matrix<Self>> {
1227        triangular_solve_matrix_direct_owned(a, b, left_side, lower, transpose_a, unit_diagonal)
1228    }
1229
1230    fn triangular_solve_matrix_in_impl(
1231        session: &mut dyn tenferro_tensor::Engine,
1232        a: &Matrix<Self>,
1233        b: &Matrix<Self>,
1234        left_side: bool,
1235        lower: bool,
1236        transpose_a: bool,
1237        unit_diagonal: bool,
1238    ) -> Result<Matrix<Self>> {
1239        triangular_solve_matrix_direct_in(
1240            session,
1241            a,
1242            b,
1243            left_side,
1244            lower,
1245            transpose_a,
1246            unit_diagonal,
1247        )
1248    }
1249}
1250
1251impl MatrixSolveScalar for f32 {
1252    fn solve_matrix_impl(a: &Matrix<Self>, b: &Matrix<Self>) -> Result<Matrix<Self>> {
1253        let a64 = Matrix::from_col_major_vec(
1254            a.nrows(),
1255            a.ncols(),
1256            a.as_col_major_slice()
1257                .iter()
1258                .map(|&value| value as f64)
1259                .collect(),
1260        );
1261        let b64 = Matrix::from_col_major_vec(
1262            b.nrows(),
1263            b.ncols(),
1264            b.as_col_major_slice()
1265                .iter()
1266                .map(|&value| value as f64)
1267                .collect(),
1268        );
1269        let x64 = solve_matrix_direct(&a64, &b64)?;
1270        Ok(Matrix::from_col_major_vec(
1271            x64.nrows(),
1272            x64.ncols(),
1273            x64.as_col_major_slice()
1274                .iter()
1275                .map(|&value| value as f32)
1276                .collect(),
1277        ))
1278    }
1279
1280    fn solve_matrix_in_impl(
1281        session: &mut dyn tenferro_tensor::Engine,
1282        a: &Matrix<Self>,
1283        b: &Matrix<Self>,
1284    ) -> Result<Matrix<Self>> {
1285        // Same narrow-scalar promotion as the global route: solve in double precision on the caller's session and
1286        // narrow the result.
1287        let a64 = Matrix::from_col_major_vec(
1288            a.nrows(),
1289            a.ncols(),
1290            a.as_col_major_slice()
1291                .iter()
1292                .map(|&value| value as f64)
1293                .collect(),
1294        );
1295        let b64 = Matrix::from_col_major_vec(
1296            b.nrows(),
1297            b.ncols(),
1298            b.as_col_major_slice()
1299                .iter()
1300                .map(|&value| value as f64)
1301                .collect(),
1302        );
1303        let x64 = solve_matrix_direct_in(session, &a64, &b64)?;
1304        Ok(Matrix::from_col_major_vec(
1305            x64.nrows(),
1306            x64.ncols(),
1307            x64.as_col_major_slice()
1308                .iter()
1309                .map(|&value| value as f32)
1310                .collect(),
1311        ))
1312    }
1313}
1314
1315impl MatrixTriangularSolveScalar for f32 {
1316    fn triangular_solve_matrix_impl(
1317        a: &Matrix<Self>,
1318        b: &Matrix<Self>,
1319        left_side: bool,
1320        lower: bool,
1321        transpose_a: bool,
1322        unit_diagonal: bool,
1323    ) -> Result<Matrix<Self>> {
1324        triangular_solve_matrix_widened(a, b, left_side, lower, transpose_a, unit_diagonal)
1325    }
1326
1327    fn triangular_solve_matrix_in_impl(
1328        session: &mut dyn tenferro_tensor::Engine,
1329        a: &Matrix<Self>,
1330        b: &Matrix<Self>,
1331        left_side: bool,
1332        lower: bool,
1333        transpose_a: bool,
1334        unit_diagonal: bool,
1335    ) -> Result<Matrix<Self>> {
1336        triangular_solve_matrix_widened_in(
1337            session,
1338            a,
1339            b,
1340            left_side,
1341            lower,
1342            transpose_a,
1343            unit_diagonal,
1344        )
1345    }
1346}
1347
1348impl MatrixSolveScalar for Complex32 {
1349    fn solve_matrix_impl(a: &Matrix<Self>, b: &Matrix<Self>) -> Result<Matrix<Self>> {
1350        let a64 = Matrix::from_col_major_vec(
1351            a.nrows(),
1352            a.ncols(),
1353            a.as_col_major_slice()
1354                .iter()
1355                .map(|&value| Complex64::new(value.re as f64, value.im as f64))
1356                .collect(),
1357        );
1358        let b64 = Matrix::from_col_major_vec(
1359            b.nrows(),
1360            b.ncols(),
1361            b.as_col_major_slice()
1362                .iter()
1363                .map(|&value| Complex64::new(value.re as f64, value.im as f64))
1364                .collect(),
1365        );
1366        let x64 = solve_matrix_direct(&a64, &b64)?;
1367        Ok(Matrix::from_col_major_vec(
1368            x64.nrows(),
1369            x64.ncols(),
1370            x64.as_col_major_slice()
1371                .iter()
1372                .map(|&value| Complex32::new(value.re as f32, value.im as f32))
1373                .collect(),
1374        ))
1375    }
1376
1377    fn solve_matrix_in_impl(
1378        session: &mut dyn tenferro_tensor::Engine,
1379        a: &Matrix<Self>,
1380        b: &Matrix<Self>,
1381    ) -> Result<Matrix<Self>> {
1382        // Same narrow-scalar promotion as the global route: solve in double precision on the caller's session and
1383        // narrow the result.
1384        let a64 = Matrix::from_col_major_vec(
1385            a.nrows(),
1386            a.ncols(),
1387            a.as_col_major_slice()
1388                .iter()
1389                .map(|&value| Complex64::new(value.re as f64, value.im as f64))
1390                .collect(),
1391        );
1392        let b64 = Matrix::from_col_major_vec(
1393            b.nrows(),
1394            b.ncols(),
1395            b.as_col_major_slice()
1396                .iter()
1397                .map(|&value| Complex64::new(value.re as f64, value.im as f64))
1398                .collect(),
1399        );
1400        let x64 = solve_matrix_direct_in(session, &a64, &b64)?;
1401        Ok(Matrix::from_col_major_vec(
1402            x64.nrows(),
1403            x64.ncols(),
1404            x64.as_col_major_slice()
1405                .iter()
1406                .map(|&value| Complex32::new(value.re as f32, value.im as f32))
1407                .collect(),
1408        ))
1409    }
1410}
1411
1412impl MatrixTriangularSolveScalar for Complex32 {
1413    fn triangular_solve_matrix_impl(
1414        a: &Matrix<Self>,
1415        b: &Matrix<Self>,
1416        left_side: bool,
1417        lower: bool,
1418        transpose_a: bool,
1419        unit_diagonal: bool,
1420    ) -> Result<Matrix<Self>> {
1421        triangular_solve_matrix_widened(a, b, left_side, lower, transpose_a, unit_diagonal)
1422    }
1423
1424    fn triangular_solve_matrix_in_impl(
1425        session: &mut dyn tenferro_tensor::Engine,
1426        a: &Matrix<Self>,
1427        b: &Matrix<Self>,
1428        left_side: bool,
1429        lower: bool,
1430        transpose_a: bool,
1431        unit_diagonal: bool,
1432    ) -> Result<Matrix<Self>> {
1433        triangular_solve_matrix_widened_in(
1434            session,
1435            a,
1436            b,
1437            left_side,
1438            lower,
1439            transpose_a,
1440            unit_diagonal,
1441        )
1442    }
1443}
1444
1445fn tensor_scalar_dtype<T: TensorScalar>() -> DType {
1446    T::dtype()
1447}
1448
1449fn try_into_typed_result<T: TensorScalar>(
1450    op: &'static str,
1451    tensor: Tensor,
1452) -> Result<TypedTensor<T>> {
1453    let actual = tensor.dtype();
1454    T::into_typed(tensor).map_err(|source| {
1455        anyhow!(
1456            "{op}: dtype mismatch lhs={actual:?} rhs={:?}: {source}",
1457            tensor_scalar_dtype::<T>()
1458        )
1459    })
1460}
1461
1462fn convert_for_typed<T: TensorScalar>(op: &'static str, tensor: Tensor) -> Result<TypedTensor<T>> {
1463    let expected = tensor_scalar_dtype::<T>();
1464    let tensor = if tensor.dtype() == expected {
1465        tensor
1466    } else {
1467        with_default_session(|session| tensor.convert(expected, session))
1468            .map_err(|e| anyhow!("{op}: dtype conversion to {expected:?} failed: {e}"))?
1469    };
1470    try_into_typed_result::<T>(op, tensor)
1471}
1472
1473fn matrix_to_typed_tensor<T>(matrix: &Matrix<T>) -> TypedTensor<T>
1474where
1475    T: TensorScalar + Copy,
1476{
1477    TypedTensor::from_vec_col_major(
1478        vec![matrix.nrows(), matrix.ncols()],
1479        matrix.as_col_major_slice().to_vec(),
1480    )
1481    .unwrap_or_else(|error| {
1482        crate::invariant_violated("validated matrix rejected by tenferro", error)
1483    })
1484}
1485
1486fn typed_tensor_to_matrix<T>(op: &'static str, tensor: TypedTensor<T>) -> Result<Matrix<T>>
1487where
1488    T: TensorScalar + Copy,
1489{
1490    Matrix::try_from_typed_tensor(tensor).map_err(|err| anyhow!("{op}: {err}"))
1491}
1492
1493fn require_host_linalg_tensor<T: TensorScalar>(
1494    op: &'static str,
1495    tensor: TypedTensor<T>,
1496) -> Result<TypedTensor<T>> {
1497    tensor
1498        .host_data()
1499        .map_err(|error| anyhow!("{op}: result must be host-backed: {error}"))?;
1500    Ok(tensor)
1501}
1502
1503/// Compute a thin/economy SVD on a typed tensor.
1504/// # Errors
1505///
1506/// Returns a [`BackendLinalgError`] when `a` is not host-backed, when the
1507/// context rejects the entry, or when the backend SVD fails.
1508///
1509pub fn svd_backend<T>(a: &TypedTensor<T>) -> std::result::Result<SvdResult<T>, BackendLinalgError>
1510where
1511    T: BackendLinalgScalar,
1512{
1513    let tensor = T::into_tensor(
1514        a.shape().to_vec(),
1515        a.host_data()
1516            .map_err(|e| anyhow!("SVD input host access failed: {e}"))?
1517            .to_vec(),
1518    )
1519    .map_err(|e| anyhow!("SVD input tensor construction failed: {e}"))?;
1520    with_default_session(|session| Ok(svd_backend_in(session, tensor)))
1521        .map_err(|e| anyhow!("SVD computation failed via tenferro-tensor: {e}"))?
1522}
1523
1524/// SVD of a typed tensor on a caller-held engine.
1525///
1526/// # Errors
1527///
1528/// Returns [`BackendLinalgError`] under the same conditions as [`svd_backend`].
1529pub fn svd_backend_in<T>(
1530    session: &mut dyn tenferro_tensor::Engine,
1531    tensor: Tensor,
1532) -> std::result::Result<SvdResult<T>, BackendLinalgError>
1533where
1534    T: BackendLinalgScalar,
1535{
1536    use tenferro_linalg::TensorLinalgExt;
1537
1538    let (u, s, vt) = tensor
1539        .svd(session)
1540        .map_err(|e| anyhow!("SVD computation failed via tenferro-tensor: {e}"))?;
1541    Ok(SvdResult {
1542        u: require_host_linalg_tensor("svd", convert_for_typed::<T>("svd", u)?)?,
1543        s: require_host_linalg_tensor("svd", convert_for_typed::<T::Real>("svd", s)?)?,
1544        vt: require_host_linalg_tensor("svd", convert_for_typed::<T>("svd", vt)?)?,
1545    })
1546}
1547
1548/// Compute a thin/economy QR decomposition, consuming the input tensor so its
1549/// column-major storage can be transferred to the backend without copying.
1550/// # Errors
1551///
1552/// Returns a [`BackendLinalgError`] when `a` is not host-backed, when the
1553/// context rejects the entry, or when the backend QR fails.
1554///
1555pub fn qr_backend<T>(
1556    a: TypedTensor<T>,
1557) -> std::result::Result<(TypedTensor<T>, TypedTensor<T>), BackendLinalgError>
1558where
1559    T: BackendLinalgScalar,
1560{
1561    let (shape, data) = a
1562        .into_vec_col_major()
1563        .map_err(|e| anyhow!("QR input host access failed: {e}"))?;
1564    let tensor = T::into_tensor(shape, data)
1565        .map_err(|e| anyhow!("QR input tensor construction failed: {e}"))?;
1566    with_default_session(|session| Ok(qr_backend_in(session, tensor)))
1567        .map_err(|e| anyhow!("QR computation failed via tenferro-tensor: {e}"))?
1568}
1569
1570/// QR of a typed tensor on a caller-held engine.
1571///
1572/// # Errors
1573///
1574/// Returns [`BackendLinalgError`] under the same conditions as [`qr_backend`].
1575pub fn qr_backend_in<T>(
1576    session: &mut dyn tenferro_tensor::Engine,
1577    tensor: Tensor,
1578) -> std::result::Result<(TypedTensor<T>, TypedTensor<T>), BackendLinalgError>
1579where
1580    T: BackendLinalgScalar,
1581{
1582    use tenferro_linalg::TensorLinalgExt;
1583
1584    let (q, r) = tensor
1585        .qr(session)
1586        .map_err(|e| anyhow!("QR computation failed via tenferro-tensor: {e}"))?;
1587    Ok((
1588        convert_for_typed::<T>("qr", q)?,
1589        convert_for_typed::<T>("qr", r)?,
1590    ))
1591}
1592
1593/// Solve `A X = B` with the configured tenferro backend.
1594/// # Errors
1595/// Returns a [`BackendLinalgError`] when `a` or `b` is not host-backed, when
1596/// the context rejects the entry, or when the solve fails (for example a
1597/// singular `a`).
1598pub fn solve_backend<T>(
1599    a: &TypedTensor<T>,
1600    b: &TypedTensor<T>,
1601) -> std::result::Result<TypedTensor<T>, BackendLinalgError>
1602where
1603    T: BackendLinalgScalar,
1604{
1605    let a_tensor = T::into_tensor(
1606        a.shape().to_vec(),
1607        a.host_data()
1608            .map_err(|e| anyhow!("solve input host access failed: {e}"))?
1609            .to_vec(),
1610    )
1611    .map_err(|e| anyhow!("solve lhs tensor construction failed: {e}"))?;
1612    let b_tensor = T::into_tensor(
1613        b.shape().to_vec(),
1614        b.host_data()
1615            .map_err(|e| anyhow!("solve rhs host access failed: {e}"))?
1616            .to_vec(),
1617    )
1618    .map_err(|e| anyhow!("solve rhs tensor construction failed: {e}"))?;
1619    let result = with_default_session(|session| a_tensor.solve(&b_tensor, session))
1620        .map_err(|e| anyhow!("linear solve failed via tenferro-tensor: {e}"))?;
1621    try_into_typed_result::<T>("solve", result).map_err(BackendLinalgError::from)
1622}
1623
1624/// Solve a triangular system with the configured tenferro backend.
1625/// If `left_side` is true, this solves `op(A) X = B`; otherwise it solves
1626/// `X op(A) = B`. `lower` selects the triangular half, `transpose_a` applies
1627/// a transpose to `A`, and `unit_diagonal` treats the diagonal of `A` as ones.
1628/// # Errors
1629///
1630/// Returns a [`BackendLinalgError`] when `a` or `b` is not host-backed, when
1631/// the context rejects the entry, or when the triangular solve fails
1632/// (for example a singular `a` or inconsistent triangular flags).
1633///
1634pub fn triangular_solve_backend<T>(
1635    a: &TypedTensor<T>,
1636    b: &TypedTensor<T>,
1637    left_side: bool,
1638    lower: bool,
1639    transpose_a: bool,
1640    unit_diagonal: bool,
1641) -> std::result::Result<TypedTensor<T>, BackendLinalgError>
1642where
1643    T: BackendLinalgScalar,
1644{
1645    let a_tensor = T::into_tensor(
1646        a.shape().to_vec(),
1647        a.host_data()
1648            .map_err(|e| anyhow!("triangular solve input host access failed: {e}"))?
1649            .to_vec(),
1650    )
1651    .map_err(|e| anyhow!("triangular solve lhs tensor construction failed: {e}"))?;
1652    let b_tensor = T::into_tensor(
1653        b.shape().to_vec(),
1654        b.host_data()
1655            .map_err(|e| anyhow!("triangular solve rhs host access failed: {e}"))?
1656            .to_vec(),
1657    )
1658    .map_err(|e| anyhow!("triangular solve rhs tensor construction failed: {e}"))?;
1659    let result = with_default_session(|session| {
1660        a_tensor.triangular_solve(
1661            &b_tensor,
1662            left_side,
1663            lower,
1664            transpose_a,
1665            unit_diagonal,
1666            session,
1667        )
1668    })
1669    .map_err(|e| anyhow!("triangular solve failed via tenferro-tensor: {e}"))?;
1670    try_into_typed_result::<T>("triangular_solve", result).map_err(BackendLinalgError::from)
1671}
1672
1673/// Solve `A X = B` for column-major [`Matrix`] values.
1674/// This routes the operation through the configured tenferro backend and keeps
1675/// matrix-to-tensor conversion centralized in `tensor4all-tensorbackend`.
1676/// # Errors
1677///
1678/// Returns a [`BackendLinalgError`] when the context rejects the entry
1679/// or the solve fails (for example a singular `a`).
1680///
1681/// # Examples
1682/// ```
1683/// use tensor4all_tensorbackend::{from_vec2d, solve_matrix};
1684/// let a = from_vec2d(vec![vec![2.0_f64, 1.0], vec![1.0, 2.0]]);
1685/// let b = from_vec2d(vec![vec![1.0_f64], vec![0.0]]);
1686/// let x = solve_matrix(&a, &b).unwrap();
1687/// assert!((x[[0, 0]] - 2.0 / 3.0).abs() < 1.0e-12);
1688/// assert!((x[[1, 0]] + 1.0 / 3.0).abs() < 1.0e-12);
1689/// ```
1690pub fn solve_matrix<T>(
1691    a: &Matrix<T>,
1692    b: &Matrix<T>,
1693) -> std::result::Result<Matrix<T>, BackendLinalgError>
1694where
1695    T: MatrixSolveScalar,
1696{
1697    T::solve_matrix_impl(a, b).map_err(BackendLinalgError::from)
1698}
1699
1700/// Solve `A X = B` while consuming column-major [`Matrix`] values.
1701/// This routes the operation through the configured tenferro backend and reuses
1702/// the input buffers when constructing backend tensors for directly supported
1703/// scalar types.
1704/// # Errors
1705///
1706/// Returns a [`BackendLinalgError`] when the context rejects the entry
1707/// or the solve fails (for example a singular `a`).
1708///
1709/// # Examples
1710/// ```
1711/// use tensor4all_tensorbackend::{from_vec2d, solve_matrix_owned};
1712/// let a = from_vec2d(vec![vec![2.0_f64, 1.0], vec![1.0, 2.0]]);
1713/// let b = from_vec2d(vec![vec![1.0_f64], vec![0.0]]);
1714/// let x = solve_matrix_owned(a, b).unwrap();
1715/// assert!((x[[0, 0]] - 2.0 / 3.0).abs() < 1.0e-12);
1716/// assert!((x[[1, 0]] + 1.0 / 3.0).abs() < 1.0e-12);
1717/// ```
1718pub fn solve_matrix_owned<T>(
1719    a: Matrix<T>,
1720    b: Matrix<T>,
1721) -> std::result::Result<Matrix<T>, BackendLinalgError>
1722where
1723    T: MatrixSolveScalar,
1724{
1725    T::solve_matrix_owned_impl(a, b).map_err(BackendLinalgError::from)
1726}
1727
1728/// Solve a triangular system for column-major [`Matrix`] values.
1729/// If `left_side` is true, this solves `op(A) X = B`; otherwise it solves
1730/// `X op(A) = B`. `lower` selects the triangular half, `transpose_a` applies
1731/// a transpose to `A`, and `unit_diagonal` treats the diagonal of `A` as ones.
1732/// # Errors
1733///
1734/// Returns a [`BackendLinalgError`] when the context rejects the entry
1735/// or the triangular solve fails (for example a singular `a` or inconsistent
1736/// triangular flags).
1737///
1738/// # Examples
1739/// ```
1740/// use tensor4all_tensorbackend::{from_vec2d, triangular_solve_matrix};
1741/// let a = from_vec2d(vec![vec![2.0_f64, 1.0], vec![0.0, 3.0]]);
1742/// let b = from_vec2d(vec![vec![2.0_f64, 7.0]]);
1743/// let x = triangular_solve_matrix(&a, &b, false, false, false, false).unwrap();
1744/// assert!((x[[0, 0]] - 1.0).abs() < 1.0e-12);
1745/// assert!((x[[0, 1]] - 2.0).abs() < 1.0e-12);
1746/// ```
1747pub fn triangular_solve_matrix<T>(
1748    a: &Matrix<T>,
1749    b: &Matrix<T>,
1750    left_side: bool,
1751    lower: bool,
1752    transpose_a: bool,
1753    unit_diagonal: bool,
1754) -> std::result::Result<Matrix<T>, BackendLinalgError>
1755where
1756    T: MatrixTriangularSolveScalar,
1757{
1758    T::triangular_solve_matrix_impl(a, b, left_side, lower, transpose_a, unit_diagonal)
1759        .map_err(BackendLinalgError::from)
1760}
1761
1762/// Solve a triangular system while consuming column-major [`Matrix`] values.
1763/// If `left_side` is true, this solves `op(A) X = B`; otherwise it solves
1764/// `X op(A) = B`. `lower` selects the triangular half, `transpose_a` applies
1765/// a transpose to `A`, and `unit_diagonal` treats the diagonal of `A` as ones.
1766/// # Errors
1767///
1768/// Returns a [`BackendLinalgError`] when the context rejects the entry
1769/// or the triangular solve fails (for example a singular `a` or inconsistent
1770/// triangular flags).
1771///
1772/// # Examples
1773/// ```
1774/// use tensor4all_tensorbackend::{from_vec2d, triangular_solve_matrix_owned};
1775/// let a = from_vec2d(vec![vec![2.0_f64, 0.0], vec![1.0, 3.0]]);
1776/// let b = from_vec2d(vec![vec![2.0_f64], vec![7.0]]);
1777/// let x = triangular_solve_matrix_owned(a, b, true, true, false, false).unwrap();
1778/// assert!((x[[0, 0]] - 1.0).abs() < 1.0e-12);
1779/// assert!((x[[1, 0]] - 2.0).abs() < 1.0e-12);
1780/// ```
1781pub fn triangular_solve_matrix_owned<T>(
1782    a: Matrix<T>,
1783    b: Matrix<T>,
1784    left_side: bool,
1785    lower: bool,
1786    transpose_a: bool,
1787    unit_diagonal: bool,
1788) -> std::result::Result<Matrix<T>, BackendLinalgError>
1789where
1790    T: MatrixTriangularSolveScalar,
1791{
1792    T::triangular_solve_matrix_owned_impl(a, b, left_side, lower, transpose_a, unit_diagonal)
1793        .map_err(BackendLinalgError::from)
1794}
1795
1796fn full_piv_lu_tensor<T>(
1797    tensor: Tensor,
1798) -> std::result::Result<FullPivLuResult<T>, BackendLinalgError>
1799where
1800    T: BackendLinalgScalar,
1801{
1802    with_default_session(|session| Ok(full_piv_lu_tensor_in(session, tensor)))
1803        .map_err(|e| anyhow!("complete-pivoting LU failed via tenferro-tensor: {e}"))?
1804}
1805
1806/// Complete-pivoting LU on a caller-held engine.
1807fn full_piv_lu_tensor_in<T>(
1808    session: &mut dyn tenferro_tensor::Engine,
1809    tensor: Tensor,
1810) -> std::result::Result<FullPivLuResult<T>, BackendLinalgError>
1811where
1812    T: BackendLinalgScalar,
1813{
1814    use tenferro_linalg::TensorLinalgExt;
1815
1816    let (p, l, u, q, _parity) = tensor
1817        .full_piv_lu(session)
1818        .map_err(|e| anyhow!("complete-pivoting LU failed via tenferro-tensor: {e}"))?;
1819    Ok(FullPivLuResult {
1820        p: require_host_linalg_tensor("full_piv_lu", convert_for_typed::<T>("full_piv_lu", p)?)?,
1821        l: require_host_linalg_tensor("full_piv_lu", convert_for_typed::<T>("full_piv_lu", l)?)?,
1822        u: require_host_linalg_tensor("full_piv_lu", convert_for_typed::<T>("full_piv_lu", u)?)?,
1823        q: require_host_linalg_tensor("full_piv_lu", convert_for_typed::<T>("full_piv_lu", q)?)?,
1824    })
1825}
1826
1827/// Compute complete-pivoting LU with the configured tenferro backend.
1828/// # Errors
1829///
1830/// Returns a [`BackendLinalgError`] when `a` is not host-backed, when the
1831/// context rejects the entry, or when the factorization fails.
1832///
1833pub fn full_piv_lu_backend<T>(
1834    a: &TypedTensor<T>,
1835) -> std::result::Result<FullPivLuResult<T>, BackendLinalgError>
1836where
1837    T: BackendLinalgScalar,
1838{
1839    let tensor = T::into_tensor(
1840        a.shape().to_vec(),
1841        a.host_data()
1842            .map_err(|e| anyhow!("LU input host access failed: {e}"))?
1843            .to_vec(),
1844    )
1845    .map_err(|e| anyhow!("LU input tensor construction failed: {e}"))?;
1846    full_piv_lu_tensor(tensor)
1847}
1848
1849/// Complete-pivoting LU of a typed tensor on a caller-held engine.
1850///
1851/// Same kernel and conversion as [`full_piv_lu_backend`], entered through the given
1852/// session instead of the process-global one.
1853///
1854/// # Errors
1855///
1856/// Returns [`BackendLinalgError`] under the same conditions as
1857/// [`full_piv_lu_backend`].
1858pub fn full_piv_lu_backend_in<T>(
1859    session: &mut dyn tenferro_tensor::Engine,
1860    a: &TypedTensor<T>,
1861) -> std::result::Result<FullPivLuResult<T>, BackendLinalgError>
1862where
1863    T: BackendLinalgScalar,
1864{
1865    let tensor = T::into_tensor(
1866        a.shape().to_vec(),
1867        a.host_data()
1868            .map_err(|e| anyhow!("LU input host access failed: {e}"))?
1869            .to_vec(),
1870    )
1871    .map_err(|e| anyhow!("LU input tensor construction failed: {e}"))?;
1872    full_piv_lu_tensor_in(session, tensor)
1873}
1874
1875/// Compute complete-pivoting LU for a column-major [`Matrix`].
1876/// This is a convenience wrapper over [`full_piv_lu_backend`] for callers that
1877/// use [`Matrix`] as their dense boundary type.
1878/// # Errors
1879///
1880/// Returns a [`BackendLinalgError`] when the context rejects the entry
1881/// or the full-pivoting LU factorization fails.
1882///
1883/// # Examples
1884/// ```
1885/// use tensor4all_tensorbackend::{from_vec2d, full_piv_lu_matrix};
1886/// let matrix = from_vec2d(vec![vec![0.0_f64, 1.0], vec![2.0, 3.0]]);
1887/// let factors = full_piv_lu_matrix(&matrix).unwrap();
1888/// assert_eq!(factors.p.nrows(), 2);
1889/// assert_eq!(factors.q.ncols(), 2);
1890/// ```
1891pub fn full_piv_lu_matrix<T>(
1892    a: &Matrix<T>,
1893) -> std::result::Result<FullPivLuMatrixResult<T>, BackendLinalgError>
1894where
1895    T: BackendLinalgScalar + Copy,
1896{
1897    let tensor = matrix_to_typed_tensor(a);
1898    let decomp = full_piv_lu_backend(&tensor)?;
1899    Ok(FullPivLuMatrixResult {
1900        p: typed_tensor_to_matrix("full_piv_lu", decomp.p)?,
1901        l: typed_tensor_to_matrix("full_piv_lu", decomp.l)?,
1902        u: typed_tensor_to_matrix("full_piv_lu", decomp.u)?,
1903        q: typed_tensor_to_matrix("full_piv_lu", decomp.q)?,
1904    })
1905}
1906
1907/// Complete-pivoting LU for a column-major [`Matrix`] on a caller-held engine.
1908///
1909/// Same kernel and conversion as [`full_piv_lu_matrix`], entered through the given
1910/// session instead of the process-global one.
1911///
1912/// # Errors
1913///
1914/// Returns [`BackendLinalgError`] under the same conditions as
1915/// [`full_piv_lu_matrix`].
1916pub fn full_piv_lu_matrix_in<T>(
1917    session: &mut dyn tenferro_tensor::Engine,
1918    a: &Matrix<T>,
1919) -> std::result::Result<FullPivLuMatrixResult<T>, BackendLinalgError>
1920where
1921    T: BackendLinalgScalar + Copy,
1922{
1923    let tensor = matrix_to_typed_tensor(a);
1924    let decomp = full_piv_lu_backend_in(session, &tensor)?;
1925    Ok(FullPivLuMatrixResult {
1926        p: typed_tensor_to_matrix("full_piv_lu", decomp.p)?,
1927        l: typed_tensor_to_matrix("full_piv_lu", decomp.l)?,
1928        u: typed_tensor_to_matrix("full_piv_lu", decomp.u)?,
1929        q: typed_tensor_to_matrix("full_piv_lu", decomp.q)?,
1930    })
1931}
1932
1933/// Compute complete-pivoting LU for an owned column-major [`Matrix`].
1934///
1935/// This is the owned-buffer counterpart of [`full_piv_lu_matrix`]. It consumes
1936/// the matrix so its column-major buffer can be transferred to tenferro without
1937/// cloning the input before factorization.
1938/// The returned factors satisfy `P * A * Qᵀ = L * U` when interpreted as
1939/// column-major matrices.
1940///
1941/// # Errors
1942///
1943/// Returns [`BackendLinalgError`] when the input is not square (tenferro
1944/// reports an incompatible shape), the configured backend rejects the scalar
1945/// dtype, the complete-pivoting factorization fails, or a factor produced by
1946/// the backend cannot be converted back to a matrix.
1947///
1948/// # Examples
1949/// ```
1950/// use tensor4all_tensorbackend::{from_vec2d, full_piv_lu_matrix_owned, Matrix};
1951///
1952/// fn matmul(a: &Matrix<f64>, b: &Matrix<f64>) -> Matrix<f64> {
1953///     let mut out = Matrix::zeros(a.nrows(), b.ncols());
1954///     for col in 0..b.ncols() {
1955///         for k in 0..a.ncols() {
1956///             for row in 0..a.nrows() {
1957///                 out[[row, col]] += a[[row, k]] * b[[k, col]];
1958///             }
1959///         }
1960///     }
1961///     out
1962/// }
1963///
1964/// fn transpose(a: &Matrix<f64>) -> Matrix<f64> {
1965///     let mut out = Matrix::zeros(a.ncols(), a.nrows());
1966///     for col in 0..a.ncols() {
1967///         for row in 0..a.nrows() {
1968///             out[[col, row]] = a[[row, col]];
1969///         }
1970///     }
1971///     out
1972/// }
1973///
1974/// let matrix = from_vec2d(vec![vec![2.0_f64, 1.0], vec![1.0, 2.0]]);
1975/// let factors = full_piv_lu_matrix_owned(matrix.clone()).unwrap();
1976/// let lhs = matmul(&factors.p, &matmul(&matrix, &transpose(&factors.q)));
1977/// let rhs = matmul(&factors.l, &factors.u);
1978/// for row in 0..2 {
1979///     for col in 0..2 {
1980///         assert!((lhs[[row, col]] - rhs[[row, col]]).abs() < 1.0e-12);
1981///     }
1982/// }
1983/// ```
1984pub fn full_piv_lu_matrix_owned<T>(
1985    a: Matrix<T>,
1986) -> std::result::Result<FullPivLuMatrixResult<T>, BackendLinalgError>
1987where
1988    T: BackendLinalgScalar + Copy,
1989{
1990    let tensor = T::typed_tensor_into_tensor(a.into_typed_tensor());
1991    let decomp = full_piv_lu_tensor(tensor)?;
1992    Ok(FullPivLuMatrixResult {
1993        p: typed_tensor_to_matrix("full_piv_lu", decomp.p)?,
1994        l: typed_tensor_to_matrix("full_piv_lu", decomp.l)?,
1995        u: typed_tensor_to_matrix("full_piv_lu", decomp.u)?,
1996        q: typed_tensor_to_matrix("full_piv_lu", decomp.q)?,
1997    })
1998}
1999
2000#[cfg(test)]
2001mod tests;