Skip to main content

tensor4all_core/defaults/
factorize.rs

1//! Unified tensor factorization module.
2//!
3//! This module provides a unified `factorize()` function that dispatches to
4//! SVD, RSVD, QR, LU, or CI (Cross Interpolation) algorithms based on options.
5//!
6//! # Note
7//!
8//! This module works with concrete types (`DynIndex`, `IdxTensor`) only.
9//! Generic tensor types are not supported.
10//!
11//! # Example
12//!
13//! ```
14//! use tensor4all_core::{factorize, Canonical, DynIndex, FactorizeOptions, IdxTensor, TensorLike};
15//!
16//! # fn main() -> anyhow::Result<()> {
17//! let i = DynIndex::new_dyn(2);
18//! let j = DynIndex::new_dyn(2);
19//! let tensor = IdxTensor::from_dense(
20//!     vec![i.clone(), j.clone()],
21//!     vec![1.0, 0.0, 0.0, 1.0],
22//! )?;
23//! let result = factorize(
24//!     &tensor,
25//!     std::slice::from_ref(&i),
26//!     &FactorizeOptions::svd().with_canonical(Canonical::Left),
27//! )?;
28//!
29//! assert_eq!(result.rank, 2);
30//! assert_eq!(result.left.dims(), vec![2, 2]);
31//! # Ok(())
32//! # }
33//! ```
34
35use super::eager_session::with_eager_session;
36use crate::defaults::idx_tensor::unfold_split_inner;
37use crate::defaults::DynIndex;
38use crate::{contract_pair, unfold_split, AnyScalar, IdxTensor, IdxTensorError};
39use crate::{
40    matrix_luci_factors_from_matrix_owned, rrlu_mut, MatrixLuciFactors, RrLUOptions,
41    Scalar as MatrixScalar,
42};
43use num_complex::{Complex32, Complex64, ComplexFloat};
44use tenferro_ad::EagerTensor;
45use tensor4all_tensorbackend::{Matrix, TensorElement};
46
47use crate::defaults::svd::{
48    compute_retained_rank, svd_for_factorize, svd_for_factorize_in, svd_for_factorize_on_session,
49    SvdFactorizeResult,
50};
51use crate::qr::{qr_with, qr_with_in, QrOptions};
52use crate::svd::SvdOptions;
53use crate::truncation::{
54    validate_svd_truncation_policy, SingularValueMeasure, SvdTruncationPolicy, ThresholdScale,
55    TruncationRule,
56};
57use crate::ExecutionContext;
58
59// Re-export types from tensor_like for backwards compatibility
60pub use crate::tensor_like::{
61    Canonical, FactorizeAlg, FactorizeError, FactorizeOptions, FactorizeResult,
62};
63
64/// Factorize a tensor into left and right factors.
65///
66/// This function dispatches to the appropriate algorithm based on `options.alg`:
67/// - `SVD`: Singular Value Decomposition
68/// - `RSVD`: Fixed-rank randomized SVD (seeded convenience call)
69/// - `QR`: QR decomposition
70/// - `LU`: Rank-revealing LU decomposition
71/// - `CI`: Cross Interpolation
72///
73/// The `canonical` option controls which factor is "canonical":
74/// - `Canonical::Left`: Left factor is orthogonal (SVD/QR) or unit-diagonal (LU/CI)
75/// - `Canonical::Right`: Right factor is orthogonal (SVD) or unit-diagonal (LU/CI)
76///
77/// # Arguments
78/// * `t` - Input tensor
79/// * `left_inds` - Indices to place on the left side
80/// * `options` - Factorization options
81///
82/// # Returns
83/// A `FactorizeResult` containing the left and right factors, bond index,
84/// singular values (for SVD/RSVD), and rank.
85///
86/// # Errors
87/// Returns `FactorizeError` if:
88/// - The storage type is not supported (f64/Complex64 for all host methods,
89///   with f32/Complex32 additionally supported by CI)
90/// - QR is used with `Canonical::Right`
91/// - LU or CI is requested for a tracked tensor (those paths do not yet
92///   preserve reverse-mode AD metadata)
93/// - RSVD is paired with an explicit threshold policy (`UnsupportedTruncationPolicy`)
94/// - The underlying algorithm fails
95pub fn factorize(
96    t: &IdxTensor,
97    left_inds: &[DynIndex],
98    options: &FactorizeOptions,
99) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
100    options.validate()?;
101    if options.alg == FactorizeAlg::RSVD {
102        use rand::SeedableRng;
103        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(options.rsvd_seed);
104        return crate::randomized::factorize(
105            t,
106            left_inds,
107            options,
108            &mut rng,
109            &mut crate::randomized::Route::Eager(None),
110        );
111    }
112
113    if t.is_diag() {
114        return Err(FactorizeError::UnsupportedStorage(
115            "Diagonal storage not supported for factorize",
116        ));
117    }
118    if t.tracks_grad() && matches!(options.alg, FactorizeAlg::LU | FactorizeAlg::CI) {
119        return Err(FactorizeError::UnsupportedStorage(
120            "LU and CI factorization do not support tracked tensors yet",
121        ));
122    }
123
124    if options.alg == FactorizeAlg::CI && t.is_f32() {
125        factorize_ci::<f32>(t, left_inds, options)
126    } else if options.alg == FactorizeAlg::CI && t.is_c32() {
127        factorize_ci::<Complex32>(t, left_inds, options)
128    } else if t.is_f64() {
129        factorize_impl::<f64>(t, left_inds, options)
130    } else if t.is_c64() {
131        factorize_impl::<Complex64>(t, left_inds, options)
132    } else {
133        Err(FactorizeError::UnsupportedStorage(
134            "factorize requires f64/Complex64, or f32/Complex32 with CI",
135        ))
136    }
137}
138
139/// Factorize with a caller-owned RNG, preserving its stream across calls.
140///
141/// RSVD uses the positive `max_bond_dim` and `randomized` sketch options;
142/// `rsvd_seed` is ignored. Deterministic algorithms do not consume randomness.
143/// Returns the same canonical factors as [`factorize`].
144///
145/// # Errors
146/// Returns [`FactorizeError`] for invalid options or indices, unsupported
147/// storage/dtype, size overflow, or a backend failure.
148///
149/// # Examples
150/// ```
151/// use rand::SeedableRng;
152/// use rand_chacha::ChaCha8Rng;
153/// use tensor4all_core::{factorize_with_rng, DynIndex, FactorizeOptions, IdxTensor, TensorContractionLike};
154/// let i = DynIndex::new_dyn(2);
155/// let j = DynIndex::new_dyn(2);
156/// let a = IdxTensor::from_dense(vec![i.clone(), j], vec![3., 0., 0., 0.])?;
157/// let mut rng = ChaCha8Rng::seed_from_u64(11);
158/// let result = factorize_with_rng(&a, &[i], &FactorizeOptions::rsvd(1), &mut rng)?;
159/// assert!(a.sub(&result.left.contract_pair(&result.right)?)?.maxabs()? < 1e-12);
160/// # Ok::<(), Box<dyn std::error::Error>>(())
161/// ```
162pub fn factorize_with_rng<R: rand::Rng + ?Sized>(
163    t: &IdxTensor,
164    left_inds: &[DynIndex],
165    options: &FactorizeOptions,
166    rng: &mut R,
167) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
168    if options.alg == FactorizeAlg::RSVD {
169        crate::randomized::factorize(
170            t,
171            left_inds,
172            options,
173            rng,
174            &mut crate::randomized::Route::Eager(None),
175        )
176    } else {
177        factorize(t, left_inds, options)
178    }
179}
180
181/// Factorize with a continuous caller RNG in a caller-owned execution context.
182///
183/// Same rank, sketch and factor contracts as [`factorize_with_rng`]. Inputs,
184/// sketches and results belong to `context`; invalid inputs leave `rng` untouched.
185///
186/// # Errors
187/// Returns [`FactorizeError`] for invalid options/indices, foreign execution
188/// contexts, unsupported storage/dtype, overflow, or a backend failure.
189///
190/// # Examples
191/// ```
192/// use std::sync::Arc;
193/// use rand::SeedableRng;
194/// use rand_chacha::ChaCha8Rng;
195/// use tensor4all_core::{factorize_with_rng_in, DynIndex, ExecutionContext, FactorizeOptions, IdxTensor, TensorContractionLike};
196/// use tensor4all_tensorbackend::{CpuBackend, CpuExecutionContext};
197/// let context = ExecutionContext::Cpu(Arc::new(CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?)));
198/// let i = DynIndex::new_dyn(2);
199/// let j = DynIndex::new_dyn(2);
200/// let a = IdxTensor::from_dense_in(&context, vec![i.clone(), j], vec![3., 0., 0., 0.])?;
201/// let mut rng = ChaCha8Rng::seed_from_u64(11);
202/// let result = factorize_with_rng_in(&a, &[i], &FactorizeOptions::rsvd(1), &mut rng, &context)?;
203/// let values = result.left.contract_pair(&result.right)?.to_vec::<f64>()?;
204/// assert!(values.iter().zip([3., 0., 0., 0.]).all(|(x, y)| (x - y).abs() < 1e-12));
205/// # Ok::<(), Box<dyn std::error::Error>>(())
206/// ```
207pub fn factorize_with_rng_in<R: rand::Rng + ?Sized>(
208    t: &IdxTensor,
209    left_inds: &[DynIndex],
210    options: &FactorizeOptions,
211    rng: &mut R,
212    context: &ExecutionContext,
213) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
214    if options.alg == FactorizeAlg::RSVD {
215        crate::randomized::factorize(
216            t,
217            left_inds,
218            options,
219            rng,
220            &mut crate::randomized::Route::Eager(Some(context)),
221        )
222    } else {
223        factorize_in(t, left_inds, options, context)
224    }
225}
226
227/// Factorize on a caller-held plain session using a caller-owned RNG.
228///
229/// Same rank, sketch and factor contracts as [`factorize_with_rng`]. All numeric
230/// operations use `session`; results are untracked host tensors. No eager runtime
231/// or second session is entered.
232///
233/// # Errors
234/// Returns [`FactorizeError`] for tracked/resident operands, unsupported storage
235/// or dtype, invalid options/indices, overflow, or a backend failure.
236///
237/// # Examples
238/// ```
239/// use rand::SeedableRng;
240/// use rand_chacha::ChaCha8Rng;
241/// use tensor4all_core::{factorize_with_rng_on_session, DynIndex, FactorizeOptions, IdxTensor, TensorContractionLike};
242/// use tensor4all_tensorbackend::{explicit::Session, CpuBackend};
243/// let i = DynIndex::new_dyn(2);
244/// let j = DynIndex::new_dyn(2);
245/// let a = IdxTensor::from_dense(vec![i.clone(), j], vec![3., 0., 0., 0.])?;
246/// let mut rng = ChaCha8Rng::seed_from_u64(11);
247/// let mut backend = CpuBackend::with_threads(1)?;
248/// let result = {
249///     let mut session = Session::new(backend.engine_mut());
250///     factorize_with_rng_on_session(&mut session, &a, &[i], &FactorizeOptions::rsvd(1), &mut rng)?
251/// };
252/// assert!(a.sub(&result.left.contract_pair(&result.right)?)?.maxabs()? < 1e-12);
253/// # Ok::<(), Box<dyn std::error::Error>>(())
254/// ```
255pub fn factorize_with_rng_on_session<R: rand::Rng + ?Sized>(
256    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
257    t: &IdxTensor,
258    left_inds: &[DynIndex],
259    options: &FactorizeOptions,
260    rng: &mut R,
261) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
262    if options.alg == FactorizeAlg::RSVD {
263        crate::randomized::factorize(
264            t,
265            left_inds,
266            options,
267            rng,
268            &mut crate::randomized::Route::Session(session),
269        )
270    } else {
271        factorize_on_session(session, t, left_inds, options)
272    }
273}
274
275/// Select Gram eigendecomposition for safe untracked SVD truncations.
276///
277/// This is intentionally crate-visible: the public entry point is the
278/// [`TensorFactorizationLike::factorize_auto`] method.
279pub(crate) fn factorize_auto(
280    t: &IdxTensor,
281    left_inds: &[DynIndex],
282    options: &FactorizeOptions,
283) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
284    if options.alg == FactorizeAlg::RSVD {
285        return factorize(t, left_inds, options);
286    }
287    if options.alg != FactorizeAlg::SVD {
288        return Err(FactorizeError::InvalidOptions(
289            "automatic factorization only supports SVD options",
290        ));
291    }
292    options.validate()?;
293
294    let Some(policy) = options.svd_policy else {
295        return factorize(t, left_inds, options);
296    };
297    validate_svd_truncation_policy(policy).map_err(|error| FactorizeError::InvalidRtol(error.0))?;
298
299    let effective_cutoff = match (policy.scale, policy.measure, policy.rule) {
300        (ThresholdScale::Relative, SingularValueMeasure::SquaredValue, _) => policy.threshold,
301        (ThresholdScale::Relative, SingularValueMeasure::Value, TruncationRule::PerValue) => {
302            policy.threshold * policy.threshold
303        }
304        _ => 0.0,
305    };
306    if effective_cutoff <= 1.0e-12 || t.tracks_grad() || t.is_diag() {
307        return factorize(t, left_inds, options);
308    }
309    if !(t.is_f64() || t.is_c64()) {
310        return factorize(t, left_inds, options);
311    }
312
313    factorize_gram(t, left_inds, options, policy).or_else(|_| factorize(t, left_inds, options))
314}
315
316fn factorize_gram(
317    t: &IdxTensor,
318    left_inds: &[DynIndex],
319    options: &FactorizeOptions,
320    policy: SvdTruncationPolicy,
321) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
322    let (matrix_inner, _, m, n, left_indices, right_indices) = unfold_split_inner(t, left_inds)
323        .map_err(|error| FactorizeError::ComputationError(anyhow::anyhow!(error)))?;
324    if m == 0 || n == 0 {
325        return Err(FactorizeError::ComputationError(anyhow::anyhow!(
326            "cannot factorize a matrix with an empty dimension"
327        )));
328    }
329
330    let row = DynIndex::new_dyn(m);
331    let column = DynIndex::new_dyn(n);
332    let matrix = IdxTensor::from_inner(vec![row.clone(), column.clone()], matrix_inner)
333        .map_err(FactorizeError::ComputationError)?;
334
335    // Form the smaller Gram tensor directly through the native contraction
336    // path. No rectangular host Matrix or Matrix↔backend round-trip is needed.
337    let eigenvectors_left = m <= n;
338    let gram = if eigenvectors_left {
339        let sim_row = DynIndex::new_dyn(m);
340        let adjoint = matrix
341            .conj()
342            .replaceind(&row, &sim_row)
343            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
344        contract_pair(&matrix, &adjoint)
345    } else {
346        let sim_column = DynIndex::new_dyn(n);
347        let adjoint = matrix
348            .conj()
349            .replaceind(&column, &sim_column)
350            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
351        contract_pair(&adjoint, &matrix)
352    }
353    .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
354    let decomposition = gram
355        .hermitian_eigendecomposition(1.0e-12)
356        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
357
358    let lambda_scale = decomposition
359        .eigenvalues
360        .iter()
361        .map(|lambda| lambda.abs())
362        .fold(0.0_f64, f64::max);
363    if lambda_scale == 0.0 {
364        return Err(FactorizeError::ComputationError(anyhow::anyhow!(
365            "zero Gram matrix uses the SVD fallback"
366        )));
367    }
368    let negative_tolerance = 1.0e-12 * lambda_scale;
369    let mut eigenpairs: Vec<(f64, usize)> = decomposition
370        .eigenvalues
371        .iter()
372        .copied()
373        .enumerate()
374        .map(|(column, mut lambda)| {
375            if !lambda.is_finite() {
376                return Err(FactorizeError::ComputationError(anyhow::anyhow!(
377                    "Gram eigendecomposition returned a non-finite eigenvalue"
378                )));
379            }
380            if lambda < -negative_tolerance {
381                return Err(FactorizeError::ComputationError(anyhow::anyhow!(
382                    "Gram eigendecomposition returned a materially negative eigenvalue"
383                )));
384            }
385            if lambda < 0.0 {
386                lambda = 0.0;
387            }
388            Ok((lambda, column))
389        })
390        .collect::<Result<_, _>>()?;
391    eigenpairs.sort_by(|(left, _), (right, _)| right.total_cmp(left));
392
393    let all_singular_values: Vec<f64> =
394        eigenpairs.iter().map(|(lambda, _)| lambda.sqrt()).collect();
395    let mut rank = compute_retained_rank(&all_singular_values, &policy);
396    if let Some(max_bond_dim) = options.max_bond_dim {
397        rank = rank.min(max_bond_dim);
398    }
399    rank = rank.max(1).min(m.min(n));
400    let singular_values = all_singular_values[..rank].to_vec();
401    if singular_values.contains(&0.0) {
402        return Err(FactorizeError::ComputationError(anyhow::anyhow!(
403            "zero retained singular value uses the SVD fallback"
404        )));
405    }
406
407    let retained_columns: Vec<usize> = eigenpairs
408        .iter()
409        .take(rank)
410        .map(|(_, column)| *column)
411        .collect();
412    let eigenvectors_inner = decomposition
413        .eigenvectors
414        .as_inner()
415        .map_err(FactorizeError::ComputationError)?;
416    let basis_inner = with_eager_session(eigenvectors_inner.runtime(), None, |session| {
417        session.take_cols(eigenvectors_inner, &retained_columns)
418    })
419    .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
420    let bond_index = DynIndex::new_bond(rank)
421        .map_err(|error| FactorizeError::ComputationError(anyhow::anyhow!(error)))?;
422    let basis_index = if eigenvectors_left {
423        row.clone()
424    } else {
425        column.clone()
426    };
427    let basis = IdxTensor::from_inner(vec![basis_index, bond_index.clone()], basis_inner)
428        .map_err(FactorizeError::ComputationError)?;
429
430    let (left_matrix, right_matrix) = if eigenvectors_left {
431        let sigma_vh = contract_pair(&basis.conj(), &matrix)
432            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?
433            .permute_indices(&[bond_index.clone(), column.clone()])
434            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
435        match options.canonical {
436            Canonical::Left => (basis, sigma_vh),
437            Canonical::Right => {
438                let inverse: Vec<f64> = singular_values.iter().map(|sigma| 1.0 / sigma).collect();
439                (
440                    scale_bond(&basis, &bond_index, &singular_values)?,
441                    scale_bond(&sigma_vh, &bond_index, &inverse)?,
442                )
443            }
444        }
445    } else {
446        let u_sigma = contract_pair(&matrix, &basis)
447            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?
448            .permute_indices(&[row.clone(), bond_index.clone()])
449            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
450        let vh = basis
451            .conj()
452            .permute_indices(&[bond_index.clone(), column.clone()])
453            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
454        match options.canonical {
455            Canonical::Right => (u_sigma, vh),
456            Canonical::Left => {
457                let inverse: Vec<f64> = singular_values.iter().map(|sigma| 1.0 / sigma).collect();
458                (
459                    scale_bond(&u_sigma, &bond_index, &inverse)?,
460                    scale_bond(&vh, &bond_index, &singular_values)?,
461                )
462            }
463        }
464    };
465
466    let mut output_left_indices = left_indices;
467    output_left_indices.push(bond_index.clone());
468    let left = reshape_factor(left_matrix, output_left_indices)?;
469    let mut output_right_indices = vec![bond_index.clone()];
470    output_right_indices.extend(right_indices);
471    let right = reshape_factor(right_matrix, output_right_indices)?;
472
473    Ok(FactorizeResult::new(
474        left,
475        right,
476        bond_index,
477        Some(singular_values),
478        rank,
479    ))
480}
481
482fn scale_bond(
483    tensor: &IdxTensor,
484    bond: &DynIndex,
485    values: &[f64],
486) -> Result<IdxTensor, FactorizeError> {
487    let temporary = DynIndex::new_bond(values.len())
488        .map_err(|error| FactorizeError::ComputationError(anyhow::anyhow!(error)))?;
489    let diagonal_values = values
490        .iter()
491        .map(|value| {
492            if tensor.is_complex() {
493                AnyScalar::new_complex(*value, 0.0)
494            } else {
495                AnyScalar::new_real(*value)
496            }
497        })
498        .collect();
499    let diagonal = IdxTensor::from_diag_any(vec![bond.clone(), temporary.clone()], diagonal_values)
500        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
501    contract_pair(tensor, &diagonal)
502        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?
503        .replaceind(&temporary, bond)
504        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?
505        .permute_indices(tensor.indices())
506        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))
507}
508
509fn reshape_factor(tensor: IdxTensor, indices: Vec<DynIndex>) -> Result<IdxTensor, FactorizeError> {
510    let dims: Vec<usize> = indices.iter().map(|index| index.dim).collect();
511    let inner = tensor
512        .as_inner()
513        .map_err(FactorizeError::ComputationError)?;
514    let inner = with_eager_session(inner.runtime(), None, |session| {
515        session.reshape(inner, &dims)
516    })
517    .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
518    IdxTensor::from_inner(indices, inner).map_err(FactorizeError::ComputationError)
519}
520
521/// Factorize a tensor without applying algorithm-specific truncation options.
522///
523/// This path is intended for canonicalization and other exact tensor-network
524/// rewrites where the decomposition must preserve the represented tensor rather
525/// than obey global SVD/QR/LU rank-dropping defaults.
526///
527/// # Arguments
528/// * `t` - Input tensor.
529/// * `left_inds` - Indices to place on the left side.
530/// * `alg` - Decomposition algorithm to use.
531/// * `canonical` - Which factor should carry the canonical form.
532///
533/// # Returns
534/// A factorization whose contracted factors reconstruct `t` up to numerical
535/// roundoff, with no tolerance-based or maximum-rank truncation applied.
536///
537/// # Errors
538/// Returns [`FactorizeError`] if the storage type is unsupported, LU or CI is
539/// requested for a tracked tensor, the canonical direction is unsupported for
540/// the selected algorithm, or the underlying decomposition fails.
541///
542/// # Examples
543///
544/// ```
545/// use tensor4all_core::{
546///     factorize_full_rank, Canonical, DynIndex, FactorizeAlg, TensorContractionLike, IdxTensor,
547/// };
548///
549/// let i = DynIndex::new_dyn(2);
550/// let j = DynIndex::new_dyn(2);
551/// let tensor = IdxTensor::from_dense(
552///     vec![i.clone(), j.clone()],
553///     vec![1.0_f64, 0.0, 0.0, 1.0e-16],
554/// )?;
555///
556/// let result = factorize_full_rank(
557///     &tensor,
558///     std::slice::from_ref(&i),
559///     FactorizeAlg::QR,
560///     Canonical::Left,
561/// )?;
562/// let reconstructed = result.left.contract_pair(&result.right).unwrap();
563/// assert!(tensor.sub(&reconstructed)?.maxabs()? < 1.0e-18);
564/// # Ok::<(), Box<dyn std::error::Error>>(())
565/// ```
566pub fn factorize_full_rank(
567    t: &IdxTensor,
568    left_inds: &[DynIndex],
569    alg: FactorizeAlg,
570    canonical: Canonical,
571) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
572    if t.is_diag() {
573        return Err(FactorizeError::UnsupportedStorage(
574            "Diagonal storage not supported for factorize",
575        ));
576    }
577    if t.tracks_grad() && matches!(alg, FactorizeAlg::LU | FactorizeAlg::CI) {
578        return Err(FactorizeError::UnsupportedStorage(
579            "LU and CI factorization do not support tracked tensors yet",
580        ));
581    }
582
583    if alg == FactorizeAlg::CI && t.is_f32() {
584        factorize_ci_full_rank::<f32>(t, left_inds, canonical)
585    } else if alg == FactorizeAlg::CI && t.is_c32() {
586        factorize_ci_full_rank::<Complex32>(t, left_inds, canonical)
587    } else if t.is_f64() {
588        factorize_impl_full_rank::<f64>(t, left_inds, alg, canonical)
589    } else if t.is_c64() {
590        factorize_impl_full_rank::<Complex64>(t, left_inds, alg, canonical)
591    } else {
592        Err(FactorizeError::UnsupportedStorage(
593            "factorize requires f64/Complex64, or f32/Complex32 with CI",
594        ))
595    }
596}
597
598/// Factorize a tensor in a caller-owned execution context.
599///
600/// Context-scoped counterpart of [`factorize`]: the input must belong to
601/// `context`, and QR/SVD factors, truncation, and results stay in `context`
602/// with only bounded decision payloads crossing the explicit readback
603/// boundary on CUDA. LU and CI have no context-scoped path and return a typed
604/// error; run them through [`factorize`] on host inputs instead.
605///
606/// # Arguments
607/// * `t` - Input tensor, which must belong to `context`.
608/// * `left_inds` - Indices to place on the left side.
609/// * `options` - Factorization options.
610/// * `context` - Caller-owned execution context owning the input and results.
611///
612/// # Examples
613///
614/// ```
615/// use std::sync::Arc;
616/// use tensor4all_core::{
617///     DynIndex, ExecutionContext, FactorizeOptions, TensorContractionLike,
618///     factorize_in, Canonical, FactorizeAlg,
619/// };
620/// use tensor4all_tensorbackend::CpuExecutionContext;
621/// use tensor4all_tensorbackend::CpuBackend;
622///
623/// let context = ExecutionContext::Cpu(Arc::new(
624///     CpuExecutionContext::from_backend(CpuBackend::new()),
625/// ));
626/// let i = DynIndex::new_dyn(4);
627/// let j = DynIndex::new_dyn(3);
628/// let data: Vec<f64> = (0..12).map(|x| x as f64).collect();
629/// let tensor =
630///     tensor4all_core::IdxTensor::from_dense_in(&context, vec![i.clone(), j.clone()], data)?;
631/// let options = FactorizeOptions::qr();
632/// let result = factorize_in(&tensor, &[i.clone()], &options, &context)?;
633/// let recovered = result.left.contract_pair(&result.right)?;
634/// assert_eq!(recovered.dims(), vec![4, 3]);
635/// # Ok::<(), Box<dyn std::error::Error>>(())
636/// ```
637///
638/// # Errors
639/// Returns `FactorizeError` when the tensor does not belong to `context`,
640/// when the storage, algorithm, or options are unsupported, or when the
641/// factorization or explicit decision readback fails. When this build cannot
642/// execute in `context`, the rejection carries
643/// [`IdxTensorError::UnsupportedExecutionContext`](crate::IdxTensorError::UnsupportedExecutionContext)
644/// as its source.
645pub fn factorize_in(
646    t: &IdxTensor,
647    left_inds: &[DynIndex],
648    options: &FactorizeOptions,
649    context: &ExecutionContext,
650) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
651    options.validate()?;
652    if options.alg == FactorizeAlg::RSVD {
653        use rand::SeedableRng;
654        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(options.rsvd_seed);
655        return crate::randomized::factorize(
656            t,
657            left_inds,
658            options,
659            &mut rng,
660            &mut crate::randomized::Route::Eager(Some(context)),
661        );
662    }
663
664    t.validate_context(context)
665        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
666
667    if t.is_diag() {
668        return Err(FactorizeError::UnsupportedStorage(
669            "Diagonal storage not supported for factorize",
670        ));
671    }
672
673    if !(t.is_f64() || t.is_complex()) {
674        return Err(FactorizeError::UnsupportedStorage(
675            "factorize currently supports only f64 and Complex64 tensors",
676        ));
677    }
678
679    match options.alg {
680        FactorizeAlg::SVD => factorize_svd_with_options_in(t, left_inds, options, context),
681        FactorizeAlg::QR => factorize_qr_with_options_in(t, left_inds, options, context),
682        FactorizeAlg::RSVD => Err(FactorizeError::InvalidOptions(
683            "RSVD needs a fixed rank and caller RNG; use factorize_with_rng",
684        )),
685        FactorizeAlg::LU | FactorizeAlg::CI => Err(FactorizeError::UnsupportedStorage(
686            "LU and CI factorization have no context-scoped path; use factorize() on host inputs",
687        )),
688    }
689}
690
691/// Full-rank factorization in a caller-owned execution context.
692///
693/// Context-scoped counterpart of [`factorize_full_rank`] with the same
694/// algorithm coverage: QR and SVD execute in `context`; LU and CI return a
695/// typed error.
696///
697/// # Errors
698/// Returns `FactorizeError` when the tensor does not belong to `context`,
699/// when the storage or algorithm is unsupported, or when the factorization
700/// fails. When this build cannot execute in `context`, the rejection carries
701/// [`IdxTensorError::UnsupportedExecutionContext`](crate::IdxTensorError::UnsupportedExecutionContext)
702/// as its source.
703pub fn factorize_full_rank_in(
704    t: &IdxTensor,
705    left_inds: &[DynIndex],
706    alg: FactorizeAlg,
707    canonical: Canonical,
708    context: &ExecutionContext,
709) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
710    t.validate_context(context)
711        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
712
713    if t.is_diag() {
714        return Err(FactorizeError::UnsupportedStorage(
715            "Diagonal storage not supported for factorize",
716        ));
717    }
718
719    if !(t.is_f64() || t.is_complex()) {
720        return Err(FactorizeError::UnsupportedStorage(
721            "factorize currently supports only f64 and Complex64 tensors",
722        ));
723    }
724
725    match alg {
726        FactorizeAlg::SVD => {
727            factorize_svd_with_options_in_full_rank(t, left_inds, canonical, context)
728        }
729        FactorizeAlg::QR => factorize_qr_full_rank_in(t, left_inds, canonical, context),
730        FactorizeAlg::RSVD => Err(FactorizeError::InvalidOptions("RSVD needs a fixed rank and caller RNG; use factorize_with_rng")),
731        FactorizeAlg::LU | FactorizeAlg::CI => Err(FactorizeError::UnsupportedStorage(
732            "LU and CI factorization have no context-scoped path; use factorize_full_rank() on host inputs",
733        )),
734    }
735}
736
737fn factorize_svd_with_options_in(
738    t: &IdxTensor,
739    left_inds: &[DynIndex],
740    options: &FactorizeOptions,
741    context: &ExecutionContext,
742) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
743    let mut svd_options = SvdOptions::new();
744    if let Some(policy) = options.svd_policy {
745        svd_options = svd_options.with_policy(policy);
746    }
747    if let Some(max_bond_dim) = options.max_bond_dim {
748        svd_options = svd_options.with_max_bond_dim(max_bond_dim);
749    }
750
751    factorize_svd_with_eager_options_in(t, left_inds, options.canonical, &svd_options, context)
752}
753
754fn factorize_svd_with_options_in_full_rank(
755    t: &IdxTensor,
756    left_inds: &[DynIndex],
757    canonical: Canonical,
758    context: &ExecutionContext,
759) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
760    let svd_options = SvdOptions::full_rank();
761    factorize_svd_with_eager_options_in(t, left_inds, canonical, &svd_options, context)
762}
763
764fn factorize_svd_with_eager_options_in(
765    t: &IdxTensor,
766    left_inds: &[DynIndex],
767    canonical: Canonical,
768    svd_options: &SvdOptions,
769    context: &ExecutionContext,
770) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
771    let result = svd_for_factorize_in(t, left_inds, svd_options, context)
772        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
773    let mut contract =
774        |lhs: &IdxTensor, rhs: &IdxTensor| context_svd_factor_contraction(lhs, rhs, context);
775    assemble_svd_factors(result, canonical, &mut contract)
776}
777
778/// Contract two SVD factors through the caller-owned context's engine.
779///
780/// The context-scoped factorization assembles `S * V^H` (or `U * S`) after the
781/// decomposition returns, so the assembly must run on the same context engine
782/// instead of the process-global default one. `S` stays a compact diagonal, so
783/// the contraction is the structured diagonal scaling of the other factor, run
784/// as one payload einsum on `context`'s engine. The result keeps the factors'
785/// own eager runtime; only the executing engine is selected by `context`.
786fn context_svd_factor_contraction(
787    lhs: &IdxTensor,
788    rhs: &IdxTensor,
789    context: &ExecutionContext,
790) -> Result<IdxTensor, FactorizeError> {
791    lhs.try_contract_pairwise_default_with_options_in(
792        rhs,
793        crate::PairwiseContractionOptions::new(),
794        context,
795    )
796    .map_err(FactorizeError::ComputationError)
797}
798
799fn factorize_qr_with_options_in(
800    t: &IdxTensor,
801    left_inds: &[DynIndex],
802    options: &FactorizeOptions,
803    context: &ExecutionContext,
804) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
805    if options.canonical == Canonical::Right {
806        return Err(FactorizeError::UnsupportedCanonical(
807            "QR only supports Canonical::Left (would need LQ for right)",
808        ));
809    }
810
811    let qr_options = if let Some(rtol) = options.qr_rtol {
812        QrOptions::new().with_rtol(rtol)
813    } else {
814        QrOptions::new()
815    };
816
817    factorize_qr_with_eager_options_in(t, left_inds, &qr_options, context)
818}
819
820fn factorize_qr_full_rank_in(
821    t: &IdxTensor,
822    left_inds: &[DynIndex],
823    canonical: Canonical,
824    context: &ExecutionContext,
825) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
826    if canonical == Canonical::Right {
827        return Err(FactorizeError::UnsupportedCanonical(
828            "QR only supports Canonical::Left (would need LQ for right)",
829        ));
830    }
831
832    factorize_qr_with_eager_options_in(t, left_inds, &QrOptions::full_rank(), context)
833}
834
835fn factorize_qr_with_eager_options_in(
836    t: &IdxTensor,
837    left_inds: &[DynIndex],
838    qr_options: &QrOptions,
839    context: &ExecutionContext,
840) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
841    let (q, r) = qr_with_in::<f64>(t, left_inds, qr_options, context)
842        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
843
844    let bond_index = q
845        .indices
846        .last()
847        .cloned()
848        .ok_or_else(|| anyhow::anyhow!("QR factorization returned a rank-0 Q tensor"))?;
849    let q_dims = q.dims();
850    let rank = *q_dims
851        .last()
852        .ok_or_else(|| anyhow::anyhow!("QR factorization returned Q with no dimensions"))?;
853
854    Ok(FactorizeResult::new(q, r, bond_index, None, rank))
855}
856
857/// The eager/global contraction the SVD factor assembly uses.
858fn global_svd_factor_contraction(
859    lhs: &IdxTensor,
860    rhs: &IdxTensor,
861) -> Result<IdxTensor, FactorizeError> {
862    contract_pair(lhs, rhs)
863        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))
864}
865
866/// Factorize a tensor on a caller-held explicit session.
867///
868/// This is the runtime-free counterpart of [`factorize`] for the concrete (non-AD) frontend: the
869/// index bookkeeping, the truncation/retention policies and the factor assembly are the same code
870/// paths as the eager route, while every decomposition runs on `session` and the factors are
871/// published as plain host-storage [`IdxTensor`]s. Nothing here enters another session or the eager
872/// runtime, so a scheduler-owned lane can call it directly.
873///
874/// QR and SVD are served. LU and CI have no session route (the same restriction as
875/// [`factorize_in`]).
876///
877/// # Errors
878///
879/// Returns [`FactorizeError`] for invalid options, an unsupported storage representation or dtype
880/// (diagonal/structured payloads and tracked or device-resident values are refused), a `Right`
881/// canonical QR request, an LU/CI request, or a rejection by the supplied session.
882///
883/// # Examples
884///
885/// ```
886/// use tensor4all_core::{
887///     factorize_on_session, DynIndex, FactorizeOptions, IdxTensor, TensorContractionLike,
888/// };
889/// use tensor4all_tensorbackend::{explicit::Session, CpuBackend};
890///
891/// let i = DynIndex::new_dyn(2);
892/// let j = DynIndex::new_dyn(2);
893/// let tensor = IdxTensor::from_dense(vec![i.clone(), j.clone()], vec![1.0_f64, 0.0, 0.0, 1.0])?;
894///
895/// let mut backend = CpuBackend::with_threads(1)?;
896/// let mut session = Session::new(backend.engine_mut());
897/// let result =
898///     factorize_on_session(&mut session, &tensor, std::slice::from_ref(&i), &FactorizeOptions::svd())?;
899/// assert_eq!(result.rank, 2);
900/// let reconstructed = result.left.contract_pair(&result.right)?;
901/// assert!(tensor.sub(&reconstructed)?.maxabs()? < 1.0e-12);
902/// # Ok::<(), Box<dyn std::error::Error>>(())
903/// ```
904pub fn factorize_on_session(
905    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
906    t: &IdxTensor,
907    left_inds: &[DynIndex],
908    options: &FactorizeOptions,
909) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
910    options.validate()?;
911    if options.alg == FactorizeAlg::RSVD {
912        use rand::SeedableRng;
913        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(options.rsvd_seed);
914        return crate::randomized::factorize(
915            t,
916            left_inds,
917            options,
918            &mut rng,
919            &mut crate::randomized::Route::Session(session),
920        );
921    }
922
923    if t.is_diag() {
924        return Err(FactorizeError::UnsupportedStorage(
925            "Diagonal storage not supported for factorize",
926        ));
927    }
928    if t.tracks_grad() {
929        return Err(FactorizeError::UnsupportedStorage(
930            "a tracked value cannot enter the plain explicit-session route; detach it explicitly before the region",
931        ));
932    }
933    match options.alg {
934        FactorizeAlg::SVD => factorize_svd_with_options_on_session(session, t, left_inds, options),
935        FactorizeAlg::QR => {
936            if options.canonical == Canonical::Right {
937                return Err(FactorizeError::UnsupportedCanonical(
938                    "QR only supports Canonical::Left (would need LQ for right)",
939                ));
940            }
941            let qr_options = if let Some(rtol) = options.qr_rtol {
942                QrOptions::new().with_rtol(rtol)
943            } else {
944                QrOptions::new()
945            };
946            let (q, r) = qr_factors_on_session(session, t, left_inds, &qr_options)
947                .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
948            let bond_index = q.indices.last().cloned().ok_or_else(|| {
949                FactorizeError::ComputationError(anyhow::anyhow!(
950                    "QR factorization returned a rank-0 Q tensor"
951                ))
952            })?;
953            let rank = *q.dims().last().ok_or_else(|| {
954                FactorizeError::ComputationError(anyhow::anyhow!(
955                    "QR factorization returned Q with no dimensions"
956                ))
957            })?;
958            Ok(FactorizeResult::new(q, r, bond_index, None, rank))
959        }
960        FactorizeAlg::RSVD => Err(FactorizeError::InvalidOptions(
961            "RSVD needs a fixed rank and caller RNG; use factorize_with_rng",
962        )),
963        FactorizeAlg::LU | FactorizeAlg::CI => Err(FactorizeError::UnsupportedStorage(
964            "LU and CI factorization have no explicit-session path",
965        )),
966    }
967}
968
969/// Full-rank factorization on a caller-held explicit session.
970///
971/// The runtime-free counterpart of [`factorize_full_rank`]: the split
972/// bookkeeping and factor assembly are shared with the eager route, while the
973/// decomposition runs on `session` and the factors are published as plain
974/// host-storage [`IdxTensor`]s. Nothing here enters another session or the
975/// eager runtime, so a caller that already owns a held session (TreeTN
976/// canonicalization, for example) can call it directly.
977///
978/// QR, SVD, and CI are served; CI uses the pivoted LU of
979/// [`matrix_luci_factors_from_matrix_owned_on_session`](crate::matrix_luci_factors_from_matrix_owned_on_session)
980/// and gives the same factors as [`factorize_full_rank`]. LU has no session
981/// route.
982///
983/// # Errors
984///
985/// Returns [`FactorizeError`] for a diagonal, structured or tracked operand, a
986/// `Right` canonical QR request, an LU request, or a rejection by the
987/// supplied session.
988///
989/// # Examples
990///
991/// ```
992/// use tensor4all_core::{
993///     factorize_full_rank_on_session, Canonical, DynIndex, FactorizeAlg, IdxTensor,
994///     TensorContractionLike,
995/// };
996/// use tensor4all_tensorbackend::{explicit::Session, CpuBackend};
997///
998/// let i = DynIndex::new_dyn(2);
999/// let j = DynIndex::new_dyn(2);
1000/// let tensor = IdxTensor::from_dense(vec![i.clone(), j.clone()], vec![1.0_f64, 0.0, 0.0, 1.0])?;
1001///
1002/// let mut backend = CpuBackend::with_threads(1)?;
1003/// let mut session = Session::new(backend.engine_mut());
1004/// let result = factorize_full_rank_on_session(
1005///     &mut session,
1006///     &tensor,
1007///     std::slice::from_ref(&i),
1008///     FactorizeAlg::QR,
1009///     Canonical::Left,
1010/// )?;
1011/// assert_eq!(result.rank, 2);
1012/// let reconstructed = result.left.contract_pair(&result.right)?;
1013/// assert!(tensor.sub(&reconstructed)?.maxabs()? < 1e-12);
1014/// # Ok::<(), Box<dyn std::error::Error>>(())
1015/// ```
1016pub fn factorize_full_rank_on_session(
1017    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1018    t: &IdxTensor,
1019    left_inds: &[DynIndex],
1020    alg: FactorizeAlg,
1021    canonical: Canonical,
1022) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1023    if t.is_diag() {
1024        return Err(FactorizeError::UnsupportedStorage(
1025            "Diagonal storage not supported for factorize",
1026        ));
1027    }
1028    if t.tracks_grad() {
1029        return Err(FactorizeError::UnsupportedStorage(
1030            "a tracked value cannot enter the plain explicit-session route; detach it explicitly before the region",
1031        ));
1032    }
1033    match alg {
1034        FactorizeAlg::SVD => {
1035            let options = SvdOptions::full_rank();
1036            let result = if t.is_f32() {
1037                svd_for_factorize_on_session::<f32>(session, t, left_inds, &options)
1038            } else if t.is_f64() {
1039                svd_for_factorize_on_session::<f64>(session, t, left_inds, &options)
1040            } else if t.is_c32() {
1041                svd_for_factorize_on_session::<Complex32>(session, t, left_inds, &options)
1042            } else if t.is_c64() {
1043                svd_for_factorize_on_session::<Complex64>(session, t, left_inds, &options)
1044            } else {
1045                Err(crate::svd::SvdError::ComputationError(anyhow::anyhow!(
1046                    "the explicit-session SVD route serves floating-point tensors"
1047                )))
1048            }
1049            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
1050            let mut contract = |lhs: &IdxTensor, rhs: &IdxTensor| {
1051                crate::contract_pair_on_session(
1052                    session,
1053                    lhs,
1054                    rhs,
1055                    crate::PairwiseContractionOptions::new(),
1056                )
1057                .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))
1058            };
1059            assemble_svd_factors(result, canonical, &mut contract)
1060        }
1061        FactorizeAlg::QR => {
1062            if canonical == Canonical::Right {
1063                return Err(FactorizeError::UnsupportedCanonical(
1064                    "QR only supports Canonical::Left (would need LQ for right)",
1065                ));
1066            }
1067            factorize_qr_full_rank_on_session(session, t, left_inds)
1068        }
1069        FactorizeAlg::RSVD => Err(FactorizeError::InvalidOptions(
1070            "RSVD needs a fixed rank and caller RNG; use factorize_with_rng",
1071        )),
1072        FactorizeAlg::CI => {
1073            if t.is_f32() {
1074                factorize_ci_full_rank_on_session::<f32>(session, t, left_inds, canonical)
1075            } else if t.is_f64() {
1076                factorize_ci_full_rank_on_session::<f64>(session, t, left_inds, canonical)
1077            } else if t.is_c32() {
1078                factorize_ci_full_rank_on_session::<Complex32>(session, t, left_inds, canonical)
1079            } else if t.is_c64() {
1080                factorize_ci_full_rank_on_session::<Complex64>(session, t, left_inds, canonical)
1081            } else {
1082                Err(FactorizeError::UnsupportedStorage(
1083                    "the explicit-session CI route serves floating-point tensors",
1084                ))
1085            }
1086        }
1087        FactorizeAlg::LU => Err(FactorizeError::UnsupportedStorage(
1088            "LU factorization has no explicit-session path",
1089        )),
1090    }
1091}
1092
1093/// Full-rank CI factors on the caller's session.
1094///
1095/// The explicit-session counterpart of `factorize_ci_full_rank`: the operand's
1096/// host payload is unfolded without entering a runtime, the pivoted LU runs on
1097/// `session`, and both factors are published as compact host storage.
1098fn factorize_ci_full_rank_on_session<T>(
1099    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1100    t: &IdxTensor,
1101    left_inds: &[DynIndex],
1102    canonical: Canonical,
1103) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1104where
1105    T: TensorElement
1106        + tensor4all_tensorbackend::StorageScalar
1107        + MatrixScalar
1108        + crate::MatrixLuciScalar
1109        + 'static,
1110{
1111    let (left_indices, right_indices, order) =
1112        crate::defaults::idx_tensor::unfold_index_sets(t, left_inds)
1113            .map_err(|error| anyhow::anyhow!("Failed to unfold tensor: {error}"))?;
1114    // Read and reorder the operand's own host payload: entering the eager
1115    // runtime for a transpose would be a second session entry on this thread.
1116    let (dims, data) = t
1117        .host_dense_permuted::<T>(&order)
1118        .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
1119    let left_len = left_indices.len();
1120    let m = crate::defaults::idx_tensor::checked_product(&dims[..left_len])
1121        .map_err(FactorizeError::ComputationError)?;
1122    let n = crate::defaults::idx_tensor::checked_product(&dims[left_len..])
1123        .map_err(FactorizeError::ComputationError)?;
1124    let lu_options = RrLUOptions {
1125        max_bond_dim: usize::MAX,
1126        rel_tol: 0.0,
1127        abs_tol: 0.0,
1128        left_orthogonal: canonical == Canonical::Left,
1129    };
1130    let factors = crate::matrix_luci_factors_from_matrix_owned_on_session(
1131        matrix_from_col_major_values(data, m, n, "host")?,
1132        Some(lu_options),
1133        session,
1134    )?;
1135    let rank = factors.rank;
1136    let (left, right, bond_index) = matrix_luci_factors_to_idx_tensors(
1137        factors,
1138        &left_indices,
1139        &right_indices,
1140        canonical,
1141        IdxTensor::from_dense_compact,
1142    )?;
1143    Ok(FactorizeResult::new(
1144        left,
1145        right,
1146        bond_index,
1147        None,
1148        rank.max(1),
1149    ))
1150}
1151
1152fn factorize_qr_full_rank_on_session(
1153    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1154    t: &IdxTensor,
1155    left_inds: &[DynIndex],
1156) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1157    let options = QrOptions::full_rank();
1158    let (q, r) = if t.is_f32() {
1159        crate::qr::qr_with_on_session::<f32>(session, t, left_inds, &options)
1160    } else if t.is_f64() {
1161        crate::qr::qr_with_on_session::<f64>(session, t, left_inds, &options)
1162    } else if t.is_c32() {
1163        crate::qr::qr_with_on_session::<Complex32>(session, t, left_inds, &options)
1164    } else if t.is_c64() {
1165        crate::qr::qr_with_on_session::<Complex64>(session, t, left_inds, &options)
1166    } else {
1167        Err(crate::qr::QrError::ComputationError(anyhow::anyhow!(
1168            "the explicit-session QR route serves floating-point tensors"
1169        )))
1170    }
1171    .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
1172
1173    let bond_index = q
1174        .indices
1175        .last()
1176        .cloned()
1177        .ok_or_else(|| anyhow::anyhow!("QR factorization returned a rank-0 Q tensor"))?;
1178    let rank = *q
1179        .dims()
1180        .last()
1181        .ok_or_else(|| anyhow::anyhow!("QR factorization returned Q with no dimensions"))?;
1182    Ok(FactorizeResult::new(q, r, bond_index, None, rank))
1183}
1184
1185/// Thin QR factors on the caller's session, in the tensor's own scalar type.
1186///
1187/// The session route keeps the operand dtype instead of narrowing the
1188/// factorization to `f64`, so `f32`/`c32` operands factorize without a widening
1189/// round trip.
1190fn qr_factors_on_session(
1191    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1192    t: &IdxTensor,
1193    left_inds: &[DynIndex],
1194    options: &QrOptions,
1195) -> Result<(IdxTensor, IdxTensor), crate::qr::QrError> {
1196    if t.is_f32() {
1197        crate::qr::qr_with_on_session::<f32>(session, t, left_inds, options)
1198    } else if t.is_f64() {
1199        crate::qr::qr_with_on_session::<f64>(session, t, left_inds, options)
1200    } else if t.is_c32() {
1201        crate::qr::qr_with_on_session::<Complex32>(session, t, left_inds, options)
1202    } else if t.is_c64() {
1203        crate::qr::qr_with_on_session::<Complex64>(session, t, left_inds, options)
1204    } else {
1205        Err(crate::qr::QrError::ComputationError(anyhow::anyhow!(
1206            "the explicit-session QR route serves floating-point tensors"
1207        )))
1208    }
1209}
1210
1211fn factorize_svd_with_options_on_session(
1212    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1213    t: &IdxTensor,
1214    left_inds: &[DynIndex],
1215    options: &FactorizeOptions,
1216) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1217    let mut svd_options = SvdOptions::new();
1218    if let Some(policy) = options.svd_policy {
1219        svd_options = svd_options.with_policy(policy);
1220    }
1221    if let Some(max_bond_dim) = options.max_bond_dim {
1222        svd_options = svd_options.with_max_bond_dim(max_bond_dim);
1223    }
1224    let result = if t.is_f32() {
1225        svd_for_factorize_on_session::<f32>(session, t, left_inds, &svd_options)
1226    } else if t.is_f64() {
1227        svd_for_factorize_on_session::<f64>(session, t, left_inds, &svd_options)
1228    } else if t.is_c32() {
1229        svd_for_factorize_on_session::<Complex32>(session, t, left_inds, &svd_options)
1230    } else if t.is_c64() {
1231        svd_for_factorize_on_session::<Complex64>(session, t, left_inds, &svd_options)
1232    } else {
1233        Err(crate::svd::SvdError::ComputationError(anyhow::anyhow!(
1234            "the explicit-session SVD route serves floating-point tensors"
1235        )))
1236    }
1237    .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))?;
1238    let mut contract = |lhs: &IdxTensor, rhs: &IdxTensor| -> Result<IdxTensor, FactorizeError> {
1239        crate::contract_pair_on_session(session, lhs, rhs, crate::PairwiseContractionOptions::new())
1240            .map_err(|error| FactorizeError::ComputationError(anyhow::Error::new(error)))
1241    };
1242    assemble_svd_factors(result, options.canonical, &mut contract)
1243}
1244
1245fn factorize_impl<T>(
1246    t: &IdxTensor,
1247    left_inds: &[DynIndex],
1248    options: &FactorizeOptions,
1249) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1250where
1251    T: TensorElement
1252        + ComplexFloat
1253        + Default
1254        + From<<T as ComplexFloat>::Real>
1255        + MatrixScalar
1256        + crate::MatrixLuciScalar
1257        + 'static,
1258    <T as ComplexFloat>::Real: Into<f64> + 'static,
1259{
1260    match options.alg {
1261        FactorizeAlg::RSVD => Err(FactorizeError::InvalidOptions(
1262            "RSVD must use the randomized dispatch",
1263        )),
1264        FactorizeAlg::SVD => factorize_svd(t, left_inds, options),
1265        FactorizeAlg::QR => factorize_qr(t, left_inds, options),
1266        FactorizeAlg::LU => factorize_lu::<T>(t, left_inds, options),
1267        FactorizeAlg::CI => factorize_ci::<T>(t, left_inds, options),
1268    }
1269}
1270
1271fn factorize_impl_full_rank<T>(
1272    t: &IdxTensor,
1273    left_inds: &[DynIndex],
1274    alg: FactorizeAlg,
1275    canonical: Canonical,
1276) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1277where
1278    T: TensorElement
1279        + ComplexFloat
1280        + Default
1281        + From<<T as ComplexFloat>::Real>
1282        + MatrixScalar
1283        + crate::MatrixLuciScalar
1284        + 'static,
1285    <T as ComplexFloat>::Real: Into<f64> + 'static,
1286{
1287    match alg {
1288        FactorizeAlg::RSVD => Err(FactorizeError::InvalidOptions(
1289            "RSVD is a fixed-rank approximation; use SVD for full-rank factorization",
1290        )),
1291        FactorizeAlg::SVD => factorize_svd_full_rank(t, left_inds, canonical),
1292        FactorizeAlg::QR => factorize_qr_full_rank(t, left_inds, canonical),
1293        FactorizeAlg::LU => factorize_lu_full_rank::<T>(t, left_inds, canonical),
1294        FactorizeAlg::CI => factorize_ci_full_rank::<T>(t, left_inds, canonical),
1295    }
1296}
1297
1298/// SVD factorization implementation.
1299fn factorize_svd(
1300    t: &IdxTensor,
1301    left_inds: &[DynIndex],
1302    options: &FactorizeOptions,
1303) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1304    let mut svd_options = SvdOptions::new();
1305    if let Some(policy) = options.svd_policy {
1306        svd_options = svd_options.with_policy(policy);
1307    }
1308    if let Some(max_bond_dim) = options.max_bond_dim {
1309        svd_options = svd_options.with_max_bond_dim(max_bond_dim);
1310    }
1311
1312    factorize_svd_with_options(t, left_inds, options.canonical, &svd_options)
1313}
1314
1315fn factorize_svd_full_rank(
1316    t: &IdxTensor,
1317    left_inds: &[DynIndex],
1318    canonical: Canonical,
1319) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1320    let svd_options = SvdOptions::full_rank();
1321    factorize_svd_with_options(t, left_inds, canonical, &svd_options)
1322}
1323
1324fn factorize_svd_with_options(
1325    t: &IdxTensor,
1326    left_inds: &[DynIndex],
1327    canonical: Canonical,
1328    svd_options: &SvdOptions,
1329) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1330    let result = svd_for_factorize(t, left_inds, svd_options)?;
1331    assemble_svd_factors(result, canonical, &mut global_svd_factor_contraction)
1332}
1333
1334/// Absorb the SVD factors into left/right canonical form.
1335///
1336/// Shared by the host and context-scoped SVD factorization paths: contracts
1337/// `S` into one side and renames the leftover `sim` leg back to `bond`.
1338pub(crate) fn assemble_svd_factors(
1339    result: SvdFactorizeResult,
1340    canonical: Canonical,
1341    contract: &mut dyn FnMut(&IdxTensor, &IdxTensor) -> Result<IdxTensor, FactorizeError>,
1342) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1343    let u = result.u;
1344    let s = result.s;
1345    let vh = result.vh;
1346    let bond_index = result.bond_index;
1347    let singular_values = result.singular_values;
1348    let rank = result.rank;
1349    // Internal SVD plumbing: svd_for_factorize keeps the legacy convention
1350    // (vh shares the original `bond` leg), so S's leftover `sim` leg is
1351    // renamed back to `bond` after each contraction. The public svd_with API
1352    // instead returns V with the `sim` leg and needs no compensation.
1353    let sim_bond_index = s.indices[1].clone();
1354
1355    match canonical {
1356        Canonical::Left => {
1357            // L = U (orthogonal), R = S * V^H
1358            let right_contracted = contract(&s, &vh)?;
1359            let right = right_contracted
1360                .replaceind(&sim_bond_index, &bond_index)
1361                .map_err(|e| FactorizeError::ComputationError(anyhow::Error::new(e)))?;
1362            Ok(FactorizeResult::new(
1363                u,
1364                right,
1365                bond_index,
1366                Some(singular_values),
1367                rank,
1368            ))
1369        }
1370        Canonical::Right => {
1371            // L = U * S, R = V^H
1372            let left_contracted = contract(&u, &s)?;
1373            let left = left_contracted
1374                .replaceind(&sim_bond_index, &bond_index)
1375                .map_err(|e| FactorizeError::ComputationError(anyhow::Error::new(e)))?;
1376            Ok(FactorizeResult::new(
1377                left,
1378                vh,
1379                bond_index,
1380                Some(singular_values),
1381                rank,
1382            ))
1383        }
1384    }
1385}
1386
1387/// QR factorization implementation.
1388fn factorize_qr(
1389    t: &IdxTensor,
1390    left_inds: &[DynIndex],
1391    options: &FactorizeOptions,
1392) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1393    if options.canonical == Canonical::Right {
1394        return Err(FactorizeError::UnsupportedCanonical(
1395            "QR only supports Canonical::Left (would need LQ for right)",
1396        ));
1397    }
1398
1399    let qr_options = if let Some(rtol) = options.qr_rtol {
1400        QrOptions::new().with_rtol(rtol)
1401    } else {
1402        QrOptions::new()
1403    };
1404
1405    factorize_qr_with_options(t, left_inds, &qr_options)
1406}
1407
1408fn factorize_qr_full_rank(
1409    t: &IdxTensor,
1410    left_inds: &[DynIndex],
1411    canonical: Canonical,
1412) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1413    if canonical == Canonical::Right {
1414        return Err(FactorizeError::UnsupportedCanonical(
1415            "QR only supports Canonical::Left (would need LQ for right)",
1416        ));
1417    }
1418
1419    factorize_qr_with_options(t, left_inds, &QrOptions::full_rank())
1420}
1421
1422fn factorize_qr_with_options(
1423    t: &IdxTensor,
1424    left_inds: &[DynIndex],
1425    qr_options: &QrOptions,
1426) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
1427    let (q, r) = qr_with::<f64>(t, left_inds, qr_options)?;
1428
1429    // Get bond index from Q tensor (last index)
1430    let bond_index = q
1431        .indices
1432        .last()
1433        .cloned()
1434        .ok_or_else(|| anyhow::anyhow!("QR factorization returned a rank-0 Q tensor"))?;
1435    // Rank is the last dimension of Q
1436    let q_dims = q.dims();
1437    let rank = *q_dims
1438        .last()
1439        .ok_or_else(|| anyhow::anyhow!("QR factorization returned Q with no dimensions"))?;
1440
1441    Ok(FactorizeResult::new(q, r, bond_index, None, rank))
1442}
1443
1444/// LU factorization implementation.
1445fn factorize_lu<T>(
1446    t: &IdxTensor,
1447    left_inds: &[DynIndex],
1448    options: &FactorizeOptions,
1449) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1450where
1451    T: TensorElement
1452        + ComplexFloat
1453        + Default
1454        + From<<T as ComplexFloat>::Real>
1455        + MatrixScalar
1456        + crate::MatrixLuciScalar
1457        + 'static,
1458    <T as ComplexFloat>::Real: Into<f64> + 'static,
1459{
1460    factorize_lu_with_options::<T>(
1461        t,
1462        left_inds,
1463        options.canonical,
1464        options.max_bond_dim.unwrap_or(usize::MAX),
1465        1e-14,
1466    )
1467}
1468
1469fn factorize_lu_full_rank<T>(
1470    t: &IdxTensor,
1471    left_inds: &[DynIndex],
1472    canonical: Canonical,
1473) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1474where
1475    T: TensorElement
1476        + ComplexFloat
1477        + Default
1478        + From<<T as ComplexFloat>::Real>
1479        + MatrixScalar
1480        + crate::MatrixLuciScalar
1481        + 'static,
1482    <T as ComplexFloat>::Real: Into<f64> + 'static,
1483{
1484    factorize_lu_with_options::<T>(t, left_inds, canonical, usize::MAX, 0.0)
1485}
1486
1487fn factorize_lu_with_options<T>(
1488    t: &IdxTensor,
1489    left_inds: &[DynIndex],
1490    canonical: Canonical,
1491    max_bond_dim: usize,
1492    rel_tol: f64,
1493) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1494where
1495    T: TensorElement
1496        + ComplexFloat
1497        + Default
1498        + From<<T as ComplexFloat>::Real>
1499        + MatrixScalar
1500        + crate::MatrixLuciScalar
1501        + 'static,
1502    <T as ComplexFloat>::Real: Into<f64> + 'static,
1503{
1504    // Unfold tensor into matrix
1505    let (a_tensor, _, m, n, left_indices, right_indices) = unfold_split(t, left_inds)
1506        .map_err(|e| anyhow::anyhow!("Failed to unfold tensor: {}", e))?;
1507
1508    // Convert to Matrix type for rrLU without rebuilding a zero-filled matrix.
1509    let a_matrix = native_tensor_to_matrix::<T>(&a_tensor, m, n)?;
1510
1511    // Set up LU options
1512    let left_orthogonal = canonical == Canonical::Left;
1513    let lu_options = RrLUOptions {
1514        max_bond_dim,
1515        rel_tol,
1516        abs_tol: 0.0,
1517        left_orthogonal,
1518    };
1519
1520    // Perform LU decomposition
1521    let mut a_matrix = a_matrix;
1522    let lu = rrlu_mut(&mut a_matrix, Some(lu_options))?;
1523    let rank = lu.npivots();
1524
1525    // Tensor factorization keeps a valid rank-one zero representation even
1526    // when low-level LU reports a rank-zero selection.
1527    let (l_matrix, u_matrix, bond_dim) = if rank == 0 {
1528        let (left, right) = rank_one_zero_factors(m, n, canonical);
1529        (left, right, 1)
1530    } else {
1531        (lu.left(true), lu.right(true), rank)
1532    };
1533
1534    let bond_index = DynIndex::new_bond(bond_dim)
1535        .map_err(|e| anyhow::anyhow!("Failed to create bond index: {:?}", e))?;
1536
1537    // Convert L matrix back to tensor
1538    let l_vec = l_matrix.into_col_major_vec();
1539    let mut l_indices = left_indices.clone();
1540    l_indices.push(bond_index.clone());
1541    let left = IdxTensor::from_dense(l_indices, l_vec)
1542        .map_err(|e| FactorizeError::ComputationError(anyhow::Error::new(e)))?;
1543
1544    // Convert U matrix back to tensor
1545    let u_vec = u_matrix.into_col_major_vec();
1546    let mut r_indices = vec![bond_index.clone()];
1547    r_indices.extend_from_slice(&right_indices);
1548    let right = IdxTensor::from_dense(r_indices, u_vec)
1549        .map_err(|e| FactorizeError::ComputationError(anyhow::Error::new(e)))?;
1550
1551    Ok(FactorizeResult::new(
1552        left, right, bond_index, None, bond_dim,
1553    ))
1554}
1555
1556/// CI (Cross Interpolation) factorization implementation.
1557fn factorize_ci<T>(
1558    t: &IdxTensor,
1559    left_inds: &[DynIndex],
1560    options: &FactorizeOptions,
1561) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1562where
1563    T: TensorElement
1564        + ComplexFloat
1565        + Default
1566        + From<<T as ComplexFloat>::Real>
1567        + MatrixScalar
1568        + crate::MatrixLuciScalar
1569        + 'static,
1570    <T as ComplexFloat>::Real: Into<f64> + 'static,
1571{
1572    factorize_ci_with_options::<T>(
1573        t,
1574        left_inds,
1575        options.canonical,
1576        options.max_bond_dim.unwrap_or(usize::MAX),
1577        1e-14,
1578    )
1579}
1580
1581fn factorize_ci_full_rank<T>(
1582    t: &IdxTensor,
1583    left_inds: &[DynIndex],
1584    canonical: Canonical,
1585) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1586where
1587    T: TensorElement
1588        + ComplexFloat
1589        + Default
1590        + From<<T as ComplexFloat>::Real>
1591        + MatrixScalar
1592        + crate::MatrixLuciScalar
1593        + 'static,
1594    <T as ComplexFloat>::Real: Into<f64> + 'static,
1595{
1596    factorize_ci_with_options::<T>(t, left_inds, canonical, usize::MAX, 0.0)
1597}
1598
1599// CI-factorization default seam.
1600//
1601// The default LU/CI factorization implementations in this module consume the
1602// TCI substrate (rrlu, MatrixLUCI, MatrixLuciScalar) that was absorbed from
1603// tensor4all-tcicore when that crate was dissolved into tensor4all-core
1604// (#639); the substrate now lives in this crate and the inverted
1605// core -> tcicore dependency no longer exists. IdxTensor data is unfolded
1606// into a column-major eager matrix at this boundary, and fixed-pivot CI
1607// factors are rebuilt from
1608// that primal value.
1609fn factorize_ci_with_options<T>(
1610    t: &IdxTensor,
1611    left_inds: &[DynIndex],
1612    canonical: Canonical,
1613    max_bond_dim: usize,
1614    rel_tol: f64,
1615) -> Result<FactorizeResult<IdxTensor>, FactorizeError>
1616where
1617    T: TensorElement
1618        + ComplexFloat
1619        + Default
1620        + From<<T as ComplexFloat>::Real>
1621        + MatrixScalar
1622        + crate::MatrixLuciScalar
1623        + 'static,
1624    <T as ComplexFloat>::Real: Into<f64> + 'static,
1625{
1626    // Unfold tensor into an eager matrix. Pivot selection is primal-only, but
1627    // fixed-pivot CI factors are rebuilt from this eager value below.
1628    let (matrix_inner, _, m, n, left_indices, right_indices) = unfold_split_inner(t, left_inds)
1629        .map_err(|e| anyhow::anyhow!("Failed to unfold tensor: {}", e))?;
1630
1631    // Convert to Matrix type for MatrixLUCI.
1632    let a_matrix = eager_tensor_to_matrix::<T>(&matrix_inner, m, n)?;
1633
1634    // Set up LU options for CI
1635    let left_orthogonal = canonical == Canonical::Left;
1636    let lu_options = RrLUOptions {
1637        max_bond_dim,
1638        rel_tol,
1639        abs_tol: 0.0,
1640        left_orthogonal,
1641    };
1642
1643    // Perform CI decomposition and reuse its backend factors directly. The
1644    // previous path gathered pivot blocks into eager tensors and solved them
1645    // element-wise at this boundary, duplicating work already done by the
1646    // backend factorization.
1647    let factors = matrix_luci_factors_from_matrix_owned(a_matrix, Some(lu_options))?;
1648    let rank = factors.rank;
1649    let (left, right, bond_index) = matrix_luci_factors_to_idx_tensors(
1650        factors,
1651        &left_indices,
1652        &right_indices,
1653        canonical,
1654        IdxTensor::from_dense,
1655    )?;
1656
1657    Ok(FactorizeResult::new(
1658        left,
1659        right,
1660        bond_index,
1661        None,
1662        rank.max(1),
1663    ))
1664}
1665
1666// The selected side still has unit diagonal; only the opposite side carries
1667// the zero value. Both factors keep a valid dimension-one bond.
1668fn rank_one_zero_factors<T: MatrixScalar>(
1669    m: usize,
1670    n: usize,
1671    canonical: Canonical,
1672) -> (Matrix<T>, Matrix<T>) {
1673    let mut left = Matrix::zeros(m, 1);
1674    let mut right = Matrix::zeros(1, n);
1675    match canonical {
1676        Canonical::Left => left[[0, 0]] = T::one(),
1677        Canonical::Right => right[[0, 0]] = T::one(),
1678    }
1679    (left, right)
1680}
1681
1682/// Build the two CI factor tensors with `build`: `IdxTensor::from_dense` on
1683/// the compatibility route, `IdxTensor::from_dense_compact` on an explicit
1684/// session, which must not adopt the factors into the process-global runtime.
1685fn matrix_luci_factors_to_idx_tensors<T>(
1686    factors: MatrixLuciFactors<T>,
1687    left_indices: &[DynIndex],
1688    right_indices: &[DynIndex],
1689    canonical: Canonical,
1690    build: fn(Vec<DynIndex>, Vec<T>) -> std::result::Result<IdxTensor, IdxTensorError>,
1691) -> Result<(IdxTensor, IdxTensor, DynIndex), FactorizeError>
1692where
1693    T: TensorElement + MatrixScalar,
1694{
1695    let bond_dim = factors.rank.max(1);
1696    let (left_matrix, right_matrix) = if factors.rank == 0 {
1697        rank_one_zero_factors(factors.left.nrows(), factors.right.ncols(), canonical)
1698    } else {
1699        (factors.left, factors.right)
1700    };
1701    let bond_index = DynIndex::new_bond(bond_dim)
1702        .map_err(|e| anyhow::anyhow!("Failed to create bond index: {:?}", e))?;
1703
1704    let mut l_indices = left_indices.to_vec();
1705    l_indices.push(bond_index.clone());
1706    let left = build(l_indices, left_matrix.into_col_major_vec())
1707        .map_err(|e| FactorizeError::ComputationError(anyhow::Error::new(e)))?;
1708
1709    let mut r_indices = vec![bond_index.clone()];
1710    r_indices.extend_from_slice(right_indices);
1711    let right = build(r_indices, right_matrix.into_col_major_vec())
1712        .map_err(|e| FactorizeError::ComputationError(anyhow::Error::new(e)))?;
1713
1714    Ok((left, right, bond_index))
1715}
1716
1717/// Convert a native rank-2 tensor into a backend [`Matrix`].
1718fn native_tensor_to_matrix<T>(
1719    tensor: &tenferro::Tensor,
1720    m: usize,
1721    n: usize,
1722) -> Result<Matrix<T>, FactorizeError>
1723where
1724    T: TensorElement + MatrixScalar + Copy,
1725{
1726    let data = T::dense_values_from_native_col_major(tensor).map_err(|e| {
1727        FactorizeError::ComputationError(anyhow::anyhow!(
1728            "failed to extract dense matrix entries from native tensor: {e}"
1729        ))
1730    })?;
1731    matrix_from_col_major_values(data, m, n, "native")
1732}
1733
1734fn eager_tensor_to_matrix<T>(
1735    tensor: &EagerTensor,
1736    m: usize,
1737    n: usize,
1738) -> Result<Matrix<T>, FactorizeError>
1739where
1740    T: TensorElement + MatrixScalar + Copy,
1741{
1742    let values = tensor
1743        .value()
1744        .map_err(|source| FactorizeError::ComputationError(anyhow::Error::new(source)))?
1745        .as_slice::<T>()
1746        .map_err(|source| FactorizeError::ComputationError(anyhow::Error::new(source)))?
1747        .to_vec();
1748    matrix_from_col_major_values(values, m, n, "eager")
1749}
1750
1751fn matrix_from_col_major_values<T>(
1752    data: Vec<T>,
1753    m: usize,
1754    n: usize,
1755    source: &str,
1756) -> Result<Matrix<T>, FactorizeError>
1757where
1758    T: MatrixScalar + Copy,
1759{
1760    Matrix::try_from_col_major_vec(m, n, data).map_err(|error| {
1761        FactorizeError::ComputationError(anyhow::anyhow!(
1762            "{source} matrix conversion failed for shape ({m}, {n}): {error}"
1763        ))
1764    })
1765}
1766
1767#[cfg(test)]
1768fn checked_matrix_len(m: usize, n: usize, source: &str) -> Result<usize, FactorizeError> {
1769    m.checked_mul(n).ok_or_else(|| {
1770        FactorizeError::ComputationError(anyhow::anyhow!(
1771            "{source} matrix shape ({m}, {n}) overflows usize"
1772        ))
1773    })
1774}
1775
1776#[cfg(test)]
1777mod tests;