tensor4all_core/matrix_luci.rs
1//! Matrix LU-based Cross Interpolation (MatrixLUCI) implementation.
2//!
3//! [`MatrixLUCI`] provides a higher-level [`Matrix`] API over the lower-level
4//! `matrixluci` substrate. It decomposes a matrix into left and right factors
5//! via LU cross interpolation and implements [`AbstractMatrixCI`].
6
7use crate::error::{MatrixCIError, Result};
8use crate::matrixlu::{
9 rrlu, rrlu_left_mut, rrlu_mut, validate_luci_options, validate_owned_luci_input, RrLU,
10 RrLUOptions,
11};
12use crate::matrixluci::block_rook::LazyBlockRookKernel;
13use crate::matrixluci::factors::CrossFactors;
14use crate::matrixluci::source::LazyMatrixSource;
15use crate::matrixluci::types::{PivotKernelOptions, PivotSelectionCore};
16use crate::matrixluci::PivotKernel;
17use crate::scalar::Scalar;
18use crate::traits::AbstractMatrixCI;
19use tensor4all_tensorbackend::{
20 explicit::Session, mat_mul_owned, submatrix, triangular_solve_matrix_owned,
21 CpuExecutionContext, Matrix,
22};
23
24/// Where MatrixLUCI factor assembly runs its matrix products and solves.
25///
26/// `Global` keeps the compatibility routes of the legacy entry points;
27/// `Context` runs every operation in one explicit concrete session of the
28/// caller's context and never consults the process-global default.
29pub(crate) enum Linalg<'a, 'session> {
30 Global,
31 Context(&'a CpuExecutionContext),
32 /// A caller-supplied session, entered by the caller rather than opened here.
33 ///
34 /// This is the form a worker lane uses: the session was entered by the phase that owns
35 /// the worker, so re-entering a context here would either be refused or pick another
36 /// backend.
37 Session(&'a mut Session<'session>),
38}
39
40impl Linalg<'_, '_> {
41 fn mat_mul<T>(&mut self, a: Matrix<T>, b: Matrix<T>) -> std::result::Result<Matrix<T>, String>
42 where
43 T: Scalar + crate::MatrixLuciScalar,
44 {
45 match self {
46 Self::Global => mat_mul_owned(a, b).map_err(|err| err.to_string()),
47 Self::Context(context) => context
48 .with_concrete_session(|session| session.mat_mul(&a, &b))
49 .map_err(|err| err.to_string())?
50 .map_err(|err| err.to_string()),
51 Self::Session(session) => session.mat_mul(&a, &b).map_err(|err| err.to_string()),
52 }
53 }
54
55 fn triangular_solve<T>(
56 &mut self,
57 a: Matrix<T>,
58 b: Matrix<T>,
59 left_side: bool,
60 lower: bool,
61 ) -> std::result::Result<Matrix<T>, String>
62 where
63 T: Scalar + crate::MatrixLuciScalar,
64 {
65 match self {
66 Self::Global => triangular_solve_matrix_owned(a, b, left_side, lower, false, false)
67 .map_err(|err| err.to_string()),
68 Self::Context(context) => context
69 .with_concrete_session(|session| {
70 T::matrix_luci_triangular_solve_in(session, &a, &b, left_side, lower)
71 })
72 .map_err(|err| err.to_string())?
73 .map_err(|err| err.to_string()),
74 Self::Session(session) => {
75 T::matrix_luci_triangular_solve_in(session, &a, &b, left_side, lower)
76 .map_err(|err| err.to_string())
77 }
78 }
79 }
80}
81
82/// Matrix LU-based Cross Interpolation.
83///
84/// This is a higher-level [`Matrix`] wrapper around the lower-level `matrixluci`
85/// substrate.
86///
87/// # Examples
88///
89/// ```
90/// use tensor4all_core::{AbstractMatrixCI, MatrixLUCI};
91/// use tensor4all_tensorbackend::from_vec2d;
92///
93/// let m = from_vec2d(vec![
94/// vec![1.0_f64, 2.0, 3.0],
95/// vec![4.0, 5.0, 6.0],
96/// vec![7.0, 8.0, 9.0],
97/// ]);
98///
99/// let ci = MatrixLUCI::from_matrix(&m, None).unwrap();
100/// // The approximation must have at most rank min(nrows, ncols)
101/// assert!(ci.rank() <= 3);
102/// // Reconstructed matrix should match original at pivot positions
103/// let row_indices = ci.row_indices().to_vec();
104/// let col_indices = ci.col_indices().to_vec();
105/// for (&i, &j) in row_indices.iter().zip(col_indices.iter()) {
106/// let approx = ci.evaluate(i, j);
107/// let exact = m[[i, j]];
108/// assert!((approx - exact).abs() < 1e-10);
109/// }
110/// ```
111#[derive(Debug, Clone)]
112pub struct MatrixLUCI<T: Scalar + crate::MatrixLuciScalar> {
113 nrows: usize,
114 ncols: usize,
115 row_indices: Vec<usize>,
116 col_indices: Vec<usize>,
117 left: Matrix<T>,
118 right: Matrix<T>,
119 pivot_errors: Vec<f64>,
120}
121
122/// High-level factors produced by MatrixLUCI.
123///
124/// This is the public result of the LUCI factorization facade. It exposes
125/// the selected pivot metadata and the left and right factors
126/// needed by higher-level tensor-network code without exposing the low-level
127/// pivot kernel substrate.
128///
129/// Related types: [`MatrixLUCI`] is the owning CI wrapper, while
130/// [`MatrixACA`](crate::MatrixACA) and [`RrLU`](crate::RrLU) are related
131/// matrix factorization entry points.
132///
133/// # Examples
134///
135/// ```
136/// use tensor4all_core::matrix_luci_factors_from_matrix;
137/// use tensor4all_tensorbackend::from_vec2d;
138///
139/// let m = from_vec2d(vec![
140/// vec![1.0_f64, 2.0],
141/// vec![3.0, 4.0],
142/// ]);
143/// let factors = matrix_luci_factors_from_matrix(&m, None).unwrap();
144/// assert!(factors.rank >= 1);
145/// assert_eq!(factors.row_indices.len(), factors.rank);
146/// assert_eq!(factors.left.nrows(), m.nrows());
147/// assert_eq!(factors.right.ncols(), m.ncols());
148/// ```
149#[derive(Debug, Clone)]
150pub struct MatrixLuciFactors<T> {
151 /// Selected row indices.
152 pub row_indices: Vec<usize>,
153 /// Selected column indices.
154 pub col_indices: Vec<usize>,
155 /// Pivot error history, or one measured maximum residual for fixed pivots.
156 ///
157 /// One entry per accepted pivot, then a trailing entry holding the largest
158 /// magnitude of the remaining residual (`0.0` once the full rank is
159 /// reached). Both kernels report that same quantity for the pivots they
160 /// selected, so the trailing entry is a residual and never a lower or upper
161 /// bound standing in for one.
162 pub pivot_errors: Vec<f64>,
163 /// Selected rank.
164 pub rank: usize,
165 /// Left factor.
166 pub left: Matrix<T>,
167 /// Right factor.
168 pub right: Matrix<T>,
169}
170
171/// Row interpolation `A ~= interpolation * A[rows, :]` selected by MatrixLUCI.
172/// Unlike [`MatrixLuciFactors`], this does not build an unused right factor.
173///
174/// # Examples
175/// ```
176/// use tensor4all_core::matrix_luci_row_interpolation_owned_in;
177/// use tensor4all_tensorbackend::{default_cpu_execution_context, Matrix};
178/// let a = Matrix::from_col_major_vec(2, 1, vec![2.0_f64, 4.0]);
179/// let id = matrix_luci_row_interpolation_owned_in(a, None, &default_cpu_execution_context())?;
180/// assert_eq!(id.rows, vec![1]);
181/// assert_eq!(id.interpolation.as_col_major_slice(), &[0.5, 1.0]);
182/// # Ok::<(), Box<dyn std::error::Error>>(())
183/// ```
184#[derive(Clone, Debug)]
185pub struct MatrixLuciRowInterpolation<T> {
186 /// Original matrix row indices, in pivot order.
187 pub rows: Vec<usize>,
188 /// Row weights, with an identity submatrix at the selected rows.
189 pub interpolation: Matrix<T>,
190 /// Accepted LU pivot magnitudes followed by the maximum absolute entry of
191 /// the remaining Schur complement. This is a local matrix diagnostic.
192 pub pivot_magnitudes: Vec<f64>,
193}
194
195/// Selects a row interpolant without constructing the complementary right factor.
196///
197/// Consumes column-major `a`, uses `options` for pivot rank/tolerances, and
198/// performs the factor solve in the supplied CPU `context`. `left_orthogonal`
199/// is always set to true because this operation returns row interpolation.
200/// A zero matrix yields zero columns; the caller chooses its zero-rank convention.
201///
202/// # Errors
203/// Returns [`MatrixCIError::InvalidArgument`] for negative or nonfinite
204/// tolerances, infinite input magnitudes, or backend solve failures; returns
205/// [`MatrixCIError::NaNEncountered`] for NaN input or nonfinite factors or
206/// residual magnitudes.
207///
208/// # Examples
209/// ```
210/// use tensor4all_core::{matrix_luci_row_interpolation_owned_in, RrLUOptions};
211/// use tensor4all_tensorbackend::{default_cpu_execution_context, Matrix};
212/// let a = Matrix::from_col_major_vec(2, 2, vec![1.0_f64, 2.0, 3.0, 6.0]);
213/// let id = matrix_luci_row_interpolation_owned_in(a, Some(RrLUOptions::default()),
214/// &default_cpu_execution_context())?;
215/// assert_eq!(id.rows, vec![1]);
216/// assert_eq!(id.interpolation.as_col_major_slice(), &[0.5, 1.0]);
217/// # Ok::<(), Box<dyn std::error::Error>>(())
218/// ```
219pub fn matrix_luci_row_interpolation_owned_in<T>(
220 a: Matrix<T>,
221 options: Option<RrLUOptions>,
222 context: &CpuExecutionContext,
223) -> Result<MatrixLuciRowInterpolation<T>>
224where
225 T: Scalar + crate::MatrixLuciScalar,
226{
227 row_interpolation_owned(a, options, Linalg::Context(context))
228}
229
230/// Selects a row interpolant on a caller-held explicit session.
231///
232/// The session counterpart of [`matrix_luci_row_interpolation_owned_in`] for
233/// code that already runs inside a session, such as a worker lane whose session
234/// was entered by the phase that owns it. The pivot search is identical; the
235/// triangular solve of the interpolation runs on `session`, and neither a
236/// process-global context nor a fresh session entry is consulted.
237///
238/// Consumes column-major `a` and uses `options` for pivot rank and tolerances
239/// (`None` uses the defaults). `left_orthogonal` is always set to true. A zero
240/// matrix yields zero rows; the caller chooses its zero-rank convention.
241///
242/// # Errors
243/// Returns [`MatrixCIError::InvalidArgument`] for negative or nonfinite
244/// tolerances, infinite input magnitudes, or session solve failures; returns
245/// [`MatrixCIError::NaNEncountered`] for NaN input or nonfinite factors or
246/// residual magnitudes.
247///
248/// # Examples
249/// ```
250/// use tensor4all_core::{matrix_luci_row_interpolation_owned_on_session, RrLUOptions};
251/// use tensor4all_tensorbackend::{CpuBackend, CpuExecutionContext, Matrix};
252/// let context = CpuExecutionContext::from_backend(CpuBackend::new());
253/// let a = Matrix::from_col_major_vec(2, 2, vec![1.0_f64, 2.0, 3.0, 6.0]);
254/// let id = context.with_concrete_session(|session| {
255/// matrix_luci_row_interpolation_owned_on_session(a, Some(RrLUOptions::default()), session)
256/// })??;
257/// assert_eq!(id.rows, vec![1]);
258/// assert_eq!(id.interpolation.as_col_major_slice(), &[0.5, 1.0]);
259/// # Ok::<(), Box<dyn std::error::Error>>(())
260/// ```
261pub fn matrix_luci_row_interpolation_owned_on_session<T>(
262 a: Matrix<T>,
263 options: Option<RrLUOptions>,
264 session: &mut Session<'_>,
265) -> Result<MatrixLuciRowInterpolation<T>>
266where
267 T: Scalar + crate::MatrixLuciScalar,
268{
269 row_interpolation_owned(a, options, Linalg::Session(session))
270}
271
272/// The row interpolation shared by the context and session entry points; only
273/// the place the triangular solve runs differs.
274fn row_interpolation_owned<T>(
275 mut a: Matrix<T>,
276 options: Option<RrLUOptions>,
277 mut linalg: Linalg<'_, '_>,
278) -> Result<MatrixLuciRowInterpolation<T>>
279where
280 T: Scalar + crate::MatrixLuciScalar,
281{
282 let mut options = options.unwrap_or_default();
283 options.left_orthogonal = true;
284 validate_owned_luci_input(&a, &options)?;
285 let lu = rrlu_left_mut(&mut a, Some(options))?;
286 let rank = lu.n_pivot;
287 Ok(MatrixLuciRowInterpolation {
288 rows: lu.row_permutation[..rank].to_vec(),
289 interpolation: cols_times_pivot_solve(&lu.l, &lu.row_permutation, rank, &mut linalg)?,
290 pivot_magnitudes: lu.pivot_magnitudes,
291 })
292}
293
294// Validation for the new owned/context facades lives with the rrLU entry
295// points (`matrixlu::validate_owned_luci_input`) so the selection-only path
296// checks inputs and tolerances identically.
297
298pub(crate) fn map_backend_error(err: crate::matrixluci::MatrixLuciError) -> MatrixCIError {
299 match err {
300 crate::matrixluci::MatrixLuciError::NaNEncountered { matrix } => {
301 MatrixCIError::NaNEncountered {
302 matrix: matrix.to_string(),
303 }
304 }
305 crate::matrixluci::MatrixLuciError::InvalidArgument { message } => {
306 MatrixCIError::InvalidArgument { message }
307 }
308 }
309}
310
311fn factors_to_public<T>(
312 selection: PivotSelectionCore,
313 factors: CrossFactors<T>,
314 left_orthogonal: bool,
315) -> Result<MatrixLuciFactors<T>>
316where
317 T: Scalar + crate::MatrixLuciScalar,
318{
319 let left = if left_orthogonal {
320 factors.cols_solve_pivot().map_err(map_backend_error)?
321 } else {
322 factors.pivot_cols.clone()
323 };
324 let right = if left_orthogonal {
325 factors.pivot_rows.clone()
326 } else {
327 factors.solve_pivot_rows().map_err(map_backend_error)?
328 };
329
330 Ok(MatrixLuciFactors {
331 row_indices: selection.row_indices,
332 col_indices: selection.col_indices,
333 pivot_errors: selection.pivot_errors,
334 rank: selection.rank,
335 left,
336 right,
337 })
338}
339
340fn backend_linalg_error(message: impl Into<String>) -> MatrixCIError {
341 MatrixCIError::InvalidArgument {
342 message: message.into(),
343 }
344}
345
346fn index_range(start: usize, end: usize) -> Vec<usize> {
347 (start..end).collect()
348}
349
350fn identity_rect<T: Scalar>(nrows: usize, ncols: usize) -> Matrix<T> {
351 let mut result = Matrix::zeros(nrows, ncols);
352 for i in 0..nrows.min(ncols) {
353 result[[i, i]] = T::one();
354 }
355 result
356}
357
358fn apply_row_permutation<T: Scalar>(matrix: &Matrix<T>, permutation: &[usize]) -> Matrix<T> {
359 let mut result = Matrix::zeros(matrix.nrows(), matrix.ncols());
360 for col in 0..matrix.ncols() {
361 for (new_row, &old_row) in permutation.iter().enumerate().take(matrix.nrows()) {
362 result[[old_row, col]] = matrix[[new_row, col]];
363 }
364 }
365 result
366}
367
368fn apply_col_permutation<T: Scalar>(matrix: &Matrix<T>, permutation: &[usize]) -> Matrix<T> {
369 let mut result = Matrix::zeros(matrix.nrows(), matrix.ncols());
370 for (new_col, &old_col) in permutation.iter().enumerate().take(matrix.ncols()) {
371 for row in 0..matrix.nrows() {
372 result[[row, old_col]] = matrix[[row, new_col]];
373 }
374 }
375 result
376}
377
378pub(crate) fn rrlu_colmatrix<T>(lu: &RrLU<T>, linalg: &mut Linalg<'_, '_>) -> Result<Matrix<T>>
379where
380 T: Scalar + crate::MatrixLuciScalar,
381{
382 let rank = lu.npivots();
383 if rank == 0 {
384 return Ok(Matrix::zeros(lu.nrows(), 0));
385 }
386 let rows = index_range(0, rank);
387 let cols = index_range(0, rank);
388 let right_pivot_cols = submatrix(lu.right_unpermuted(), &rows, &cols);
389 linalg
390 .mat_mul(lu.left(true), right_pivot_cols)
391 .map_err(|err| backend_linalg_error(format!("MatrixLUCI colmatrix multiply failed: {err}")))
392}
393
394pub(crate) fn rrlu_rowmatrix<T>(lu: &RrLU<T>, linalg: &mut Linalg<'_, '_>) -> Result<Matrix<T>>
395where
396 T: Scalar + crate::MatrixLuciScalar,
397{
398 let rank = lu.npivots();
399 if rank == 0 {
400 return Ok(Matrix::zeros(0, lu.ncols()));
401 }
402 let rows = index_range(0, rank);
403 let cols = index_range(0, rank);
404 let left_pivot_rows = submatrix(lu.left_unpermuted(), &rows, &cols);
405 linalg
406 .mat_mul(left_pivot_rows, lu.right(true))
407 .map_err(|err| backend_linalg_error(format!("MatrixLUCI rowmatrix multiply failed: {err}")))
408}
409
410pub(crate) fn rrlu_cols_times_pivot_solve<T>(
411 lu: &RrLU<T>,
412 linalg: &mut Linalg<'_, '_>,
413) -> Result<Matrix<T>>
414where
415 T: Scalar + crate::MatrixLuciScalar,
416{
417 cols_times_pivot_solve(
418 lu.left_unpermuted(),
419 lu.row_permutation(),
420 lu.npivots(),
421 linalg,
422 )
423}
424
425fn cols_times_pivot_solve<T>(
426 left: &Matrix<T>,
427 row_permutation: &[usize],
428 rank: usize,
429 linalg: &mut Linalg<'_, '_>,
430) -> Result<Matrix<T>>
431where
432 T: Scalar + crate::MatrixLuciScalar,
433{
434 let mut result = identity_rect(left.nrows(), rank);
435 if rank > 0 && rank < left.nrows() {
436 let pivot_rows = index_range(0, rank);
437 let pivot_cols = index_range(0, rank);
438 let rest_rows = index_range(rank, left.nrows());
439 let pivot = submatrix(left, &pivot_rows, &pivot_cols);
440 let rest = submatrix(left, &rest_rows, &pivot_cols);
441 let solved = linalg
442 .triangular_solve(pivot, rest, false, true)
443 .map_err(|err| {
444 backend_linalg_error(format!("MatrixLUCI lower triangular solve failed: {err}"))
445 })?;
446 for row in 0..solved.nrows() {
447 for col in 0..solved.ncols() {
448 result[[rank + row, col]] = solved[[row, col]];
449 }
450 }
451 }
452 Ok(apply_row_permutation(&result, row_permutation))
453}
454
455pub(crate) fn rrlu_pivot_solve_times_rows<T>(
456 lu: &RrLU<T>,
457 linalg: &mut Linalg<'_, '_>,
458) -> Result<Matrix<T>>
459where
460 T: Scalar + crate::MatrixLuciScalar,
461{
462 let rank = lu.npivots();
463 let mut result = identity_rect(rank, lu.ncols());
464 if rank > 0 && rank < lu.ncols() {
465 let pivot_rows = index_range(0, rank);
466 let pivot_cols = index_range(0, rank);
467 let rest_cols = index_range(rank, lu.ncols());
468 let pivot = submatrix(lu.right_unpermuted(), &pivot_rows, &pivot_cols);
469 let rest = submatrix(lu.right_unpermuted(), &pivot_rows, &rest_cols);
470 let solved = linalg
471 .triangular_solve(pivot, rest, true, false)
472 .map_err(|err| {
473 backend_linalg_error(format!("MatrixLUCI upper triangular solve failed: {err}"))
474 })?;
475 for row in 0..solved.nrows() {
476 for col in 0..solved.ncols() {
477 result[[row, rank + col]] = solved[[row, col]];
478 }
479 }
480 }
481 Ok(apply_col_permutation(&result, lu.col_permutation()))
482}
483
484fn factors_from_rrlu<T>(lu: &RrLU<T>, linalg: &mut Linalg<'_, '_>) -> Result<MatrixLuciFactors<T>>
485where
486 T: Scalar + crate::MatrixLuciScalar,
487{
488 let left = if lu.is_left_orthogonal() {
489 rrlu_cols_times_pivot_solve(lu, linalg)?
490 } else {
491 rrlu_colmatrix(lu, linalg)?
492 };
493 let right = if lu.is_left_orthogonal() {
494 rrlu_rowmatrix(lu, linalg)?
495 } else {
496 rrlu_pivot_solve_times_rows(lu, linalg)?
497 };
498
499 Ok(MatrixLuciFactors {
500 row_indices: lu.row_indices(),
501 col_indices: lu.col_indices(),
502 pivot_errors: lu.pivot_errors(),
503 rank: lu.npivots(),
504 left,
505 right,
506 })
507}
508
509pub(crate) fn dense_matrix_luci_factors_from_matrix<T>(
510 a: &Matrix<T>,
511 options: RrLUOptions,
512) -> Result<MatrixLuciFactors<T>>
513where
514 T: Scalar + crate::MatrixLuciScalar,
515{
516 validate_owned_luci_input(a, &options)?;
517 let lu = rrlu(a, Some(options))?;
518 factors_from_rrlu(&lu, &mut Linalg::Global)
519}
520
521pub(crate) fn dense_matrix_luci_factors_from_matrix_owned<T>(
522 mut a: Matrix<T>,
523 options: RrLUOptions,
524 mut linalg: Linalg<'_, '_>,
525) -> Result<MatrixLuciFactors<T>>
526where
527 T: Scalar + crate::MatrixLuciScalar,
528{
529 let lu = rrlu_mut(&mut a, Some(options))?;
530 factors_from_rrlu(&lu, &mut linalg)
531}
532
533pub(crate) fn lazy_matrix_luci_factors_from_blocks<T, F>(
534 nrows: usize,
535 ncols: usize,
536 fill_block: F,
537 options: RrLUOptions,
538) -> Result<MatrixLuciFactors<T>>
539where
540 T: Scalar + crate::MatrixLuciScalar,
541 F: Fn(&[usize], &[usize], &mut [T]),
542 LazyBlockRookKernel: PivotKernel<T>,
543{
544 lazy_matrix_luci_factors_from_blocks_seeded(nrows, ncols, fill_block, &[], options)
545}
546
547pub(crate) fn lazy_matrix_luci_factors_from_blocks_seeded<T, F>(
548 nrows: usize,
549 ncols: usize,
550 fill_block: F,
551 seeds: &[(usize, usize)],
552 options: RrLUOptions,
553) -> Result<MatrixLuciFactors<T>>
554where
555 T: Scalar + crate::MatrixLuciScalar,
556 F: Fn(&[usize], &[usize], &mut [T]),
557 LazyBlockRookKernel: PivotKernel<T>,
558{
559 validate_luci_options(&options)?;
560 let source = LazyMatrixSource::new(nrows, ncols, fill_block);
561 let kernel_options = PivotKernelOptions {
562 max_bond_dim: options.max_bond_dim,
563 rel_tol: options.rel_tol,
564 abs_tol: options.abs_tol,
565 left_orthogonal: options.left_orthogonal,
566 seeds,
567 };
568
569 let selection = LazyBlockRookKernel
570 .factorize(&source, &kernel_options)
571 .map_err(map_backend_error)?;
572 let factors = CrossFactors::from_source(&source, &selection).map_err(map_backend_error)?;
573 factors_to_public(selection, factors, options.left_orthogonal)
574}
575
576/// Factorize a dense matrix with MatrixLUCI.
577///
578/// Returns the selected pivot metadata together with left and
579/// right factors. This is the public facade used by higher-level crates.
580///
581/// # Arguments
582///
583/// * `a` - Dense matrix to factorize.
584/// * `options` - Optional rank and tolerance controls. `None` uses the
585///
586/// default LUCI settings.
587///
588/// # Returns
589///
590/// A [`MatrixLuciFactors`] value containing the selected pivot indices,
591/// error history, rank, and factors.
592///
593/// # Errors
594///
595/// Returns [`MatrixCIError::InvalidArgument`] for negative or non-finite
596/// tolerances, infinite input magnitudes, or backend failures; returns
597/// [`MatrixCIError::NaNEncountered`] for NaN input or non-finite factors.
598///
599/// # Examples
600///
601/// ```
602/// use tensor4all_core::matrix_luci_factors_from_matrix;
603/// use tensor4all_tensorbackend::from_vec2d;
604///
605/// let m = from_vec2d(vec![
606/// vec![1.0_f64, 0.0],
607/// vec![0.0, 2.0],
608/// ]);
609/// let factors = matrix_luci_factors_from_matrix(&m, None).unwrap();
610/// assert_eq!(factors.left.nrows(), 2);
611/// assert_eq!(factors.right.ncols(), 2);
612/// assert_eq!(factors.row_indices.len(), factors.rank);
613/// ```
614pub fn matrix_luci_factors_from_matrix<T>(
615 a: &Matrix<T>,
616 options: Option<RrLUOptions>,
617) -> Result<MatrixLuciFactors<T>>
618where
619 T: Scalar + crate::MatrixLuciScalar,
620{
621 <T as crate::MatrixLuciScalar>::matrix_luci_factors_from_matrix(a, options.unwrap_or_default())
622}
623
624/// Factorize a dense matrix with MatrixLUCI while consuming the input matrix.
625///
626/// This is the owned-buffer counterpart of [`matrix_luci_factors_from_matrix`].
627/// It reuses the local matrix storage for the rrLU pivot selection step.
628///
629/// # Errors
630///
631/// Returns a [`MatrixCIError`] if the factorization fails, for example if the
632/// pivot block is singular or the backend rejects a factor solve.
633pub fn matrix_luci_factors_from_matrix_owned<T>(
634 a: Matrix<T>,
635 options: Option<RrLUOptions>,
636) -> Result<MatrixLuciFactors<T>>
637where
638 T: Scalar + crate::MatrixLuciScalar,
639{
640 let options = options.unwrap_or_default();
641 validate_owned_luci_input(&a, &options)?;
642 dense_matrix_luci_factors_from_matrix_owned(a, options, Linalg::Global)
643}
644
645/// Factorize a dense matrix with MatrixLUCI in a caller-owned CPU context.
646///
647/// Context-scoped counterpart of [`matrix_luci_factors_from_matrix_owned`].
648/// The rank-revealing pivot search is identical; the left and right factors
649/// are assembled with `context`'s configured backend (matrix products and
650/// triangular solves). No process-global context is consulted.
651///
652/// # Arguments
653///
654/// * `a` - Dense column-major matrix to factorize; its storage is reused.
655/// * `options` - Optional rank and tolerance controls. `None` uses the
656/// default LUCI settings.
657/// * `context` - Caller-owned CPU execution context running the factor
658/// assembly.
659///
660/// # Returns
661///
662/// A [`MatrixLuciFactors`] value with the selected pivots, pivot error
663/// history, rank, and factors satisfying `a ~= left * right`.
664///
665/// # Errors
666///
667/// Returns [`MatrixCIError::InvalidArgument`] for negative or nonfinite
668/// tolerances, infinite input magnitudes, or backend solve failures; returns
669/// [`MatrixCIError::NaNEncountered`] for NaN input or factors.
670///
671/// # Examples
672///
673/// ```
674/// use tensor4all_core::{matrix_luci_factors_from_matrix_owned_in, RrLUOptions};
675/// use tensor4all_tensorbackend::{from_vec2d, mat_mul, CpuExecutionContext};
676/// use tensor4all_tensorbackend::CpuBackend;
677///
678/// let context = CpuExecutionContext::from_backend(CpuBackend::new());
679/// // Rank-1 matrix [1 2; 2 4].
680/// let a = from_vec2d(vec![vec![1.0_f64, 2.0], vec![2.0, 4.0]]);
681/// let options = RrLUOptions { left_orthogonal: true, ..RrLUOptions::default() };
682/// let factors = matrix_luci_factors_from_matrix_owned_in(a.clone(), Some(options), &context)?;
683/// assert_eq!(factors.rank, 1);
684/// let rebuilt = mat_mul(&factors.left, &factors.right)?;
685/// for (x, y) in rebuilt.as_col_major_slice().iter().zip(a.as_col_major_slice()) {
686/// assert!((x - y).abs() < 1e-12);
687/// }
688/// # Ok::<(), Box<dyn std::error::Error>>(())
689/// ```
690pub fn matrix_luci_factors_from_matrix_owned_in<T>(
691 a: Matrix<T>,
692 options: Option<RrLUOptions>,
693 context: &CpuExecutionContext,
694) -> Result<MatrixLuciFactors<T>>
695where
696 T: Scalar + crate::MatrixLuciScalar,
697{
698 let options = options.unwrap_or_default();
699 validate_owned_luci_input(&a, &options)?;
700 dense_matrix_luci_factors_from_matrix_owned(a, options, Linalg::Context(context))
701}
702
703/// Factorize a dense matrix with MatrixLUCI in a session the caller already entered.
704///
705/// Session-taking counterpart of [`matrix_luci_factors_from_matrix_owned_in`], for callers that own their
706/// execution rather than a context: a worker lane entered by the phase that owns it, for example, whose session
707/// must be used as it is. The rank-revealing pivot search is identical; the factor assembly's matrix products
708/// and triangular solves run on `session`, and neither a process-global context nor a fresh session entry is
709/// consulted.
710///
711/// # Arguments
712///
713/// * `a` - Dense column-major matrix to factorize; its storage is reused.
714/// * `options` - Optional rank and tolerance controls. `None` uses the default LUCI settings.
715/// * `session` - An already-entered explicit session that runs the factor assembly.
716///
717/// # Returns
718///
719/// A [`MatrixLuciFactors`] value with the selected pivots, pivot error history, rank, and factors satisfying
720/// `a ~= left * right`.
721///
722/// # Errors
723///
724/// Returns [`MatrixCIError::InvalidArgument`] for negative or nonfinite tolerances, infinite input magnitudes,
725/// or backend solve failures; returns [`MatrixCIError::NaNEncountered`] for NaN input or factors.
726///
727/// # Examples
728///
729/// ```
730/// use tensor4all_core::{matrix_luci_factors_from_matrix_owned_on_session, RrLUOptions};
731/// use tensor4all_tensorbackend::{from_vec2d, mat_mul, CpuExecutionContext};
732/// use tensor4all_tensorbackend::CpuBackend;
733///
734/// let context = CpuExecutionContext::from_backend(CpuBackend::new());
735/// let a = from_vec2d(vec![vec![1.0_f64, 2.0], vec![2.0, 4.0]]);
736/// let factors = context.with_concrete_session(|session| {
737/// matrix_luci_factors_from_matrix_owned_on_session(
738/// a.clone(),
739/// Some(RrLUOptions { left_orthogonal: true, ..RrLUOptions::default() }),
740/// session,
741/// )
742/// })??;
743/// assert_eq!(factors.rank, 1);
744/// # Ok::<(), Box<dyn std::error::Error>>(())
745/// ```
746pub fn matrix_luci_factors_from_matrix_owned_on_session<T>(
747 a: Matrix<T>,
748 options: Option<RrLUOptions>,
749 session: &mut Session<'_>,
750) -> Result<MatrixLuciFactors<T>>
751where
752 T: Scalar + crate::MatrixLuciScalar,
753{
754 let options = options.unwrap_or_default();
755 validate_owned_luci_input(&a, &options)?;
756 dense_matrix_luci_factors_from_matrix_owned(a, options, Linalg::Session(session))
757}
758
759/// Factorize a dense matrix with MatrixLUCI and let the caller choose how many
760/// of the selected pivots to keep.
761///
762/// The rank-revealing search runs once with `options`. `select_rank` then
763/// receives its pivot error history (one magnitude per selected pivot, then the
764/// remaining residual) and returns the rank to keep. Only that prefix is turned
765/// into factors. Use it when the kept rank depends on more than one threshold,
766/// for example when pivots between two tolerances are kept only under a
767/// condition: search with the looser tolerance and select the prefix, instead
768/// of factorizing twice.
769///
770/// The result equals [`matrix_luci_factors_from_matrix_owned`] with
771/// `max_bond_dim` set to the selected rank: full pivoting fixes a prefix of
772/// pivots once they are chosen. The trailing pivot error is the magnitude of
773/// the first discarded pivot, which is the largest entry of the remaining
774/// Schur complement.
775///
776/// # Arguments
777///
778/// * `a` - Dense column-major matrix to factorize; its storage is reused.
779/// * `options` - Rank and tolerance controls for the search. `None` uses the
780/// default LUCI settings. The selected rank never exceeds the rank this
781/// search finds.
782/// * `select_rank` - Called once with the pivot error history; returns the
783/// rank to keep. Values above the found rank keep every pivot.
784///
785/// # Returns
786///
787/// A [`MatrixLuciFactors`] value with the kept pivots, their error history,
788/// and factors satisfying `a ~= left * right`.
789///
790/// # Errors
791///
792/// Returns [`MatrixCIError::InvalidArgument`] for negative or nonfinite
793/// tolerances, infinite input magnitudes, or backend solve failures; returns
794/// [`MatrixCIError::NaNEncountered`] for NaN input or factors.
795///
796/// # Examples
797///
798/// ```
799/// use tensor4all_core::{
800/// matrix_luci_factors_from_matrix_owned, matrix_luci_factors_from_matrix_owned_with_rank_selection,
801/// RrLUOptions,
802/// };
803/// use tensor4all_tensorbackend::from_vec2d;
804///
805/// let a = from_vec2d(vec![
806/// vec![4.0_f64, 0.0, 0.0],
807/// vec![0.0, 2.0, 0.0],
808/// vec![0.0, 0.0, 1.0],
809/// ]);
810/// let options = RrLUOptions { rel_tol: 0.0, ..RrLUOptions::default() };
811/// // Keep the pivots above 1.5 only.
812/// let selected = matrix_luci_factors_from_matrix_owned_with_rank_selection(
813/// a.clone(),
814/// Some(options.clone()),
815/// |errors| errors.iter().take_while(|&&e| e > 1.5).count(),
816/// )?;
817/// let capped = matrix_luci_factors_from_matrix_owned(
818/// a,
819/// Some(RrLUOptions { max_bond_dim: 2, ..options }),
820/// )?;
821/// assert_eq!(selected.rank, 2);
822/// assert_eq!(selected.pivot_errors, vec![4.0, 2.0, 1.0]);
823/// assert_eq!(selected.row_indices, capped.row_indices);
824/// assert_eq!(selected.pivot_errors, capped.pivot_errors);
825/// assert_eq!(selected.left.as_col_major_slice(), capped.left.as_col_major_slice());
826/// assert_eq!(selected.right.as_col_major_slice(), capped.right.as_col_major_slice());
827/// # Ok::<(), Box<dyn std::error::Error>>(())
828/// ```
829pub fn matrix_luci_factors_from_matrix_owned_with_rank_selection<T, F>(
830 a: Matrix<T>,
831 options: Option<RrLUOptions>,
832 select_rank: F,
833) -> Result<MatrixLuciFactors<T>>
834where
835 T: Scalar + crate::MatrixLuciScalar,
836 F: FnOnce(&[f64]) -> usize,
837{
838 let options = options.unwrap_or_default();
839 validate_owned_luci_input(&a, &options)?;
840 dense_matrix_luci_factors_with_rank_selection(a, options, select_rank, Linalg::Global)
841}
842
843/// Session-taking counterpart of
844/// [`matrix_luci_factors_from_matrix_owned_with_rank_selection`].
845///
846/// The search and the rank selection are identical; the factor assembly runs
847/// on `session`, as in [`matrix_luci_factors_from_matrix_owned_on_session`].
848///
849/// # Arguments
850///
851/// * `a` - Dense column-major matrix to factorize; its storage is reused.
852/// * `options` - Rank and tolerance controls for the search. `None` uses the
853/// default LUCI settings.
854/// * `select_rank` - Called once with the pivot error history; returns the
855/// rank to keep. Values above the found rank keep every pivot.
856/// * `session` - An already-entered explicit session that runs the factor
857/// assembly.
858///
859/// # Returns
860///
861/// A [`MatrixLuciFactors`] value with the kept pivots, their error history,
862/// and factors satisfying `a ~= left * right`.
863///
864/// # Errors
865///
866/// Returns [`MatrixCIError::InvalidArgument`] for negative or nonfinite
867/// tolerances, infinite input magnitudes, or backend solve failures; returns
868/// [`MatrixCIError::NaNEncountered`] for NaN input or factors.
869///
870/// # Examples
871///
872/// ```
873/// use tensor4all_core::{matrix_luci_factors_from_matrix_owned_with_rank_selection_on_session, RrLUOptions};
874/// use tensor4all_tensorbackend::{from_vec2d, CpuBackend, CpuExecutionContext};
875///
876/// let context = CpuExecutionContext::from_backend(CpuBackend::new());
877/// let a = from_vec2d(vec![vec![4.0_f64, 0.0], vec![0.0, 1.0]]);
878/// let factors = context.with_concrete_session(|session| {
879/// matrix_luci_factors_from_matrix_owned_with_rank_selection_on_session(
880/// a.clone(),
881/// Some(RrLUOptions { rel_tol: 0.0, ..RrLUOptions::default() }),
882/// |_| 1,
883/// session,
884/// )
885/// })??;
886/// assert_eq!(factors.rank, 1);
887/// assert_eq!(factors.row_indices, vec![0]);
888/// assert_eq!(factors.pivot_errors, vec![4.0, 1.0]);
889/// # Ok::<(), Box<dyn std::error::Error>>(())
890/// ```
891pub fn matrix_luci_factors_from_matrix_owned_with_rank_selection_on_session<T, F>(
892 a: Matrix<T>,
893 options: Option<RrLUOptions>,
894 select_rank: F,
895 session: &mut Session<'_>,
896) -> Result<MatrixLuciFactors<T>>
897where
898 T: Scalar + crate::MatrixLuciScalar,
899 F: FnOnce(&[f64]) -> usize,
900{
901 let options = options.unwrap_or_default();
902 validate_owned_luci_input(&a, &options)?;
903 dense_matrix_luci_factors_with_rank_selection(a, options, select_rank, Linalg::Session(session))
904}
905
906fn dense_matrix_luci_factors_with_rank_selection<T, F>(
907 mut a: Matrix<T>,
908 options: RrLUOptions,
909 select_rank: F,
910 mut linalg: Linalg<'_, '_>,
911) -> Result<MatrixLuciFactors<T>>
912where
913 T: Scalar + crate::MatrixLuciScalar,
914 F: FnOnce(&[f64]) -> usize,
915{
916 let mut lu = rrlu_mut(&mut a, Some(options))?;
917 lu.truncate(select_rank(&lu.pivot_errors()));
918 factors_from_rrlu(&lu, &mut linalg)
919}
920
921/// Conservative logical working-byte estimate for owned dense LUCI factors.
922///
923/// Includes the consumed matrix, rrLU L/U, factor construction, permutation
924/// and triangular-solve operands/results, and pivot/index metadata. The
925/// factor rank is bounded by `min(nrows, ncols, max_rank)`. The estimate sums
926/// potentially overlapping factor buffers conservatively; it excludes
927/// allocator overhead and provider-private workspace. Callers must add their
928/// own buffers retained across the factorization.
929///
930/// Returns `None` when checked shape/byte arithmetic overflows `usize`.
931///
932/// # Examples
933///
934/// ```
935/// use tensor4all_core::matrix_luci_factors_working_bytes;
936/// let bytes = matrix_luci_factors_working_bytes::<f64>(32, 32, 32).unwrap();
937/// // Even just the matrix and full-rank L/U require three matrix payloads.
938/// assert!(bytes >= 3 * 32 * 32 * std::mem::size_of::<f64>());
939/// assert!(matrix_luci_factors_working_bytes::<f64>(usize::MAX, 2, 1).is_none());
940/// ```
941pub fn matrix_luci_factors_working_bytes<T: Scalar>(
942 nrows: usize,
943 ncols: usize,
944 max_rank: usize,
945) -> Option<usize> {
946 let rank = max_rank.min(nrows).min(ncols);
947 let axes = nrows.checked_add(ncols)?;
948 let matrix = nrows.checked_mul(ncols)?;
949 // L/U, both output factors, permutation copies, and triangular solve
950 // operands/results. Charge both orientations rather than assuming which
951 // side has the larger solve, including Matrix/backend operand copies.
952 let factors = axes.checked_mul(rank)?.checked_mul(6)?;
953 let pivots = rank.checked_mul(rank)?.checked_mul(2)?;
954 let scalar_bytes = matrix
955 .checked_add(factors)?
956 .checked_add(pivots)?
957 .checked_mul(std::mem::size_of::<T>())?;
958 let index_bytes = axes
959 .checked_add(rank)?
960 .checked_mul(4)?
961 .checked_mul(std::mem::size_of::<usize>())?;
962 let error_bytes = rank
963 .checked_add(1)?
964 .checked_mul(std::mem::size_of::<f64>())?;
965 scalar_bytes
966 .checked_add(index_bytes)?
967 .checked_add(error_bytes)
968}
969
970/// Factorize a lazily supplied matrix with MatrixLUCI block-rook search.
971///
972/// The caller provides a block-fill closure that receives row and column
973/// index lists and writes the corresponding matrix block in column-major
974/// order.
975/// Exactly zero starting residual columns are skipped. An all-zero residual
976/// can require inspecting all remaining entries, without materializing the
977/// full candidate matrix.
978///
979/// Each pivot costs one rook walk over residual rows and columns, and the
980/// factorization stops heuristically: when the current rook pivot, and two
981/// more walks started from other columns, find nothing above tolerance,
982/// without scanning the rest of the matrix. Use
983/// [`MatrixLUCI::from_matrix`] or [`rrlu`](crate::rrlu) on the materialized
984/// matrix when a certified bound on the remaining residual is required.
985///
986/// # Arguments
987///
988/// * `nrows` - Number of matrix rows.
989/// * `ncols` - Number of matrix columns.
990/// * `fill_block` - Closure that fills `out` with `A[rows, cols]` in
991///
992/// column-major order.
993/// * `options` - Rank and tolerance controls.
994///
995/// # Returns
996///
997/// A [`MatrixLuciFactors`] value containing the pivot metadata and
998/// factors. Its trailing `pivot_errors` entry is the last rook pivot: the
999/// pivot the search rejected on tolerance, or, at a rank cap, the pivot one
1000/// extra rook walk finds next. It is `0.0` at full rank or when the remaining
1001/// residual is exactly zero. It is not an upper bound on the remaining
1002/// residual: a larger entry outside the walked rows and columns is not seen.
1003///
1004/// # Errors
1005///
1006/// Returns [`MatrixCIError::InvalidArgument`] for negative or non-finite
1007/// tolerances; returns a [`MatrixCIError`] if the lazy factorization fails or
1008/// if the block callback is inconsistent.
1009///
1010/// # Examples
1011///
1012/// ```
1013/// use tensor4all_core::matrix_luci_factors_from_blocks;
1014/// use tensor4all_core::RrLUOptions;
1015///
1016/// let factors = matrix_luci_factors_from_blocks(
1017/// 2,
1018/// 2,
1019/// |rows, cols, out| {
1020/// for (j, &col) in cols.iter().enumerate() {
1021/// for (i, &row) in rows.iter().enumerate() {
1022/// out[i + rows.len() * j] = if row == col { 1.0 } else { 0.0 };
1023/// }
1024/// }
1025/// },
1026/// RrLUOptions::default(),
1027/// ).unwrap();
1028/// assert_eq!(factors.rank, 2);
1029///
1030/// // A = [[4, 2, 0], [2, 4, 0], [0, 0, 1]] in column-major order. A rank cap
1031/// // reports the rook pivot the search rejects next; here the walk on the
1032/// // Schur complement [[3, 0], [0, 1]] starts in its first column and finds 3.
1033/// let capped = matrix_luci_factors_from_blocks(
1034/// 3,
1035/// 3,
1036/// |rows, cols, out| {
1037/// let data = [4.0_f64, 2.0, 0.0, 2.0, 4.0, 0.0, 0.0, 0.0, 1.0];
1038/// for (j, &col) in cols.iter().enumerate() {
1039/// for (i, &row) in rows.iter().enumerate() {
1040/// out[i + rows.len() * j] = data[row + 3 * col];
1041/// }
1042/// }
1043/// },
1044/// RrLUOptions { max_bond_dim: 1, ..Default::default() },
1045/// ).unwrap();
1046/// assert_eq!(capped.pivot_errors, vec![4.0, 3.0]);
1047/// ```
1048pub fn matrix_luci_factors_from_blocks<T, F>(
1049 nrows: usize,
1050 ncols: usize,
1051 fill_block: F,
1052 options: RrLUOptions,
1053) -> Result<MatrixLuciFactors<T>>
1054where
1055 T: Scalar + crate::MatrixLuciScalar,
1056 F: Fn(&[usize], &[usize], &mut [T]),
1057{
1058 <T as crate::MatrixLuciScalar>::matrix_luci_factors_from_blocks(
1059 nrows, ncols, fill_block, options,
1060 )
1061}
1062
1063/// [`matrix_luci_factors_from_blocks`] that also hands the rook kernel the
1064/// pivots of the previous factorization of the same candidate matrix.
1065///
1066/// `seeds` are `(row, col)` pairs of source indices, in the order the previous
1067/// factorization accepted them. They decide where each rook walk starts
1068/// (`arrlu`'s `I0`/`J0`), which can change which pivots are accepted and
1069/// therefore the rank and the `pivot_errors` history: a walk that starts
1070/// elsewhere converges to another local rook. Seeds do not restore any error
1071/// guarantee: the stop is as heuristic as in
1072/// [`matrix_luci_factors_from_blocks`], and the trailing `pivot_errors` entry is
1073/// still the last rook pivot, not a bound on the remaining residual. Internal
1074/// plumbing for callers that factorize the same matrix once per sweep; see
1075/// `tensorci2::update_pivots`.
1076#[doc(hidden)]
1077pub fn matrix_luci_factors_from_blocks_seeded<T, F>(
1078 nrows: usize,
1079 ncols: usize,
1080 fill_block: F,
1081 seeds: &[(usize, usize)],
1082 options: RrLUOptions,
1083) -> Result<MatrixLuciFactors<T>>
1084where
1085 T: Scalar + crate::MatrixLuciScalar,
1086 F: Fn(&[usize], &[usize], &mut [T]),
1087{
1088 <T as crate::MatrixLuciScalar>::matrix_luci_factors_from_blocks_seeded(
1089 nrows, ncols, fill_block, seeds, options,
1090 )
1091}
1092
1093impl<T> MatrixLUCI<T>
1094where
1095 T: Scalar + crate::MatrixLuciScalar,
1096{
1097 /// Create a MatrixLUCI from a dense matrix.
1098 ///
1099 /// # Errors
1100 ///
1101 /// Returns [`MatrixCIError`] when `a` is not a valid matrix for LU cross
1102 /// interpolation or when the factor construction fails.
1103 ///
1104 /// # Examples
1105 ///
1106 /// ```
1107 /// use tensor4all_core::{AbstractMatrixCI, MatrixLUCI};
1108 /// use tensor4all_tensorbackend::from_vec2d;
1109 ///
1110 /// let m = from_vec2d(vec![
1111 /// vec![2.0_f64, 0.0],
1112 /// vec![0.0, 3.0],
1113 /// ]);
1114 /// let ci = MatrixLUCI::from_matrix(&m, None).unwrap();
1115 /// assert!(ci.rank() >= 1);
1116 /// ```
1117 pub fn from_matrix(a: &Matrix<T>, options: Option<RrLUOptions>) -> Result<Self> {
1118 let factors = matrix_luci_factors_from_matrix(a, options)?;
1119
1120 Ok(Self {
1121 nrows: a.nrows(),
1122 ncols: a.ncols(),
1123 row_indices: factors.row_indices,
1124 col_indices: factors.col_indices,
1125 left: factors.left,
1126 right: factors.right,
1127 pivot_errors: factors.pivot_errors,
1128 })
1129 }
1130
1131 /// Left CI factor (shape: `nrows x rank`).
1132 ///
1133 /// The approximation is `left * right`.
1134 ///
1135 /// # Examples
1136 ///
1137 /// ```
1138 /// use tensor4all_core::{AbstractMatrixCI, MatrixLUCI};
1139 /// use tensor4all_tensorbackend::{from_vec2d, mat_mul};
1140 ///
1141 /// let m = from_vec2d(vec![
1142 /// vec![1.0_f64, 2.0],
1143 /// vec![3.0, 4.0],
1144 /// ]);
1145 /// let ci = MatrixLUCI::from_matrix(&m, None).unwrap();
1146 /// let reconstructed = mat_mul(&ci.left(), &ci.right()).unwrap();
1147 /// for i in 0..2 {
1148 /// for j in 0..2 {
1149 /// assert!((reconstructed[[i, j]] - m[[i, j]]).abs() < 1e-10);
1150 /// }
1151 /// }
1152 /// ```
1153 pub fn left(&self) -> Matrix<T> {
1154 self.left.clone()
1155 }
1156
1157 /// Right CI factor (shape: `rank x ncols`).
1158 ///
1159 /// The approximation is `left * right`.
1160 ///
1161 /// # Examples
1162 ///
1163 /// ```
1164 /// use tensor4all_core::{AbstractMatrixCI, MatrixLUCI};
1165 /// use tensor4all_tensorbackend::{from_vec2d, mat_mul};
1166 ///
1167 /// let m = from_vec2d(vec![vec![1.0_f64, 2.0], vec![3.0, 4.0]]);
1168 /// let ci = MatrixLUCI::from_matrix(&m, None).unwrap();
1169 /// let r = ci.right();
1170 /// assert_eq!(r.nrows(), ci.rank());
1171 /// assert_eq!(r.ncols(), ci.ncols());
1172 /// // left * right reconstructs the matrix
1173 /// let recon = mat_mul(&ci.left(), &r).unwrap();
1174 /// for i in 0..2 {
1175 /// for j in 0..2 {
1176 /// assert!((recon[[i, j]] - m[[i, j]]).abs() < 1e-10);
1177 /// }
1178 /// }
1179 /// ```
1180 pub fn right(&self) -> Matrix<T> {
1181 self.right.clone()
1182 }
1183
1184 /// Pivot error history (one entry per pivot, plus a final residual estimate).
1185 ///
1186 /// # Examples
1187 ///
1188 /// ```
1189 /// use tensor4all_core::MatrixLUCI;
1190 /// use tensor4all_tensorbackend::from_vec2d;
1191 ///
1192 /// let m = from_vec2d(vec![vec![1.0_f64, 2.0], vec![3.0, 4.0]]);
1193 /// let ci = MatrixLUCI::from_matrix(&m, None).unwrap();
1194 /// let errs = ci.pivot_errors();
1195 /// assert!(!errs.is_empty());
1196 /// // All errors are non-negative
1197 /// for &e in &errs {
1198 /// assert!(e >= 0.0);
1199 /// }
1200 /// ```
1201 pub fn pivot_errors(&self) -> Vec<f64> {
1202 self.pivot_errors.clone()
1203 }
1204
1205 /// Last pivot error (the residual estimate after all pivots).
1206 ///
1207 /// # Examples
1208 ///
1209 /// ```
1210 /// use tensor4all_core::MatrixLUCI;
1211 /// use tensor4all_tensorbackend::from_vec2d;
1212 ///
1213 /// let m = from_vec2d(vec![vec![1.0_f64, 2.0], vec![3.0, 4.0]]);
1214 /// let ci = MatrixLUCI::from_matrix(&m, None).unwrap();
1215 /// let err = ci.last_pivot_error();
1216 /// assert!(err >= 0.0);
1217 /// ```
1218 pub fn last_pivot_error(&self) -> f64 {
1219 self.pivot_errors.last().copied().unwrap_or(0.0)
1220 }
1221}
1222
1223impl<T> AbstractMatrixCI<T> for MatrixLUCI<T>
1224where
1225 T: Scalar + crate::MatrixLuciScalar,
1226{
1227 fn nrows(&self) -> usize {
1228 self.nrows
1229 }
1230
1231 fn ncols(&self) -> usize {
1232 self.ncols
1233 }
1234
1235 fn rank(&self) -> usize {
1236 self.row_indices.len()
1237 }
1238
1239 fn row_indices(&self) -> &[usize] {
1240 &self.row_indices
1241 }
1242
1243 fn col_indices(&self) -> &[usize] {
1244 &self.col_indices
1245 }
1246
1247 fn evaluate(&self, i: usize, j: usize) -> T {
1248 let mut sum = T::zero();
1249 for k in 0..self.rank() {
1250 sum = sum + self.left[[i, k]] * self.right[[k, j]];
1251 }
1252 sum
1253 }
1254
1255 fn submatrix(&self, rows: &[usize], cols: &[usize]) -> Matrix<T> {
1256 let r = self.rank();
1257 let mut result = Matrix::zeros(rows.len(), cols.len());
1258 for (j_out, &col) in cols.iter().enumerate() {
1259 for (i_out, &row) in rows.iter().enumerate() {
1260 let mut sum = T::zero();
1261 for k in 0..r {
1262 sum = sum + self.left[[row, k]] * self.right[[k, col]];
1263 }
1264 result[[i_out, j_out]] = sum;
1265 }
1266 }
1267 result
1268 }
1269}
1270
1271#[cfg(test)]
1272mod tests;