Skip to main content

cg

Function cg 

Source
pub fn cg<T, F>(
    apply_a: F,
    b: &T,
    x0: &T,
    options: &CgOptions,
) -> Result<CgResult<T>, KrylovError>
where T: TensorVectorSpace, F: Fn(&T) -> Result<T>,
Expand description

Solve A x = b with matrix-free conjugate gradients.

§Arguments

  • apply_a - Fixed linear operator x -> A*x, preserving the vector space. The caller must supply a Hermitian positive-definite operator; checking visited curvatures cannot certify the full matrix-free operator.
  • b - Right-hand side, in the same vector space as x0.
  • x0 - Initial guess, which may be zero. A zero-norm RHS returns the zero vector, the exact solution, after the initial residual confirms that x0 and b share a vector space.
  • options - Iteration budget and finite, nonnegative tolerances. In doubt, start with CgOptions::default for double precision.

§Returns

The approximate solution, completed step count, absolute true residual norm, and convergence flag. Iteration exhaustion returns converged = false. Working vectors are rescaled by exact powers of two before inner products to keep CG reductions in range. The true residual is recomputed before declaring convergence. If the recursive residual was optimistic, CG restarts from the true residual within the original iteration budget, following KrylovKit.

Vector and recurrence arithmetic stays in TensorVectorSpace/AnyScalar operations. Norm, curvature, and stopping decisions are scalar control-flow boundaries; this API does not promise a differentiable solve. No dense operator, preconditioner, or tensor-network truncation is introduced.

§Errors

Returns KrylovError::InvalidOptions for invalid tolerances or an overflowing stopping threshold, KrylovError::NonHermitian for a visited curvature with an excessive imaginary part, KrylovError::NonPositiveCurvature for zero or negative curvature, KrylovError::NumericalBreakdown for nonfinite or unusable recurrence quantities, and KrylovError::Operation for incompatible vector spaces, invalid tensor structures, operator errors, or failed tensor operations. Underlying operation errors retain their source chains; an error returned by apply_a, including a KrylovError from a nested solve, is always wrapped in KrylovError::Operation.

§Examples

use tensor4all_core::{krylov::{cg, CgOptions}, DynIndex, IdxTensor, TensorVectorSpace};
let i = DynIndex::new_dyn(2);
let b = IdxTensor::from_dense(vec![i.clone()], vec![2.0_f64, 4.0])?;
let x0 = IdxTensor::zeros::<f64>(vec![i])?;
let result = cg(
    |x: &IdxTensor| Ok(x.scale(2.0.into())?), &b, &x0, &CgOptions::default(),
)?;
assert!(result.converged);
assert_eq!(result.solution.to_vec::<f64>()?, vec![1.0, 2.0]);