1use 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
59pub use crate::tensor_like::{
61 Canonical, FactorizeAlg, FactorizeError, FactorizeOptions, FactorizeResult,
62};
63
64pub 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
139pub 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
181pub 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
227pub 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
275pub(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 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
521pub 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
598pub 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
691pub 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
778fn 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
857fn 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
866pub 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
969pub 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
1093fn 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 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
1185fn 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
1298fn 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
1334pub(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 let sim_bond_index = s.indices[1].clone();
1354
1355 match canonical {
1356 Canonical::Left => {
1357 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 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
1387fn 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 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 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
1444fn 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 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 let a_matrix = native_tensor_to_matrix::<T>(&a_tensor, m, n)?;
1510
1511 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 let mut a_matrix = a_matrix;
1522 let lu = rrlu_mut(&mut a_matrix, Some(lu_options))?;
1523 let rank = lu.npivots();
1524
1525 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 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 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
1556fn 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
1599fn 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 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 let a_matrix = eager_tensor_to_matrix::<T>(&matrix_inner, m, n)?;
1633
1634 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 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
1666fn 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
1682fn 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
1717fn 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;