diff --git a/.github/workflows/plugins.yml b/.github/workflows/plugins.yml new file mode 100644 index 00000000..9d716342 --- /dev/null +++ b/.github/workflows/plugins.yml @@ -0,0 +1,140 @@ +# Compile the plugin layer. +# +# The plugins are not part of the default build and no other workflow installs +# them, so a plugin module can stay uncompilable for months: between the size_t +# conversion (PR #437) and the yyjson rewrite (5a721280) the TC closure +# accumulated ten defects that only surfaced when someone built it by hand +# (2026-12-01, PR #440). This job is what would have caught the first of them. +# +# The list lives in ci/plugins.txt; `qp plugins install` resolves the NEED +# closure, so the file lists leaves, not every module. +name: QP Plugins + +on: + push: + branches: + - qp3 + pull_request: + branches: + - qp3 + workflow_dispatch: + +concurrency: + group: plugins-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + + plugins: + name: Compilation (plugins) + runs-on: ubuntu-24.04 + timeout-minutes: 60 + + steps: + - uses: actions/checkout@v3 + + - name: Restore dependency cache + uses: actions/cache@v3 + with: + key: qp2-config + fail-on-cache-miss: false + path: | + include/ + lib/ + lib64/ + libexec/ + restore-keys: qp2- + + - name: Install dependencies + run: | + sudo apt update + sudo apt install -y --fix-missing --no-install-recommends \ + gfortran gcc liblapack-dev libblas-dev wget python3 make m4 pkg-config + + - name: Install Rust toolchain + run: rustup toolchain install 1.92.0 --profile minimal --component rustfmt,clippy + + - name: Configuration + run: | + # Same recipe as the Compilation job: the cache is an + # optimization, every package is installed explicitly, so a cache + # miss only costs time. configure also initializes the submodules + # (git submodule update --init --recursive). + if ! ls lib/libz.* >/dev/null 2>&1; then + ./configure -i zlib || : + fi + ./configure -i ninja || : + ./configure -i docopt || : + ./configure -i resultsFile || : + ./configure -i bats || : + ./configure -i trexio-nohdf5 || : + ./configure -i qmckl || : + ./configure -i simple_gpu || : + ./configure -i libcint || : + ./configure -c ./config/gfortran_debug.cfg -b ninja + + - name: Core compilation + run: bash -c "source quantum_package.rc ; exec ninja" + + - name: Install the plugins listed in ci/plugins.txt + run: | + source quantum_package.rc + # Several names in one call; it installs the NEED closure and + # runs `qp_create_ninja update` (graph + EZFIO interfaces). + qp plugins install $(grep -v '^#' ci/plugins.txt | tr '\n' ' ') + echo "installed: $(qp plugins list -i | tr '\n' ' ')" + + - name: Compile the plugin closure + run: | + source quantum_package.rc + set -o pipefail + # Cold-tree race, rehearsed 2026-12-01: IRPF90's per-module graph + # declares no .mod outputs, and one program stub edge has no + # dependency that would build the sizet.mod it reads, so a cold + # module can compile the stub before sizet.f90. A serial retry + # cannot fix it (ninja runs independent edges in graph order even + # at -j1, and a parallel re-run is a fresh coin flip). + # Keep going instead: -k 0 builds every other edge of the module, + # so the .mod producers are done before the pass that compiles the + # stub. The wrapper's "Compiling all modules" edge is itself a + # sub-ninja that does not inherit -k 0, hence the direct call. + # TODO: fix the IRPF90 stub edge and delete this cascade. + ninja -k 0 2>&1 | tee -a plugin-build.log || true + ninja -f config/build.ninja -k 0 2>&1 | tee -a plugin-build.log || true + for dir in src/*/IRPF90_temp ; do + ( cd "$dir" && ninja -k 0 ; ninja -k 0 ) >>plugin-build.log 2>&1 || true + done + ninja 2>&1 | tee -a plugin-build.log + + - name: No integer-kind mismatch at a call boundary + # gfortran only warns on an INTEGER(8)/INTEGER(4) mismatch across a call + # boundary (implicit interface) and silently reads 32 bits of a 64-bit + # actual. The conventions forbid the mix, so make the warning fatal for + # the code this job compiles. + run: | + if grep -n -i "type mismatch" plugin-build.log ; then + echo "::error::integer kind mismatch across a call boundary" + exit 1 + fi + + - name: Unit tests (tc_scf) + run: | + source quantum_package.rc + cd plugins/local/tc_scf/tests + ninja # builds test_diis_history (its build.ninja default) + ./test_diis_history + # tests/build.ninja has no target for the biorthogonal test + # (upstream gap): compile it here instead of editing a ported file. + gfortran -O0 -g -fcheck=all -I. -J. -c ../biorthogonal_scaling.f90 -o biorthogonal_scaling.o + gfortran -O0 -g -fcheck=all -I. -J. test_biorthogonal_scaling.f90 \ + biorthogonal_scaling.o -llapack -lblas -o test_biorthogonal_scaling + ./test_biorthogonal_scaling + cd "$QP_ROOT" + ./src/tc_scf/diis_history_qp_test # IRPF90-level integration of the same module + + - name: Report the first errors on failure + if: failure() + run: | + git status --porcelain | head -40 + echo + grep -n -E "Error:|error:|FAILED:" plugin-build.log | head -40 || true diff --git a/ci/plugins.txt b/ci/plugins.txt new file mode 100644 index 00000000..71e8a689 --- /dev/null +++ b/ci/plugins.txt @@ -0,0 +1,16 @@ +# Plugins built by .github/workflows/plugins.yml. +# +# `qp plugins install` resolves each name's NEED closure, so listing the leaves +# is enough: tc_scf non_h_ints_mu non_hermit_dav => 12 modules today +# (ao_many_one_e_ints ao_tc_eff_map bi_ort_ints bi_ortho_mos jastrow +# non_h_ints_mu non_hermit_dav ortho_three_e_ints qmckl spher_harm +# tc_keywords tc_scf). +# +# Grow this list toward every directory in plugins/local as the remaining +# breakage is fixed. Today these two still write through the JSON API deleted +# in 5a721280, so they are not listed: +# plugins/local/fci_tc_bi/fci_tc_bi_ortho.irp.f +# plugins/local/cipsi_tc_bi_ortho/write_cipsi_json.irp.f +tc_scf +non_h_ints_mu +non_hermit_dav diff --git a/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f b/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f index a6afbca8..2220c6e5 100644 --- a/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f +++ b/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f @@ -57,9 +57,9 @@ !DIR$ FORCEINLINE call map_get(ao_tc_sym_two_e_pot_map, idx, integral) ii = l-ao_tc_sym_two_e_pot_cache_min - ii = ior( ishft(ii,6), k-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), j-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), i-ao_tc_sym_two_e_pot_cache_min) + ii = ior( ishft(ii,6), int(k-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(j-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(i-ao_tc_sym_two_e_pot_cache_min, 4)) ao_tc_sym_two_e_pot_cache(ii) = integral enddo enddo @@ -118,9 +118,9 @@ double precision function get_ao_tc_sym_two_e_pot(i, j, k, l, map) result(result ! tmp = 0.d0 else ii = l-ao_tc_sym_two_e_pot_cache_min - ii = ior(ii, k-ao_tc_sym_two_e_pot_cache_min) - ii = ior(ii, j-ao_tc_sym_two_e_pot_cache_min) - ii = ior(ii, i-ao_tc_sym_two_e_pot_cache_min) + ii = ior(ii, int(k-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior(ii, int(j-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior(ii, int(i-ao_tc_sym_two_e_pot_cache_min, 4)) if (iand(ii, -64) /= 0) then !DIR$ FORCEINLINE call two_e_integrals_index(i, j, k, l, idx) @@ -129,9 +129,9 @@ double precision function get_ao_tc_sym_two_e_pot(i, j, k, l, map) result(result tmp = tmp else ii = l-ao_tc_sym_two_e_pot_cache_min - ii = ior( ishft(ii,6), k-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), j-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), i-ao_tc_sym_two_e_pot_cache_min) + ii = ior( ishft(ii,6), int(k-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(j-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(i-ao_tc_sym_two_e_pot_cache_min, 4)) tmp = ao_tc_sym_two_e_pot_cache(ii) endif endif diff --git a/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f b/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f index 1587f6fb..8d13fcf6 100644 --- a/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f +++ b/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f @@ -63,7 +63,7 @@ ! parallel-do because its result is already in the map (the ! pt2_omp pattern). allocate ( buffer_i(ao_num*ao_num), buffer_value(ao_num*ao_num) ) - call compute_ao_tc_sym_two_e_pot_jl(1,1,n_integrals,buffer_i,buffer_value) + call compute_ao_tc_sym_two_e_pot_jl(1_size_t,1_size_t,n_integrals,buffer_i,buffer_value) call insert_into_ao_tc_sym_two_e_pot_map(n_integrals,buffer_i,buffer_value) accu = accu + n_integrals deallocate ( buffer_i, buffer_value ) @@ -75,7 +75,7 @@ allocate ( buffer_i_t(ao_num*ao_num), buffer_value_t(ao_num*ao_num) ) !$OMP DO SCHEDULE(DYNAMIC,1) do l=2,ao_num - call compute_ao_tc_sym_two_e_pot_jl(1,l,n_integrals,buffer_i_t,buffer_value_t) + call compute_ao_tc_sym_two_e_pot_jl(1_size_t,l,n_integrals,buffer_i_t,buffer_value_t) !$OMP CRITICAL call insert_into_ao_tc_sym_two_e_pot_map(n_integrals,buffer_i_t,buffer_value_t) accu = accu + n_integrals diff --git a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f index 6c493ef7..8dd9782a 100644 --- a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f +++ b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f @@ -238,10 +238,11 @@ double precision function env_gauss_2e_j1_schwartz(i, j, k, l) ! --- subroutine get_cxcycz_j1( dim1, cx, cy, cz & - use sizet , P1_center, P1_new, pp1, fact_p1, p1_inv, iorder_p & , Q1_center, Q1_new, qq1, fact_q1, q1_inv, iorder_q ) + use sizet + include 'utils/constants.include.F' implicit none diff --git a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f index 6752bd9c..926cf48b 100644 --- a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f +++ b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f @@ -241,10 +241,11 @@ double precision function env_gauss_2e_j2_schwartz(i, j, k, l) ! --- subroutine get_cxcycz_j2( dim1, cx, cy, cz & - use sizet , P1_center, P1_new, pp1, fact_p1, p1_inv, iorder_p & , Q1_center, Q1_new, qq1, fact_q1, q1_inv, iorder_q ) + use sizet + include 'utils/constants.include.F' implicit none diff --git a/plugins/local/bi_ort_ints/three_body_ijmk.irp.f b/plugins/local/bi_ort_ints/three_body_ijmk.irp.f index 909fca17..9bf94d84 100644 --- a/plugins/local/bi_ort_ints/three_body_ijmk.irp.f +++ b/plugins/local/bi_ort_ints/three_body_ijmk.irp.f @@ -78,7 +78,7 @@ !$OMP PARALLEL & !$OMP DEFAULT (NONE) & !$OMP PRIVATE (k, i, j, m, n, ipoint, tmp_loc_1, tmp_loc_2, tmp_2d, tmp1, tmp2) & - !$OMP SHARED (mo_num, n_points_final_grid, & + !$OMP SHARED (mo_num, n_points_final_grid, n_points4, & !$OMP mos_l_in_r_array_transp, mos_r_in_r_array_transp, & !$OMP int2_grad1_u12_bimo_t, final_weight_at_r_vector, & !$OMP tmp_aux_1, tmp_aux_2, & diff --git a/plugins/local/bi_ortho_mos/bi_density.irp.f b/plugins/local/bi_ortho_mos/bi_density.irp.f index 0b2ac8bd..159892f6 100644 --- a/plugins/local/bi_ortho_mos/bi_density.irp.f +++ b/plugins/local/bi_ortho_mos/bi_density.irp.f @@ -87,7 +87,7 @@ ! END_DOC PROVIDE mo_r_core_coef mo_l_core_coef - call dgemm( 'N', 'T', ao_num, ao_num, n_core_orb, 1.d0 & + call dgemm( 'N', 'T', ao_num, ao_num, int(n_core_orb, 4), 1.d0 & , mo_l_core_coef, size(mo_l_core_coef, 1), mo_r_core_coef, size(mo_r_core_coef, 1) & , 0.d0, TCSCF_bi_ort_core_dm_ao, size(TCSCF_bi_ort_core_dm_ao, 1) ) ! factor two because it is the total DM diff --git a/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f b/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f index fc70be70..14d9b4fe 100644 --- a/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f +++ b/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f @@ -150,6 +150,114 @@ subroutine get_grad1_u12_withsq_r1_seq(ipoint, n_grid2, resx, resy, resz, res) ! --- +subroutine get_grad1_u12_withsq_qmckl_block(ipoint_first, n_grid1, n_grid2, resx, resy, resz, res) + + BEGIN_DOC + ! QMCkl gradient for a contiguous block of r1 grid points. + ! The shared QMCkl context is updated once, outside OpenMP regions. + END_DOC + + use sizet + use qmckl + + implicit none + integer(size_t), intent(in) :: ipoint_first, n_grid1, n_grid2 + double precision, intent(out) :: resx(n_grid2,n_grid1), resy(n_grid2,n_grid1) + double precision, intent(out) :: resz(n_grid2,n_grid1), res (n_grid2,n_grid1) + + integer(size_t) :: i_grid1, ipoint, jpoint + integer(size_t) :: k, n_points + double precision :: dx, dy, dz, fac_en + double precision, allocatable :: rij(:,:,:), gl(:,:,:) + integer(qmckl_exit_code) :: rc + + PROVIDE qmckl_ctx_jastrow + PROVIDE elec_num + PROVIDE final_grid_points final_grid_points_extra + + n_points = n_grid1 * n_grid2 + allocate(rij(3,2,n_points), gl(2,4,n_points)) + + k = 0_size_t + do i_grid1 = 1, n_grid1 + ipoint = ipoint_first + i_grid1 - 1 + do jpoint = 1, n_grid2 + k = k + 1_size_t + rij(1:3,1,k) = final_grid_points (1:3,ipoint) + rij(1:3,2,k) = final_grid_points_extra(1:3,jpoint) + enddo + enddo + + rc = qmckl_set_electron_coord(qmckl_ctx_jastrow, 'N', n_points, rij, 6_size_t*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in set_electron_coord' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + rc = qmckl_get_jastrow_champ_factor_ee_gl(qmckl_ctx_jastrow, gl, 8_size_t*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in fact_ee_gl' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + k = 0_size_t + do i_grid1 = 1, n_grid1 + do jpoint = 1, n_grid2 + k = k + 1_size_t + resx(jpoint,i_grid1) = gl(1,1,k) + resy(jpoint,i_grid1) = gl(1,2,k) + resz(jpoint,i_grid1) = gl(1,3,k) + enddo + enddo + + rc = qmckl_get_jastrow_champ_factor_een_gl(qmckl_ctx_jastrow, gl, 8_size_t*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in fact_een_gl' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + k = 0_size_t + do i_grid1 = 1, n_grid1 + do jpoint = 1, n_grid2 + k = k + 1_size_t + resx(jpoint,i_grid1) = resx(jpoint,i_grid1) + gl(1,1,k) + resy(jpoint,i_grid1) = resy(jpoint,i_grid1) + gl(1,2,k) + resz(jpoint,i_grid1) = resz(jpoint,i_grid1) + gl(1,3,k) + enddo + enddo + + rc = qmckl_get_jastrow_champ_factor_en_gl(qmckl_ctx_jastrow, gl, 8_size_t*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in fact_en_gl' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + fac_en = 1.d0 / dble(elec_num - 1) + k = 0_size_t + do i_grid1 = 1, n_grid1 + do jpoint = 1, n_grid2 + k = k + 1_size_t + dx = resx(jpoint,i_grid1) + fac_en * gl(1,1,k) + dy = resy(jpoint,i_grid1) + fac_en * gl(1,2,k) + dz = resz(jpoint,i_grid1) + fac_en * gl(1,3,k) + resx(jpoint,i_grid1) = dx + resy(jpoint,i_grid1) = dy + resz(jpoint,i_grid1) = dz + res (jpoint,i_grid1) = dx*dx + dy*dy + dz*dz + enddo + enddo + + deallocate(rij, gl) + + return +end + +! --- + subroutine grad1_j12_r1_seq(r1, n_grid2, gradx, grady, gradz) use sizet diff --git a/plugins/local/non_h_ints_mu/tc_integ.irp.f b/plugins/local/non_h_ints_mu/tc_integ.irp.f index abd4c1ed..fc77a222 100644 --- a/plugins/local/non_h_ints_mu/tc_integ.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ.irp.f @@ -48,93 +48,10 @@ print *, ' Numerical integration over r1 and r2 will be performed' if(tc_save_mem) then - - integer(size_t) :: n_blocks, n_rest, n_pass - integer(size_t) :: i_blocks, i_rest, i_pass, ii - double precision :: mem, n_double - double precision, allocatable :: tmp(:,:,:), xx(:) - double precision, allocatable :: tmp_grad1_u12(:,:,:) - - PROVIDE final_weight_at_r_vector_extra aos_in_r_array_extra - - allocate(tmp(n_points_extra_final_grid,ao_num,ao_num), xx(n_points_extra_final_grid)) - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (j, i, jpoint) & - !$OMP SHARED (tmp, ao_num, n_points_extra_final_grid, final_weight_at_r_vector_extra, aos_in_r_array_extra_transp) - !$OMP DO COLLAPSE(2) - do j = 1, ao_num - do i = 1, ao_num - do jpoint = 1, n_points_extra_final_grid - tmp(jpoint,i,j) = final_weight_at_r_vector_extra(jpoint) * aos_in_r_array_extra_transp(jpoint,i) * aos_in_r_array_extra_transp(jpoint,j) - enddo - enddo - enddo - !$OMP END DO - !$OMP END PARALLEL - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), & - 1.d0*n_points_final_grid), size_t) - n_rest = int(mod(n_points_final_grid, n_blocks), size_t) - n_pass = int((n_points_final_grid - n_rest) / n_blocks, size_t) - call write_int(6, int(n_pass, 4), 'Number of passes') - call write_int(6, int(n_blocks, 4), 'Size of the blocks') - call write_int(6, int(n_rest, 4), 'Size of the last block') - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3)) - do i_pass = 1, n_pass - ii = (i_pass-1)*n_blocks + 1 - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_blocks,1), tmp_grad1_u12(1,i_blocks,2), tmp_grad1_u12(1,i_blocks,3), xx(1)) - enddo - !$OMP END DO - !$OMP END PARALLEL - do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) - enddo - enddo - deallocate(tmp_grad1_u12) - if(n_rest .gt. 0) then - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_rest,3)) - ii = n_pass*n_blocks + 1 - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_rest,1), tmp_grad1_u12(1,i_rest,2), tmp_grad1_u12(1,i_rest,3), xx(1)) - enddo - !$OMP END DO - !$OMP END PARALLEL - do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) - enddo - deallocate(tmp_grad1_u12) - endif - deallocate(tmp,xx) - + PROVIDE int2_grad1_u12_ao_num + int2_grad1_u12_ao = int2_grad1_u12_ao_num else - ! TODO combine 1shot & int2_grad1_u12_ao_num -! PROVIDE int2_grad1_u12_ao_num -! int2_grad1_u12_ao = int2_grad1_u12_ao_num - PROVIDE int2_grad1_u12_ao_num_1shot + PROVIDE int2_grad1_u12_ao_num_1shot int2_grad1_u12_ao = int2_grad1_u12_ao_num_1shot endif @@ -264,90 +181,10 @@ print *, ' Numerical integration over r1 and r2 will be performed' if(tc_save_mem) then - - integer(size_t) :: n_blocks, n_rest, n_pass - integer(size_t) :: i_blocks, i_rest, i_pass, ii - double precision :: mem, n_double - double precision, allocatable :: tmp(:,:,:), xx(:,:,:) - double precision, allocatable :: tmp_grad1_u12_squared(:,:) - - PROVIDE final_weight_at_r_vector_extra aos_in_r_array_extra - - allocate(tmp(n_points_extra_final_grid,ao_num,ao_num)) - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (j, i, jpoint) & - !$OMP SHARED (tmp, ao_num, n_points_extra_final_grid, final_weight_at_r_vector_extra, aos_in_r_array_extra_transp) - !$OMP DO COLLAPSE(2) - do j = 1, ao_num - do i = 1, ao_num - do jpoint = 1, n_points_extra_final_grid - tmp(jpoint,i,j) = final_weight_at_r_vector_extra(jpoint) * aos_in_r_array_extra_transp(jpoint,i) * aos_in_r_array_extra_transp(jpoint,j) - enddo - enddo - enddo - !$OMP END DO - !$OMP END PARALLEL - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), & - 1.d0*n_points_final_grid), size_t) - n_rest = int(mod(n_points_final_grid, n_blocks), size_t) - n_pass = int((n_points_final_grid - n_rest) / n_blocks, size_t) - call write_int(6, int(n_pass, 4), 'Number of passes') - call write_int(6, int(n_blocks, 4), 'Size of the blocks') - call write_int(6, int(n_rest, 4), 'Size of the last block') - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks), xx(n_points_extra_final_grid,n_blocks,3)) - do i_pass = 1, n_pass - ii = (i_pass-1)*n_blocks + 1 - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_blocks,1), xx(1,i_blocks,2), xx(1,i_blocks,3), tmp_grad1_u12_squared(1,i_blocks)) - enddo - !$OMP END DO - !$OMP END PARALLEL - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) - enddo - deallocate(tmp_grad1_u12_squared, xx) - if(n_rest .gt. 0) then - ii = n_pass*n_blocks + 1 - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_rest), xx(n_points_extra_final_grid,n_rest,3)) - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_rest,1), xx(1,i_rest,2), xx(1,i_rest,3), tmp_grad1_u12_squared(1,i_rest)) - enddo - !$OMP END DO - !$OMP END PARALLEL - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) - deallocate(tmp_grad1_u12_squared, xx) - endif - deallocate(tmp) - + PROVIDE int2_grad1_u12_square_ao_num + int2_grad1_u12_square_ao = int2_grad1_u12_square_ao_num else - - ! TODO combine 1shot & int2_grad1_u12_square_ao_num -! PROVIDE int2_grad1_u12_square_ao_num -! int2_grad1_u12_square_ao = int2_grad1_u12_square_ao_num - PROVIDE int2_grad1_u12_square_ao_num_1shot + PROVIDE int2_grad1_u12_square_ao_num_1shot int2_grad1_u12_square_ao = int2_grad1_u12_square_ao_num_1shot endif diff --git a/plugins/local/non_h_ints_mu/tc_integ_num.irp.f b/plugins/local/non_h_ints_mu/tc_integ_num.irp.f index 043d2b5e..629024ce 100644 --- a/plugins/local/non_h_ints_mu/tc_integ_num.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ_num.irp.f @@ -16,16 +16,13 @@ implicit none integer :: m integer(size_t) :: ipoint, i, j, jpoint - integer(size_t) :: n_blocks, n_rest, n_pass - integer(size_t) :: i_blocks, i_rest, i_pass, ii + integer(size_t) :: n_blocks, n_this + integer(size_t) :: i_blocks, ii double precision :: time0, time1 double precision :: mem, n_double double precision, allocatable :: tmp(:,:,:) double precision, allocatable :: tmp_grad1_u12(:,:,:), tmp_grad1_u12_squared(:,:) - ! TODO - ! tmp_grad1_u12_squared get be obtained from tmp_grad1_u12 - print*, ' providing int2_grad1_u12_ao_num & int2_grad1_u12_square_ao_num ...' call wall_time(time0) @@ -36,7 +33,7 @@ !$OMP DEFAULT (NONE) & !$OMP PRIVATE (j, i, jpoint) & !$OMP SHARED (tmp, ao_num, n_points_extra_final_grid, final_weight_at_r_vector_extra, aos_in_r_array_extra_transp) - !$OMP DO SCHEDULE (static) + !$OMP DO COLLAPSE(2) do j = 1, ao_num do i = 1, ao_num do jpoint = 1, n_points_extra_final_grid @@ -47,94 +44,51 @@ !$OMP END DO !$OMP END PARALLEL - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), & - 1.d0*n_points_final_grid), size_t) - n_rest = int(mod(n_points_final_grid, n_blocks), size_t) - n_pass = int((n_points_final_grid - n_rest) / n_blocks, size_t) + if (j2e_type == 'Qmckl') then + ! Bound the number of electron pairs held by the QMCkl context. + n_blocks = min(32_size_t, n_points_final_grid) + else + call total_memory(mem) + mem = max(1.d0, qp_max_mem - mem) + n_double = mem * 1.d8 + n_blocks = int(max(1.d0, min(n_double / (4.d0 * n_points_extra_final_grid), & + dble(n_points_final_grid))), size_t) + endif - call write_int(6, int(n_pass, 4), 'Number of passes') call write_int(6, int(n_blocks, 4), 'Size of the blocks') - call write_int(6, int(n_rest, 4), 'Size of the last block') - - - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks)) allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3)) - - do i_pass = 1, n_pass - ii = (i_pass-1)*n_blocks + 1 - - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, final_grid_points, tmp_grad1_u12, tmp_grad1_u12_squared) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_blocks,1) & - , tmp_grad1_u12(1,i_blocks,2) & - , tmp_grad1_u12(1,i_blocks,3) & - , tmp_grad1_u12_squared(1,i_blocks)) - enddo - !$OMP END DO - !$OMP END PARALLEL + allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks)) + + do ii = 1, n_points_final_grid, n_blocks + n_this = min(n_blocks, n_points_final_grid - ii + 1) + if (j2e_type == 'Qmckl') then + call get_grad1_u12_withsq_qmckl_block(ii, n_this, n_points_extra_final_grid, & + tmp_grad1_u12(1,1,1), tmp_grad1_u12(1,1,2), tmp_grad1_u12(1,1,3), & + tmp_grad1_u12_squared(1,1)) + else + !$OMP PARALLEL DO DEFAULT(NONE) PRIVATE(i_blocks,ipoint) & + !$OMP SHARED(ii,n_this,n_points_extra_final_grid,tmp_grad1_u12,tmp_grad1_u12_squared) + do i_blocks = 1, n_this + ipoint = ii + i_blocks - 1 + call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, & + tmp_grad1_u12(1,i_blocks,1), tmp_grad1_u12(1,i_blocks,2), & + tmp_grad1_u12(1,i_blocks,3), tmp_grad1_u12_squared(1,i_blocks)) + enddo + !$OMP END PARALLEL DO + endif + ! Use both results before reusing the pair-grid workspace for the next block. do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao_num(1,1,ii,m), ao_num*ao_num) + call dgemm('T','N',ao_num*ao_num,int(n_this, 4),int(n_points_extra_final_grid, 4),1.d0, & + tmp,int(n_points_extra_final_grid, 4),tmp_grad1_u12(1,1,m),int(n_points_extra_final_grid, 4), & + 0.d0,int2_grad1_u12_ao_num(1,1,ii,m),ao_num*ao_num) enddo - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao_num(1,1,ii), ao_num*ao_num) + call dgemm('T','N',ao_num*ao_num,int(n_this, 4),int(n_points_extra_final_grid, 4),-0.5d0, & + tmp,int(n_points_extra_final_grid, 4),tmp_grad1_u12_squared,int(n_points_extra_final_grid, 4), & + 0.d0,int2_grad1_u12_square_ao_num(1,1,ii),ao_num*ao_num) enddo - - deallocate(tmp_grad1_u12, tmp_grad1_u12_squared) - - if(n_rest .gt. 0) then - - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_rest)) - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_rest,3)) - - ii = n_pass*n_blocks + 1 - - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, final_grid_points, tmp_grad1_u12, tmp_grad1_u12_squared) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_rest,1) & - , tmp_grad1_u12(1,i_rest,2) & - , tmp_grad1_u12(1,i_rest,3) & - , tmp_grad1_u12_squared(1,i_rest)) - enddo - !$OMP END DO - !$OMP END PARALLEL - - do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao_num(1,1,ii,m), ao_num*ao_num) - enddo - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao_num(1,1,ii), ao_num*ao_num) - - deallocate(tmp_grad1_u12, tmp_grad1_u12_squared) - endif + deallocate(tmp_grad1_u12, tmp_grad1_u12_squared) deallocate(tmp) call wall_time(time1) diff --git a/plugins/local/non_hermit_dav/biorthog.irp.f b/plugins/local/non_hermit_dav/biorthog.irp.f index 271301e5..2c0127b1 100644 --- a/plugins/local/non_hermit_dav/biorthog.irp.f +++ b/plugins/local/non_hermit_dav/biorthog.irp.f @@ -170,8 +170,8 @@ subroutine non_hrmt_bieig_degen(n, A, s_right_in, thr_d, thr_nd, leigvec, reigve enddo enddo ! orthogonalize the right eigenvectors by diagonalizing the S matrix -! call lapack_diagd(seigval,seigvec,sphichi,n_dim,n_dim) - call pivoted_cholesky( sphichi, n_dim, -1.d0, n_dim, seigvec) + call lapack_diagd(seigval,seigvec,sphichi,n_dim,n_dim) + !call pivoted_cholesky( sphichi, n_dim, -1.d0, n_dim, seigvec) ! get the orthogonal eigenvectors in the big basis reigvec_tmp = 0.d0 do j = 1, n_dim diff --git a/plugins/local/non_hermit_dav/gram_schmit.irp.f b/plugins/local/non_hermit_dav/gram_schmit.irp.f index cdc49ff8..f344331f 100644 --- a/plugins/local/non_hermit_dav/gram_schmit.irp.f +++ b/plugins/local/non_hermit_dav/gram_schmit.irp.f @@ -1,6 +1,7 @@ use sizet subroutine bi_ortho_gram_schmidt(wi,vi,n,ni,wk,wk_schmidt) + use sizet implicit none BEGIN_DOC ! you enter with a set of "ni" BI-ORTHONORMAL vectors of length "n" diff --git a/plugins/local/non_hermit_dav/project.irp.f b/plugins/local/non_hermit_dav/project.irp.f index cce9ea67..3939a5bf 100644 --- a/plugins/local/non_hermit_dav/project.irp.f +++ b/plugins/local/non_hermit_dav/project.irp.f @@ -1,6 +1,7 @@ use sizet subroutine h_non_hermite(v,u,Hmat,a,N_st,sze) + use sizet implicit none BEGIN_DOC ! Template of routine for the application of H @@ -28,6 +29,7 @@ subroutine h_non_hermite(v,u,Hmat,a,N_st,sze) subroutine exp_tau_H(u,v,hmat,tau,et,N_st,sze) + use sizet implicit none BEGIN_DOC ! realises v = (1 - tau (H - et)) u @@ -44,6 +46,7 @@ subroutine exp_tau_H(u,v,hmat,tau,et,N_st,sze) end double precision function project_phi0(u,Hmat0,N_st,sze) + use sizet implicit none integer, intent(in) :: N_st integer(size_t), intent(in) :: sze diff --git a/plugins/local/tc_scf/EZFIO.cfg b/plugins/local/tc_scf/EZFIO.cfg index e3d24338..4594d53a 100644 --- a/plugins/local/tc_scf/EZFIO.cfg +++ b/plugins/local/tc_scf/EZFIO.cfg @@ -23,7 +23,7 @@ default: 0. [thresh_tcscf] type: Threshold -doc: Threshold on the convergence of the Hartree Fock energy. +doc: TC-SCF converges when the largest singular value of the residual in orthonormal AO coordinates is below the square root of this value. interface: ezfio,provider,ocaml default: 1.e-8 diff --git a/plugins/local/tc_scf/README.md b/plugins/local/tc_scf/README.md index 45f5c60f..df5141d8 100644 --- a/plugins/local/tc_scf/README.md +++ b/plugins/local/tc_scf/README.md @@ -1,2 +1,19 @@ Transcorrelated SCF =================== + +### Three-electron contribution + +With `three_body_h_tc=True`, each spin Fock matrix includes its +three-electron contribution. The total Fock matrix combines the spin +matrices and their three-electron terms are therefore already present. +With the default `three_body_h_tc=False` and `noL_standard=True`, +TC-SCF includes the scalar three-electron energy in its reported total +and omits the explicit three-electron term from the orbital update. + +### Level-shift retries + +When the fallback orbital update increases the residual by more than +10%, TC-SCF clears the DIIS history and tries up to five level shifts +from the saved incoming orbitals. It accepts the first shifted update +that lowers the incoming residual. If all attempts fail, it restores +both sets of incoming orbitals and checks convergence as usual. diff --git a/plugins/local/tc_scf/biorthogonal_scaling.f90 b/plugins/local/tc_scf/biorthogonal_scaling.f90 new file mode 100644 index 00000000..559abe1b --- /dev/null +++ b/plugins/local/tc_scf/biorthogonal_scaling.f90 @@ -0,0 +1,169 @@ +module biorthogonal_scaling_module + + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + + implicit none + private + + integer, parameter, public :: scaling_success = 0 + integer, parameter, public :: scaling_bad_shape = 1 + integer, parameter, public :: scaling_bad_metric = 2 + integer, parameter, public :: scaling_bad_norm = 3 + integer, parameter, public :: scaling_bad_overlap = 4 + integer, parameter, public :: scaling_nonfinite = 5 + integer, parameter, public :: scaling_overlap_changed = 6 + integer, parameter :: wide_real = selected_real_kind(18) + + public :: balance_biorthogonal_pairs + +contains + + pure subroutine balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + + implicit none + + double precision, intent(in) :: left(:,:), right(:,:), metric(:,:) + double precision, intent(out) :: left_balanced(:,:), right_balanced(:,:) + double precision, intent(out) :: left_scale(:) + integer, intent(out) :: info + + double precision, allocatable :: overlap_before(:,:), overlap_after(:,:) + double precision, allocatable :: left_trial(:,:), right_trial(:,:) + double precision, allocatable :: scale_trial(:) + real(wide_real), allocatable :: metric_wide(:,:) + real(wide_real), allocatable :: left_wide(:), right_wide(:) + double precision :: left_norm_sq, right_norm_sq + double precision :: left_norm, right_norm, alpha + double precision :: metric_scale, metric_asymmetry + double precision :: overlap_scale, overlap_tolerance + double precision :: offdiag_before, offdiag_after + real(wide_real) :: overlap_before_diag, overlap_after_diag + real(wide_real) :: diagonal_change, overlap_tolerance_wide + integer :: i, j, n, m + + info = scaling_bad_shape + n = size(left, 1) + m = size(left, 2) + if((n < 1) .or. (m < 1)) return + if((size(right,1) /= n) .or. (size(right,2) /= m)) return + if((size(metric,1) /= n) .or. (size(metric,2) /= n)) return + if((size(left_balanced,1) /= n) .or. & + (size(left_balanced,2) /= m)) return + if((size(right_balanced,1) /= n) .or. & + (size(right_balanced,2) /= m)) return + if(size(left_scale) /= m) return + + left_balanced = left + right_balanced = right + left_scale = 1.d0 + + info = scaling_nonfinite + if(.not. all(ieee_is_finite(left))) return + if(.not. all(ieee_is_finite(right))) return + if(.not. all(ieee_is_finite(metric))) return + + metric_scale = max(1.d0, maxval(abs(metric))) + metric_asymmetry = maxval(abs(metric - transpose(metric))) + info = scaling_bad_metric + if(metric_asymmetry > 100.d0 * epsilon(1.d0) * metric_scale) return + + allocate(overlap_before(m,m), overlap_after(m,m)) + allocate(left_trial(n,m), right_trial(n,m)) + allocate(scale_trial(m)) + left_trial = left + right_trial = right + scale_trial = 1.d0 + overlap_before = matmul(transpose(left), matmul(metric, right)) + info = scaling_nonfinite + if(.not. all(ieee_is_finite(overlap_before))) return + + info = scaling_bad_overlap + do i = 1, m + if(abs(overlap_before(i,i)) <= tiny(1.d0)) return + enddo + + do i = 1, m + left_norm_sq = dot_product(left(:,i), matmul(metric, left(:,i))) + right_norm_sq = dot_product(right(:,i), matmul(metric, right(:,i))) + info = scaling_nonfinite + if(.not. ieee_is_finite(left_norm_sq)) return + if(.not. ieee_is_finite(right_norm_sq)) return + + info = scaling_bad_norm + if((left_norm_sq <= 0.d0) .or. (right_norm_sq <= 0.d0)) return + + left_norm = sqrt(left_norm_sq) + right_norm = sqrt(right_norm_sq) + alpha = sqrt(right_norm) / sqrt(left_norm) + info = scaling_nonfinite + if((.not. ieee_is_finite(alpha)) .or. (alpha <= 0.d0)) return + + left_trial(:,i) = alpha * left(:,i) + right_trial(:,i) = right(:,i) / alpha + scale_trial(i) = alpha + enddo + + if(.not. all(ieee_is_finite(left_trial))) return + if(.not. all(ieee_is_finite(right_trial))) return + + overlap_after = matmul(transpose(left_trial), & + matmul(metric, right_trial)) + if(.not. all(ieee_is_finite(overlap_after))) return + + overlap_scale = max(1.d0, maxval(abs(overlap_before))) + overlap_tolerance = 100.d0 * epsilon(1.d0) * overlap_scale + overlap_tolerance_wide = real(overlap_tolerance, wide_real) + diagonal_change = 0._wide_real + offdiag_before = 0.d0 + offdiag_after = 0.d0 + allocate(metric_wide(n,n), left_wide(n), right_wide(n)) + metric_wide = real(metric, wide_real) + do j = 1, m + ! The left and right scales cancel in this overlap. Wider sums keep + ! rounding from making a valid rescaling look like a failure. + left_wide = real(left(:,j), wide_real) + right_wide = real(right(:,j), wide_real) + overlap_before_diag = dot_product(left_wide, & + matmul(metric_wide, right_wide)) + left_wide = real(left_trial(:,j), wide_real) + right_wide = real(right_trial(:,j), wide_real) + overlap_after_diag = dot_product(left_wide, & + matmul(metric_wide, right_wide)) + if((.not. ieee_is_finite(overlap_before_diag)) .or. & + (.not. ieee_is_finite(overlap_after_diag))) then + info = scaling_nonfinite + return + endif + diagonal_change = max(diagonal_change, & + abs(overlap_after_diag - overlap_before_diag)) + do i = 1, m + if(i == j) cycle + offdiag_before = max(offdiag_before, abs(overlap_before(i,j))) + offdiag_after = max(offdiag_after, abs(overlap_after(i,j))) + enddo + enddo + + info = scaling_overlap_changed + if(diagonal_change > overlap_tolerance_wide) then + left_balanced = left + right_balanced = right + left_scale = 1.d0 + return + endif + if(offdiag_after > offdiag_before + overlap_tolerance) then + left_balanced = left + right_balanced = right + left_scale = 1.d0 + return + endif + + info = scaling_success + left_balanced = left_trial + right_balanced = right_trial + left_scale = scale_trial + + end subroutine balance_biorthogonal_pairs + +end module biorthogonal_scaling_module diff --git a/plugins/local/tc_scf/biorthogonal_scaling_provider.irp.f b/plugins/local/tc_scf/biorthogonal_scaling_provider.irp.f new file mode 100644 index 00000000..1c082670 --- /dev/null +++ b/plugins/local/tc_scf/biorthogonal_scaling_provider.irp.f @@ -0,0 +1,28 @@ +BEGIN_PROVIDER [ double precision, fock_tc_reigvec_ao_balanced, (ao_num, mo_num) ] +&BEGIN_PROVIDER [ double precision, fock_tc_leigvec_ao_balanced, (ao_num, mo_num) ] + + use biorthogonal_scaling_module + + implicit none + + integer :: info + double precision :: left_scale(mo_num) + + PROVIDE fock_tc_reigvec_ao fock_tc_leigvec_ao ao_overlap + + call balance_biorthogonal_pairs( fock_tc_leigvec_ao, & + fock_tc_reigvec_ao, ao_overlap, & + fock_tc_leigvec_ao_balanced, & + fock_tc_reigvec_ao_balanced, & + left_scale, info ) + + if(info == scaling_success) then + if(maxval(abs(log(left_scale))) > log(10.d0)) then + print *, ' TC-SCF left/right orbital scaling range = ', & + minval(left_scale), maxval(left_scale) + endif + else + print *, ' TC-SCF left/right orbital balancing skipped, status = ', info + endif + +END_PROVIDER diff --git a/plugins/local/tc_scf/diis_history.f90 b/plugins/local/tc_scf/diis_history.f90 new file mode 100644 index 00000000..a466f772 --- /dev/null +++ b/plugins/local/tc_scf/diis_history.f90 @@ -0,0 +1,369 @@ +module diis_history_module + + implicit none + private + + integer, parameter, public :: diis_success = 0 + integer, parameter, public :: diis_bad_state = 1 + integer, parameter, public :: diis_bad_shape = 2 + integer, parameter, public :: diis_ill_conditioned = 3 + integer, parameter, public :: diis_lapack_failure = 4 + + type, public :: diis_history + private + integer :: matrix_size = 0 + integer :: capacity = 0 + integer :: count = 0 + integer :: next_slot = 1 + double precision, allocatable :: matrix(:,:,:) + double precision, allocatable :: error(:,:,:) + end type diis_history + + public :: diis_initialize + public :: diis_reset + public :: diis_push + public :: diis_count + public :: diis_next_slot + public :: diis_logical_slots + public :: diis_get_entry + public :: diis_build_gram + public :: diis_solve_coefficients + public :: diis_combine_matrix + public :: diis_extrapolate + + interface + subroutine dgetrf(m, n, a, lda, ipiv, info) + integer, intent(in) :: m, n, lda + double precision, intent(inout) :: a(lda,*) + integer, intent(out) :: ipiv(*), info + end subroutine dgetrf + + subroutine dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info) + character, intent(in) :: norm + integer, intent(in) :: n, lda + double precision, intent(in) :: a(lda,*), anorm + double precision, intent(out) :: rcond, work(*) + integer, intent(out) :: iwork(*), info + end subroutine dgecon + + subroutine dgesv(n, nrhs, a, lda, ipiv, b, ldb, info) + integer, intent(in) :: n, nrhs, lda, ldb + double precision, intent(inout) :: a(lda,*), b(ldb,*) + integer, intent(out) :: ipiv(*), info + end subroutine dgesv + end interface + +contains + + subroutine diis_initialize(history, matrix_size, capacity, info) + + implicit none + + type(diis_history), intent(out) :: history + integer, intent(in) :: matrix_size, capacity + integer, intent(out) :: info + + if((matrix_size < 1) .or. (capacity < 1)) then + info = diis_bad_shape + return + endif + + allocate(history%matrix(matrix_size,matrix_size,capacity)) + allocate(history%error(matrix_size,matrix_size,capacity)) + + history%matrix_size = matrix_size + history%capacity = capacity + history%count = 0 + history%next_slot = 1 + history%matrix = 0.d0 + history%error = 0.d0 + info = diis_success + + end subroutine diis_initialize + + + pure subroutine diis_reset(history) + + implicit none + + type(diis_history), intent(inout) :: history + + history%count = 0 + history%next_slot = 1 + + end subroutine diis_reset + + + pure subroutine diis_push(history, matrix, error, inserted_slot, info) + + implicit none + + type(diis_history), intent(inout) :: history + double precision, intent(in) :: matrix(:,:), error(:,:) + integer, intent(out) :: inserted_slot, info + + inserted_slot = 0 + if(.not. allocated(history%matrix)) then + info = diis_bad_state + return + endif + if( (size(matrix,1) /= history%matrix_size) .or. & + (size(matrix,2) /= history%matrix_size) .or. & + (size(error,1) /= history%matrix_size) .or. & + (size(error,2) /= history%matrix_size) ) then + info = diis_bad_shape + return + endif + + inserted_slot = history%next_slot + history%matrix(:,:,inserted_slot) = matrix(:,:) + history%error(:,:,inserted_slot) = error(:,:) + + history%count = min(history%count + 1, history%capacity) + history%next_slot = modulo(inserted_slot, history%capacity) + 1 + info = diis_success + + end subroutine diis_push + + + pure integer function diis_count(history) + + implicit none + + type(diis_history), intent(in) :: history + + diis_count = history%count + + end function diis_count + + + pure integer function diis_next_slot(history) + + implicit none + + type(diis_history), intent(in) :: history + + diis_next_slot = history%next_slot + + end function diis_next_slot + + + pure function diis_logical_slots(history) result(slots) + + implicit none + + type(diis_history), intent(in) :: history + integer, allocatable :: slots(:) + integer :: i, physical_slot + + allocate(slots(history%count)) + if(history%count == 0) return + + ! next_slot points to the oldest entry once the circular buffer is full. + physical_slot = modulo( history%next_slot - history%count - 1, & + history%capacity ) + 1 + do i = 1, history%count + slots(i) = physical_slot + physical_slot = modulo(physical_slot, history%capacity) + 1 + enddo + + end function diis_logical_slots + + + pure subroutine diis_get_entry(history, logical_index, matrix, error, info) + + implicit none + + type(diis_history), intent(in) :: history + integer, intent(in) :: logical_index + double precision, intent(out) :: matrix(:,:), error(:,:) + integer, intent(out) :: info + integer, allocatable :: slots(:) + integer :: physical_slot + + if( (logical_index < 1) .or. & + (logical_index > history%count) ) then + info = diis_bad_state + return + endif + if( (size(matrix,1) /= history%matrix_size) .or. & + (size(matrix,2) /= history%matrix_size) .or. & + (size(error,1) /= history%matrix_size) .or. & + (size(error,2) /= history%matrix_size) ) then + info = diis_bad_shape + return + endif + + slots = diis_logical_slots(history) + physical_slot = slots(logical_index) + matrix(:,:) = history%matrix(:,:,physical_slot) + error(:,:) = history%error(:,:,physical_slot) + info = diis_success + + end subroutine diis_get_entry + + + pure subroutine diis_build_gram(history, gram, info) + + implicit none + + type(diis_history), intent(in) :: history + double precision, allocatable, intent(out) :: gram(:,:) + integer, intent(out) :: info + integer, allocatable :: slots(:) + integer :: i, j + + if(history%count < 1) then + allocate(gram(0,0)) + info = diis_bad_state + return + endif + + slots = diis_logical_slots(history) + allocate(gram(history%count,history%count)) + do j = 1, history%count + do i = 1, history%count + gram(i,j) = sum( history%error(:,:,slots(i)) * & + history%error(:,:,slots(j)) ) + enddo + enddo + info = diis_success + + end subroutine diis_build_gram + + + subroutine diis_solve_coefficients(gram, coefficients, rcond, info, rcond_min) + + implicit none + + double precision, intent(in) :: gram(:,:) + double precision, allocatable, intent(out) :: coefficients(:) + double precision, intent(out) :: rcond + integer, intent(out) :: info + double precision, intent(in), optional :: rcond_min + double precision, allocatable :: augmented(:,:), factorized(:,:) + double precision, allocatable :: rhs(:), work(:) + integer, allocatable :: ipiv(:), iwork(:) + integer :: i, lapack_info, n, system_size + double precision :: anorm, minimum_rcond + + n = size(gram,1) + allocate(coefficients(n)) + coefficients = 0.d0 + rcond = 0.d0 + + if((n < 1) .or. (size(gram,2) /= n)) then + info = diis_bad_shape + return + endif + + minimum_rcond = 1.d-14 + if(present(rcond_min)) minimum_rcond = rcond_min + + system_size = n + 1 + allocate(augmented(system_size,system_size)) + allocate(factorized(system_size,system_size)) + allocate(rhs(system_size), ipiv(system_size)) + allocate(work(4*system_size), iwork(system_size)) + + augmented = 0.d0 + augmented(1:n,1:n) = gram(:,:) + augmented(1:n,system_size) = -1.d0 + augmented(system_size,1:n) = -1.d0 + rhs = 0.d0 + rhs(system_size) = -1.d0 + + anorm = 0.d0 + do i = 1, system_size + anorm = max(anorm, sum(abs(augmented(:,i)))) + enddo + + factorized(:,:) = augmented(:,:) + call dgetrf( system_size, system_size, factorized, system_size, & + ipiv, lapack_info ) + if(lapack_info /= 0) then + info = diis_lapack_failure + return + endif + + call dgecon( '1', system_size, factorized, system_size, anorm, & + rcond, work, iwork, lapack_info ) + if(lapack_info /= 0) then + info = diis_lapack_failure + return + endif + if(rcond < minimum_rcond) then + info = diis_ill_conditioned + return + endif + + call dgesv( system_size, 1, augmented, system_size, ipiv, rhs, & + system_size, lapack_info ) + if(lapack_info /= 0) then + info = diis_lapack_failure + return + endif + + coefficients(:) = rhs(1:n) + info = diis_success + + end subroutine diis_solve_coefficients + + + pure subroutine diis_combine_matrix(history, coefficients, matrix, info) + + implicit none + + type(diis_history), intent(in) :: history + double precision, intent(in) :: coefficients(:) + double precision, intent(out) :: matrix(:,:) + integer, intent(out) :: info + integer, allocatable :: slots(:) + integer :: i + + if( (size(coefficients) /= history%count) .or. & + (size(matrix,1) /= history%matrix_size) .or. & + (size(matrix,2) /= history%matrix_size) ) then + info = diis_bad_shape + return + endif + + slots = diis_logical_slots(history) + matrix = 0.d0 + do i = 1, history%count + matrix(:,:) = matrix(:,:) + coefficients(i) * & + history%matrix(:,:,slots(i)) + enddo + info = diis_success + + end subroutine diis_combine_matrix + + + subroutine diis_extrapolate(history, matrix, coefficients, rcond, info, rcond_min) + + implicit none + + type(diis_history), intent(in) :: history + double precision, intent(out) :: matrix(:,:) + double precision, allocatable, intent(out) :: coefficients(:) + double precision, intent(out) :: rcond + integer, intent(out) :: info + double precision, intent(in), optional :: rcond_min + double precision, allocatable :: gram(:,:) + + call diis_build_gram(history, gram, info) + if(info /= diis_success) return + + if(present(rcond_min)) then + call diis_solve_coefficients( gram, coefficients, rcond, & + info, rcond_min ) + else + call diis_solve_coefficients( gram, coefficients, rcond, info ) + endif + if(info /= diis_success) return + + call diis_combine_matrix(history, coefficients, matrix, info) + + end subroutine diis_extrapolate + +end module diis_history_module diff --git a/plugins/local/tc_scf/diis_history_qp_test.irp.f b/plugins/local/tc_scf/diis_history_qp_test.irp.f new file mode 100644 index 00000000..4edf2ff4 --- /dev/null +++ b/plugins/local/tc_scf/diis_history_qp_test.irp.f @@ -0,0 +1,64 @@ +! --- + +program diis_history_qp_test + + use diis_history_module + + implicit none + + type(diis_history) :: history + double precision :: fock(2,2), error(2,2) + integer :: expected, info, inserted_slot, iteration + + call diis_initialize(history, 2, 3, info) + if(info /= diis_success) then + stop 'QP DIIS test: initialization failed' + endif + + do iteration = 1, 5 + fock(:,:) = dble(iteration) + error(:,:) = -dble(iteration) + call diis_push(history, fock, error, inserted_slot, info) + if(info /= diis_success) then + stop 'QP DIIS test: insertion failed' + endif + expected = modulo(iteration - 1, 3) + 1 + if(inserted_slot /= expected) then + stop 'QP DIIS test: wrong physical insertion slot' + endif + enddo + + if(diis_count(history) /= 3) then + stop 'QP DIIS test: wrong count after wraparound' + endif + if(diis_next_slot(history) /= 3) then + stop 'QP DIIS test: wrong next slot after wraparound' + endif + + do iteration = 1, 3 + call diis_get_entry(history, iteration, fock, error, info) + if(info /= diis_success) then + stop 'QP DIIS test: logical retrieval failed' + endif + expected = iteration + 2 + if(fock(1,1) /= dble(expected)) then + stop 'QP DIIS test: wrong logical Fock chronology' + endif + if(error(1,1) /= -dble(expected)) then + stop 'QP DIIS test: Fock/error pair separated' + endif + enddo + + call diis_reset(history) + if(diis_count(history) /= 0) then + stop 'QP DIIS test: reset did not clear logical history' + endif + if(diis_next_slot(history) /= 1) then + stop 'QP DIIS test: reset did not restore first slot' + endif + + print *, 'PASS: QP/IRPF90 TC-SCF DIIS history integration test' + +end + +! --- diff --git a/plugins/local/tc_scf/diis_tcscf.irp.f b/plugins/local/tc_scf/diis_tcscf.irp.f index ccc8eb15..b9e9491c 100644 --- a/plugins/local/tc_scf/diis_tcscf.irp.f +++ b/plugins/local/tc_scf/diis_tcscf.irp.f @@ -145,3 +145,43 @@ ! --- + +subroutine tc_orthogonalize_span(coef, x) + implicit none + double precision, intent(in) :: coef(ao_num,mo_num) + double precision, intent(out) :: x(ao_num,mo_num) + double precision :: scale + double precision, allocatable :: gram(:,:) + integer :: i, info + + ! Strip arbitrary column scales before forming the overlap matrix. + do i=1,mo_num + scale = maxval(abs(coef(:,i))) + if (scale == 0.d0) error stop 'Empty TC orbital column' + x(:,i) = coef(:,i)/scale + enddo + allocate(gram(mo_num,mo_num)) + gram = matmul(transpose(x),matmul(ao_overlap,x)) + call dpotrf('U',mo_num,gram,mo_num,info) + if (info /= 0) error stop 'Cannot orthonormalize truncated TC orbital space' + call dtrsm('R','U','N','N',ao_num,mo_num,1.d0,gram,mo_num,x,ao_num) +end + +subroutine tc_ao_residual_norm(x_left, x_right, residual) + use ieee_arithmetic, only: ieee_is_finite + implicit none + double precision, intent(in) :: x_left(ao_num,mo_num), x_right(ao_num,mo_num) + double precision, intent(out) :: residual + double precision, allocatable :: projected(:,:), singular(:), work(:) + double precision :: unused_u(1), unused_v(1) + integer :: info + + allocate(projected(mo_num,mo_num), singular(mo_num), work(5*mo_num)) + projected = matmul(transpose(x_left),matmul(FQS_SQF_ao,x_right)) + if (.not.all(ieee_is_finite(projected))) error stop 'Nonfinite AO residual' + ! Only the singular values are needed; LAPACK returns the largest first. + call dgesvd('N','N',mo_num,mo_num,projected,mo_num,singular, & + unused_u,1,unused_v,1,work,size(work),info) + if (info /= 0) error stop 'AO residual singular value calculation failed' + residual = singular(1) +end diff --git a/plugins/local/tc_scf/fock_tc_core.irp.f b/plugins/local/tc_scf/fock_tc_core.irp.f index 4f411ce6..055887af 100644 --- a/plugins/local/tc_scf/fock_tc_core.irp.f +++ b/plugins/local/tc_scf/fock_tc_core.irp.f @@ -140,22 +140,24 @@ END_DOC integer :: m,n,l,s,j + integer :: cholesky_ao_num_4 double precision :: integral double precision, allocatable :: X(:), X2(:,:,:,:), X3(:,:,:,:) allocate (X(cholesky_ao_num)) + cholesky_ao_num_4 = int(cholesky_ao_num, 4) ! X(j) = \sum_{mn} TCSCF_bi_ort_core_dm_ao(m,n) * cholesky_ao(m,n,j) - call dgemm('T','N',cholesky_ao_num,1,ao_num*ao_num,1.d0, & + call dgemm('T','N',cholesky_ao_num_4,1,ao_num*ao_num,1.d0, & cholesky_ao, ao_num*ao_num, & TCSCF_bi_ort_core_dm_ao, ao_num*ao_num,0.d0, & - X, cholesky_ao_num) + X, cholesky_ao_num_4) ! ! ao_two_e_core_integral_chol(m,n) = \sum_{j} cholesky_ao(m,n,j) * X(j) - call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num, 1.d0, & + call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num_4, 1.d0, & cholesky_ao, ao_num*ao_num, & - X, cholesky_ao_num, 0.d0, & + X, cholesky_ao_num_4, 0.d0, & ao_two_e_core_integral_chol, ao_num*ao_num) deallocate(X) @@ -186,7 +188,7 @@ do iblock=1,cholesky_ao_num,block_size - call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size),ao_num, 1.d0, & + call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size),ao_num, 1.d0, & TCSCF_bi_ort_core_dm_ao, ao_num, & cholesky_ao(1,1,iblock), ao_num, 0.d0, & X2(1,1,1,1), ao_num) @@ -199,7 +201,7 @@ enddo enddo - call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size), -1.d0, & + call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size), -1.d0, & cholesky_ao(1,1,iblock), ao_num, & X3(1,1,1,1), ao_num*block_size, 1.d0, & ao_two_e_core_integral_chol, ao_num) @@ -220,22 +222,24 @@ END_DOC integer :: m,n,l,s,j + integer :: cholesky_ao_num_4 double precision :: integral double precision, allocatable :: X(:), X2(:,:,:,:), X3(:,:,:,:) allocate (X(cholesky_ao_num)) + cholesky_ao_num_4 = int(cholesky_ao_num, 4) ! X(j) = \sum_{mn} SCF_density_matrix_ao(m,n) * cholesky_ao(m,n,j) - call dgemm('T','N',cholesky_ao_num,1,ao_num*ao_num,1.d0, & + call dgemm('T','N',cholesky_ao_num_4,1,ao_num*ao_num,1.d0, & cholesky_ao, ao_num*ao_num, & TCSCF_bi_ort_valence_dm_ao_full, ao_num*ao_num,0.d0, & - X, cholesky_ao_num) + X, cholesky_ao_num_4) ! ! ao_two_e_integral_alpha(m,n) = \sum_{j} cholesky_ao(m,n,j) * X(j) - call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num, 1.d0, & + call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num_4, 1.d0, & cholesky_ao, ao_num*ao_num, & - X, cholesky_ao_num, 0.d0, & + X, cholesky_ao_num_4, 0.d0, & ao_two_e_valence_integral_alpha_chol, ao_num*ao_num) deallocate(X) @@ -271,13 +275,13 @@ do iblock=1,cholesky_ao_num,block_size - call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size),ao_num, 1.d0, & + call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size),ao_num, 1.d0, & TCSCF_bi_ort_valence_dm_ao_alpha, ao_num, & cholesky_ao(1,1,iblock), ao_num, 0.d0, & X2(1,1,1,1), ao_num) if (elec_alpha_num > elec_beta_num) then - call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size),ao_num, 1.d0, & + call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size),ao_num, 1.d0, & TCSCF_bi_ort_valence_dm_ao_beta, ao_num, & cholesky_ao(1,1,iblock), ao_num, 0.d0, & X2(1,1,1,2), ao_num) @@ -302,13 +306,13 @@ enddo endif - call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size), -1.d0, & + call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size), -1.d0, & cholesky_ao(1,1,iblock), ao_num, & X3(1,1,1,1), ao_num*block_size, 1.d0, & ao_two_e_valence_integral_alpha_chol, ao_num) if (elec_alpha_num > elec_beta_num) then - call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size), -1.d0, & + call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size), -1.d0, & cholesky_ao(1,1,iblock), ao_num, & X3(1,1,1,2), ao_num*block_size, 1.d0, & ao_two_e_valence_integral_beta_chol, ao_num) diff --git a/plugins/local/tc_scf/fock_tc_mo_tot.irp.f b/plugins/local/tc_scf/fock_tc_mo_tot.irp.f index ace61fe7..870b64d7 100644 --- a/plugins/local/tc_scf/fock_tc_mo_tot.irp.f +++ b/plugins/local/tc_scf/fock_tc_mo_tot.irp.f @@ -26,6 +26,7 @@ double precision :: t0, t1 PROVIDE Fock_matrix_tc_mo_beta Fock_matrix_tc_mo_alpha + ! Each spin Fock matrix already includes its explicit three-electron term. if (all_shells_closed) then Fock_matrix_tc_mo_tot = Fock_matrix_tc_mo_alpha else @@ -81,36 +82,6 @@ enddo endif - if(three_body_h_tc) then - - PROVIDE fock_a_tot_3e_bi_orth fock_b_tot_3e_bi_orth - - ! C-O - do j = 1, elec_beta_num - do i = elec_beta_num+1, elec_alpha_num - Fock_matrix_tc_mo_tot(i,j) += 0.5d0*(fock_a_tot_3e_bi_orth(i,j) + fock_b_tot_3e_bi_orth(i,j)) - Fock_matrix_tc_mo_tot(j,i) += 0.5d0*(fock_a_tot_3e_bi_orth(j,i) + fock_b_tot_3e_bi_orth(j,i)) - enddo - enddo - ! C-V - do j = 1, elec_beta_num - do i = elec_alpha_num+1, mo_num - Fock_matrix_tc_mo_tot(i,j) += 0.5d0*(fock_a_tot_3e_bi_orth(i,j) + fock_b_tot_3e_bi_orth(i,j)) - Fock_matrix_tc_mo_tot(j,i) += 0.5d0*(fock_a_tot_3e_bi_orth(j,i) + fock_b_tot_3e_bi_orth(j,i)) - enddo - enddo - ! O-V - do j = elec_beta_num+1, elec_alpha_num - do i = elec_alpha_num+1, mo_num - Fock_matrix_tc_mo_tot(i,j) += 0.5d0*(fock_a_tot_3e_bi_orth(i,j) + fock_b_tot_3e_bi_orth(i,j)) - Fock_matrix_tc_mo_tot(j,i) += 0.5d0*(fock_a_tot_3e_bi_orth(j,i) + fock_b_tot_3e_bi_orth(j,i)) - enddo - enddo - endif - - - - if(frozen_orb_scf)then integer :: iorb,jorb do i = 1, n_core_orb diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 04aab8e8..fb856f4e 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -1,48 +1,65 @@ ! --- -! TODO -! level shift of SCF is well adapted -! for 0.5 x F -! - subroutine rh_tcscf_diis() - implicit none + use qp_json, only: json_add + use diis_history_module - integer :: i, j, it - integer :: dim_DIIS, index_dim_DIIS - logical :: converged - double precision :: etc_tot, etc_1e, etc_2e, etc_3e, e_save, e_delta - double precision :: tc_grad, g_save, g_delta, g_delta_th - double precision :: level_shift_save, rate_th - double precision :: t0, t1 - double precision :: er_DIIS, er_delta, er_save, er_delta_th - double precision, allocatable :: F_DIIS(:,:,:), E_DIIS(:,:,:) - double precision, allocatable :: mo_r_coef_save(:,:), mo_l_coef_save(:,:) + implicit none - logical, external :: qp_stop + type(diis_history) :: history + integer :: info, inserted_slot, it + integer :: history_count + integer, parameter :: max_level_shift_tries = 5 + integer :: n_retry + logical :: converged + double precision :: etc_tot, etc_1e, etc_2e, etc_3e + double precision :: e_save, e_delta + double precision :: level_shift_save, rate_th + double precision :: t0, t1 + double precision :: er_DIIS, er_delta, er_save + double precision :: trial_residual + double precision :: rcond + double precision, allocatable :: coefficients(:) + double precision, allocatable :: fock_before_diis(:,:) + double precision, allocatable :: fock_extrapolated(:,:) + double precision, allocatable :: mo_r_coef_save(:,:) + double precision, allocatable :: mo_l_coef_save(:,:) + + double precision, allocatable :: x_left(:,:), x_right(:,:) + double precision :: ao_residual + logical, external :: qp_stop PROVIDE level_shift_TCSCF PROVIDE mo_l_coef mo_r_coef - it = 0 - e_save = 0.d0 - dim_DIIS = 0 - g_delta_th = 1d0 - er_delta_th = 1d0 - rate_th = 0.1d0 + it = 0 + e_save = 0.d0 + rate_th = 0.1d0 - allocate(mo_r_coef_save(ao_num,mo_num), mo_l_coef_save(ao_num,mo_num)) + allocate(mo_r_coef_save(ao_num,mo_num)) + allocate(mo_l_coef_save(ao_num,mo_num)) + allocate(fock_before_diis(ao_num,ao_num)) + allocate(fock_extrapolated(ao_num,ao_num)) mo_l_coef_save = 0.d0 mo_r_coef_save = 0.d0 - allocate(F_DIIS(ao_num,ao_num,max_dim_DIIS_TCSCF), E_DIIS(ao_num,ao_num,max_dim_DIIS_TCSCF)) - F_DIIS = 0.d0 - E_DIIS = 0.d0 + allocate(x_left(ao_num,mo_num), x_right(ao_num,mo_num)) + if (mo_num == ao_ortho_canonical_num) then + x_left = ao_ortho_canonical_coef(:,1:mo_num) + x_right = x_left + else + ! A truncated MO calculation tests only the supplied left/right spaces. + call tc_orthogonalize_span(mo_l_coef, x_left) + call tc_orthogonalize_span(mo_r_coef, x_right) + endif - call write_time(6) + call diis_initialize(history, ao_num, max_dim_DIIS_TCSCF, info) + if(info /= diis_success) then + stop 'TC-SCF DIIS history initialization failed' + endif - ! --- + call write_time(6) write(6, '(A4,1X, A16,1X, A16,1X, A16,1X, A16,1X, A16,1X, A16,1X, A16,1X, A4, 1X, A8)') & '====', '================', '================', '================', '================', '================' & @@ -54,36 +71,32 @@ subroutine rh_tcscf_diis() '====', '================', '================', '================', '================', '================' & , '================', '================', '====', '========' - - ! first iteration (HF orbitals) call wall_time(t0) etc_tot = TC_HF_energy etc_1e = TC_HF_one_e_energy etc_2e = TC_HF_two_e_energy etc_3e = TC_HF_three_e_energy - !tc_grad = grad_non_hermit er_DIIS = maxval(abs(FQS_SQF_mo)) e_delta = dabs(etc_tot - e_save) e_save = etc_tot - !g_save = tc_grad er_save = er_DIIS + history_count = diis_count(history) call wall_time(t1) write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & - it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, dim_DIIS, (t1-t0)/60.d0 + it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, history_count, (t1-t0)/60.d0 - ! --- + call tc_ao_residual_norm(x_left, x_right, ao_residual) + write(6,'(A,I5,1X,ES22.14)') ' TC-SCF AO residual ', it, ao_residual PROVIDE FQS_SQF_ao Fock_matrix_tc_ao_tot converged = .false. call ezfio_set_tc_scf_converged_tcscf(converged) - !do while((tc_grad .gt. dsqrt(thresh_tcscf)) .and. (er_DIIS .gt. dsqrt(thresh_tcscf))) do while(.not. converged) -! call print_angles_tc() call wall_time(t0) it += 1 @@ -92,97 +105,112 @@ subroutine rh_tcscf_diis() exit endif - dim_DIIS = min(dim_DIIS+1, max_dim_DIIS_TCSCF) - - ! --- + ! This snapshot is independent of whether the current pair is inserted. + fock_before_diis(:,:) = Fock_matrix_tc_ao_tot(:,:) + ! A level-shift retry must restart from the orbitals entering this step. + mo_l_coef_save(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) + mo_r_coef_save(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) + level_shift_save = level_shift_TCSCF + inserted_slot = 0 + rcond = 0.d0 if(dabs(e_delta) > 1.d-12) then + call diis_push( history, Fock_matrix_tc_ao_tot, FQS_SQF_ao, & + inserted_slot, info ) + if(info /= diis_success) then + stop 'TC-SCF DIIS history insertion failed' + endif - index_dim_DIIS = mod(dim_DIIS-1, max_dim_DIIS_TCSCF) + 1 - do j = 1, ao_num - do i = 1, ao_num - F_DIIS(i,j,index_dim_DIIS) = Fock_matrix_tc_ao_tot(i,j) - E_DIIS(i,j,index_dim_DIIS) = FQS_SQF_ao (i,j) - enddo - enddo - - call extrapolate_TC_Fock_matrix(E_DIIS, F_DIIS, Fock_matrix_tc_ao_tot, size(Fock_matrix_tc_ao_tot, 1), it, dim_DIIS) - - call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, size(Fock_matrix_tc_ao_tot, 1) & - , Fock_matrix_tc_mo_tot, size(Fock_matrix_tc_mo_tot, 1) ) - TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot + call diis_extrapolate( history, fock_extrapolated, & + coefficients, rcond, info ) + if(info == diis_success) then + Fock_matrix_tc_ao_tot(:,:) = fock_extrapolated(:,:) + call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, & + size(Fock_matrix_tc_ao_tot, 1), & + Fock_matrix_tc_mo_tot, & + size(Fock_matrix_tc_mo_tot, 1) ) + TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot + else + ! A rejected solve keeps the unextrapolated Fock and starts fresh. + call diis_reset(history) + print *, ' TC-DIIS history reset after rejected solve, info = ', info + print *, ' TC-DIIS reciprocal condition estimate = ', rcond + endif endif - ! --- - - mo_l_coef(1:ao_num,1:mo_num) = fock_tc_leigvec_ao(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = fock_tc_reigvec_ao(1:ao_num,1:mo_num) - !call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) - !call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef - ! --- - - !g_delta = grad_non_hermit - g_save er_delta = maxval(abs(FQS_SQF_mo)) - er_save if((er_delta > rate_th * er_save) .and. (it > 1)) then - - Fock_matrix_tc_ao_tot(1:ao_num,1:ao_num) = F_DIIS(1:ao_num,1:ao_num,index_dim_DIIS) - call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, size(Fock_matrix_tc_ao_tot, 1) & - , Fock_matrix_tc_mo_tot, size(Fock_matrix_tc_mo_tot, 1) ) + Fock_matrix_tc_ao_tot(1:ao_num,1:ao_num) = & + fock_before_diis(1:ao_num,1:ao_num) + call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, & + size(Fock_matrix_tc_ao_tot, 1), & + Fock_matrix_tc_mo_tot, & + size(Fock_matrix_tc_mo_tot, 1) ) TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot - mo_l_coef(1:ao_num,1:mo_num) = fock_tc_leigvec_ao(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = fock_tc_reigvec_ao(1:ao_num,1:mo_num) - !call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) - !call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef - endif - ! --- - - !g_delta = grad_non_hermit - g_save er_delta = maxval(abs(FQS_SQF_mo)) - er_save - - mo_l_coef_save(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) - mo_r_coef_save(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) - - do while((er_delta > rate_th * er_save) .and. (it > 1)) + n_retry = 0 + if((er_delta > rate_th * er_save) .and. (it > 1)) then print *, ' big or bad step ' - !print *, g_delta , rate_th * g_save print *, er_delta, rate_th * er_save - mo_l_coef(1:ao_num,1:mo_num) = mo_l_coef_save(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = mo_r_coef_save(1:ao_num,1:mo_num) - if(level_shift_TCSCF <= .1d0) then - level_shift_TCSCF = 1.d0 - else - level_shift_TCSCF = level_shift_TCSCF * 3.0d0 - endif - TOUCH mo_l_coef mo_r_coef level_shift_TCSCF - - mo_l_coef(1:ao_num,1:mo_num) = fock_tc_leigvec_ao(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = fock_tc_reigvec_ao(1:ao_num,1:mo_num) - !call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) - !call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) - TOUCH mo_l_coef mo_r_coef - - !g_delta = grad_non_hermit - g_save - er_delta = maxval(abs(FQS_SQF_mo)) - er_save + ! Discard entries belonging to the step that just failed, once. + call diis_reset(history) + + ! Retry from the incoming orbitals. Keep a trial only if it improves + ! their residual; the unextrapolated fallback already failed this test. + do while(n_retry < max_level_shift_tries) + n_retry += 1 + + mo_l_coef(1:ao_num,1:mo_num) = & + mo_l_coef_save(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + mo_r_coef_save(1:ao_num,1:mo_num) + if(level_shift_TCSCF <= .1d0) then + level_shift_TCSCF = 1.d0 + else + level_shift_TCSCF = level_shift_TCSCF * 3.d0 + endif + TOUCH mo_l_coef mo_r_coef level_shift_TCSCF + + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) + TOUCH mo_l_coef mo_r_coef + + trial_residual = maxval(abs(FQS_SQF_mo)) + if(trial_residual < er_save) exit + enddo - if(level_shift_TCSCF - level_shift_save > 40.d0) then - level_shift_TCSCF = level_shift_save * 4.d0 - SOFT_TOUCH level_shift_TCSCF - exit + if(.not. (trial_residual < er_save)) then + mo_l_coef(:,:) = mo_l_coef_save(:,:) + mo_r_coef(:,:) = mo_r_coef_save(:,:) + TOUCH mo_l_coef mo_r_coef + print *, ' TC-SCF retries did not improve the residual; restored incoming orbitals' endif + endif - dim_DIIS = 0 - enddo - - ! --- - + ! Retries use temporary shifts. Keep the existing per-iteration shift + ! decay, but do not let a trial shift leak into the next SCF step. + if(n_retry > 0) then + level_shift_TCSCF = level_shift_save + SOFT_TOUCH level_shift_TCSCF + endif level_shift_TCSCF = level_shift_TCSCF * 0.5d0 SOFT_TOUCH level_shift_TCSCF @@ -190,82 +218,65 @@ subroutine rh_tcscf_diis() etc_1e = TC_HF_one_e_energy etc_2e = TC_HF_two_e_energy etc_3e = TC_HF_three_e_energy - !tc_grad = grad_non_hermit - er_DIIS = maxval(abs(FQS_SQF_mo)) - e_delta = dabs(etc_tot - e_save) - !g_delta = tc_grad - g_save + er_DIIS = maxval(abs(FQS_SQF_mo)) + e_delta = dabs(etc_tot - e_save) er_delta = er_DIIS - er_save - + e_save = etc_tot - !g_save = tc_grad - level_shift_save = level_shift_TCSCF er_save = er_DIIS - !g_delta_th = dabs(tc_grad) ! g_delta) - er_delta_th = dabs(er_DIIS) !er_delta) - - converged = er_DIIS .lt. dsqrt(thresh_tcscf) + call tc_ao_residual_norm(x_left, x_right, ao_residual) + write(6,'(A,I5,1X,ES22.14)') ' TC-SCF AO residual ', it, ao_residual + converged = ao_residual .lt. dsqrt(thresh_tcscf) + history_count = diis_count(history) call wall_time(t1) - !write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & - ! it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, tc_grad, er_DIIS, level_shift_tcscf, dim_DIIS, (t1-t0)/60.d0 write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & - it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, dim_DIIS, (t1-t0)/60.d0 - - -! Write data in JSON file + it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, history_count, (t1-t0)/60.d0 call lock_io - if (it == 1) then - write(json_unit, json_dict_uopen_fmt) - else - write(json_unit, json_dict_close_uopen_fmt) - endif - write(json_unit, json_int_fmt) ' iteration ', it - write(json_unit, json_real_fmt) ' SCF TC Energy ', etc_tot - write(json_unit, json_real_fmt) ' E(1e) ', etc_1e - write(json_unit, json_real_fmt) ' E(2e) ', etc_2e - write(json_unit, json_real_fmt) ' E(3e) ', etc_3e - write(json_unit, json_real_fmt) ' delta Energy ', e_delta - write(json_unit, json_real_fmt) ' DIIS error ', er_DIIS - write(json_unit, json_real_fmt) ' level_shift ', level_shift_tcscf - write(json_unit, json_int_fmtx) ' DIIS ', dim_DIIS - write(json_unit, json_real_fmt) ' Wall time (min)', (t1-t0)/60.d0 + call json_add('/results/tc_scf/iteration', it) + call json_add('/results/tc_scf/scf_tc_energy', etc_tot) + call json_add('/results/tc_scf/energy_1e', etc_1e) + call json_add('/results/tc_scf/energy_2e', etc_2e) + call json_add('/results/tc_scf/energy_3e', etc_3e) + call json_add('/results/tc_scf/ao_residual', ao_residual) + call json_add('/results/tc_scf/delta_energy', e_delta) + call json_add('/results/tc_scf/diis_error', er_DIIS) + call json_add('/results/tc_scf/level_shift', level_shift_tcscf) + call json_add('/results/tc_scf/diis_size', history_count) + call json_add('/results/tc_scf/wall_time_min', (t1-t0)/60.d0) call unlock_io if(er_delta .lt. 0.d0) then call ezfio_set_tc_scf_tcscf_energy(etc_tot) call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) - write(json_unit, json_true_fmt) 'saved' + call json_add('/results/tc_scf/saved', .true.) else - write(json_unit, json_false_fmt) 'saved' + call json_add('/results/tc_scf/saved', .false.) endif call lock_io if(converged) then - write(json_unit, json_true_fmtx) 'converged' + call json_add('/results/tc_scf/converged', .true.) call ezfio_set_tc_scf_converged_tcscf(converged) else - write(json_unit, json_false_fmtx) 'converged' + call json_add('/results/tc_scf/converged', .false.) endif call unlock_io if(qp_stop()) exit enddo - write(json_unit, json_dict_close_fmtx) - - ! --- - - if(converged)then - print *, ' TCSCF DIIS converged !' + if(converged) then + print *, ' TCSCF DIIS converged !' else - print*,'Warning, TCSCF DIIS did not converge ...' + print *, 'Warning, TCSCF DIIS did not converge ...' endif - !call print_energy_and_mos(good_angles) call write_time(6) - deallocate(mo_r_coef_save, mo_l_coef_save, F_DIIS, E_DIIS) + deallocate(mo_r_coef_save, mo_l_coef_save) + deallocate(fock_before_diis, fock_extrapolated) call ezfio_set_tc_scf_tcscf_energy(TC_HF_energy) call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) @@ -275,130 +286,3 @@ subroutine rh_tcscf_diis() ! --- -subroutine extrapolate_TC_Fock_matrix(E_DIIS, F_DIIS, F_ao, size_F_ao, it, dim_DIIS) - - BEGIN_DOC - ! - ! Compute the extrapolated Fock matrix using the DIIS procedure - ! - ! e = \sum_i c_i e_i and \sum_i c_i = 1 - ! ==> lagrange multiplier with L = |e|^2 - \lambda (\sum_i c_i = 1) - ! - END_DOC - - implicit none - - integer, intent(in) :: it, size_F_ao - integer, intent(inout) :: dim_DIIS - double precision, intent(in) :: F_DIIS(ao_num,ao_num,dim_DIIS) - double precision, intent(in) :: E_DIIS(ao_num,ao_num,dim_DIIS) - double precision, intent(inout) :: F_ao(size_F_ao,ao_num) - - double precision, allocatable :: B_matrix_DIIS(:,:), X_vector_DIIS(:), C_vector_DIIS(:) - - integer :: i, j, k, l, i_DIIS, j_DIIS - integer :: lwork - double precision :: rcond, ferr, berr - integer, allocatable :: iwork(:) - double precision, allocatable :: scratch(:,:) - - if(dim_DIIS < 1) then - return - endif - - allocate( B_matrix_DIIS(dim_DIIS+1,dim_DIIS+1), X_vector_DIIS(dim_DIIS+1) & - , C_vector_DIIS(dim_DIIS+1), scratch(ao_num,ao_num) ) - - ! Compute the matrices B and X - B_matrix_DIIS(:,:) = 0.d0 - do j = 1, dim_DIIS - j_DIIS = min(dim_DIIS, mod(it-j, max_dim_DIIS_TCSCF)+1) - - do i = 1, dim_DIIS - i_DIIS = min(dim_DIIS, mod(it-i, max_dim_DIIS_TCSCF)+1) - - ! Compute product of two errors vectors - do l = 1, ao_num - do k = 1, ao_num - B_matrix_DIIS(i,j) = B_matrix_DIIS(i,j) + E_DIIS(k,l,i_DIIS) * E_DIIS(k,l,j_DIIS) - enddo - enddo - - enddo - enddo - - ! Pad B matrix and build the X matrix - - C_vector_DIIS(:) = 0.d0 - do i = 1, dim_DIIS - B_matrix_DIIS(i,dim_DIIS+1) = -1.d0 - B_matrix_DIIS(dim_DIIS+1,i) = -1.d0 - enddo - C_vector_DIIS(dim_DIIS+1) = -1.d0 - - deallocate(scratch) - - ! Estimate condition number of B - integer :: info - double precision :: anorm - integer, allocatable :: ipiv(:) - double precision, allocatable :: AF(:,:) - double precision, external :: dlange - - lwork = max((dim_DIIS+1)**2, (dim_DIIS+1)*5) - allocate(AF(dim_DIIS+1,dim_DIIS+1)) - allocate(ipiv(2*(dim_DIIS+1)), iwork(2*(dim_DIIS+1)) ) - allocate(scratch(lwork,1)) - scratch(:,1) = 0.d0 - - anorm = dlange('1', dim_DIIS+1, dim_DIIS+1, B_matrix_DIIS, size(B_matrix_DIIS, 1), scratch(1,1)) - - AF(:,:) = B_matrix_DIIS(:,:) - call dgetrf(dim_DIIS+1, dim_DIIS+1, AF, size(AF, 1), ipiv, info) - if(info /= 0) then - dim_DIIS = 0 - return - endif - - call dgecon('1', dim_DIIS+1, AF, size(AF, 1), anorm, rcond, scratch, iwork, info) - if(info /= 0) then - dim_DIIS = 0 - return - endif - - if(rcond < 1.d-14) then - dim_DIIS = 0 - return - endif - - ! solve the linear system C = B x X - - X_vector_DIIS = C_vector_DIIS - call dgesv(dim_DIIS+1, 1, B_matrix_DIIS, size(B_matrix_DIIS, 1), ipiv , X_vector_DIIS, size(X_vector_DIIS, 1), info) - - deallocate(scratch, AF, iwork) - if(info < 0) then - stop ' bug in TC-DIIS' - endif - - ! Compute extrapolated Fock matrix - - !$OMP PARALLEL DO PRIVATE(i,j,k) DEFAULT(SHARED) if (ao_num > 200) - do j = 1, ao_num - do i = 1, ao_num - F_ao(i,j) = 0.d0 - enddo - do k = 1, dim_DIIS - if(dabs(X_vector_DIIS(k)) < 1.d-10) cycle - do i = 1,ao_num - ! FPE here - F_ao(i,j) = F_ao(i,j) + X_vector_DIIS(k) * F_DIIS(i,j,dim_DIIS-k+1) - enddo - enddo - enddo - !$OMP END PARALLEL DO - -end - -! --- - diff --git a/plugins/local/tc_scf/tc_scf.irp.f b/plugins/local/tc_scf/tc_scf.irp.f index e82082e8..d39069ee 100644 --- a/plugins/local/tc_scf/tc_scf.irp.f +++ b/plugins/local/tc_scf/tc_scf.irp.f @@ -49,7 +49,7 @@ subroutine main() print *, ' env_type = ', env_type print *, ' core_tc_op = ',core_tc_op - write(json_unit,json_array_open_fmt) 'tc-scf' + call json_init('tc_scf') call rh_tcscf_diis() @@ -64,8 +64,6 @@ subroutine main() endif call print_energy_and_mos(good_angles) - write(json_unit,json_array_close_fmtx) - call json_close end diff --git a/plugins/local/tc_scf/tests/build.ninja b/plugins/local/tc_scf/tests/build.ninja new file mode 100644 index 00000000..fb807f6c --- /dev/null +++ b/plugins/local/tc_scf/tests/build.ninja @@ -0,0 +1,10 @@ +rule compile_history + command = gfortran -O0 -g -fcheck=all -Wall -Wextra -J. -c $in -o $out + +rule link_test + command = gfortran -O0 -g -fcheck=all -Wall -Wextra -I. $in -llapack -lblas -o $out + +build diis_history.o: compile_history ../diis_history.f90 +build test_diis_history: link_test diis_history.o test_diis_history.f90 + +default test_diis_history diff --git a/plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 b/plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 new file mode 100644 index 00000000..2b7c7c60 --- /dev/null +++ b/plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 @@ -0,0 +1,198 @@ +program test_biorthogonal_scaling + + use biorthogonal_scaling_module + + implicit none + + call test_reciprocal_balance_and_invariants() + call test_reject_overlap_growth() + call test_reject_zero_norm_without_partial_output() + call test_reject_nonsymmetric_metric() + + print *, 'PASS: biorthogonal scaling tests' + +contains + + subroutine assert_true(condition, message) + + implicit none + + logical, intent(in) :: condition + character(*), intent(in) :: message + + if(.not. condition) then + print *, 'FAIL: ', trim(message) + error stop 1 + endif + + end subroutine assert_true + + + subroutine assert_close(actual, expected, tolerance, message) + + implicit none + + double precision, intent(in) :: actual, expected, tolerance + character(*), intent(in) :: message + + call assert_true(abs(actual - expected) <= tolerance, trim(message)) + + end subroutine assert_close + + + subroutine test_reciprocal_balance_and_invariants() + + implicit none + + double precision :: left(2,2), right(2,2), metric(2,2) + double precision :: left_balanced(2,2), right_balanced(2,2) + double precision :: left_scale(2), overlap_before(2,2), overlap_after(2,2) + double precision :: projector_before(2,2), projector_after(2,2) + double precision :: left_norm, right_norm + integer :: info, i + + metric = 0.d0 + metric(1,1) = 4.d0 + metric(2,2) = 1.d0 + left = 0.d0 + right = 0.d0 + left(1,1) = 1.d8 + left(2,2) = 1.d-8 + right(1,1) = 2.5d-9 + right(2,2) = 1.d8 + + overlap_before = matmul(transpose(left), matmul(metric, right)) + projector_before = matmul(right, transpose(left)) + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_success, 'valid reciprocal scaling rejected') + + overlap_after = matmul(transpose(left_balanced), & + matmul(metric, right_balanced)) + projector_after = matmul(right_balanced, transpose(left_balanced)) + call assert_true(maxval(abs(overlap_after-overlap_before)) < 1.d-13, & + 'cross overlap changed') + call assert_true(maxval(abs(projector_after-projector_before)) < 1.d-13, & + 'projector changed') + + do i = 1, 2 + left_norm = sqrt(dot_product(left_balanced(:,i), & + matmul(metric,left_balanced(:,i)))) + right_norm = sqrt(dot_product(right_balanced(:,i), & + matmul(metric,right_balanced(:,i)))) + call assert_close(left_norm, right_norm, 1.d-13, & + 'left/right metric norms not balanced') + call assert_true(left_scale(i) > 0.d0, 'invalid scale factor') + enddo + + end subroutine test_reciprocal_balance_and_invariants + + + subroutine test_reject_overlap_growth() + + implicit none + + double precision :: left(2,2), right(2,2), metric(2,2) + double precision :: left_balanced(2,2), right_balanced(2,2) + double precision :: left_scale(2), overlap_before(2,2), overlap_after(2,2) + integer :: info + + metric = 0.d0 + metric(1,1) = 1.d0 + metric(2,2) = 1.d0 + left = 0.d0 + left(1,1) = 100.d0 + left(2,2) = 1.d-2 + right = 0.d0 + right(1,1) = 1.d-2 + right(2,1) = 1.d-4 + right(1,2) = 1.d-6 + right(2,2) = 100.d0 + overlap_before = matmul(transpose(left), matmul(metric, right)) + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_overlap_changed, & + 'balancing that grows off-diagonal overlap was accepted') + call assert_true(maxval(abs(left_balanced-left)) <= tiny(1.d0), & + 'rejected left matrix was partially changed') + call assert_true(maxval(abs(right_balanced-right)) <= tiny(1.d0), & + 'rejected right matrix was partially changed') + call assert_true(maxval(abs(left_scale-1.d0)) <= epsilon(1.d0), & + 'rejected scale factors were not reset') + + overlap_after = matmul(transpose(left_balanced), & + matmul(metric, right_balanced)) + call assert_true(maxval(abs(overlap_after-overlap_before)) <= tiny(1.d0), & + 'rejected overlap changed') + + end subroutine test_reject_overlap_growth + + + subroutine test_reject_zero_norm_without_partial_output() + + implicit none + + double precision :: left(2,2), right(2,2), metric(2,2) + double precision :: left_balanced(2,2), right_balanced(2,2) + double precision :: left_scale(2) + integer :: info + + metric = 0.d0 + metric(1,1) = 1.d0 + metric(2,2) = 1.d0 + left = 0.d0 + left(1,1) = 1.d0 + right = 0.d0 + right(1,1) = 1.d0 + right(2,2) = 1.d0 + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_bad_overlap, & + 'zero pair overlap was not rejected') + call assert_true(maxval(abs(left_balanced-left)) <= tiny(1.d0), & + 'invalid input changed left output') + call assert_true(maxval(abs(right_balanced-right)) <= tiny(1.d0), & + 'invalid input changed right output') + call assert_true(maxval(abs(left_scale-1.d0)) <= epsilon(1.d0), & + 'invalid input changed scales') + + end subroutine test_reject_zero_norm_without_partial_output + + + subroutine test_reject_nonsymmetric_metric() + + implicit none + + double precision :: left(2,1), right(2,1), metric(2,2) + double precision :: left_balanced(2,1), right_balanced(2,1) + double precision :: left_scale(1) + integer :: info + + left = 0.d0 + right = 0.d0 + left(1,1) = 1.d0 + right(1,1) = 1.d0 + metric = 0.d0 + metric(1,1) = 1.d0 + metric(2,2) = 1.d0 + metric(1,2) = 0.1d0 + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_bad_metric, & + 'nonsymmetric metric was accepted') + call assert_true(maxval(abs(left_balanced-left)) <= tiny(1.d0), & + 'bad metric changed left output') + call assert_true(maxval(abs(right_balanced-right)) <= tiny(1.d0), & + 'bad metric changed right output') + + end subroutine test_reject_nonsymmetric_metric + +end program test_biorthogonal_scaling diff --git a/plugins/local/tc_scf/tests/test_diis_history.f90 b/plugins/local/tc_scf/tests/test_diis_history.f90 new file mode 100644 index 00000000..b7a00f6b --- /dev/null +++ b/plugins/local/tc_scf/tests/test_diis_history.f90 @@ -0,0 +1,215 @@ +program test_diis_history + + use diis_history_module + + implicit none + + call test_wraparound_and_pairing() + call test_reset_and_skipped_insertion() + call test_gram_and_extrapolation() + call test_ill_conditioned_rejection() + + print *, 'PASS: diis_history regression tests' + +contains + + subroutine assert_true(condition, message) + + implicit none + + logical, intent(in) :: condition + character(*), intent(in) :: message + + if(.not. condition) then + print *, 'FAIL: ', trim(message) + error stop 1 + endif + + end subroutine assert_true + + + subroutine assert_close(actual, expected, tolerance, message) + + implicit none + + double precision, intent(in) :: actual, expected, tolerance + character(*), intent(in) :: message + + call assert_true( abs(actual - expected) <= tolerance, & + trim(message) ) + + end subroutine assert_close + + + subroutine push_label(history, label) + + implicit none + + type(diis_history), intent(inout) :: history + integer, intent(in) :: label + double precision :: fock(2,2), error(2,2) + integer :: info, inserted_slot + + fock = dble(label) + error = -dble(label) + call diis_push(history, fock, error, inserted_slot, info) + call assert_true(info == diis_success, 'push_label failed') + + end subroutine push_label + + + subroutine assert_history_labels(history, expected, message) + + implicit none + + type(diis_history), intent(in) :: history + integer, intent(in) :: expected(:) + character(*), intent(in) :: message + double precision :: fock(2,2), error(2,2) + integer :: i, info + + call assert_true( diis_count(history) == size(expected), & + trim(message)//': wrong count' ) + do i = 1, size(expected) + call diis_get_entry(history, i, fock, error, info) + call assert_true(info == diis_success, & + trim(message)//': get_entry failed') + call assert_close(fock(1,1), dble(expected(i)), 0.d0, & + trim(message)//': wrong Fock chronology') + call assert_close(error(1,1), -dble(expected(i)), 0.d0, & + trim(message)//': Fock/error pair separated') + enddo + + end subroutine assert_history_labels + + + subroutine test_wraparound_and_pairing() + + implicit none + + type(diis_history) :: history + integer :: info, iteration + + call diis_initialize(history, 2, 4, info) + call assert_true(info == diis_success, 'initialization failed') + + do iteration = 1, 4 + call push_label(history, iteration) + enddo + call assert_history_labels(history, [1, 2, 3, 4], & + 'history before wraparound') + call assert_true(diis_next_slot(history) == 1, & + 'next slot before wraparound') + + call push_label(history, 5) + call assert_history_labels(history, [2, 3, 4, 5], & + 'iteration 5 must evict iteration 1') + call assert_true(diis_next_slot(history) == 2, & + 'next slot after first wraparound') + + do iteration = 6, 8 + call push_label(history, iteration) + enddo + call assert_history_labels(history, [5, 6, 7, 8], & + 'history after full wraparound') + + end subroutine test_wraparound_and_pairing + + + subroutine test_reset_and_skipped_insertion() + + implicit none + + type(diis_history) :: history + integer :: info + + call diis_initialize(history, 2, 4, info) + call push_label(history, 17) + call push_label(history, 18) + call diis_reset(history) + call assert_true(diis_count(history) == 0, 'reset count') + call assert_true(diis_next_slot(history) == 1, 'reset next slot') + + call push_label(history, 19) + call push_label(history, 20) + call assert_history_labels(history, [19, 20], & + 'fresh chronology after reset') + + ! A skipped insertion is represented by not calling diis_push. + call assert_history_labels(history, [19, 20], & + 'skipped insertion must not change history') + + end subroutine test_reset_and_skipped_insertion + + + subroutine test_gram_and_extrapolation() + + implicit none + + type(diis_history) :: history + double precision :: fock(2,2), error(2,2), extrapolated(2,2) + double precision, allocatable :: gram(:,:), coefficients(:) + double precision :: rcond + integer :: info, inserted_slot + + call diis_initialize(history, 2, 2, info) + + ! Fill slot 1 with a stale pair. The two useful entries below then occupy + ! physical slots 2 and 1, so extrapolation must follow logical chronology. + fock = -999.d0 + error = -999.d0 + call diis_push(history, fock, error, inserted_slot, info) + + fock = 0.d0 + fock(1,1) = 10.d0 + fock(2,2) = 10.d0 + error = 0.d0 + error(1,1) = 1.d0 + call diis_push(history, fock, error, inserted_slot, info) + + fock = 0.d0 + fock(1,1) = 20.d0 + fock(2,2) = 20.d0 + error = 0.d0 + error(2,2) = 2.d0 + call diis_push(history, fock, error, inserted_slot, info) + + call diis_build_gram(history, gram, info) + call assert_true(info == diis_success, 'Gram construction failed') + call assert_close(gram(1,1), 1.d0, 1.d-14, 'Gram(1,1)') + call assert_close(gram(1,2), 0.d0, 1.d-14, 'Gram(1,2)') + call assert_close(gram(2,1), 0.d0, 1.d-14, 'Gram(2,1)') + call assert_close(gram(2,2), 4.d0, 1.d-14, 'Gram(2,2)') + + call diis_extrapolate( history, extrapolated, coefficients, & + rcond, info ) + call assert_true(info == diis_success, 'extrapolation failed') + call assert_close(coefficients(1), 0.8d0, 1.d-13, 'coefficient 1') + call assert_close(coefficients(2), 0.2d0, 1.d-13, 'coefficient 2') + call assert_close(sum(coefficients), 1.d0, 1.d-13, & + 'coefficient sum') + call assert_close(extrapolated(1,1), 12.d0, 1.d-12, & + 'extrapolated Fock(1,1)') + call assert_close(extrapolated(2,2), 12.d0, 1.d-12, & + 'extrapolated Fock(2,2)') + + end subroutine test_gram_and_extrapolation + + + subroutine test_ill_conditioned_rejection() + + implicit none + + double precision :: gram(2,2), rcond + double precision, allocatable :: coefficients(:) + integer :: info + + gram = 1.d0 + call diis_solve_coefficients(gram, coefficients, rcond, info) + call assert_true( info == diis_lapack_failure .or. & + info == diis_ill_conditioned, & + 'singular DIIS system must be rejected' ) + + end subroutine test_ill_conditioned_rejection + +end program test_diis_history diff --git a/src/symmetry_det/det_irrep.irp.f b/src/symmetry_det/det_irrep.irp.f index 86d43873..91660659 100644 --- a/src/symmetry_det/det_irrep.irp.f +++ b/src/symmetry_det/det_irrep.irp.f @@ -496,13 +496,13 @@ subroutine pg_family_fill(nsel, np, mask) if (mtot /= np) then ! Called from a parallel region: one writer at a time for the two ! messages and the shared error flag. - !$OMP CRITICAL(pg_label_msg) + !$OMP CRITICAL(pg_label_lock) write(6,'(A,I0,A,I0,A)') 'symmetry_det: family enumeration produced ', & mtot, ' members where the size was ', np, ' (internal inconsistency)' write(pg_label_msg,'(A,I0,A,I0,A)') 'family enumeration produced ', mtot, & ' members where the size was ', np, ' (internal inconsistency)' pg_label_ierr = 5 - !$OMP END CRITICAL(pg_label_msg) + !$OMP END CRITICAL(pg_label_lock) mask(1:2,1:pg_n_mo_block,1:np) = 0 return endif @@ -672,7 +672,7 @@ subroutine pg_fam_setup(np, nsel, mask, npart, nfull, fsec, psec, pn, pos, xrow, if (n > pg_det_nmax) then ! Called from a parallel region: one writer at a time for the four ! lines and the shared error flag. - !$OMP CRITICAL(pg_label_msg) + !$OMP CRITICAL(pg_label_lock) write(6,'(A,I0,A)') 'symmetry_det: one symmetry block contributes ', & n, ' occupied MOs; family enumeration supports at most 12.' write(6,'(A)') ' A block is one irrep (at most 5 MOs) unless the MO '// & @@ -682,7 +682,7 @@ subroutine pg_fam_setup(np, nsel, mask, npart, nfull, fsec, psec, pn, pos, xrow, write(pg_label_msg,'(A,I0,A)') 'one symmetry block holds ', n, & ' occupied MOs (at most 12 supported)' pg_label_ierr = 6 - !$OMP END CRITICAL(pg_label_msg) + !$OMP END CRITICAL(pg_label_lock) npart = -1 return endif @@ -742,13 +742,13 @@ subroutine pg_fam_setup(np, nsel, mask, npart, nfull, fsec, psec, pn, pos, xrow, if (msum /= np .or. nfound /= npart) then ! Called from a parallel region: one writer at a time for the two ! lines and the shared error flag. - !$OMP CRITICAL(pg_label_msg) + !$OMP CRITICAL(pg_label_lock) write(6,'(A,I0,A)') 'symmetry_det: the sector radices do not '// & 'decompose a family of ', np, ' members (internal inconsistency)' write(pg_label_msg,'(A,I0,A)') 'the sector radices do not decompose '// & 'a family of ', np, ' members (internal inconsistency)' pg_label_ierr = 7 - !$OMP END CRITICAL(pg_label_msg) + !$OMP END CRITICAL(pg_label_lock) npart = -1 return endif