Add conjugate gradient linear solver

This commit is contained in:
shenw
2026-06-22 21:00:21 +08:00
parent 0ffd3e12b8
commit 5375112eaf
3 changed files with 256 additions and 0 deletions
+115
View File
@@ -0,0 +1,115 @@
module fem_linear_solver_cg
use fem_precision
use fem_error
use fem_sparse_csr
implicit none
private
public :: linear_cg_solve
contains
subroutine linear_cg_solve(a, b, x, max_iter, tol, iter, res_norm, ierr)
type(csr_matrix), intent(in) :: a
real(rk), intent(in) :: b(:)
real(rk), intent(inout) :: x(:)
integer, intent(in) :: max_iter
real(rk), intent(in) :: tol
integer, intent(out) :: iter
real(rk), intent(out) :: res_norm
integer, intent(out) :: ierr
real(rk), allocatable :: r(:)
real(rk), allocatable :: p(:)
real(rk), allocatable :: ap(:)
real(rk) :: alpha
real(rk) :: beta
real(rk) :: denom
real(rk) :: norm_b
real(rk) :: rsold
real(rk) :: rsnew
real(rk) :: threshold
integer :: n
integer :: stat
iter = 0
res_norm = ZERO
if (a%nrow .le. 0 .or. a%ncol .le. 0) then
call error_set(FEM_ERR_SOLVER, 'CG solver received an empty matrix', ierr)
return
end if
if (a%nrow .ne. a%ncol) then
call error_set(FEM_ERR_SOLVER, 'CG solver requires a square matrix', ierr)
return
end if
if (size(b) .ne. a%nrow .or. size(x) .ne. a%ncol) then
call error_set(FEM_ERR_SOLVER, 'CG solver vector size mismatch', ierr)
return
end if
if (max_iter .le. 0) then
call error_set(FEM_ERR_SOLVER, 'CG solver max_iter must be positive', ierr)
return
end if
if (tol .le. ZERO) then
call error_set(FEM_ERR_SOLVER, 'CG solver tolerance must be positive', ierr)
return
end if
n = a%nrow
allocate(r(n), p(n), ap(n), stat=stat)
if (stat .ne. 0) then
call error_set(FEM_ERR_SOLVER, 'failed to allocate CG workspace', ierr)
return
end if
call csr_matvec(a, x, ap, ierr)
if (ierr .ne. FEM_SUCCESS) go to 900
r = b - ap
p = r
norm_b = sqrt(dot_product(b, b))
threshold = tol * max(ONE, norm_b)
rsold = dot_product(r, r)
res_norm = sqrt(rsold)
if (res_norm .le. threshold) then
ierr = FEM_SUCCESS
go to 900
end if
do iter = 1, max_iter
call csr_matvec(a, p, ap, ierr)
if (ierr .ne. FEM_SUCCESS) go to 900
denom = dot_product(p, ap)
if (denom .le. tiny(ONE)) then
call error_set(FEM_ERR_SOLVER, 'CG solver detected non-positive curvature', ierr)
go to 900
end if
alpha = rsold / denom
x = x + alpha * p
r = r - alpha * ap
rsnew = dot_product(r, r)
res_norm = sqrt(rsnew)
if (res_norm .le. threshold) then
ierr = FEM_SUCCESS
go to 900
end if
beta = rsnew / rsold
p = r + beta * p
rsold = rsnew
end do
iter = max_iter
call error_set(FEM_ERR_SOLVER, 'CG solver did not converge', ierr)
900 continue
if (allocated(r)) deallocate(r)
if (allocated(p)) deallocate(p)
if (allocated(ap)) deallocate(ap)
end subroutine linear_cg_solve
end module fem_linear_solver_cg