From ddbde1b3f4d0c074ad1849100e791d024eec6529 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:52:35 +0000 Subject: [PATCH] FEM: Fix 'zerob' BC in hcurl_grad_getmop Fix several bugs in the 'zerob' boundary-condition branch of the H(Curl) + Grad(H^1) mass matrix construction: - Zero global-boundary Grad(H^1) rows in mop21 instead of mop12. The old code indexed mop12 (size hcurl nce x hgrad nce) with Grad(H^1) row indices, writing out of bounds and corrupting the heap. The loop now starts at cell_np+1 since vertex rows are already zeroed. - Add unit diagonals for Grad(H^1) Dirichlet rows to block (2,2) rather than block (1,1). - Add vertex Grad(H^1) diagonals following the 'none' pattern (interior vertices plus owned processor-boundary vertices), instead of only vertices shared with other processors, and skip vertex DOFs in the boundary-DOF loop so each gets exactly one unit diagonal. Add a regression test to test_hcurl_grad that L2-projects an analytic field with vanishing tangential boundary component using the 'zerob' mass matrix at orders 1-3, serial and MPI, checking solver convergence and projection error. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NKQvs9uG822LSFyCgTSuSz --- src/fem/hcurl_grad_operators.F90 | 20 +++-- src/tests/fem/test_hcurl_grad.F90 | 127 ++++++++++++++++++++++++++++-- src/tests/fem/test_hcurl_grad.py | 41 +++++++++- 3 files changed, 176 insertions(+), 12 deletions(-) diff --git a/src/fem/hcurl_grad_operators.F90 b/src/fem/hcurl_grad_operators.F90 index d81103320..df205ef79 100644 --- a/src/fem/hcurl_grad_operators.F90 +++ b/src/fem/hcurl_grad_operators.F90 @@ -1051,11 +1051,12 @@ subroutine hcurl_grad_getmop(hcurl_grad_rep,mat,bc) mop12(jr,:)=0.d0 END IF END DO + !---Vertex Grad(H^1) DOFs are always removed (duplicate lowest-order H(Curl) DOFs) mop21(1:hgrad_rep%mesh%cell_np,:)=0.d0 mop22(1:hgrad_rep%mesh%cell_np,:)=0.d0 - DO jr=hgrad_rep%mesh%cell_np,hgrad_rep%nce + DO jr=hgrad_rep%mesh%cell_np+1,hgrad_rep%nce IF(hgrad_rep%global%gbe(j_grad(jr)))THEN - mop12(jr,:)=0.d0 + mop21(jr,:)=0.d0 mop22(jr,:)=0.d0 END IF END DO @@ -1096,17 +1097,26 @@ subroutine hcurl_grad_getmop(hcurl_grad_rep,mat,bc) j_curl=jr call mat%add_values(j_curl,j_curl,mop11,1,1,1,1) END DO + !---Vertex Grad(H^1) DOFs (always removed, including those on the global boundary) DO i=1,hgrad_rep%mesh%np - IF(.NOT.hgrad_rep%linkage%be(i))CYCLE + IF(hgrad_rep%mesh%bp(i))CYCLE j_curl=i - call mat%add_values(j_curl,j_curl,mop11,1,1,1,1) + call mat%add_values(j_curl,j_curl,mop11,1,1,2,2) + END DO + DO i=1,hgrad_rep%mesh%nbp + jr=hgrad_rep%mesh%lbp(i) + IF(.NOT.hgrad_rep%mesh%pstitch%leo(i))CYCLE + j_curl=jr + call mat%add_values(j_curl,j_curl,mop11,1,1,2,2) END DO + !---Non-vertex Grad(H^1) DOFs on the global boundary DO i=1,hgrad_rep%nbe jr=hgrad_rep%lbe(i) + IF(jr<=hgrad_rep%mesh%np)CYCLE ! Vertex DOFs handled above IF(.NOT.hgrad_rep%global%gbe(jr))CYCLE IF(.NOT.hgrad_rep%linkage%leo(i))CYCLE j_curl=jr - call mat%add_values(j_curl,j_curl,mop11,1,1,1,1) + call mat%add_values(j_curl,j_curl,mop11,1,1,2,2) END DO END SELECT DEALLOCATE(j_curl,mop11) diff --git a/src/tests/fem/test_hcurl_grad.F90 b/src/tests/fem/test_hcurl_grad.F90 index 1a00aaadb..554125425 100644 --- a/src/tests/fem/test_hcurl_grad.F90 +++ b/src/tests/fem/test_hcurl_grad.F90 @@ -10,14 +10,44 @@ !! !! The current test cases are: !! - Solve the equation \f$ M B = M \hat{I} \f$ +!! - L2 projection of an analytic field with vanishing tangential boundary +!! component using the `'zerob'` mass matrix !! !! @authors Chris Hansen !! @date April 2013 !! @ingroup testing !------------------------------------------------------------------------------ +!------------------------------------------------------------------------------ +! Analytic vector field with vanishing tangential component on the boundary of +! the unit cube, used to test projection with the 'zerob' mass matrix +!------------------------------------------------------------------------------ +MODULE test_hcurl_grad_helpers +USE oft_base +USE fem_utils, ONLY: fem_interp +IMPLICIT NONE +TYPE, EXTENDS(fem_interp) :: tang_zero_field +CONTAINS + PROCEDURE :: interp => tang_zero_field_interp +END TYPE tang_zero_field +CONTAINS +SUBROUTINE tang_zero_field_interp(self,cell,f,gop,val) +CLASS(tang_zero_field), INTENT(inout) :: self +INTEGER(i4), INTENT(in) :: cell +REAL(r8), INTENT(in) :: f(:) +REAL(r8), INTENT(in) :: gop(3,4) +REAL(r8), INTENT(out) :: val(:) +REAL(r8) :: pt(3),s(3) +pt=self%mesh%log2phys(cell,f) +s=SIN(pi*pt) +val(1)=s(2)*s(3)*(1.d0+pt(1)) +val(2)=s(1)*s(3)*(1.d0+pt(2)**2) +val(3)=s(1)*s(2)*COS(pt(3)) +END SUBROUTINE tang_zero_field_interp +END MODULE test_hcurl_grad_helpers program test_hcurl_grad USE oft_base USE oft_mesh_cube, ONLY: mesh_cube_id +USE oft_mesh_type, ONLY: cell_is_curved ! USE oft_io USE multigrid, ONLY: multigrid_mesh USE multigrid_build, ONLY: multigrid_construct @@ -33,10 +63,11 @@ program test_hcurl_grad USE oft_h1_basis, ONLY: oft_h1_setup USE oft_h1_operators, ONLY: h1_setup_interp !---H(Curl) FE space -USE oft_hcurl_basis, ONLY: oft_hcurl_setup, oft_hcurl_grad_setup +USE oft_hcurl_basis, ONLY: oft_hcurl_setup, oft_hcurl_grad_setup, oft_hcurl_fem USE oft_hcurl_operators, ONLY: hcurl_setup_interp USE oft_hcurl_grad_operators, ONLY: hcurl_grad_getmop, hcurl_grad_setup_interp, hcurl_grad_getmop_pre, hcurl_grad_mloptions, & - oft_hcurl_grad_rinterp, oft_hcurl_grad_gzerop + oft_hcurl_grad_rinterp, oft_hcurl_grad_gzerop, oft_hcurl_grad_zerob, oft_hcurl_grad_project +USE test_hcurl_grad_helpers, ONLY: tang_zero_field IMPLICIT NONE INTEGER(i4) :: order,ierr,io_unit,minlev TYPE(multigrid_mesh) :: mg_mesh @@ -44,11 +75,14 @@ program test_hcurl_grad TYPE(oft_ml_fem_type), TARGET :: ML_oft_hcurl TYPE(oft_ml_fem_comp_type), TARGET :: ML_hcurl_grad TYPE(oft_hcurl_grad_gzerop), TARGET :: hcurl_grad_gzerop -LOGICAL :: mg_test -NAMELIST/test_hcurl_grad_options/order,mg_test +TYPE(oft_hcurl_grad_zerob), TARGET :: hcurl_grad_zerob +LOGICAL :: mg_test,zerob_test +NAMELIST/test_hcurl_grad_options/order,mg_test,zerob_test !---Initialize enviroment CALL oft_init !---Read in options +mg_test=.FALSE. +zerob_test=.FALSE. OPEN(NEWUNIT=io_unit,FILE=oft_env%ifile) READ(io_unit,test_hcurl_grad_options,IOSTAT=ierr) CLOSE(io_unit) @@ -70,13 +104,16 @@ program test_hcurl_grad !--- Full H(Curl) space CALL oft_hcurl_grad_setup(ML_oft_hcurl,ML_oft_h1,ML_hcurl_grad,ML_h1grad,minlev=minlev) hcurl_grad_gzerop%ML_hcurl_grad_rep=>ML_hcurl_grad +hcurl_grad_zerob%ML_hcurl_grad_rep=>ML_hcurl_grad IF(mg_test)THEN CALL hcurl_grad_setup_interp(ML_hcurl_grad,ML_oft_h1,create_full=.TRUE.) CALL hcurl_grad_mloptions END IF !---Run tests oft_env%pm=.FALSE. -IF(mg_test)THEN +IF(zerob_test)THEN + CALL test_mop_zerob +ELSE IF(mg_test)THEN CALL test_mopmg ELSE CALL test_mop @@ -175,4 +212,84 @@ SUBROUTINE test_mopmg CALL u%delete CALL v%delete END SUBROUTINE test_mopmg +!--------------------------------------------------------------------------------- +! L2 project an analytic field with vanishing tangential boundary component +! using the 'zerob' mass matrix and compute the relative projection error +!--------------------------------------------------------------------------------- +SUBROUTINE test_mop_zerob +CLASS(oft_solver), POINTER :: winv => NULL() +INTEGER(i4) :: i,m +REAL(r8) :: res_norm,rhs_norm,err_sq,ref_sq,vol,det,goptmp(3,4),bh(3),bex(3) +LOGICAL :: curved +CLASS(oft_vector), POINTER :: u,v,w,rhs +CLASS(oft_matrix), POINTER :: mop => NULL() +TYPE(tang_zero_field) :: field_ex +TYPE(oft_hcurl_grad_rinterp) :: field_h +CLASS(oft_hcurl_fem), POINTER :: hcurl_rep +!---Set FE level +CALL ML_hcurl_grad%set_level(ML_hcurl_grad%nlevels,propogate=.TRUE.) +!---Create solver fields +CALL ML_hcurl_grad%vec_create(u) +CALL ML_hcurl_grad%vec_create(v) +CALL ML_hcurl_grad%vec_create(w) +CALL ML_hcurl_grad%vec_create(rhs) +!---Get FE operators +CALL hcurl_grad_getmop(ML_hcurl_grad%current_level,mop,'zerob') +!---Setup matrix solver +CALL create_cg_solver(winv) +winv%A=>mop +winv%its=-3 +winv%rtol=1.d-12 +CALL create_diag_pre(winv%pre) +!---Build RHS with boundary and vertex Grad(H^1) entries zeroed +field_ex%mesh=>mg_mesh%mesh +CALL oft_hcurl_grad_project(ML_hcurl_grad%current_level,field_ex,v) +CALL hcurl_grad_zerob%apply(v) +CALL hcurl_grad_gzerop%apply(v) +rhs_norm=v%norm(2) +CALL rhs%add(0.d0,1.d0,v) +!---Solve +CALL u%set(0.d0) +CALL winv%apply(u,v) +!---Check true residual +CALL mop%apply(u,w) +CALL w%add(1.d0,-1.d0,rhs) +res_norm=w%norm(2)/rhs_norm +!---Compute relative L2 projection error +field_h%u=>u +CALL field_h%setup(ML_hcurl_grad%current_level) +SELECT TYPE(this=>ML_oft_hcurl%current_level) + CLASS IS(oft_hcurl_fem) + hcurl_rep=>this + CLASS DEFAULT + CALL oft_abort('Invalid H(Curl) space','test_mop_zerob',__FILE__) +END SELECT +err_sq=0.d0; ref_sq=0.d0 +DO i=1,mg_mesh%mesh%nc + curved=cell_is_curved(mg_mesh%mesh,i) + DO m=1,hcurl_rep%quad%np + IF(curved.OR.m==1)CALL mg_mesh%mesh%jacobian(i,hcurl_rep%quad%pts(:,m),goptmp,vol) + det=vol*hcurl_rep%quad%wts(m) + CALL field_h%interp(i,hcurl_rep%quad%pts(:,m),goptmp,bh) + CALL field_ex%interp(i,hcurl_rep%quad%pts(:,m),goptmp,bex) + err_sq=err_sq+SUM((bh-bex)**2)*det + ref_sq=ref_sq+SUM(bex**2)*det + END DO +END DO +err_sq=oft_mpi_sum(err_sq) +ref_sq=oft_mpi_sum(ref_sq) +IF(oft_env%head_proc)THEN + OPEN(NEWUNIT=io_unit,FILE='hcurl_grad.results') + WRITE(io_unit,*)winv%cits + WRITE(io_unit,*)res_norm + WRITE(io_unit,*)SQRT(err_sq/ref_sq) + CLOSE(io_unit) +END IF +!---Destroy vectors +CALL field_h%delete +CALL u%delete +CALL v%delete +CALL w%delete +CALL rhs%delete +END SUBROUTINE test_mop_zerob end program test_hcurl_grad diff --git a/src/tests/fem/test_hcurl_grad.py b/src/tests/fem/test_hcurl_grad.py index 7c8bf0596..bbcf64fb0 100644 --- a/src/tests/fem/test_hcurl_grad.py +++ b/src/tests/fem/test_hcurl_grad.py @@ -34,20 +34,22 @@ &test_hcurl_grad_options order={2} mg_test={4} + zerob_test={8} / """ # Common setup function and process handling -def hcurl_grad_setup(nbase, nlevels, order, grid_type, mg=False, df='', nu='', petsc=False): +def hcurl_grad_setup(nbase, nlevels, order, grid_type, mg=False, df='', nu='', petsc=False, zerob=False): petsc_flag=('T' if petsc else 'F') mg_flag=('T' if mg else 'F') + zerob_flag=('T' if zerob else 'F') nproc = 1 if nbase != nlevels: nproc = 2 # os.chdir(test_dir) with open('oft.in', 'w+') as fid: - fid.write(oft_in_template.format(nbase, nlevels, order, grid_type, mg_flag, df, nu, petsc_flag)) + fid.write(oft_in_template.format(nbase, nlevels, order, grid_type, mg_flag, df, nu, petsc_flag, zerob_flag)) return run_OFT("./test_hcurl_grad", nproc, 120) def validate_result(iteration_count,converged_error): @@ -67,6 +69,34 @@ def validate_result(iteration_count,converged_error): return False return True +def validate_zerob_result(exp_error): + with open('hcurl_grad.results','r') as fid: + its_test = int(fid.readline()) + res_test = float(fid.readline()) + error_test = float(fid.readline()) + if (its_test <= 0) or (not res_test < 1.E-8): + print("FAILED: Solver did not converge!") + print(" Iterations = {0}".format(its_test)) + print(" Residual = {0}".format(res_test)) + return False + if not abs(error_test-exp_error) < 0.05*exp_error: + print("FAILED: Projection error incorrect!") + print(" Expected = {0}".format(exp_error)) + print(" Actual = {0}".format(error_test)) + return False + return True + +# 'zerob' mass matrix projection test function +def zerob_projection(nlevels,order,exp_error,grid_type=1,mpi=False,petsc=False): + if mpi: + nbase = nlevels-1 + nlev = nlevels+1 + else: + nbase = nlevels + nlev = nlevels + assert hcurl_grad_setup(nbase, nlev, order, grid_type, petsc=petsc, zerob=True) + assert validate_zerob_result(exp_error) + # Single level test function def single_level(nlevels,order,exp_its,exp_error,grid_type=1,mpi=False,petsc=False): if mpi: @@ -179,3 +209,10 @@ def test_hex_r3_p4(mpi, petsc_flag): single_level(3, 4, 1035, 1.0, grid_type=2, mpi=mpi, petsc=petsc_flag) def test_hex_r3_p4_mg(petsc_flag=False): multi_level(3, 4, 248, 1.0, grid_type=2, petsc=petsc_flag) + +#============================================================================ +# Projection tests using 'zerob' mass matrix +@pytest.mark.parametrize("mpi", (False, True)) +@pytest.mark.parametrize("order,exp_error", ((1, 2.7564E-2), (2, 2.0973E-3), (3, 1.4600E-4))) +def test_zerob_proj(order, exp_error, mpi): + zerob_projection(3, order, exp_error, mpi=mpi)