1use 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#[derive(Debug)]
31pub struct SvdResult<T: TensorScalar> {
32 u: TypedTensor<T>,
33 s: TypedTensor<T::Real>,
34 vt: TypedTensor<T>,
35}
36
37#[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 pub fn u(&self) -> &TypedTensor<T> {
58 &self.u
59 }
60
61 pub fn s(&self) -> &TypedTensor<T::Real> {
63 &self.s
64 }
65
66 pub fn vt(&self) -> &TypedTensor<T> {
68 &self.vt
69 }
70
71 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 pub fn p(&self) -> &TypedTensor<T> {
80 &self.p
81 }
82
83 pub fn l(&self) -> &TypedTensor<T> {
85 &self.l
86 }
87
88 pub fn u(&self) -> &TypedTensor<T> {
90 &self.u
91 }
92
93 pub fn q(&self) -> &TypedTensor<T> {
95 &self.q
96 }
97
98 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#[derive(Debug, Clone)]
145pub struct FullPivLuMatrixResult<T> {
146 pub p: Matrix<T>,
148 pub l: Matrix<T>,
150 pub u: Matrix<T>,
152 pub q: Matrix<T>,
154}
155
156pub trait BackendLinalgScalar: TensorScalar {}
158
159pub trait FullPivLuScalar: BackendLinalgScalar {
174 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 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 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 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
328struct 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
411fn 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
428pub 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 #[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#[derive(Debug, thiserror::Error)]
481#[error("backend linear algebra failed: {source}")]
482pub struct BackendLinalgError {
483 #[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
494pub 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 #[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#[derive(Debug, Clone, Copy, PartialEq)]
573pub struct SrcErrorEstimate {
574 pub error: f64,
576 pub norm: f64,
578}
579
580pub 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
621pub 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
683pub(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 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
750pub(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
861pub 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#[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
1024trait 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#[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
1100fn 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 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 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
1503pub 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
1524pub 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
1548pub 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
1570pub 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
1593pub 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
1624pub 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
1673pub 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
1700pub 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
1728pub 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
1762pub 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
1806fn 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
1827pub 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
1849pub 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
1875pub 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
1907pub 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
1933pub 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;