11 if (
A.rows() != n ||
A.cols() != n || x.
size() != n)
12 throw std::invalid_argument(
"Dimension mismatch in CG solver");
16 const_cast<Matrix&
>(
A).to_gpu();
17 const_cast<Vector&
>(
b).to_gpu();
42 if (std::abs(
pAp) < 1
e-15)
break;
58 axpy(1.0,
r, p, backend);
83 if (std::abs(
pAp) < 1
e-15)
break;
Conjugate gradient solvers (dense and matrix-free)
constexpr idx size() const noexcept
Dense row-major matrix with optional GPU storage.
void to_device(real *dst, const real *src, idx n)
Copy host to device.
Backend
Selects which backend handles a linalg operation.
@ gpu
CUDA – custom kernels or cuBLAS.
@ seq
Naive textbook loops – always available.
real beta(real a, real b)
B(a, b) – beta function.
constexpr T ipow(T x) noexcept
Compute x^N at compile time via repeated squaring.
void matvec(const Matrix &A, const Vector &x, Vector &y, Backend b=default_backend)
y = A * x
void scale(Vector &v, real alpha, Backend b=default_backend)
v *= alpha
real dot(const Vector &x, const Vector &y, Backend b=default_backend)
dot product
void axpy(real alpha, const Vector &x, Vector &y, Backend b=default_backend)
y += alpha * x
SolverResult cg_matfree(MatVecFn matvec, const Vector &b, Vector &x, real tol=1e-6, idx max_iter=1000)
Matrix-free conjugate gradient for Ax = b where A is SPD.
SolverResult cg(const Matrix &A, const Vector &b, Vector &x, real tol=1e-10, idx max_iter=1000, Backend backend=default_backend)
Conjugate gradient solver for Ax = b.
std::function< void(const Vector &, Vector &)> MatVecFn
Callable type for matrix-free matvec: computes y = A*x.
idx iterations
Number of iterations performed.