LCOV - code coverage report
Current view: top level - src - hfx_ri_kp.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 97.3 % 2286 2224
Test Date: 2026-11-24 01:22:08 Functions: 93.2 % 44 41

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief RI-methods for HFX and K-points.
      10              : !> \auhtor Augustin Bussy (01.2023)
      11              : ! **************************************************************************************************
      12              : 
      13              : MODULE hfx_ri_kp
      14              :    USE admm_types,                      ONLY: get_admm_env
      15              :    USE atomic_kind_types,               ONLY: atomic_kind_type,&
      16              :                                               get_atomic_kind_set
      17              :    USE basis_set_types,                 ONLY: get_gto_basis_set,&
      18              :                                               gto_basis_set_p_type
      19              :    USE bibliography,                    ONLY: Bussy2024,&
      20              :                                               cite_reference
      21              :    USE cell_types,                      ONLY: cell_type,&
      22              :                                               pbc,&
      23              :                                               real_to_scaled,&
      24              :                                               scaled_to_real
      25              :    USE cp_array_utils,                  ONLY: cp_1d_logical_p_type,&
      26              :                                               cp_2d_r_p_type
      27              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      28              :                                               cp_blacs_env_release,&
      29              :                                               cp_blacs_env_type
      30              :    USE cp_control_types,                ONLY: dft_control_type
      31              :    USE cp_dbcsr_api,                    ONLY: &
      32              :         dbcsr_add, dbcsr_clear, dbcsr_copy, dbcsr_create, dbcsr_distribution_get, &
      33              :         dbcsr_distribution_new, dbcsr_distribution_release, dbcsr_distribution_type, dbcsr_filter, &
      34              :         dbcsr_finalize, dbcsr_get_block_p, dbcsr_get_info, dbcsr_iterator_blocks_left, &
      35              :         dbcsr_iterator_next_block, dbcsr_iterator_start, dbcsr_iterator_stop, dbcsr_iterator_type, &
      36              :         dbcsr_p_type, dbcsr_put_block, dbcsr_release, dbcsr_type, dbcsr_type_no_symmetry, &
      37              :         dbcsr_type_symmetric
      38              :    USE cp_dbcsr_cholesky,               ONLY: cp_dbcsr_cholesky_decompose,&
      39              :                                               cp_dbcsr_cholesky_invert
      40              :    USE cp_dbcsr_contrib,                ONLY: dbcsr_dot
      41              :    USE cp_dbcsr_cp2k_link,              ONLY: cp_dbcsr_alloc_block_from_nbl
      42              :    USE cp_dbcsr_diag,                   ONLY: cp_dbcsr_power
      43              :    USE cp_dbcsr_operations,             ONLY: cp_dbcsr_dist2d_to_dist
      44              :    USE dbt_api,                         ONLY: &
      45              :         dbt_batched_contract_finalize, dbt_batched_contract_init, dbt_clear, dbt_contract, &
      46              :         dbt_copy, dbt_copy_block, dbt_copy_indexed, dbt_copy_matrix_to_tensor, &
      47              :         dbt_copy_tensor_to_matrix, dbt_create, dbt_destroy, dbt_distribution_destroy, &
      48              :         dbt_distribution_new, dbt_distribution_type, dbt_filter, dbt_finalize, dbt_get_block, &
      49              :         dbt_get_block_data, dbt_get_block_pattern, dbt_get_info, dbt_get_stored_coordinates, &
      50              :         dbt_iterator_blocks_left, dbt_iterator_next_block, dbt_iterator_start, dbt_iterator_stop, &
      51              :         dbt_iterator_type, dbt_mp_environ_pgrid, dbt_pgrid_create, dbt_pgrid_destroy, &
      52              :         dbt_pgrid_type, dbt_put_block, dbt_put_block_data, dbt_reserve_blocks, dbt_scale, dbt_type
      53              :    USE distribution_2d_types,           ONLY: distribution_2d_release,&
      54              :                                               distribution_2d_type
      55              :    USE hfx_ri,                          ONLY: get_idx_to_atom,&
      56              :                                               hfx_ri_pre_scf_calc_tensors
      57              :    USE hfx_types,                       ONLY: hfx_ri_type
      58              :    USE input_constants,                 ONLY: do_potential_short,&
      59              :                                               hfx_ri_do_2c_cholesky,&
      60              :                                               hfx_ri_do_2c_diag,&
      61              :                                               hfx_ri_do_2c_iter
      62              :    USE input_cp2k_hfx,                  ONLY: ri_pmat
      63              :    USE input_section_types,             ONLY: section_vals_get_subs_vals,&
      64              :                                               section_vals_type,&
      65              :                                               section_vals_val_get,&
      66              :                                               section_vals_val_set
      67              :    USE integral_library_types,          ONLY: cutoff_screen_factor
      68              :    USE iterate_matrix,                  ONLY: invert_hotelling
      69              :    USE kinds,                           ONLY: default_string_length,&
      70              :                                               dp,&
      71              :                                               int_8
      72              :    USE kpoint_types,                    ONLY: get_kpoint_info,&
      73              :                                               kpoint_type
      74              :    USE machine,                         ONLY: m_flush,&
      75              :                                               m_memory,&
      76              :                                               m_walltime
      77              :    USE mathlib,                         ONLY: erfc_cutoff
      78              :    USE memory_utilities,                ONLY: reallocate
      79              :    USE message_passing,                 ONLY: mp_cart_type,&
      80              :                                               mp_para_env_type,&
      81              :                                               mp_request_type,&
      82              :                                               mp_waitall
      83              :    USE particle_methods,                ONLY: get_particle_set
      84              :    USE particle_types,                  ONLY: particle_type
      85              :    USE physcon,                         ONLY: angstrom
      86              :    USE qs_environment_types,            ONLY: get_qs_env,&
      87              :                                               qs_environment_type
      88              :    USE qs_force_types,                  ONLY: qs_force_type
      89              :    USE qs_integral_utils,               ONLY: basis_set_list_setup
      90              :    USE qs_interactions,                 ONLY: init_interaction_radii_orb_basis
      91              :    USE qs_kind_types,                   ONLY: qs_kind_type
      92              :    USE qs_neighbor_list_types,          ONLY: get_iterator_info,&
      93              :                                               neighbor_list_iterate,&
      94              :                                               neighbor_list_iterator_create,&
      95              :                                               neighbor_list_iterator_p_type,&
      96              :                                               neighbor_list_iterator_release,&
      97              :                                               neighbor_list_set_p_type,&
      98              :                                               release_neighbor_list_sets
      99              :    USE qs_scf_types,                    ONLY: qs_scf_env_type
     100              :    USE qs_tensors,                      ONLY: &
     101              :         build_2c_derivatives, build_2c_neighbor_lists, build_3c_derivatives, &
     102              :         build_3c_neighbor_lists, get_3c_iterator_info, get_tensor_occupancy, &
     103              :         neighbor_list_3c_destroy, neighbor_list_3c_iterate, neighbor_list_3c_iterator_create, &
     104              :         neighbor_list_3c_iterator_destroy
     105              :    USE qs_tensors_types,                ONLY: create_2c_tensor,&
     106              :                                               create_3c_tensor,&
     107              :                                               create_tensor_batches,&
     108              :                                               distribution_2d_create,&
     109              :                                               distribution_3d_create,&
     110              :                                               distribution_3d_type,&
     111              :                                               neighbor_list_3c_iterator_type,&
     112              :                                               neighbor_list_3c_type
     113              :    USE virial_types,                    ONLY: virial_type
     114              : #include "./base/base_uses.f90"
     115              : 
     116              : !$ USE OMP_LIB, ONLY: omp_get_num_threads
     117              : 
     118              :    IMPLICIT NONE
     119              :    PRIVATE
     120              : 
     121              :    PUBLIC :: hfx_ri_update_ks_kp, hfx_ri_update_forces_kp
     122              : 
     123              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'hfx_ri_kp'
     124              : CONTAINS
     125              : 
     126              : ! **************************************************************************************************
     127              : !> \brief I_1nitialize the ri_data for K-point. For now, we take the normal, usual existing ri_data
     128              : !>        and we adapt it to our needs
     129              : !> \param dbcsr_template ...
     130              : !> \param ri_data ...
     131              : !> \param qs_env ...
     132              : ! **************************************************************************************************
     133           96 :    SUBROUTINE adapt_ri_data_to_kp(dbcsr_template, ri_data, qs_env)
     134              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: dbcsr_template
     135              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
     136              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     137              : 
     138              :       INTEGER                                            :: i_img, i_RI, i_spin, iatom, natom, &
     139              :                                                             nblks_RI, nimg, nkind, nspins
     140           96 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bsizes_RI_ext, dist1, dist2, dist3
     141              :       TYPE(dft_control_type), POINTER                    :: dft_control
     142              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     143              : 
     144           96 :       NULLIFY (dft_control, para_env)
     145              : 
     146              :       !The main thing that we need to do is to allocate more space for the integrals, such that there
     147              :       !is room for each periodic image. Note that we only go in 1D, i.e. we store (mu^0 sigma^a|P^0),
     148              :       !and (P^0|Q^a) => the RI basis is always in the main cell.
     149              : 
     150              :       !Get kpoint info
     151           96 :       CALL get_qs_env(qs_env, dft_control=dft_control, natom=natom, para_env=para_env, nkind=nkind)
     152           96 :       nimg = ri_data%nimg
     153          384 :       ALLOCATE (ri_data%kp_RI_neighbors(natom*ri_data%ncell_RI, natom))
     154         2824 :       ri_data%kp_RI_neighbors = .FALSE.
     155              : 
     156              :       !Along the RI direction we have basis elements spread accross ncell_RI images.
     157           96 :       nblks_RI = SIZE(ri_data%bsizes_RI_split)
     158          288 :       ALLOCATE (bsizes_RI_ext(nblks_RI*ri_data%ncell_RI))
     159          730 :       DO i_RI = 1, ri_data%ncell_RI
     160         3606 :          bsizes_RI_ext((i_RI - 1)*nblks_RI + 1:i_RI*nblks_RI) = ri_data%bsizes_RI_split(:)
     161              :       END DO
     162              : 
     163         6324 :       ALLOCATE (ri_data%t_3c_int_ctr_1(1, nimg))
     164              :       CALL create_3c_tensor(ri_data%t_3c_int_ctr_1(1, 1), dist1, dist2, dist3, &
     165              :                             ri_data%pgrid_1, ri_data%bsizes_AO_split, bsizes_RI_ext, &
     166           96 :                             ri_data%bsizes_AO_split, [1, 2], [3], name="(AO RI | AO)")
     167              : 
     168         2634 :       DO i_img = 2, nimg
     169         2634 :          CALL dbt_create(ri_data%t_3c_int_ctr_1(1, 1), ri_data%t_3c_int_ctr_1(1, i_img))
     170              :       END DO
     171           96 :       DEALLOCATE (dist1, dist2, dist3)
     172              : 
     173         1056 :       ALLOCATE (ri_data%t_3c_int_ctr_2(1, 1))
     174              :       CALL create_3c_tensor(ri_data%t_3c_int_ctr_2(1, 1), dist1, dist2, dist3, &
     175              :                             ri_data%pgrid_1, ri_data%bsizes_AO_split, bsizes_RI_ext, &
     176           96 :                             ri_data%bsizes_AO_split, [1], [2, 3], name="(AO RI | AO)")
     177           96 :       DEALLOCATE (dist1, dist2, dist3)
     178              : 
     179              :       !We use full block sizes for the 2c quantities
     180           96 :       DEALLOCATE (bsizes_RI_ext)
     181           96 :       nblks_RI = SIZE(ri_data%bsizes_RI)
     182          288 :       ALLOCATE (bsizes_RI_ext(nblks_RI*ri_data%ncell_RI))
     183          730 :       DO i_RI = 1, ri_data%ncell_RI
     184         1998 :          bsizes_RI_ext((i_RI - 1)*nblks_RI + 1:i_RI*nblks_RI) = ri_data%bsizes_RI(:)
     185              :       END DO
     186              : 
     187         4128 :       ALLOCATE (ri_data%t_2c_inv(1, natom), ri_data%t_2c_int(1, natom), ri_data%t_2c_pot(1, natom))
     188              :       CALL create_2c_tensor(ri_data%t_2c_inv(1, 1), dist1, dist2, ri_data%pgrid_2d, &
     189              :                             bsizes_RI_ext, bsizes_RI_ext, &
     190           96 :                             name="(RI | RI)")
     191           96 :       DEALLOCATE (dist1, dist2)
     192           96 :       CALL dbt_create(ri_data%t_2c_inv(1, 1), ri_data%t_2c_int(1, 1))
     193           96 :       CALL dbt_create(ri_data%t_2c_inv(1, 1), ri_data%t_2c_pot(1, 1))
     194          192 :       DO iatom = 2, natom
     195           96 :          CALL dbt_create(ri_data%t_2c_inv(1, 1), ri_data%t_2c_inv(1, iatom))
     196           96 :          CALL dbt_create(ri_data%t_2c_inv(1, 1), ri_data%t_2c_int(1, iatom))
     197          192 :          CALL dbt_create(ri_data%t_2c_inv(1, 1), ri_data%t_2c_pot(1, iatom))
     198              :       END DO
     199              : 
     200          480 :       ALLOCATE (ri_data%kp_cost(natom, natom, nimg))
     201        18534 :       ri_data%kp_cost = 0.0_dp
     202              : 
     203              :       !We store the density and KS matrix in tensor format
     204           96 :       nspins = dft_control%nspins
     205        13420 :       ALLOCATE (ri_data%rho_ao_t(nspins, nimg), ri_data%ks_t(nspins, nimg))
     206              :       CALL create_2c_tensor(ri_data%rho_ao_t(1, 1), dist1, dist2, ri_data%pgrid_2d, &
     207              :                             ri_data%bsizes_AO_split, ri_data%bsizes_AO_split, &
     208           96 :                             name="(AO | AO)")
     209           96 :       DEALLOCATE (dist1, dist2)
     210              : 
     211           96 :       CALL dbt_create(dbcsr_template, ri_data%ks_t(1, 1))
     212              : 
     213           96 :       IF (nspins == 2) THEN
     214           26 :          CALL dbt_create(ri_data%rho_ao_t(1, 1), ri_data%rho_ao_t(2, 1))
     215           26 :          CALL dbt_create(ri_data%ks_t(1, 1), ri_data%ks_t(2, 1))
     216              :       END IF
     217         2634 :       DO i_img = 2, nimg
     218         5532 :          DO i_spin = 1, nspins
     219         2898 :             CALL dbt_create(ri_data%rho_ao_t(1, 1), ri_data%rho_ao_t(i_spin, i_img))
     220         5436 :             CALL dbt_create(ri_data%ks_t(1, 1), ri_data%ks_t(i_spin, i_img))
     221              :          END DO
     222              :       END DO
     223              : 
     224           96 :    END SUBROUTINE adapt_ri_data_to_kp
     225              : 
     226              : ! **************************************************************************************************
     227              : !> \brief The pre-scf steps for RI-HFX k-points calculation. Namely the calculation of the integrals
     228              : !> \param dbcsr_template ...
     229              : !> \param ri_data ...
     230              : !> \param qs_env ...
     231              : ! **************************************************************************************************
     232           96 :    SUBROUTINE hfx_ri_pre_scf_kp(dbcsr_template, ri_data, qs_env)
     233              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: dbcsr_template
     234              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
     235              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     236              : 
     237              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'hfx_ri_pre_scf_kp'
     238              : 
     239              :       INTEGER                                            :: handle, i_img, iatom, natom, nimg, nkind
     240           96 :       TYPE(dbcsr_type), ALLOCATABLE, DIMENSION(:)        :: t_2c_op_pot, t_2c_op_RI
     241           96 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:, :)       :: t_3c_int
     242              :       TYPE(dft_control_type), POINTER                    :: dft_control
     243              : 
     244           96 :       NULLIFY (dft_control)
     245              : 
     246           96 :       CALL timeset(routineN, handle)
     247              : 
     248           96 :       CALL get_qs_env(qs_env, dft_control=dft_control, natom=natom, nkind=nkind)
     249              : 
     250           96 :       CALL cleanup_kp(ri_data)
     251              : 
     252              :       !We do all the checks on what we allow in this initial implementation
     253           96 :       IF (ri_data%flavor /= ri_pmat) CPABORT("K-points RI-HFX only with RHO flavor")
     254           96 :       IF (ri_data%same_op) ri_data%same_op = .FALSE. !force the full calculation with RI metric
     255           96 :       IF (ABS(ri_data%eps_pgf_orb - dft_control%qs_control%eps_pgf_orb) > 1.0E-16_dp) THEN
     256            0 :          CPABORT("RI%EPS_PGF_ORB and QS%EPS_PGF_ORB must be identical for RI-HFX k-points")
     257              :       END IF
     258              : 
     259           96 :       CALL get_kp_and_ri_images(ri_data, qs_env)
     260           96 :       nimg = ri_data%nimg
     261              : 
     262              :       !Calculate the integrals
     263         5652 :       ALLOCATE (t_2c_op_pot(nimg), t_2c_op_RI(nimg))
     264         6324 :       ALLOCATE (t_3c_int(1, nimg))
     265           96 :       CALL hfx_ri_pre_scf_calc_tensors(qs_env, ri_data, t_2c_op_RI, t_2c_op_pot, t_3c_int, do_kpoints=.TRUE.)
     266              : 
     267              :       !Make sure the internals have the k-point format
     268           96 :       CALL adapt_ri_data_to_kp(dbcsr_template, ri_data, qs_env)
     269              : 
     270              :       !For each atom i, we calculate the inverse RI metric (P^0 | Q^0)^-1 without external bumping yet
     271              :       !Also store the off-diagonal integrals of the RI metric in case of forces, bumped from the left
     272          288 :       DO iatom = 1, natom
     273              :          CALL get_ext_2c_int(ri_data%t_2c_inv(1, iatom), t_2c_op_RI, iatom, iatom, 1, ri_data, qs_env, &
     274          192 :                              do_inverse=.TRUE.)
     275              :          !for the forces:
     276              :          !off-diagonl RI metric bumped from the left
     277              :          CALL get_ext_2c_int(ri_data%t_2c_int(1, iatom), t_2c_op_RI, iatom, iatom, 1, ri_data, &
     278          192 :                              qs_env, off_diagonal=.TRUE.)
     279          192 :          CALL apply_bump(ri_data%t_2c_int(1, iatom), iatom, ri_data, qs_env, from_left=.TRUE., from_right=.FALSE.)
     280              : 
     281              :          !RI metric with bumped off-diagonal blocks (but not inverted), depumed from left and right
     282              :          CALL get_ext_2c_int(ri_data%t_2c_pot(1, iatom), t_2c_op_RI, iatom, iatom, 1, ri_data, qs_env, &
     283          192 :                              do_inverse=.TRUE., skip_inverse=.TRUE.)
     284              :          CALL apply_bump(ri_data%t_2c_pot(1, iatom), iatom, ri_data, qs_env, from_left=.TRUE., &
     285          288 :                          from_right=.TRUE., debump=.TRUE.)
     286              : 
     287              :       END DO
     288              : 
     289         2730 :       DO i_img = 1, nimg
     290         2730 :          CALL dbcsr_release(t_2c_op_RI(i_img))
     291              :       END DO
     292              : 
     293         5460 :       ALLOCATE (ri_data%kp_mat_2c_pot(1, nimg))
     294         2730 :       DO i_img = 1, nimg
     295         2634 :          CALL dbcsr_create(ri_data%kp_mat_2c_pot(1, i_img), template=t_2c_op_pot(i_img))
     296         2634 :          CALL dbcsr_copy(ri_data%kp_mat_2c_pot(1, i_img), t_2c_op_pot(i_img))
     297         2730 :          CALL dbcsr_release(t_2c_op_pot(i_img))
     298              :       END DO
     299              : 
     300              :       !reorder the 3c integrals such that empty images are bunched up together
     301           96 :       CALL reorder_3c_ints(t_3c_int(1, :), ri_data)
     302              : 
     303              :       !Pre-contract all 3c integrals with the bumped inverse RI metric (P^0|Q^0)^-1,
     304              :       !and store in ri_data%t_3c_int_ctr_1
     305           96 :       CALL precontract_3c_ints(t_3c_int, ri_data, qs_env)
     306              : 
     307           96 :       CALL timestop(handle)
     308              : 
     309         2826 :    END SUBROUTINE hfx_ri_pre_scf_kp
     310              : 
     311              : ! **************************************************************************************************
     312              : !> \brief clean-up the KP specific data from ri_data
     313              : !> \param ri_data ...
     314              : ! **************************************************************************************************
     315           96 :    SUBROUTINE cleanup_kp(ri_data)
     316              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
     317              : 
     318              :       INTEGER                                            :: i, j
     319              : 
     320           96 :       IF (ALLOCATED(ri_data%kp_cost)) DEALLOCATE (ri_data%kp_cost)
     321           96 :       IF (ALLOCATED(ri_data%idx_to_img)) DEALLOCATE (ri_data%idx_to_img)
     322           96 :       IF (ALLOCATED(ri_data%img_to_idx)) DEALLOCATE (ri_data%img_to_idx)
     323           96 :       IF (ALLOCATED(ri_data%present_images)) DEALLOCATE (ri_data%present_images)
     324           96 :       IF (ALLOCATED(ri_data%img_to_RI_cell)) DEALLOCATE (ri_data%img_to_RI_cell)
     325           96 :       IF (ALLOCATED(ri_data%RI_cell_to_img)) DEALLOCATE (ri_data%RI_cell_to_img)
     326              : 
     327           96 :       IF (ALLOCATED(ri_data%kp_mat_2c_pot)) THEN
     328          870 :          DO j = 1, SIZE(ri_data%kp_mat_2c_pot, 2)
     329         1712 :             DO i = 1, SIZE(ri_data%kp_mat_2c_pot, 1)
     330         1684 :                CALL dbcsr_release(ri_data%kp_mat_2c_pot(i, j))
     331              :             END DO
     332              :          END DO
     333           28 :          DEALLOCATE (ri_data%kp_mat_2c_pot)
     334              :       END IF
     335              : 
     336           96 :       IF (ALLOCATED(ri_data%kp_t_3c_G_sub)) THEN
     337          540 :          DO i = 1, SIZE(ri_data%kp_t_3c_G_sub)
     338          540 :             CALL dbt_destroy(ri_data%kp_t_3c_G_sub(i))
     339              :          END DO
     340          540 :          DEALLOCATE (ri_data%kp_t_3c_G_sub)
     341              :       END IF
     342           96 :       IF (ALLOCATED(ri_data%kp_G_to_RI)) DEALLOCATE (ri_data%kp_G_to_RI)
     343           96 :       IF (ALLOCATED(ri_data%kp_RI_atom)) DEALLOCATE (ri_data%kp_RI_atom)
     344           96 :       IF (ALLOCATED(ri_data%kp_RI_neighbors)) DEALLOCATE (ri_data%kp_RI_neighbors)
     345           96 :       ri_data%kp_G_ngroups = 0
     346              : 
     347           96 :       IF (ALLOCATED(ri_data%kp_t_3c_int)) THEN
     348          720 :          DO i = 1, SIZE(ri_data%kp_t_3c_int)
     349          720 :             CALL dbt_destroy(ri_data%kp_t_3c_int(i))
     350              :          END DO
     351          720 :          DEALLOCATE (ri_data%kp_t_3c_int)
     352              :       END IF
     353              : 
     354           96 :       IF (ALLOCATED(ri_data%t_2c_inv)) THEN
     355          220 :          DO j = 1, SIZE(ri_data%t_2c_inv, 2)
     356          344 :             DO i = 1, SIZE(ri_data%t_2c_inv, 1)
     357          248 :                CALL dbt_destroy(ri_data%t_2c_inv(i, j))
     358              :             END DO
     359              :          END DO
     360          220 :          DEALLOCATE (ri_data%t_2c_inv)
     361              :       END IF
     362              : 
     363           96 :       IF (ALLOCATED(ri_data%t_2c_int)) THEN
     364          220 :          DO j = 1, SIZE(ri_data%t_2c_int, 2)
     365          344 :             DO i = 1, SIZE(ri_data%t_2c_int, 1)
     366          248 :                CALL dbt_destroy(ri_data%t_2c_int(i, j))
     367              :             END DO
     368              :          END DO
     369          220 :          DEALLOCATE (ri_data%t_2c_int)
     370              :       END IF
     371              : 
     372           96 :       IF (ALLOCATED(ri_data%t_2c_pot)) THEN
     373          220 :          DO j = 1, SIZE(ri_data%t_2c_pot, 2)
     374          344 :             DO i = 1, SIZE(ri_data%t_2c_pot, 1)
     375          248 :                CALL dbt_destroy(ri_data%t_2c_pot(i, j))
     376              :             END DO
     377              :          END DO
     378          220 :          DEALLOCATE (ri_data%t_2c_pot)
     379              :       END IF
     380              : 
     381           96 :       IF (ALLOCATED(ri_data%t_3c_int_ctr_1)) THEN
     382         1006 :          DO j = 1, SIZE(ri_data%t_3c_int_ctr_1, 2)
     383         1916 :             DO i = 1, SIZE(ri_data%t_3c_int_ctr_1, 1)
     384         1820 :                CALL dbt_destroy(ri_data%t_3c_int_ctr_1(i, j))
     385              :             END DO
     386              :          END DO
     387         1006 :          DEALLOCATE (ri_data%t_3c_int_ctr_1)
     388              :       END IF
     389              : 
     390           96 :       IF (ALLOCATED(ri_data%t_3c_int_ctr_2)) THEN
     391          192 :          DO j = 1, SIZE(ri_data%t_3c_int_ctr_2, 2)
     392          288 :             DO i = 1, SIZE(ri_data%t_3c_int_ctr_2, 1)
     393          192 :                CALL dbt_destroy(ri_data%t_3c_int_ctr_2(i, j))
     394              :             END DO
     395              :          END DO
     396          192 :          DEALLOCATE (ri_data%t_3c_int_ctr_2)
     397              :       END IF
     398              : 
     399           96 :       IF (ALLOCATED(ri_data%rho_ao_t)) THEN
     400         1006 :          DO j = 1, SIZE(ri_data%rho_ao_t, 2)
     401         2166 :             DO i = 1, SIZE(ri_data%rho_ao_t, 1)
     402         2070 :                CALL dbt_destroy(ri_data%rho_ao_t(i, j))
     403              :             END DO
     404              :          END DO
     405         1256 :          DEALLOCATE (ri_data%rho_ao_t)
     406              :       END IF
     407              : 
     408           96 :       IF (ALLOCATED(ri_data%ks_t)) THEN
     409         1006 :          DO j = 1, SIZE(ri_data%ks_t, 2)
     410         2166 :             DO i = 1, SIZE(ri_data%ks_t, 1)
     411         2070 :                CALL dbt_destroy(ri_data%ks_t(i, j))
     412              :             END DO
     413              :          END DO
     414         1256 :          DEALLOCATE (ri_data%ks_t)
     415              :       END IF
     416              : 
     417           96 :    END SUBROUTINE cleanup_kp
     418              : 
     419              : ! **************************************************************************************************
     420              : !> \brief Prints a progress bar for the k-point RI-HFX triple loop
     421              : !> \param b_img ...
     422              : !> \param nimg ...
     423              : !> \param iprint ...
     424              : !> \param ri_data ...
     425              : ! **************************************************************************************************
     426            0 :    SUBROUTINE print_progress_bar(b_img, nimg, iprint, ri_data)
     427              :       INTEGER, INTENT(IN)                                :: b_img, nimg
     428              :       INTEGER, INTENT(INOUT)                             :: iprint
     429              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
     430              : 
     431              :       CHARACTER(LEN=default_string_length)               :: bar
     432              :       INTEGER                                            :: rep
     433              : 
     434            0 :       IF (ri_data%unit_nr > 0) THEN
     435            0 :          IF (b_img == 1) THEN
     436            0 :             WRITE (ri_data%unit_nr, '(/T6,A)', advance="no") '[-'
     437            0 :             CALL m_flush(ri_data%unit_nr)
     438              :          END IF
     439            0 :          IF (b_img > iprint*nimg/71) THEN
     440            0 :             rep = MAX(1, 71/nimg)
     441            0 :             bar = REPEAT("-", rep)
     442            0 :             WRITE (ri_data%unit_nr, '(A)', advance="no") TRIM(bar)
     443            0 :             CALL m_flush(ri_data%unit_nr)
     444            0 :             iprint = iprint + 1
     445              :          END IF
     446            0 :          IF (b_img == nimg) THEN
     447            0 :             rep = MAX(0, 1 + 71 - iprint*rep)
     448            0 :             bar = REPEAT("-", rep)
     449            0 :             WRITE (ri_data%unit_nr, '(A,A)') TRIM(bar), '-]'
     450            0 :             CALL m_flush(ri_data%unit_nr)
     451              :          END IF
     452              :       END IF
     453              : 
     454            0 :    END SUBROUTINE print_progress_bar
     455              : 
     456              : ! **************************************************************************************************
     457              : !> \brief Update the KS matrices for each real-space image
     458              : !> \param qs_env ...
     459              : !> \param ri_data ...
     460              : !> \param ks_matrix ...
     461              : !> \param ehfx ...
     462              : !> \param rho_ao ...
     463              : !> \param geometry_did_change ...
     464              : !> \param nspins ...
     465              : !> \param hf_fraction ...
     466              : ! **************************************************************************************************
     467          508 :    SUBROUTINE hfx_ri_update_ks_kp(qs_env, ri_data, ks_matrix, ehfx, rho_ao, &
     468              :                                   geometry_did_change, nspins, hf_fraction)
     469              : 
     470              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     471              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
     472              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_matrix
     473              :       REAL(KIND=dp), INTENT(OUT)                         :: ehfx
     474              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao
     475              :       LOGICAL, INTENT(IN)                                :: geometry_did_change
     476              :       INTEGER, INTENT(IN)                                :: nspins
     477              :       REAL(KIND=dp), INTENT(IN)                          :: hf_fraction
     478              : 
     479              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'hfx_ri_update_ks_kp'
     480              : 
     481              :       INTEGER :: b_img, batch_size, group_size, handle, handle2, i_batch, i_img, i_spin, iatom, &
     482              :          iblk, igroup, iprint, jatom, mb_img, n_batch_nze, n_nze, natom, ngroups, nimg, nimg_nze
     483              :       INTEGER(int_8)                                     :: mem, nflop, nflop_sub, nze
     484          508 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: batch_ranges_at, batch_ranges_nze, &
     485          508 :                                                             idx_to_at_AO
     486          508 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: iapc_pairs
     487          508 :       INTEGER, ALLOCATABLE, DIMENSION(:, :, :)           :: sparsity_pattern
     488              :       LOGICAL                                            :: estimate_mem, G_ready, print_progress, &
     489              :                                                             use_delta_p
     490              :       REAL(dp)                                           :: etmp, fac, occ, pfac, pref, t1, t2, t3, &
     491              :                                                             t4
     492              :       TYPE(dbcsr_type)                                   :: ks_desymm, rho_desymm, tmp
     493          508 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:)          :: ks_t_split, t_2c_ao_tmp, t_3c_work_2
     494          508 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:, :)       :: ks_t, ks_t_sub, t_3c_apc, t_3c_apc_sub
     495              :       TYPE(mp_para_env_type), POINTER                    :: para_env, para_env_sub
     496              :       TYPE(section_vals_type), POINTER                   :: hfx_section, print_section
     497              : 
     498          508 :       NULLIFY (para_env, para_env_sub, hfx_section, print_section)
     499              : 
     500          508 :       CALL cite_reference(Bussy2024)
     501              : 
     502          508 :       CALL timeset(routineN, handle)
     503              : 
     504          508 :       CALL get_qs_env(qs_env, para_env=para_env, natom=natom)
     505              : 
     506          508 :       IF (nspins == 1) THEN
     507          420 :          fac = 0.5_dp*hf_fraction
     508              :       ELSE
     509           88 :          fac = 1.0_dp*hf_fraction
     510              :       END IF
     511              : 
     512          508 :       hfx_section => section_vals_get_subs_vals(qs_env%input, "DFT%XC%HF%RI")
     513          508 :       CALL section_vals_val_get(hfx_section, "KP_NGROUPS", i_val=ngroups)
     514          508 :       CALL section_vals_val_get(hfx_section, "KP_STACK_SIZE", i_val=batch_size)
     515          508 :       CALL section_vals_val_get(hfx_section, "KP_USE_DELTA_P", l_val=use_delta_p)
     516          508 :       ri_data%kp_stack_size = batch_size
     517          508 :       ri_data%kp_ngroups = ngroups
     518              : 
     519          508 :       IF (geometry_did_change) THEN
     520           96 :          CALL hfx_ri_pre_scf_kp(ks_matrix(1, 1)%matrix, ri_data, qs_env)
     521              :       END IF
     522          508 :       nimg = ri_data%nimg
     523          508 :       nimg_nze = ri_data%nimg_nze
     524              : 
     525              :       !We need to calculate the KS matrix for each periodic cell with index b: F_mu^0,nu^b
     526              :       !F_mu^0,nu^b = -0.5 sum_a,c P_sigma^0,lambda^c (mu^0, sigma^a| P^0) V_P^0,Q^b (Q^b| nu^b lambda^a+c)
     527              :       !with V_P^0,Q^b = (P^0|R^0)^-1 * (R^0|S^b) * (S^b|Q^b)^-1
     528              : 
     529              :       !We use a local RI basis set for each atom in the system, which inlcudes RI basis elements for
     530              :       !each neighboring atom standing within the KIND radius (decay of Gaussian with smallest exponent)
     531              : 
     532              :       !We also limit the number of periodic images we consider accorrding to the HFX potentail in the
     533              :       !RI basis, because if V_P^0,Q^b is zero everywhere, then image b can be ignored (RI basis less diffuse)
     534              : 
     535              :       !We manage to calculate each KS matrix doing a double loop on iamges, and a double loop on atoms
     536              :       !First, we pre-contract and store P_sigma^0,lambda^c (mu^0, sigma^a| P^0) (P^0|R^0)^-1 into T_mu^0,lambda^a+c,P^0
     537              :       !The remaining potential action on the right fitted pairs is geometry-dependent.
     538              :       !Store its unique G_j(P^x;nu^0,lambda^l), with x=p-b and l=a+c-b,
     539              :       !and select the required rows for each (iatom,jatom,b_img) before contracting with T.
     540              : 
     541              :       !Note that the 3-center integrals are pre-contracted with the RI metric, and that the same tensor can be used
     542              :       !(mu^0, sigma^a| P^0) (P^0|R^0)  <===> (S^b|Q^b)^-1 (Q^b| nu^b lambda^a+c) by relabelling the images
     543              : 
     544          508 :       IF (MOD(para_env%num_pe, ngroups) /= 0) THEN
     545            0 :          CPWARN("KP_NGROUPS must be an integer divisor of the total number of MPI ranks. It was set to 1.")
     546            0 :          ngroups = 1
     547            0 :          CALL section_vals_val_set(hfx_section, "KP_NGROUPS", i_val=ngroups)
     548              :       END IF
     549          508 :       IF ((MOD(ngroups, natom) /= 0) .AND. (MOD(natom, ngroups) /= 0) .AND. geometry_did_change) THEN
     550            0 :          IF (ngroups > 1) THEN
     551            0 :             CPWARN("Better load balancing is reached if NGROUPS is a multiple/divisor of the number of atoms")
     552              :          END IF
     553              :       END IF
     554          508 :       group_size = para_env%num_pe/ngroups
     555          508 :       igroup = para_env%mepos/group_size
     556              : 
     557          508 :       ALLOCATE (para_env_sub)
     558          508 :       CALL para_env_sub%from_split(para_env, igroup)
     559              : 
     560              :       ! The sparsity pattern of each iatom, jatom pair, on each b_img, and on which subgroup
     561         2540 :       ALLOCATE (sparsity_pattern(natom, natom, nimg))
     562          508 :       CALL get_sparsity_pattern(sparsity_pattern, ri_data, qs_env)
     563          508 :       CALL get_sub_dist(sparsity_pattern, ngroups, ri_data)
     564              : 
     565              :       ! Build geometry-only G before allocating the density-dependent T workspace.
     566          508 :       IF (.NOT. ALLOCATED(ri_data%kp_t_3c_G_sub)) THEN
     567           96 :          CALL build_kp_exchange_integrals(ri_data, qs_env, sparsity_pattern, ngroups, para_env_sub)
     568              :       END IF
     569          508 :       CPASSERT(ri_data%kp_G_ngroups == ngroups)
     570              : 
     571              :       !By default, build the density tensor based on the difference of this SCF P and that of the prev. SCF
     572          508 :       pfac = -1.0_dp
     573          508 :       IF (.NOT. use_delta_p) pfac = 0.0_dp
     574          508 :       CALL get_pmat_images(ri_data%rho_ao_t, rho_ao, pfac, ri_data, qs_env)
     575              : 
     576          508 :       n_nze = 0
     577        17142 :       DO i_img = 1, nimg
     578        35478 :          DO i_spin = 1, nspins
     579        18336 :             CALL get_tensor_occupancy(ri_data%rho_ao_t(i_spin, i_img), nze, occ)
     580        34970 :             IF (nze > 0) THEN
     581        12692 :                n_nze = n_nze + 1
     582              :             END IF
     583              :          END DO
     584              :       END DO
     585          508 :       IF (n_nze == nspins) THEN
     586           38 :          CPWARN("It is highly recommended to restart from a converged GGA K-point calculations.")
     587              :       END IF
     588              : 
     589        41066 :       ALLOCATE (ks_t(nspins, nimg))
     590        17142 :       DO i_img = 1, nimg
     591        35478 :          DO i_spin = 1, nspins
     592        34970 :             CALL dbt_create(ri_data%ks_t(1, 1), ks_t(i_spin, i_img))
     593              :          END DO
     594              :       END DO
     595              : 
     596         1524 :       ALLOCATE (idx_to_at_AO(SIZE(ri_data%bsizes_AO_split)))
     597          508 :       CALL get_idx_to_atom(idx_to_at_AO, ri_data%bsizes_AO_split, ri_data%bsizes_AO)
     598              : 
     599              :       !First we calculate and store T^1_mu^0,lambda^a+c,P = P_mu^0,lambda^c * (mu_0 sigma^a | P^0) (P^0|R^0)^-1
     600              :       !To avoid doing nimg**2 tiny contractions that do not scale well with a large number of CPUs,
     601              :       !we instead do a single loop over the a+c image index. For each a+c, we get a list of allowed
     602              :       !combination of a,c indices. Then we build TAS tensors P_mu^0,lambda^c with all concerned c's
     603              :       !and (mu^0 sigma^a | P^0)*(P^0|R^0)^-1 with all a's. Then we perform a single contraction with larger tensors,
     604              :       !were the sum over a,c is automatically taken care of
     605        40558 :       ALLOCATE (t_3c_apc(nspins, nimg))
     606        17142 :       DO i_img = 1, nimg
     607        35478 :          DO i_spin = 1, nspins
     608        34970 :             CALL dbt_create(ri_data%t_3c_int_ctr_2(1, 1), t_3c_apc(i_spin, i_img))
     609              :          END DO
     610              :       END DO
     611          508 :       CALL contract_pmat_3c(t_3c_apc, ri_data%rho_ao_t, ri_data, qs_env)
     612              : 
     613              :       !Get all the required tensors in the subgroups
     614        50210 :       ALLOCATE (ks_t_sub(nspins, nimg), t_2c_ao_tmp(1), ks_t_split(2))
     615          508 :       CALL get_subgroup_ks_tensors(t_2c_ao_tmp, ks_t_split, ks_t_sub, para_env_sub, ri_data)
     616              : 
     617        46654 :       ALLOCATE (t_3c_apc_sub(nspins, nimg), t_3c_work_2(3))
     618              :       CALL get_subgroup_3c_tensors(t_3c_work_2, t_3c_apc, t_3c_apc_sub, &
     619          508 :                                    para_env_sub, ri_data)
     620              : 
     621              :       !We go atom by atom, therefore there is an automatic batching along that direction
     622              :       !Also, because we stack the 3c tensors nimg times, we naturally do some batching there too
     623         1524 :       ALLOCATE (batch_ranges_at(natom + 1))
     624          508 :       batch_ranges_at(natom + 1) = SIZE(ri_data%bsizes_AO_split) + 1
     625          508 :       iatom = 0
     626         1942 :       DO iblk = 1, SIZE(ri_data%bsizes_AO_split)
     627         1942 :          IF (idx_to_at_AO(iblk) == iatom + 1) THEN
     628         1016 :             iatom = iatom + 1
     629         1016 :             batch_ranges_at(iatom) = iblk
     630              :          END IF
     631              :       END DO
     632              : 
     633          508 :       n_batch_nze = nimg_nze/batch_size
     634          508 :       IF (MODULO(nimg_nze, batch_size) /= 0) n_batch_nze = n_batch_nze + 1
     635         1524 :       ALLOCATE (batch_ranges_nze(n_batch_nze + 1))
     636         1352 :       DO i_batch = 1, n_batch_nze
     637         1352 :          batch_ranges_nze(i_batch) = (i_batch - 1)*batch_size + 1
     638              :       END DO
     639          508 :       batch_ranges_nze(n_batch_nze + 1) = nimg_nze + 1
     640              : 
     641          508 :       print_section => section_vals_get_subs_vals(qs_env%input, "DFT%XC%HF%RI%PRINT")
     642          508 :       CALL section_vals_val_get(print_section, "KP_RI_PROGRESS_BAR", l_val=print_progress)
     643          508 :       CALL section_vals_val_get(print_section, "KP_RI_MEMORY_ESTIMATE", l_val=estimate_mem)
     644              : 
     645         1524 :       ALLOCATE (iapc_pairs(nimg, 2))
     646          508 :       IF (estimate_mem .AND. geometry_did_change) THEN
     647              :          !Populate work tensors to simulate maximum usage
     648            0 :          CALL get_iapc_pairs(iapc_pairs, 1, ri_data, qs_env)
     649              :          CALL fill_kp_exchange_stack(t_3c_work_2(2), ri_data, iapc_pairs, 1, 1, 1, &
     650            0 :                                      idx_to_at_AO, [batch_ranges_nze(1), batch_ranges_nze(2)])
     651              :          CALL fill_3c_stack(t_3c_work_2(1), t_3c_apc_sub(1, :), iapc_pairs(:, 2), 3, &
     652              :                             ri_data, filter_at=1, filter_dim=1, idx_to_at=idx_to_at_AO, &
     653            0 :                             img_bounds=[batch_ranges_nze(1), batch_ranges_nze(2)])
     654              :          CALL fill_3c_stack(t_3c_work_2(3), t_3c_apc_sub(1, :), iapc_pairs(:, 2), 3, &
     655              :                             ri_data, filter_at=1, filter_dim=1, idx_to_at=idx_to_at_AO, &
     656            0 :                             img_bounds=[batch_ranges_nze(1), batch_ranges_nze(2)])
     657            0 :          CALL m_memory(mem)
     658            0 :          CALL para_env%max(mem)
     659            0 :          CALL dbt_clear(t_3c_work_2(1))
     660            0 :          CALL dbt_clear(t_3c_work_2(2))
     661            0 :          CALL dbt_clear(t_3c_work_2(3))
     662              : 
     663            0 :          IF (ri_data%unit_nr > 0) THEN
     664              :             WRITE (ri_data%unit_nr, FMT="(T3,A,I14)") &
     665            0 :                "KP-HFX_RI_INFO| Estimated peak memory usage per MPI rank (MiB):", mem/(1024*1024)
     666            0 :             CALL m_flush(ri_data%unit_nr)
     667              :          END IF
     668              :       END IF
     669              : 
     670          508 :       CALL dbt_batched_contract_init(t_3c_work_2(1), batch_range_1=batch_ranges_at)
     671          508 :       CALL dbt_batched_contract_init(t_3c_work_2(2), batch_range_1=batch_ranges_at)
     672              : 
     673          508 :       iprint = 1
     674          508 :       t1 = m_walltime()
     675          508 :       nflop_sub = 0_int_8
     676       116946 :       ri_data%kp_cost(:, :, :) = 0.0_dp
     677        17142 :       DO b_img = 1, nimg
     678        16634 :          IF (print_progress) CALL print_progress_bar(b_img, nimg, iprint, ri_data)
     679        16634 :          CALL get_iapc_pairs(iapc_pairs, b_img, ri_data, qs_env)
     680        16634 :          CALL dbt_batched_contract_init(ks_t_split(1))
     681        16634 :          CALL dbt_batched_contract_init(ks_t_split(2))
     682        49902 :          DO jatom = 1, natom
     683       116438 :             DO iatom = 1, natom
     684        66536 :                IF (.NOT. sparsity_pattern(iatom, jatom, b_img) == igroup) CYCLE
     685        14202 :                pref = 1.0_dp
     686        14202 :                IF (iatom == jatom .AND. b_img == 1) pref = 0.5_dp
     687              : 
     688              :                !measure the cost of the given i, j, b configuration
     689        14202 :                t3 = m_walltime()
     690              : 
     691        14202 :                CALL timeset(routineN//"_3c", handle2)
     692              : 
     693              :                ! G_j(P^x; nu^0, lambda^l) is independent of the density.
     694              :                ! Here x=p-b and l=a+c-b; retain the original finite image domain.
     695        38556 :                DO i_batch = 1, n_batch_nze
     696              :                   G_ready = .FALSE.
     697              : 
     698              :                   !Stack the P_sigma^a,lambda^a+c * (mu^0 sigma^a | P^0)*(P^0|R^0)^-1 integrals over a+c and contract
     699              :                   !to get the final block of the KS matrix
     700        65122 :                   DO i_spin = 1, nspins
     701              :                      CALL fill_3c_stack(t_3c_work_2(3), t_3c_apc_sub(i_spin, :), iapc_pairs(:, 2), 3, &
     702              :                                         ri_data, filter_at=iatom, filter_dim=1, idx_to_at=idx_to_at_AO, &
     703        79698 :                                         img_bounds=[batch_ranges_nze(i_batch), batch_ranges_nze(i_batch + 1)])
     704        26566 :                      CALL get_tensor_occupancy(t_3c_work_2(3), nze, occ)
     705              : 
     706        26566 :                      IF (nze == 0) CYCLE
     707        24444 :                      IF (.NOT. G_ready) THEN
     708              :                         CALL fill_kp_exchange_stack(t_3c_work_2(2), ri_data, iapc_pairs, iatom, jatom, b_img, &
     709              :                                                     idx_to_at_AO, &
     710        67092 :                                                     [batch_ranges_nze(i_batch), batch_ranges_nze(i_batch + 1)])
     711        22364 :                         G_ready = .TRUE.
     712              :                      END IF
     713        24444 :                      CALL dbt_copy(t_3c_work_2(3), t_3c_work_2(1), move_data=.TRUE.)
     714              :                      CALL dbt_contract(-pref*fac, t_3c_work_2(1), t_3c_work_2(2), &
     715              :                                        1.0_dp, ks_t_split(i_spin), map_1=[1], map_2=[2], &
     716              :                                        contract_1=[2, 3], notcontract_1=[1], &
     717              :                                        contract_2=[2, 3], notcontract_2=[1], &
     718              :                                        filter_eps=ri_data%filter_eps, &
     719        24444 :                                        move_data=i_spin == nspins, flop=nflop)
     720        75364 :                      nflop_sub = nflop_sub + nflop
     721              :                   END DO
     722              :                END DO !i_batch
     723        14202 :                CALL timestop(handle2)
     724              : 
     725        14202 :                t4 = m_walltime()
     726       114006 :                ri_data%kp_cost(iatom, jatom, b_img) = t4 - t3
     727              :             END DO !iatom
     728              :          END DO !jatom
     729        16634 :          CALL dbt_batched_contract_finalize(ks_t_split(1))
     730        16634 :          CALL dbt_batched_contract_finalize(ks_t_split(2))
     731              : 
     732        35478 :          DO i_spin = 1, nspins
     733        18336 :             CALL dbt_copy(ks_t_split(i_spin), t_2c_ao_tmp(1), move_data=.TRUE.)
     734        34970 :             CALL dbt_copy(t_2c_ao_tmp(1), ks_t_sub(i_spin, b_img), summation=.TRUE.)
     735              :          END DO
     736              :       END DO !b_img
     737          508 :       CALL dbt_batched_contract_finalize(t_3c_work_2(1))
     738          508 :       CALL dbt_batched_contract_finalize(t_3c_work_2(2))
     739          508 :       CALL para_env%sync()
     740              :       ! DBT returns the average flop count per rank in each subgroup. Reduce only
     741              :       ! this step's subgroup work and keep the accumulated counter per rank.
     742          508 :       CALL para_env%sum(nflop_sub)
     743          508 :       ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + (nflop_sub + para_env%num_pe - 1)/para_env%num_pe
     744          508 :       CALL para_env%sum(ri_data%kp_cost)
     745          508 :       t2 = m_walltime()
     746          508 :       ri_data%dbcsr_time = ri_data%dbcsr_time + t2 - t1
     747              : 
     748              :       !transfer KS tensor from subgroup to main group
     749          508 :       CALL gather_ks_matrix(ks_t, ks_t_sub, group_size, sparsity_pattern, para_env, ri_data)
     750              : 
     751              :       !clean-up subgroup tensors
     752          508 :       CALL dbt_destroy(t_2c_ao_tmp(1))
     753          508 :       CALL dbt_destroy(ks_t_split(1))
     754          508 :       CALL dbt_destroy(ks_t_split(2))
     755          508 :       CALL dbt_destroy(t_3c_work_2(1))
     756          508 :       CALL dbt_destroy(t_3c_work_2(2))
     757          508 :       CALL dbt_destroy(t_3c_work_2(3))
     758        17142 :       DO i_img = 1, nimg
     759        35478 :          DO i_spin = 1, nspins
     760        18336 :             CALL dbt_destroy(t_3c_apc_sub(i_spin, i_img))
     761        34970 :             CALL dbt_destroy(ks_t_sub(i_spin, i_img))
     762              :          END DO
     763              :       END DO
     764              :       !End of subgroup parallelization
     765          508 :       CALL para_env_sub%free()
     766          508 :       DEALLOCATE (para_env_sub)
     767              : 
     768              :       !Currently, rho_ao_t holds the density difference (wrt to pref SCF step).
     769              :       !ks_t also hold that diff, while only having half the blocks => need to add to prev ks_t and symmetrize
     770              :       !We need the full thing for the energy, on the next SCF step
     771          508 :       CALL get_pmat_images(ri_data%rho_ao_t, rho_ao, 0.0_dp, ri_data, qs_env)
     772         1104 :       DO i_spin = 1, nspins
     773        19440 :          DO b_img = 1, nimg
     774        18336 :             CALL dbt_copy(ks_t(i_spin, b_img), ri_data%ks_t(i_spin, b_img), summation=.TRUE.)
     775              : 
     776              :             !desymmetrize
     777        18336 :             mb_img = get_opp_index(b_img, qs_env)
     778        18932 :             IF (mb_img > 0 .AND. mb_img <= nimg) THEN
     779        17168 :                CALL dbt_copy(ks_t(i_spin, mb_img), ri_data%ks_t(i_spin, b_img), order=[2, 1], summation=.TRUE.)
     780              :             END IF
     781              :          END DO
     782              :       END DO
     783        17142 :       DO b_img = 1, nimg
     784        35478 :          DO i_spin = 1, nspins
     785        34970 :             CALL dbt_destroy(ks_t(i_spin, b_img))
     786              :          END DO
     787              :       END DO
     788              : 
     789              :       !calculate the energy
     790          508 :       CALL dbt_create(ri_data%ks_t(1, 1), t_2c_ao_tmp(1))
     791          508 :       CALL dbcsr_create(tmp, template=ks_matrix(1, 1)%matrix, matrix_type=dbcsr_type_symmetric)
     792          508 :       CALL dbcsr_create(ks_desymm, template=ks_matrix(1, 1)%matrix, matrix_type=dbcsr_type_no_symmetry)
     793          508 :       CALL dbcsr_create(rho_desymm, template=ks_matrix(1, 1)%matrix, matrix_type=dbcsr_type_no_symmetry)
     794          508 :       ehfx = 0.0_dp
     795        17142 :       DO i_img = 1, nimg
     796        35478 :          DO i_spin = 1, nspins
     797        18336 :             CALL dbt_filter(ri_data%ks_t(i_spin, i_img), ri_data%filter_eps)
     798        18336 :             CALL dbt_copy(ri_data%ks_t(i_spin, i_img), t_2c_ao_tmp(1))
     799        18336 :             CALL dbt_copy_tensor_to_matrix(t_2c_ao_tmp(1), ks_desymm)
     800        18336 :             CALL dbt_copy_tensor_to_matrix(t_2c_ao_tmp(1), tmp)
     801        18336 :             CALL dbcsr_add(ks_matrix(i_spin, i_img)%matrix, tmp, 1.0_dp, 1.0_dp)
     802              : 
     803        18336 :             CALL dbt_copy(ri_data%rho_ao_t(i_spin, i_img), t_2c_ao_tmp(1))
     804        18336 :             CALL dbt_copy_tensor_to_matrix(t_2c_ao_tmp(1), rho_desymm)
     805              : 
     806        18336 :             CALL dbcsr_dot(ks_desymm, rho_desymm, etmp)
     807        18336 :             ehfx = ehfx + 0.5_dp*etmp
     808              : 
     809        34970 :             IF (.NOT. use_delta_p) CALL dbt_clear(ri_data%ks_t(i_spin, i_img))
     810              :          END DO
     811              :       END DO
     812          508 :       CALL dbcsr_release(rho_desymm)
     813          508 :       CALL dbcsr_release(ks_desymm)
     814          508 :       CALL dbcsr_release(tmp)
     815          508 :       CALL dbt_destroy(t_2c_ao_tmp(1))
     816              : 
     817          508 :       CALL timestop(handle)
     818              : 
     819        78932 :    END SUBROUTINE hfx_ri_update_ks_kp
     820              : 
     821              : ! **************************************************************************************************
     822              : !> \brief Update the K-points RI-HFX forces
     823              : !> \param qs_env ...
     824              : !> \param ri_data ...
     825              : !> \param nspins ...
     826              : !> \param hf_fraction ...
     827              : !> \param rho_ao ...
     828              : !> \param use_virial ...
     829              : !> \note Because this routine uses stored quantities calculated in the energy calculation, they should
     830              : !>       always be called by pairs, and with the same input densities
     831              : ! **************************************************************************************************
     832           54 :    SUBROUTINE hfx_ri_update_forces_kp(qs_env, ri_data, nspins, hf_fraction, rho_ao, use_virial)
     833              : 
     834              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     835              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
     836              :       INTEGER, INTENT(IN)                                :: nspins
     837              :       REAL(KIND=dp), INTENT(IN)                          :: hf_fraction
     838              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao
     839              :       LOGICAL, INTENT(IN), OPTIONAL                      :: use_virial
     840              : 
     841              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'hfx_ri_update_forces_kp'
     842              : 
     843              :       INTEGER :: b_img, batch_size, group_size, handle, handle2, i_batch, i_img, i_loop, i_spin, &
     844              :          i_xyz, iatom, iblk, igroup, j_xyz, jatom, k_xyz, n_batch, natom, ngroups, nimg, nimg_nze
     845              :       INTEGER(int_8)                                     :: nflop, nze
     846           54 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: atom_of_kind, batch_ranges_at, &
     847           54 :                                                             batch_ranges_nze, dist1, dist2, &
     848           54 :                                                             i_images, idx_to_at_AO, idx_to_at_RI, &
     849           54 :                                                             kind_of
     850           54 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: iapc_pairs
     851           54 :       INTEGER, ALLOCATABLE, DIMENSION(:, :, :)           :: force_pattern, sparsity_pattern
     852              :       INTEGER, DIMENSION(2, 1)                           :: bounds_iat, bounds_jat
     853              :       LOGICAL                                            :: use_virial_prv
     854              :       REAL(dp)                                           :: fac, occ, pref, t1, t2
     855              :       REAL(dp), DIMENSION(3, 3)                          :: work_virial
     856           54 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     857              :       TYPE(cell_type), POINTER                           :: cell
     858              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env_sub
     859           54 :       TYPE(dbcsr_type), ALLOCATABLE, DIMENSION(:)        :: mat_2c_pot
     860           54 :       TYPE(dbcsr_type), ALLOCATABLE, DIMENSION(:, :)     :: mat_der_pot, mat_der_pot_sub
     861              :       TYPE(dbcsr_type), POINTER                          :: dbcsr_template
     862          918 :       TYPE(dbt_type)                                     :: t_2c_R, t_2c_R_split
     863           54 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:)          :: t_2c_bint, t_2c_binv, t_2c_der_pot, &
     864          108 :                                                             t_2c_inv, t_2c_metric, t_2c_work, &
     865           54 :                                                             t_3c_der_stack, t_3c_work_2, &
     866           54 :                                                             t_3c_work_3
     867           54 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:, :) :: rho_ao_t, rho_ao_t_sub, t_2c_der_metric, &
     868          108 :          t_2c_der_metric_sub, t_3c_apc, t_3c_apc_sub, t_3c_der_AO, t_3c_der_AO_sub, t_3c_der_RI, &
     869           54 :          t_3c_der_RI_sub
     870              :       TYPE(mp_para_env_type), POINTER                    :: para_env, para_env_sub
     871           54 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     872           54 :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
     873              :       TYPE(section_vals_type), POINTER                   :: hfx_section
     874              :       TYPE(virial_type), POINTER                         :: virial
     875              : 
     876           54 :       NULLIFY (para_env, para_env_sub, hfx_section, blacs_env_sub, dbcsr_template, force, atomic_kind_set, &
     877           54 :                virial, particle_set, cell)
     878              : 
     879           54 :       CALL timeset(routineN, handle)
     880              : 
     881           54 :       use_virial_prv = .FALSE.
     882           54 :       IF (PRESENT(use_virial)) use_virial_prv = use_virial
     883              : 
     884           54 :       IF (nspins == 1) THEN
     885           38 :          fac = 0.5_dp*hf_fraction
     886              :       ELSE
     887           16 :          fac = 1.0_dp*hf_fraction
     888              :       END IF
     889              : 
     890              :       CALL get_qs_env(qs_env, natom=natom, para_env=para_env, force=force, cell=cell, virial=virial, &
     891           54 :                       atomic_kind_set=atomic_kind_set, particle_set=particle_set)
     892           54 :       CALL get_atomic_kind_set(atomic_kind_set, kind_of=kind_of, atom_of_kind=atom_of_kind)
     893              : 
     894          162 :       ALLOCATE (idx_to_at_AO(SIZE(ri_data%bsizes_AO_split)))
     895           54 :       CALL get_idx_to_atom(idx_to_at_AO, ri_data%bsizes_AO_split, ri_data%bsizes_AO)
     896              : 
     897          162 :       ALLOCATE (idx_to_at_RI(SIZE(ri_data%bsizes_RI_split)))
     898           54 :       CALL get_idx_to_atom(idx_to_at_RI, ri_data%bsizes_RI_split, ri_data%bsizes_RI)
     899              : 
     900           54 :       nimg = ri_data%nimg
     901        16326 :       ALLOCATE (t_3c_der_RI(nimg, 3), t_3c_der_AO(nimg, 3), mat_der_pot(nimg, 3), t_2c_der_metric(natom, 3))
     902              : 
     903              :       !We assume that the integrals are available from the SCF
     904              :       !pre-calculate the derivs. 3c tensors as (P^0| sigma^a mu^0), with t_3c_der_AO holding deriv wrt mu^0
     905           54 :       CALL precalc_derivatives(t_3c_der_RI, t_3c_der_AO, mat_der_pot, t_2c_der_metric, ri_data, qs_env)
     906              : 
     907              :       !Calculate the density matrix at each image
     908         3856 :       ALLOCATE (rho_ao_t(nspins, nimg))
     909              :       CALL create_2c_tensor(rho_ao_t(1, 1), dist1, dist2, ri_data%pgrid_2d, &
     910              :                             ri_data%bsizes_AO_split, ri_data%bsizes_AO_split, &
     911           54 :                             name="(AO | AO)")
     912           54 :       DEALLOCATE (dist1, dist2)
     913           54 :       IF (nspins == 2) CALL dbt_create(rho_ao_t(1, 1), rho_ao_t(2, 1))
     914         1514 :       DO i_img = 2, nimg
     915         3138 :          DO i_spin = 1, nspins
     916         3084 :             CALL dbt_create(rho_ao_t(1, 1), rho_ao_t(i_spin, i_img))
     917              :          END DO
     918              :       END DO
     919           54 :       CALL get_pmat_images(rho_ao_t, rho_ao, 0.0_dp, ri_data, qs_env)
     920              : 
     921              :       !Contract integrals with the density matrix
     922         3856 :       ALLOCATE (t_3c_apc(nspins, nimg))
     923         1568 :       DO i_img = 1, nimg
     924         3262 :          DO i_spin = 1, nspins
     925         3208 :             CALL dbt_create(ri_data%t_3c_int_ctr_2(1, 1), t_3c_apc(i_spin, i_img))
     926              :          END DO
     927              :       END DO
     928           54 :       CALL contract_pmat_3c(t_3c_apc, rho_ao_t, ri_data, qs_env)
     929              : 
     930              :       !Setup the subgroups
     931           54 :       hfx_section => section_vals_get_subs_vals(qs_env%input, "DFT%XC%HF%RI")
     932           54 :       CALL section_vals_val_get(hfx_section, "KP_NGROUPS", i_val=ngroups)
     933           54 :       group_size = para_env%num_pe/ngroups
     934           54 :       igroup = para_env%mepos/group_size
     935              : 
     936           54 :       ALLOCATE (para_env_sub)
     937           54 :       CALL para_env_sub%from_split(para_env, igroup)
     938           54 :       CALL cp_blacs_env_create(blacs_env_sub, para_env_sub)
     939              : 
     940              :       !Get the ususal sparsity pattern
     941          270 :       ALLOCATE (sparsity_pattern(natom, natom, nimg))
     942           54 :       CALL get_sparsity_pattern(sparsity_pattern, ri_data, qs_env)
     943           54 :       CALL get_sub_dist(sparsity_pattern, ngroups, ri_data)
     944              : 
     945              :       !Get the 2-center quantities in the subgroups (note: main group derivs are deleted wihtin)
     946            0 :       ALLOCATE (t_2c_inv(natom), mat_2c_pot(nimg), rho_ao_t_sub(nspins, nimg), t_2c_work(5), &
     947            0 :                 t_2c_der_metric_sub(natom, 3), mat_der_pot_sub(nimg, 3), t_2c_bint(natom), &
     948        14502 :                 t_2c_metric(natom), t_2c_binv(natom))
     949              :       CALL get_subgroup_2c_derivs(t_2c_inv, t_2c_bint, t_2c_metric, mat_2c_pot, t_2c_work, rho_ao_t, &
     950              :                                   rho_ao_t_sub, t_2c_der_metric, t_2c_der_metric_sub, mat_der_pot, &
     951           54 :                                   mat_der_pot_sub, group_size, ngroups, para_env, para_env_sub, ri_data)
     952           54 :       CALL dbt_create(t_2c_work(1), t_2c_R) !nRI x nRI
     953           54 :       CALL dbt_create(t_2c_work(5), t_2c_R_split) !nRI x nRI with split blocks
     954              : 
     955          648 :       ALLOCATE (t_2c_der_pot(3))
     956          216 :       DO i_xyz = 1, 3
     957          216 :          CALL dbt_create(t_2c_R, t_2c_der_pot(i_xyz))
     958              :       END DO
     959              : 
     960              :       !Get the 3-center quantities in the subgroups. The integrals and t_3c_apc already there
     961            0 :       ALLOCATE (t_3c_work_2(3), t_3c_work_3(4), t_3c_der_stack(6), t_3c_der_AO_sub(nimg, 3), &
     962        16234 :                 t_3c_der_RI_sub(nimg, 3), t_3c_apc_sub(nspins, nimg))
     963              :       CALL get_subgroup_3c_derivs(t_3c_work_2, t_3c_work_3, t_3c_der_AO, t_3c_der_AO_sub, &
     964              :                                   t_3c_der_RI, t_3c_der_RI_sub, t_3c_apc, t_3c_apc_sub, t_3c_der_stack, &
     965           54 :                                   para_env_sub, ri_data)
     966              : 
     967              :       !Set up batched contraction (go atom by atom)
     968          162 :       ALLOCATE (batch_ranges_at(natom + 1))
     969           54 :       batch_ranges_at(natom + 1) = SIZE(ri_data%bsizes_AO_split) + 1
     970           54 :       iatom = 0
     971          256 :       DO iblk = 1, SIZE(ri_data%bsizes_AO_split)
     972          256 :          IF (idx_to_at_AO(iblk) == iatom + 1) THEN
     973          108 :             iatom = iatom + 1
     974          108 :             batch_ranges_at(iatom) = iblk
     975              :          END IF
     976              :       END DO
     977              : 
     978           54 :       CALL dbt_batched_contract_init(t_3c_work_3(1), batch_range_2=batch_ranges_at)
     979           54 :       CALL dbt_batched_contract_init(t_3c_work_3(2), batch_range_2=batch_ranges_at)
     980           54 :       CALL dbt_batched_contract_init(t_3c_work_3(3), batch_range_2=batch_ranges_at)
     981           54 :       CALL dbt_batched_contract_init(t_3c_work_2(1), batch_range_1=batch_ranges_at)
     982           54 :       CALL dbt_batched_contract_init(t_3c_work_2(2), batch_range_1=batch_ranges_at)
     983              : 
     984              :       !Preparing for the stacking of 3c tensors
     985           54 :       nimg_nze = ri_data%nimg_nze
     986           54 :       batch_size = ri_data%kp_stack_size
     987           54 :       n_batch = nimg_nze/batch_size
     988           54 :       IF (MODULO(nimg_nze, batch_size) /= 0) n_batch = n_batch + 1
     989          162 :       ALLOCATE (batch_ranges_nze(n_batch + 1))
     990          148 :       DO i_batch = 1, n_batch
     991          148 :          batch_ranges_nze(i_batch) = (i_batch - 1)*batch_size + 1
     992              :       END DO
     993           54 :       batch_ranges_nze(n_batch + 1) = nimg_nze + 1
     994              : 
     995              :       !Applying the external bump to ((P|Q)_D + B*(P|Q)_OD*B)^-1 from left and right
     996              :       !And keep the bump on LHS only version as well, with B*M^-1 = (M^-1*B)^T
     997          162 :       DO iatom = 1, natom
     998          108 :          CALL dbt_create(t_2c_inv(iatom), t_2c_binv(iatom))
     999          108 :          CALL dbt_copy(t_2c_inv(iatom), t_2c_binv(iatom))
    1000          108 :          CALL apply_bump(t_2c_binv(iatom), iatom, ri_data, qs_env, from_left=.TRUE., from_right=.FALSE.)
    1001          162 :          CALL apply_bump(t_2c_inv(iatom), iatom, ri_data, qs_env, from_left=.TRUE., from_right=.TRUE.)
    1002              :       END DO
    1003              : 
    1004           54 :       t1 = m_walltime()
    1005           54 :       work_virial = 0.0_dp
    1006          270 :       ALLOCATE (iapc_pairs(nimg, 2), i_images(nimg))
    1007          270 :       ALLOCATE (force_pattern(natom, natom, nimg))
    1008        10652 :       force_pattern(:, :, :) = -1
    1009              :       !We proceed with 2 loops: one over the sparsity pattern from the SCF, one over the rest
    1010              :       !We use the SCF cost model for the first loop, while we calculate the cost of the upcoming loop
    1011          162 :       DO i_loop = 1, 2
    1012         3136 :          DO b_img = 1, nimg
    1013         9192 :             DO jatom = 1, natom
    1014        21196 :                DO iatom = 1, natom
    1015              : 
    1016        12112 :                   pref = -0.5_dp*fac
    1017        12112 :                   IF (i_loop == 1 .AND. (.NOT. sparsity_pattern(iatom, jatom, b_img) == igroup)) CYCLE
    1018         6900 :                   IF (i_loop == 2 .AND. (.NOT. force_pattern(iatom, jatom, b_img) == igroup)) CYCLE
    1019              : 
    1020              :                   !Get the proper HFX potential 2c integrals (R_i^0|S_j^b), times (S_j^b|Q_j^b)^-1
    1021         1615 :                   CALL timeset(routineN//"_2c_1", handle2)
    1022              :                   CALL get_ext_2c_int(t_2c_work(1), mat_2c_pot, iatom, jatom, b_img, ri_data, qs_env, &
    1023              :                                       blacs_env_ext=blacs_env_sub, para_env_ext=para_env_sub, &
    1024         1615 :                                       dbcsr_template=dbcsr_template)
    1025              :                   CALL dbt_contract(1.0_dp, t_2c_work(1), t_2c_inv(jatom), &
    1026              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1027              :                                     contract_1=[2], notcontract_1=[1], &
    1028              :                                     contract_2=[1], notcontract_2=[2], &
    1029         1615 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1030         1615 :                   CALL dbt_copy(t_2c_work(2), t_2c_work(5), move_data=.TRUE.) !move to split blocks
    1031         1615 :                   CALL dbt_filter(t_2c_work(5), ri_data%filter_eps)
    1032         1615 :                   CALL timestop(handle2)
    1033              : 
    1034         1615 :                   CALL timeset(routineN//"_3c", handle2)
    1035         8054 :                   bounds_iat(:, 1) = [SUM(ri_data%bsizes_AO(1:iatom - 1)) + 1, SUM(ri_data%bsizes_AO(1:iatom))]
    1036         8016 :                   bounds_jat(:, 1) = [SUM(ri_data%bsizes_AO(1:jatom - 1)) + 1, SUM(ri_data%bsizes_AO(1:jatom))]
    1037         1615 :                   CALL dbt_clear(t_2c_R_split)
    1038              : 
    1039         3491 :                   DO i_spin = 1, nspins
    1040         3491 :                      CALL dbt_batched_contract_init(rho_ao_t_sub(i_spin, b_img))
    1041              :                   END DO
    1042              : 
    1043         1615 :                   CALL get_iapc_pairs(iapc_pairs, b_img, ri_data, qs_env, i_images) !i = a+c-b
    1044         5221 :                   DO i_batch = 1, n_batch
    1045              : 
    1046              :                      !Stack the 3c derivatives to take the trace later on
    1047        14424 :                      DO i_xyz = 1, 3
    1048        10818 :                         CALL dbt_clear(t_3c_der_stack(i_xyz))
    1049              :                         CALL fill_3c_stack(t_3c_der_stack(i_xyz), t_3c_der_RI_sub(:, i_xyz), &
    1050              :                                            iapc_pairs(:, 1), 3, ri_data, filter_at=jatom, &
    1051              :                                            filter_dim=2, idx_to_at=idx_to_at_AO, &
    1052        32454 :                                            img_bounds=[batch_ranges_nze(i_batch), batch_ranges_nze(i_batch + 1)])
    1053              : 
    1054        10818 :                         CALL dbt_clear(t_3c_der_stack(3 + i_xyz))
    1055              :                         CALL fill_3c_stack(t_3c_der_stack(3 + i_xyz), t_3c_der_AO_sub(:, i_xyz), &
    1056              :                                            iapc_pairs(:, 1), 3, ri_data, filter_at=jatom, &
    1057              :                                            filter_dim=2, idx_to_at=idx_to_at_AO, &
    1058        36060 :                                            img_bounds=[batch_ranges_nze(i_batch), batch_ranges_nze(i_batch + 1)])
    1059              :                      END DO
    1060              : 
    1061         9188 :                      DO i_spin = 1, nspins
    1062              :                         !stack the t_3c_apc tensors
    1063         3967 :                         CALL dbt_clear(t_3c_work_2(3))
    1064              :                         CALL fill_3c_stack(t_3c_work_2(3), t_3c_apc_sub(i_spin, :), iapc_pairs(:, 2), 3, &
    1065              :                                            ri_data, filter_at=iatom, filter_dim=1, idx_to_at=idx_to_at_AO, &
    1066        11901 :                                            img_bounds=[batch_ranges_nze(i_batch), batch_ranges_nze(i_batch + 1)])
    1067         3967 :                         CALL get_tensor_occupancy(t_3c_work_2(3), nze, occ)
    1068         3967 :                         IF (nze == 0) CYCLE
    1069         3946 :                         CALL dbt_copy(t_3c_work_2(3), t_3c_work_2(1), move_data=.TRUE.)
    1070              : 
    1071              :                         !Contract with the second density matrix: P_mu^0,nu^b * t_3c_apc,
    1072              :                         !where t_3c_apc = P_sigma^a,lambda^a+c (mu^0 P^0 sigma^a) *(P^0|R^0)^-1 (stacked along a+c)
    1073              :                         CALL dbt_contract(1.0_dp, rho_ao_t_sub(i_spin, b_img), t_3c_work_2(1), &
    1074              :                                           0.0_dp, t_3c_work_2(2), map_1=[1], map_2=[2, 3], &
    1075              :                                           contract_1=[1], notcontract_1=[2], &
    1076              :                                           contract_2=[1], notcontract_2=[2, 3], &
    1077              :                                           bounds_1=bounds_iat, bounds_2=bounds_jat, &
    1078         3946 :                                           filter_eps=ri_data%filter_eps, flop=nflop)
    1079         3946 :                         ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1080              : 
    1081         3946 :                         CALL get_tensor_occupancy(t_3c_work_2(2), nze, occ)
    1082         3946 :                         IF (nze == 0) CYCLE
    1083              : 
    1084              :                         !Contract with V_PQ so that we can take the trace with (Q^b|nu^b lmabda^a+c)^(x)
    1085         3172 :                         CALL dbt_copy(t_3c_work_2(2), t_3c_work_3(1), order=[2, 1, 3], move_data=.TRUE.)
    1086         3172 :                         CALL dbt_batched_contract_init(t_2c_work(5))
    1087              :                         CALL dbt_contract(1.0_dp, t_2c_work(5), t_3c_work_3(1), &
    1088              :                                           0.0_dp, t_3c_work_3(2), map_1=[1], map_2=[2, 3], &
    1089              :                                           contract_1=[1], notcontract_1=[2], &
    1090              :                                           contract_2=[1], notcontract_2=[2, 3], &
    1091         3172 :                                           filter_eps=ri_data%filter_eps, flop=nflop)
    1092         3172 :                         ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1093         3172 :                         CALL dbt_batched_contract_finalize(t_2c_work(5))
    1094              : 
    1095              :                         !Contract with the 3c derivatives to get the force/virial
    1096         3172 :                         CALL dbt_copy(t_3c_work_3(2), t_3c_work_3(4), move_data=.TRUE.)
    1097         3172 :                         IF (use_virial_prv) THEN
    1098              :                            CALL get_force_from_3c_trace(force, t_3c_work_3(4), t_3c_der_stack(1:3), &
    1099              :                                                         t_3c_der_stack(4:6), atom_of_kind, kind_of, &
    1100              :                                                         idx_to_at_RI, idx_to_at_AO, i_images, &
    1101              :                                                         batch_ranges_nze(i_batch), 2.0_dp*pref, &
    1102          690 :                                                         ri_data, qs_env, work_virial, cell, particle_set)
    1103              :                         ELSE
    1104              :                            CALL get_force_from_3c_trace(force, t_3c_work_3(4), t_3c_der_stack(1:3), &
    1105              :                                                         t_3c_der_stack(4:6), atom_of_kind, kind_of, &
    1106              :                                                         idx_to_at_RI, idx_to_at_AO, i_images, &
    1107              :                                                         batch_ranges_nze(i_batch), 2.0_dp*pref, &
    1108         2482 :                                                         ri_data, qs_env)
    1109              :                         END IF
    1110         3172 :                         CALL dbt_clear(t_3c_work_3(4))
    1111              : 
    1112              :                         !Contract with the 3-center integrals in order to have a matrix R_PQ such that
    1113              :                         !we can take the trace sum_PQ R_PQ (P^0|Q^b)^(x)
    1114         3172 :                         IF (i_loop == 2) CYCLE
    1115              : 
    1116              :                         !Stack the 3c integrals
    1117              :                         CALL fill_3c_stack(t_3c_work_3(4), ri_data%kp_t_3c_int, iapc_pairs(:, 1), 3, ri_data, &
    1118              :                                            filter_at=jatom, filter_dim=2, idx_to_at=idx_to_at_AO, &
    1119         4989 :                                            img_bounds=[batch_ranges_nze(i_batch), batch_ranges_nze(i_batch + 1)])
    1120         1663 :                         CALL dbt_copy(t_3c_work_3(4), t_3c_work_3(3), move_data=.TRUE.)
    1121              : 
    1122         1663 :                         CALL dbt_batched_contract_init(t_2c_R_split)
    1123              :                         CALL dbt_contract(1.0_dp, t_3c_work_3(1), t_3c_work_3(3), &
    1124              :                                           1.0_dp, t_2c_R_split, map_1=[1], map_2=[2], &
    1125              :                                           contract_1=[2, 3], notcontract_1=[1], &
    1126              :                                           contract_2=[2, 3], notcontract_2=[1], &
    1127         1663 :                                           filter_eps=ri_data%filter_eps, flop=nflop)
    1128         1663 :                         ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1129         1663 :                         CALL dbt_batched_contract_finalize(t_2c_R_split)
    1130        13182 :                         CALL dbt_copy(t_3c_work_3(4), t_3c_work_3(1))
    1131              :                      END DO
    1132              :                   END DO
    1133         3491 :                   DO i_spin = 1, nspins
    1134         3491 :                      CALL dbt_batched_contract_finalize(rho_ao_t_sub(i_spin, b_img))
    1135              :                   END DO
    1136         1615 :                   CALL timestop(handle2)
    1137              : 
    1138         1615 :                   IF (i_loop == 2) CYCLE
    1139          844 :                   pref = 2.0_dp*pref
    1140          844 :                   IF (iatom == jatom .AND. b_img == 1) pref = 0.5_dp*pref
    1141              : 
    1142          844 :                   CALL timeset(routineN//"_2c_2", handle2)
    1143              :                   !Note that the derivatives are in atomic block format (not split)
    1144          844 :                   CALL dbt_copy(t_2c_R_split, t_2c_R, move_data=.TRUE.)
    1145              : 
    1146              :                   CALL get_ext_2c_int(t_2c_work(1), mat_2c_pot, iatom, jatom, b_img, ri_data, qs_env, &
    1147              :                                       blacs_env_ext=blacs_env_sub, para_env_ext=para_env_sub, &
    1148          844 :                                       dbcsr_template=dbcsr_template)
    1149              : 
    1150              :                   !We have to calculate: S^-1(iat) * R_PQ * S^-1(jat)    to trace with HFX pot der
    1151              :                   !                      + R_PQ * S^-1(jat) * pot^T      to trace with S^(x) (iat)
    1152              :                   !                      + pot^T * S^-1(iat) *R_PQ       to trace with S^(x) (jat)
    1153              : 
    1154              :                   !Because 3c tensors are all precontracted with the inverse RI metric,
    1155              :                   !t_2c_R is currently implicitely multiplied by S^-1(iat) from the left
    1156              :                   !and S^-1(jat) from the right, directly in the proper format for the trace
    1157              :                   !with the HFX potential derivative
    1158              : 
    1159              :                   !Trace with HFX pot deriv, that we need to build first
    1160         3376 :                   DO i_xyz = 1, 3
    1161              :                      CALL get_ext_2c_int(t_2c_der_pot(i_xyz), mat_der_pot_sub(:, i_xyz), iatom, jatom, &
    1162              :                                          b_img, ri_data, qs_env, blacs_env_ext=blacs_env_sub, &
    1163         3376 :                                          para_env_ext=para_env_sub, dbcsr_template=dbcsr_template)
    1164              :                   END DO
    1165              : 
    1166          844 :                   IF (use_virial_prv) THEN
    1167              :                      CALL get_2c_der_force(force, t_2c_R, t_2c_der_pot, atom_of_kind, kind_of, &
    1168          218 :                                            b_img, pref, ri_data, qs_env, work_virial, cell, particle_set)
    1169              :                   ELSE
    1170              :                      CALL get_2c_der_force(force, t_2c_R, t_2c_der_pot, atom_of_kind, kind_of, &
    1171          626 :                                            b_img, pref, ri_data, qs_env)
    1172              :                   END IF
    1173              : 
    1174         3376 :                   DO i_xyz = 1, 3
    1175         3376 :                      CALL dbt_clear(t_2c_der_pot(i_xyz))
    1176              :                   END DO
    1177              : 
    1178              :                   !R_PQ * S^-1(jat) * pot^T  (=A)
    1179              :                   CALL dbt_contract(1.0_dp, t_2c_metric(iatom), t_2c_R, & !get rid of implicit S^-1(iat)
    1180              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1181              :                                     contract_1=[2], notcontract_1=[1], &
    1182              :                                     contract_2=[1], notcontract_2=[2], &
    1183          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1184          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1185              :                   CALL dbt_contract(1.0_dp, t_2c_work(2), t_2c_work(1), &
    1186              :                                     0.0_dp, t_2c_work(3), map_1=[1], map_2=[2], &
    1187              :                                     contract_1=[2], notcontract_1=[1], &
    1188              :                                     contract_2=[2], notcontract_2=[1], &
    1189          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1190          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1191              : 
    1192              :                   !With the RI bump function, things get more complex. M = (S|P)_D + B*(S|P)_OD*B
    1193              :                   !Calculate M^-1*B*A + A*B*M^-1 to contract with B^x. A is in t_2c_work(3)
    1194              :                   CALL dbt_contract(1.0_dp, t_2c_work(3), t_2c_binv(iatom), &
    1195              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1196              :                                     contract_1=[2], notcontract_1=[1], &
    1197              :                                     contract_2=[1], notcontract_2=[2], &
    1198          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1199          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1200              : 
    1201              :                   CALL dbt_contract(1.0_dp, t_2c_binv(iatom), t_2c_work(3), & !use transpose of B*M^-1 = M^-1*B
    1202              :                                     0.0_dp, t_2c_work(4), map_1=[1], map_2=[2], &
    1203              :                                     contract_1=[1], notcontract_1=[2], &
    1204              :                                     contract_2=[1], notcontract_2=[2], &
    1205          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1206          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1207              : 
    1208          844 :                   CALL dbt_copy(t_2c_work(2), t_2c_work(4), summation=.TRUE.)
    1209              :                   CALL get_2c_bump_forces(force, t_2c_work(4), iatom, atom_of_kind, kind_of, pref, &
    1210          844 :                                           ri_data, qs_env, work_virial)
    1211              : 
    1212              :                   !Calculate -M^-1*B*A*B*M^-1 to contracte with diagonal RI metric deriv. t_2c_work(2) holds A*B*M^-1
    1213              :                   CALL dbt_contract(1.0_dp, t_2c_binv(iatom), t_2c_work(2), &
    1214              :                                     0.0_dp, t_2c_work(4), map_1=[1], map_2=[2], &
    1215              :                                     contract_1=[1], notcontract_1=[2], &
    1216              :                                     contract_2=[1], notcontract_2=[2], &
    1217          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1218          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1219              : 
    1220          844 :                   IF (use_virial_prv) THEN
    1221              :                      CALL get_2c_der_force(force, t_2c_work(4), t_2c_der_metric_sub(iatom, :), atom_of_kind, &
    1222              :                                            kind_of, 1, -pref, ri_data, qs_env, work_virial, cell, particle_set, &
    1223          218 :                                            diag=.TRUE., offdiag=.FALSE.)
    1224              :                   ELSE
    1225              :                      CALL get_2c_der_force(force, t_2c_work(4), t_2c_der_metric_sub(iatom, :), atom_of_kind, &
    1226          626 :                                            kind_of, 1, -pref, ri_data, qs_env, diag=.TRUE., offdiag=.FALSE.)
    1227              :                   END IF
    1228              : 
    1229              :                   !Calculate -B*M^-1*B*A*B*M^-1*B to contract with off-diagonal RI metric derivs
    1230          844 :                   CALL dbt_copy(t_2c_work(4), t_2c_work(2))
    1231          844 :                   CALL apply_bump(t_2c_work(2), iatom, ri_data, qs_env, from_left=.TRUE., from_right=.TRUE.)
    1232              : 
    1233          844 :                   IF (use_virial_prv) THEN
    1234              :                      CALL get_2c_der_force(force, t_2c_work(2), t_2c_der_metric_sub(iatom, :), atom_of_kind, &
    1235              :                                            kind_of, 1, -pref, ri_data, qs_env, work_virial, cell, particle_set, &
    1236          218 :                                            diag=.FALSE., offdiag=.TRUE.)
    1237              :                   ELSE
    1238              :                      CALL get_2c_der_force(force, t_2c_work(2), t_2c_der_metric_sub(iatom, :), atom_of_kind, &
    1239          626 :                                            kind_of, 1, -pref, ri_data, qs_env, diag=.FALSE., offdiag=.TRUE.)
    1240              :                   END IF
    1241              : 
    1242              :                   !Calculate -O*B*M^-1*B*A*B*M^-1 - M^-1*B*A*B*M^-1*B*O, where O is off-diagonal integrals
    1243              :                   !t_2c_work(4) holds M^-1*B*A*B*M^-1, and exploit transpose of B*O (stored in t_2c_bint)
    1244              :                   CALL dbt_contract(1.0_dp, t_2c_work(4), t_2c_bint(iatom), &
    1245              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1246              :                                     contract_1=[2], notcontract_1=[1], &
    1247              :                                     contract_2=[1], notcontract_2=[2], &
    1248          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1249          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1250              : 
    1251              :                   CALL dbt_contract(1.0_dp, t_2c_bint(iatom), t_2c_work(4), &
    1252              :                                     1.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1253              :                                     contract_1=[1], notcontract_1=[2], &
    1254              :                                     contract_2=[1], notcontract_2=[2], &
    1255          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1256          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1257              : 
    1258              :                   CALL get_2c_bump_forces(force, t_2c_work(2), iatom, atom_of_kind, kind_of, -pref, &
    1259          844 :                                           ri_data, qs_env, work_virial)
    1260              : 
    1261              :                   ! pot^T * S^-1(iat) * R_PQ (=A)
    1262              :                   CALL dbt_contract(1.0_dp, t_2c_work(1), t_2c_R, &
    1263              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1264              :                                     contract_1=[1], notcontract_1=[2], &
    1265              :                                     contract_2=[1], notcontract_2=[2], &
    1266          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1267          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1268              : 
    1269              :                   CALL dbt_contract(1.0_dp, t_2c_work(2), t_2c_metric(jatom), & !get rid of implicit S^-1(jat)
    1270              :                                     0.0_dp, t_2c_work(3), map_1=[1], map_2=[2], &
    1271              :                                     contract_1=[2], notcontract_1=[1], &
    1272              :                                     contract_2=[1], notcontract_2=[2], &
    1273          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1274          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1275              : 
    1276              :                   !Do the same shenanigans with the S^(x) (jatom)
    1277              :                   !Calculate M^-1*B*A + A*B*M^-1 to contract with B^x. A is in t_2c_work(3)
    1278              :                   CALL dbt_contract(1.0_dp, t_2c_work(3), t_2c_binv(jatom), &
    1279              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1280              :                                     contract_1=[2], notcontract_1=[1], &
    1281              :                                     contract_2=[1], notcontract_2=[2], &
    1282          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1283          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1284              : 
    1285              :                   CALL dbt_contract(1.0_dp, t_2c_binv(jatom), t_2c_work(3), & !use transpose of B*M^-1 = M^-1*B
    1286              :                                     0.0_dp, t_2c_work(4), map_1=[1], map_2=[2], &
    1287              :                                     contract_1=[1], notcontract_1=[2], &
    1288              :                                     contract_2=[1], notcontract_2=[2], &
    1289          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1290          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1291              : 
    1292          844 :                   CALL dbt_copy(t_2c_work(2), t_2c_work(4), summation=.TRUE.)
    1293              :                   CALL get_2c_bump_forces(force, t_2c_work(4), jatom, atom_of_kind, kind_of, pref, &
    1294          844 :                                           ri_data, qs_env, work_virial)
    1295              : 
    1296              :                   !Calculate -M^-1*B*A*B*M^-1 to contracte with diagonal RI metric deriv. t_2c_work(2) holds A*B*M^-1
    1297              :                   CALL dbt_contract(1.0_dp, t_2c_binv(jatom), t_2c_work(2), &
    1298              :                                     0.0_dp, t_2c_work(4), map_1=[1], map_2=[2], &
    1299              :                                     contract_1=[1], notcontract_1=[2], &
    1300              :                                     contract_2=[1], notcontract_2=[2], &
    1301          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1302          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1303              : 
    1304          844 :                   IF (use_virial_prv) THEN
    1305              :                      CALL get_2c_der_force(force, t_2c_work(4), t_2c_der_metric_sub(jatom, :), atom_of_kind, &
    1306              :                                            kind_of, 1, -pref, ri_data, qs_env, work_virial, cell, particle_set, &
    1307          218 :                                            diag=.TRUE., offdiag=.FALSE.)
    1308              :                   ELSE
    1309              :                      CALL get_2c_der_force(force, t_2c_work(4), t_2c_der_metric_sub(jatom, :), atom_of_kind, &
    1310          626 :                                            kind_of, 1, -pref, ri_data, qs_env, diag=.TRUE., offdiag=.FALSE.)
    1311              :                   END IF
    1312              : 
    1313              :                   !Calculate -B*M^-1*B*A*B*M^-1*B to contract with off-diagonal RI metric derivs
    1314          844 :                   CALL dbt_copy(t_2c_work(4), t_2c_work(2))
    1315          844 :                   CALL apply_bump(t_2c_work(2), jatom, ri_data, qs_env, from_left=.TRUE., from_right=.TRUE.)
    1316              : 
    1317          844 :                   IF (use_virial_prv) THEN
    1318              :                      CALL get_2c_der_force(force, t_2c_work(2), t_2c_der_metric_sub(jatom, :), atom_of_kind, &
    1319              :                                            kind_of, 1, -pref, ri_data, qs_env, work_virial, cell, particle_set, &
    1320          218 :                                            diag=.FALSE., offdiag=.TRUE.)
    1321              :                   ELSE
    1322              :                      CALL get_2c_der_force(force, t_2c_work(2), t_2c_der_metric_sub(jatom, :), atom_of_kind, &
    1323          626 :                                            kind_of, 1, -pref, ri_data, qs_env, diag=.FALSE., offdiag=.TRUE.)
    1324              :                   END IF
    1325              : 
    1326              :                   !Calculate -O*B*M^-1*B*A*B*M^-1 - M^-1*B*A*B*M^-1*B*O, where O is off-diagonal integrals
    1327              :                   !t_2c_work(4) holds M^-1*B*A*B*M^-1, and exploit transpose of B*O (stored in t_2c_bint)
    1328              :                   CALL dbt_contract(1.0_dp, t_2c_work(4), t_2c_bint(jatom), &
    1329              :                                     0.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1330              :                                     contract_1=[2], notcontract_1=[1], &
    1331              :                                     contract_2=[1], notcontract_2=[2], &
    1332          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1333          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1334              : 
    1335              :                   CALL dbt_contract(1.0_dp, t_2c_bint(jatom), t_2c_work(4), &
    1336              :                                     1.0_dp, t_2c_work(2), map_1=[1], map_2=[2], &
    1337              :                                     contract_1=[1], notcontract_1=[2], &
    1338              :                                     contract_2=[1], notcontract_2=[2], &
    1339          844 :                                     filter_eps=ri_data%filter_eps, flop=nflop)
    1340          844 :                   ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    1341              : 
    1342              :                   CALL get_2c_bump_forces(force, t_2c_work(2), jatom, atom_of_kind, kind_of, -pref, &
    1343          844 :                                           ri_data, qs_env, work_virial)
    1344              : 
    1345        21471 :                   CALL timestop(handle2)
    1346              :                END DO !iatom
    1347              :             END DO !jatom
    1348              :          END DO !b_img
    1349              : 
    1350          162 :          IF (i_loop == 1) THEN
    1351           54 :             CALL update_pattern_to_forces(force_pattern, sparsity_pattern, ngroups, ri_data, qs_env)
    1352              :          END IF
    1353              :       END DO !i_loop
    1354              : 
    1355           54 :       CALL dbt_batched_contract_finalize(t_3c_work_3(1))
    1356           54 :       CALL dbt_batched_contract_finalize(t_3c_work_3(2))
    1357           54 :       CALL dbt_batched_contract_finalize(t_3c_work_3(3))
    1358           54 :       CALL dbt_batched_contract_finalize(t_3c_work_2(1))
    1359           54 :       CALL dbt_batched_contract_finalize(t_3c_work_2(2))
    1360              : 
    1361           54 :       IF (use_virial_prv) THEN
    1362           56 :          DO k_xyz = 1, 3
    1363          182 :             DO j_xyz = 1, 3
    1364          546 :                DO i_xyz = 1, 3
    1365              :                   virial%pv_fock_4c(i_xyz, j_xyz) = virial%pv_fock_4c(i_xyz, j_xyz) &
    1366          504 :                                                     + work_virial(i_xyz, k_xyz)*cell%hmat(j_xyz, k_xyz)
    1367              :                END DO
    1368              :             END DO
    1369              :          END DO
    1370              :       END IF
    1371              : 
    1372              :       !End of subgroup parallelization
    1373           54 :       CALL cp_blacs_env_release(blacs_env_sub)
    1374           54 :       CALL para_env_sub%free()
    1375           54 :       DEALLOCATE (para_env_sub)
    1376              : 
    1377           54 :       CALL para_env%sync()
    1378           54 :       t2 = m_walltime()
    1379           54 :       ri_data%dbcsr_time = ri_data%dbcsr_time + t2 - t1
    1380              : 
    1381              :       !clean-up
    1382           54 :       IF (ASSOCIATED(dbcsr_template)) THEN
    1383           54 :          CALL dbcsr_release(dbcsr_template)
    1384           54 :          DEALLOCATE (dbcsr_template)
    1385              :       END IF
    1386           54 :       CALL dbt_destroy(t_2c_R)
    1387           54 :       CALL dbt_destroy(t_2c_R_split)
    1388           54 :       CALL dbt_destroy(t_2c_work(1))
    1389           54 :       CALL dbt_destroy(t_2c_work(2))
    1390           54 :       CALL dbt_destroy(t_2c_work(3))
    1391           54 :       CALL dbt_destroy(t_2c_work(4))
    1392           54 :       CALL dbt_destroy(t_2c_work(5))
    1393           54 :       CALL dbt_destroy(t_3c_work_2(1))
    1394           54 :       CALL dbt_destroy(t_3c_work_2(2))
    1395           54 :       CALL dbt_destroy(t_3c_work_2(3))
    1396           54 :       CALL dbt_destroy(t_3c_work_3(1))
    1397           54 :       CALL dbt_destroy(t_3c_work_3(2))
    1398           54 :       CALL dbt_destroy(t_3c_work_3(3))
    1399           54 :       CALL dbt_destroy(t_3c_work_3(4))
    1400           54 :       CALL dbt_destroy(t_3c_der_stack(1))
    1401           54 :       CALL dbt_destroy(t_3c_der_stack(2))
    1402           54 :       CALL dbt_destroy(t_3c_der_stack(3))
    1403           54 :       CALL dbt_destroy(t_3c_der_stack(4))
    1404           54 :       CALL dbt_destroy(t_3c_der_stack(5))
    1405           54 :       CALL dbt_destroy(t_3c_der_stack(6))
    1406          216 :       DO i_xyz = 1, 3
    1407          216 :          CALL dbt_destroy(t_2c_der_pot(i_xyz))
    1408              :       END DO
    1409          162 :       DO iatom = 1, natom
    1410          108 :          CALL dbt_destroy(t_2c_inv(iatom))
    1411          108 :          CALL dbt_destroy(t_2c_binv(iatom))
    1412          108 :          CALL dbt_destroy(t_2c_bint(iatom))
    1413          108 :          CALL dbt_destroy(t_2c_metric(iatom))
    1414          486 :          DO i_xyz = 1, 3
    1415          432 :             CALL dbt_destroy(t_2c_der_metric_sub(iatom, i_xyz))
    1416              :          END DO
    1417              :       END DO
    1418         1568 :       DO i_img = 1, nimg
    1419         1514 :          CALL dbcsr_release(mat_2c_pot(i_img))
    1420         3262 :          DO i_spin = 1, nspins
    1421         1694 :             CALL dbt_destroy(rho_ao_t_sub(i_spin, i_img))
    1422         3208 :             CALL dbt_destroy(t_3c_apc_sub(i_spin, i_img))
    1423              :          END DO
    1424              :       END DO
    1425          216 :       DO i_xyz = 1, 3
    1426         4758 :          DO i_img = 1, nimg
    1427         4542 :             CALL dbt_destroy(t_3c_der_RI_sub(i_img, i_xyz))
    1428         4542 :             CALL dbt_destroy(t_3c_der_AO_sub(i_img, i_xyz))
    1429         4704 :             CALL dbcsr_release(mat_der_pot_sub(i_img, i_xyz))
    1430              :          END DO
    1431              :       END DO
    1432              : 
    1433           54 :       CALL timestop(handle)
    1434              : 
    1435        27374 :    END SUBROUTINE hfx_ri_update_forces_kp
    1436              : 
    1437              : ! **************************************************************************************************
    1438              : !> \brief A routine the applies the RI bump matrix from the left and/or the right, given an input
    1439              : !>        matrix and the central RI atom. We assume atomic block sizes
    1440              : !> \param t_2c_inout ...
    1441              : !> \param atom_i ...
    1442              : !> \param ri_data ...
    1443              : !> \param qs_env ...
    1444              : !> \param from_left ...
    1445              : !> \param from_right ...
    1446              : !> \param debump ...
    1447              : ! **************************************************************************************************
    1448         2480 :    SUBROUTINE apply_bump(t_2c_inout, atom_i, ri_data, qs_env, from_left, from_right, debump)
    1449              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_2c_inout
    1450              :       INTEGER, INTENT(IN)                                :: atom_i
    1451              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    1452              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1453              :       LOGICAL, INTENT(IN), OPTIONAL                      :: from_left, from_right, debump
    1454              : 
    1455              :       INTEGER                                            :: i_img, i_RI, iatom, ind(2), j_img, j_RI, &
    1456              :                                                             jatom, natom, nblks(2), nimg, nkind
    1457         2480 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1458         2480 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1459              :       LOGICAL                                            :: found, my_debump, my_left, my_right
    1460              :       REAL(dp)                                           :: bval, r0, r1, ri(3), rj(3), rref(3), &
    1461              :                                                             scoord(3)
    1462         2480 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :)             :: blk
    1463              :       TYPE(cell_type), POINTER                           :: cell
    1464              :       TYPE(dbt_iterator_type)                            :: iter
    1465              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1466         2480 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1467         2480 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1468              : 
    1469         2480 :       NULLIFY (qs_kind_set, particle_set, kpoints, index_to_cell, cell_to_index, cell)
    1470              : 
    1471              :       CALL get_qs_env(qs_env, natom=natom, nkind=nkind, qs_kind_set=qs_kind_set, cell=cell, &
    1472         2480 :                       kpoints=kpoints, particle_set=particle_set)
    1473         2480 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    1474              : 
    1475         2480 :       my_debump = .FALSE.
    1476         2480 :       IF (PRESENT(debump)) my_debump = debump
    1477              : 
    1478         2480 :       my_left = .FALSE.
    1479         2480 :       IF (PRESENT(from_left)) my_left = from_left
    1480              : 
    1481         2480 :       my_right = .FALSE.
    1482         2480 :       IF (PRESENT(from_right)) my_right = from_right
    1483         2480 :       CPASSERT(my_left .OR. my_right)
    1484              : 
    1485         2480 :       CALL dbt_get_info(t_2c_inout, nblks_total=nblks)
    1486         2480 :       CPASSERT(nblks(1) == ri_data%ncell_RI*natom)
    1487         2480 :       CPASSERT(nblks(2) == ri_data%ncell_RI*natom)
    1488              : 
    1489         2480 :       nimg = ri_data%nimg
    1490              : 
    1491              :       !Loop over the RI cells and atoms, and apply bump accordingly
    1492         2480 :       r1 = ri_data%kp_RI_range
    1493         2480 :       r0 = ri_data%kp_bump_rad
    1494         2480 :       rref = pbc(particle_set(atom_i)%r, cell)
    1495              : 
    1496              : !$OMP PARALLEL DEFAULT(NONE) SHARED(t_2c_inout,natom,ri_data,cell,particle_set,index_to_cell,my_left, &
    1497              : !$OMP                               my_right,r0,r1,rref,my_debump) &
    1498         2480 : !$OMP PRIVATE(iter,ind,blk,found,i_RI,i_img,iatom,j_RI,j_img,jatom,scoord,ri,rj,bval)
    1499              :       CALL dbt_iterator_start(iter, t_2c_inout)
    1500              :       DO WHILE (dbt_iterator_blocks_left(iter))
    1501              :          CALL dbt_iterator_next_block(iter, ind)
    1502              :          CALL dbt_get_block(t_2c_inout, ind, blk, found)
    1503              :          IF (.NOT. found) CYCLE
    1504              : 
    1505              :          i_RI = (ind(1) - 1)/natom + 1
    1506              :          i_img = ri_data%RI_cell_to_img(i_RI)
    1507              :          iatom = ind(1) - (i_RI - 1)*natom
    1508              : 
    1509              :          CALL real_to_scaled(scoord, pbc(particle_set(iatom)%r, cell), cell)
    1510              :          CALL scaled_to_real(ri, scoord(:) + index_to_cell(:, i_img), cell)
    1511              : 
    1512              :          j_RI = (ind(2) - 1)/natom + 1
    1513              :          j_img = ri_data%RI_cell_to_img(j_RI)
    1514              :          jatom = ind(2) - (j_RI - 1)*natom
    1515              : 
    1516              :          CALL real_to_scaled(scoord, pbc(particle_set(jatom)%r, cell), cell)
    1517              :          CALL scaled_to_real(rj, scoord(:) + index_to_cell(:, j_img), cell)
    1518              : 
    1519              :          IF (.NOT. my_debump) THEN
    1520              :             IF (my_left) blk(:, :) = blk(:, :)*bump(NORM2(ri - rref), r0, r1)
    1521              :             IF (my_right) blk(:, :) = blk(:, :)*bump(NORM2(rj - rref), r0, r1)
    1522              :          ELSE
    1523              :             !Note: by construction, the bump function is never quite zero, as its range is the same
    1524              :             !      as that of the extended RI basis (but we are safe)
    1525              :             bval = bump(NORM2(ri - rref), r0, r1)
    1526              :             IF (my_left .AND. bval > EPSILON(1.0_dp)) blk(:, :) = blk(:, :)/bval
    1527              :             bval = bump(NORM2(rj - rref), r0, r1)
    1528              :             IF (my_right .AND. bval > EPSILON(1.0_dp)) blk(:, :) = blk(:, :)/bval
    1529              :          END IF
    1530              : 
    1531              :          CALL dbt_put_block(t_2c_inout, ind, SHAPE(blk), blk)
    1532              : 
    1533              :          DEALLOCATE (blk)
    1534              :       END DO
    1535              :       CALL dbt_iterator_stop(iter)
    1536              : !$OMP END PARALLEL
    1537         2480 :       CALL dbt_filter(t_2c_inout, ri_data%filter_eps)
    1538              : 
    1539         4960 :    END SUBROUTINE apply_bump
    1540              : 
    1541              : ! **************************************************************************************************
    1542              : !> \brief A routine that calculates the forces due to the derivative of the bump function
    1543              : !> \param force ...
    1544              : !> \param t_2c_in ...
    1545              : !> \param atom_i ...
    1546              : !> \param atom_of_kind ...
    1547              : !> \param kind_of ...
    1548              : !> \param pref ...
    1549              : !> \param ri_data ...
    1550              : !> \param qs_env ...
    1551              : !> \param work_virial ...
    1552              : ! **************************************************************************************************
    1553         3376 :    SUBROUTINE get_2c_bump_forces(force, t_2c_in, atom_i, atom_of_kind, kind_of, pref, ri_data, &
    1554              :                                  qs_env, work_virial)
    1555              :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
    1556              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_2c_in
    1557              :       INTEGER, INTENT(IN)                                :: atom_i
    1558              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: atom_of_kind, kind_of
    1559              :       REAL(dp), INTENT(IN)                               :: pref
    1560              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    1561              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1562              :       REAL(dp), DIMENSION(3, 3), INTENT(INOUT)           :: work_virial
    1563              : 
    1564              :       INTEGER :: i, i_img, i_RI, i_xyz, iat_of_kind, iatom, ikind, ind(2), j_img, j_RI, j_xyz, &
    1565              :          jat_of_kind, jatom, jkind, natom, nblks(2), nimg, nkind
    1566         3376 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1567         3376 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1568              :       LOGICAL                                            :: found
    1569              :       REAL(dp)                                           :: new_force, r0, r1, ri(3), rj(3), &
    1570              :                                                             rref(3), scoord(3), x
    1571         3376 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :)             :: blk
    1572              :       TYPE(cell_type), POINTER                           :: cell
    1573              :       TYPE(dbt_iterator_type)                            :: iter
    1574              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1575         3376 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1576         3376 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1577              : 
    1578         3376 :       NULLIFY (qs_kind_set, particle_set, kpoints, index_to_cell, cell_to_index, cell)
    1579              : 
    1580              :       CALL get_qs_env(qs_env, natom=natom, nkind=nkind, qs_kind_set=qs_kind_set, cell=cell, &
    1581         3376 :                       kpoints=kpoints, particle_set=particle_set)
    1582         3376 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    1583              : 
    1584         3376 :       CALL dbt_get_info(t_2c_in, nblks_total=nblks)
    1585         3376 :       CPASSERT(nblks(1) == ri_data%ncell_RI*natom)
    1586         3376 :       CPASSERT(nblks(2) == ri_data%ncell_RI*natom)
    1587              : 
    1588         3376 :       nimg = ri_data%nimg
    1589              : 
    1590              :       !Loop over the RI cells and atoms, and apply bump accordingly
    1591         3376 :       r1 = ri_data%kp_RI_range
    1592         3376 :       r0 = ri_data%kp_bump_rad
    1593         3376 :       rref = pbc(particle_set(atom_i)%r, cell)
    1594              : 
    1595         3376 :       iat_of_kind = atom_of_kind(atom_i)
    1596         3376 :       ikind = kind_of(atom_i)
    1597              : 
    1598              : !$OMP PARALLEL DEFAULT(NONE) SHARED(t_2c_in,natom,ri_data,cell,particle_set,index_to_cell,pref, &
    1599              : !$OMP force,r0,r1,rref,atom_of_kind,kind_of,iat_of_kind,ikind,work_virial) &
    1600              : !$OMP PRIVATE(iter,ind,blk,found,i_RI,i_img,iatom,j_RI,j_img,jatom,scoord,ri,rj,jkind,jat_of_kind, &
    1601         3376 : !$OMP         new_force,i_xyz,i,x,j_xyz)
    1602              :       CALL dbt_iterator_start(iter, t_2c_in)
    1603              :       DO WHILE (dbt_iterator_blocks_left(iter))
    1604              :          CALL dbt_iterator_next_block(iter, ind)
    1605              :          IF (ind(1) /= ind(2)) CYCLE !bump matrix is diagonal
    1606              : 
    1607              :          CALL dbt_get_block(t_2c_in, ind, blk, found)
    1608              :          IF (.NOT. found) CYCLE
    1609              : 
    1610              :          !bump is a function of x = SQRT((R - Rref)^2). We refer to R as jatom, and Rref as atom_i
    1611              :          j_RI = (ind(2) - 1)/natom + 1
    1612              :          j_img = ri_data%RI_cell_to_img(j_RI)
    1613              :          jatom = ind(2) - (j_RI - 1)*natom
    1614              :          jat_of_kind = atom_of_kind(jatom)
    1615              :          jkind = kind_of(jatom)
    1616              : 
    1617              :          CALL real_to_scaled(scoord, pbc(particle_set(jatom)%r, cell), cell)
    1618              :          CALL scaled_to_real(rj, scoord(:) + index_to_cell(:, j_img), cell)
    1619              :          x = NORM2(rj - rref)
    1620              :          IF (x < r0 .OR. x > r1) CYCLE
    1621              : 
    1622              :          new_force = 0.0_dp
    1623              :          DO i = 1, SIZE(blk, 1)
    1624              :             new_force = new_force + blk(i, i)
    1625              :          END DO
    1626              :          new_force = pref*new_force*dbump(x, r0, r1)
    1627              : 
    1628              :          !x = SQRT((R - Rref)^2), so we multiply by dx/dR and dx/dRref
    1629              :          DO i_xyz = 1, 3
    1630              :             !Force acting on second atom
    1631              : !$OMP ATOMIC
    1632              :             force(jkind)%fock_4c(i_xyz, jat_of_kind) = force(jkind)%fock_4c(i_xyz, jat_of_kind) + &
    1633              :                                                        new_force*(rj(i_xyz) - rref(i_xyz))/x
    1634              : 
    1635              :             !virial acting on second atom
    1636              :             CALL real_to_scaled(scoord, rj, cell)
    1637              :             DO j_xyz = 1, 3
    1638              : !$OMP ATOMIC
    1639              :                work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) &
    1640              :                                            + new_force*scoord(j_xyz)*(rj(i_xyz) - rref(i_xyz))/x
    1641              :             END DO
    1642              : 
    1643              :             !Force acting on reference atom, defining the RI basis
    1644              : !$OMP ATOMIC
    1645              :             force(ikind)%fock_4c(i_xyz, iat_of_kind) = force(ikind)%fock_4c(i_xyz, iat_of_kind) - &
    1646              :                                                        new_force*(rj(i_xyz) - rref(i_xyz))/x
    1647              : 
    1648              :             !virial of ref atom
    1649              :             CALL real_to_scaled(scoord, rref, cell)
    1650              :             DO j_xyz = 1, 3
    1651              : !$OMP ATOMIC
    1652              :                work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) &
    1653              :                                            - new_force*scoord(j_xyz)*(rj(i_xyz) - rref(i_xyz))/x
    1654              :             END DO
    1655              :          END DO !i_xyz
    1656              : 
    1657              :          DEALLOCATE (blk)
    1658              :       END DO
    1659              :       CALL dbt_iterator_stop(iter)
    1660              : !$OMP END PARALLEL
    1661              : 
    1662         6752 :    END SUBROUTINE get_2c_bump_forces
    1663              : 
    1664              : ! **************************************************************************************************
    1665              : !> \brief The bumb function as defined by Juerg
    1666              : !> \param x ...
    1667              : !> \param r0 ...
    1668              : !> \param r1 ...
    1669              : !> \return ...
    1670              : ! **************************************************************************************************
    1671        41769 :    FUNCTION bump(x, r0, r1) RESULT(b)
    1672              :       REAL(dp), INTENT(IN)                               :: x, r0, r1
    1673              :       REAL(dp)                                           :: b
    1674              : 
    1675              :       REAL(dp)                                           :: r
    1676              : 
    1677              :       !Head-Gordon
    1678              :       !b = 1.0_dp/(1.0_dp+EXP((r1-r0)/(r1-x)-(r1-r0)/(x-r0)))
    1679              :       !Juerg
    1680        41769 :       r = (x - r0)/(r1 - r0)
    1681        41769 :       b = -6.0_dp*r**5 + 15.0_dp*r**4 - 10.0_dp*r**3 + 1.0_dp
    1682        41769 :       IF (x >= r1) b = 0.0_dp
    1683        41769 :       IF (x <= r0) b = 1.0_dp
    1684              : 
    1685        41769 :    END FUNCTION bump
    1686              : 
    1687              : ! **************************************************************************************************
    1688              : !> \brief The derivative of the bump function
    1689              : !> \param x ...
    1690              : !> \param r0 ...
    1691              : !> \param r1 ...
    1692              : !> \return ...
    1693              : ! **************************************************************************************************
    1694          710 :    FUNCTION dbump(x, r0, r1) RESULT(b)
    1695              :       REAL(dp), INTENT(IN)                               :: x, r0, r1
    1696              :       REAL(dp)                                           :: b
    1697              : 
    1698              :       REAL(dp)                                           :: r
    1699              : 
    1700          710 :       r = (x - r0)/(r1 - r0)
    1701          710 :       b = (-30.0_dp*r**4 + 60.0_dp*r**3 - 30.0_dp*r**2)/(r1 - r0)
    1702          710 :       IF (x >= r1) b = 0.0_dp
    1703          710 :       IF (x <= r0) b = 0.0_dp
    1704              : 
    1705          710 :    END FUNCTION dbump
    1706              : 
    1707              : ! **************************************************************************************************
    1708              : !> \brief return the cell index a+c corresponding to given cell index i and b, with i = a+c-b
    1709              : !> \param i_index ...
    1710              : !> \param b_index ...
    1711              : !> \param qs_env ...
    1712              : !> \return ...
    1713              : ! **************************************************************************************************
    1714      1642870 :    FUNCTION get_apc_index_from_ib(i_index, b_index, qs_env) RESULT(apc_index)
    1715              :       INTEGER, INTENT(IN)                                :: i_index, b_index
    1716              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1717              :       INTEGER                                            :: apc_index
    1718              : 
    1719              :       INTEGER, DIMENSION(3)                              :: cell_apc
    1720      1642870 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1721      1642870 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1722              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1723              : 
    1724      1642870 :       CALL get_qs_env(qs_env, kpoints=kpoints)
    1725      1642870 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    1726              : 
    1727              :       !i = a+c-b => a+c = i+b
    1728      6571480 :       cell_apc(:) = index_to_cell(:, i_index) + index_to_cell(:, b_index)
    1729              : 
    1730     11218898 :       IF (ANY([cell_apc(1), cell_apc(2), cell_apc(3)] < LBOUND(cell_to_index)) .OR. &
    1731              :           ANY([cell_apc(1), cell_apc(2), cell_apc(3)] > UBOUND(cell_to_index))) THEN
    1732              : 
    1733              :          apc_index = 0
    1734              :       ELSE
    1735      1427146 :          apc_index = cell_to_index(cell_apc(1), cell_apc(2), cell_apc(3))
    1736              :       END IF
    1737              : 
    1738      1642870 :    END FUNCTION get_apc_index_from_ib
    1739              : 
    1740              : ! **************************************************************************************************
    1741              : !> \brief return the cell index i corresponding to the summ of cell_a and cell_c
    1742              : !> \param a_index ...
    1743              : !> \param c_index ...
    1744              : !> \param qs_env ...
    1745              : !> \return ...
    1746              : ! **************************************************************************************************
    1747            0 :    FUNCTION get_apc_index(a_index, c_index, qs_env) RESULT(i_index)
    1748              :       INTEGER, INTENT(IN)                                :: a_index, c_index
    1749              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1750              :       INTEGER                                            :: i_index
    1751              : 
    1752              :       INTEGER, DIMENSION(3)                              :: cell_i
    1753            0 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1754            0 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1755              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1756              : 
    1757            0 :       CALL get_qs_env(qs_env, kpoints=kpoints)
    1758            0 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    1759              : 
    1760            0 :       cell_i(:) = index_to_cell(:, a_index) + index_to_cell(:, c_index)
    1761              : 
    1762            0 :       IF (ANY([cell_i(1), cell_i(2), cell_i(3)] < LBOUND(cell_to_index)) .OR. &
    1763              :           ANY([cell_i(1), cell_i(2), cell_i(3)] > UBOUND(cell_to_index))) THEN
    1764              : 
    1765              :          i_index = 0
    1766              :       ELSE
    1767            0 :          i_index = cell_to_index(cell_i(1), cell_i(2), cell_i(3))
    1768              :       END IF
    1769              : 
    1770            0 :    END FUNCTION get_apc_index
    1771              : 
    1772              : ! **************************************************************************************************
    1773              : !> \brief return the cell index i corresponding to the summ of cell_a + cell_c - cell_b
    1774              : !> \param apc_index ...
    1775              : !> \param b_index ...
    1776              : !> \param qs_env ...
    1777              : !> \return ...
    1778              : ! **************************************************************************************************
    1779      1799390 :    FUNCTION get_i_index(apc_index, b_index, qs_env) RESULT(i_index)
    1780              :       INTEGER, INTENT(IN)                                :: apc_index, b_index
    1781              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1782              :       INTEGER                                            :: i_index
    1783              : 
    1784              :       INTEGER, DIMENSION(3)                              :: cell_i
    1785      1799390 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1786      1799390 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1787              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1788              : 
    1789      1799390 :       CALL get_qs_env(qs_env, kpoints=kpoints)
    1790      1799390 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    1791              : 
    1792      7197560 :       cell_i(:) = index_to_cell(:, apc_index) - index_to_cell(:, b_index)
    1793              : 
    1794     12350314 :       IF (ANY([cell_i(1), cell_i(2), cell_i(3)] < LBOUND(cell_to_index)) .OR. &
    1795              :           ANY([cell_i(1), cell_i(2), cell_i(3)] > UBOUND(cell_to_index))) THEN
    1796              : 
    1797              :          i_index = 0
    1798              :       ELSE
    1799      1597446 :          i_index = cell_to_index(cell_i(1), cell_i(2), cell_i(3))
    1800              :       END IF
    1801              : 
    1802      1799390 :    END FUNCTION get_i_index
    1803              : 
    1804              : ! **************************************************************************************************
    1805              : !> \brief A routine that returns all allowed a,c pairs such that a+c images corresponds to the value
    1806              : !>        of the apc_index input. Takes into account that image a corresponds to 3c integrals, which
    1807              : !>        are ordered in their own way
    1808              : !> \param ac_pairs ...
    1809              : !> \param apc_index ...
    1810              : !> \param ri_data ...
    1811              : !> \param qs_env ...
    1812              : ! **************************************************************************************************
    1813        39638 :    SUBROUTINE get_ac_pairs(ac_pairs, apc_index, ri_data, qs_env)
    1814              :       INTEGER, DIMENSION(:, :), INTENT(INOUT)            :: ac_pairs
    1815              :       INTEGER, INTENT(IN)                                :: apc_index
    1816              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    1817              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1818              : 
    1819              :       INTEGER                                            :: a_index, actual_img, c_index, nimg
    1820              : 
    1821        39638 :       nimg = SIZE(ac_pairs, 1)
    1822              : 
    1823      3717694 :       ac_pairs(:, :) = 0
    1824              : !$OMP PARALLEL DO DEFAULT(NONE) SHARED(ac_pairs,nimg,ri_data,qs_env,apc_index) &
    1825        39638 : !$OMP PRIVATE(a_index,actual_img,c_index)
    1826              :       DO a_index = 1, nimg
    1827              :          actual_img = ri_data%idx_to_img(a_index)
    1828              :          !c = a+c - a
    1829              :          c_index = get_i_index(apc_index, actual_img, qs_env)
    1830              :          ac_pairs(a_index, 1) = a_index
    1831              :          ac_pairs(a_index, 2) = c_index
    1832              :       END DO
    1833              : !$OMP END PARALLEL DO
    1834              : 
    1835        39638 :    END SUBROUTINE get_ac_pairs
    1836              : 
    1837              : ! **************************************************************************************************
    1838              : !> \brief A routine that returns all allowed i,a+c pairs such that, for the given value of b, we have
    1839              : !>        i = a+c-b. Takes into account that image i corrsponds to the 3c ints, which are ordered in
    1840              : !>        their own way
    1841              : !> \param iapc_pairs ...
    1842              : !> \param b_index ...
    1843              : !> \param ri_data ...
    1844              : !> \param qs_env ...
    1845              : !> \param actual_i_img ...
    1846              : ! **************************************************************************************************
    1847        39031 :    SUBROUTINE get_iapc_pairs(iapc_pairs, b_index, ri_data, qs_env, actual_i_img)
    1848              :       INTEGER, DIMENSION(:, :), INTENT(INOUT)            :: iapc_pairs
    1849              :       INTEGER, INTENT(IN)                                :: b_index
    1850              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    1851              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1852              :       INTEGER, DIMENSION(:), INTENT(INOUT), OPTIONAL     :: actual_i_img
    1853              : 
    1854              :       INTEGER                                            :: actual_img, apc_index, i_index, nimg
    1855              : 
    1856        39031 :       nimg = SIZE(iapc_pairs, 1)
    1857       104728 :       IF (PRESENT(actual_i_img)) actual_i_img(:) = 0
    1858              : 
    1859      3402833 :       iapc_pairs(:, :) = 0
    1860              : !$OMP PARALLEL DO DEFAULT(NONE) SHARED(iapc_pairs,nimg,ri_data,qs_env,b_index,actual_i_img) &
    1861        39031 : !$OMP PRIVATE(i_index,actual_img,apc_index)
    1862              :       DO i_index = 1, nimg
    1863              :          actual_img = ri_data%idx_to_img(i_index)
    1864              :          apc_index = get_apc_index_from_ib(actual_img, b_index, qs_env)
    1865              :          IF (apc_index == 0) CYCLE
    1866              :          iapc_pairs(i_index, 1) = i_index
    1867              :          iapc_pairs(i_index, 2) = apc_index
    1868              :          IF (PRESENT(actual_i_img)) actual_i_img(i_index) = actual_img
    1869              :       END DO
    1870              : 
    1871        39031 :    END SUBROUTINE get_iapc_pairs
    1872              : 
    1873              : ! **************************************************************************************************
    1874              : !> \brief A function that, given a cell index a, returun the index corresponding to -a, and zero if
    1875              : !>        if out of bounds
    1876              : !> \param a_index ...
    1877              : !> \param qs_env ...
    1878              : !> \return ...
    1879              : ! **************************************************************************************************
    1880       189369 :    FUNCTION get_opp_index(a_index, qs_env) RESULT(opp_index)
    1881              :       INTEGER, INTENT(IN)                                :: a_index
    1882              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1883              :       INTEGER                                            :: opp_index
    1884              : 
    1885              :       INTEGER, DIMENSION(3)                              :: opp_cell
    1886       189369 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1887       189369 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1888              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1889              : 
    1890       189369 :       NULLIFY (kpoints, cell_to_index, index_to_cell)
    1891              : 
    1892       189369 :       CALL get_qs_env(qs_env, kpoints=kpoints)
    1893       189369 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    1894              : 
    1895       757476 :       opp_cell(:) = -index_to_cell(:, a_index)
    1896              : 
    1897      1325583 :       IF (ANY([opp_cell(1), opp_cell(2), opp_cell(3)] < LBOUND(cell_to_index)) .OR. &
    1898              :           ANY([opp_cell(1), opp_cell(2), opp_cell(3)] > UBOUND(cell_to_index))) THEN
    1899              : 
    1900              :          opp_index = 0
    1901              :       ELSE
    1902       189369 :          opp_index = cell_to_index(opp_cell(1), opp_cell(2), opp_cell(3))
    1903              :       END IF
    1904              : 
    1905       189369 :    END FUNCTION get_opp_index
    1906              : 
    1907              : ! **************************************************************************************************
    1908              : !> \brief A routine that returns the actual non-symemtric density matrix for each image, by Fourier
    1909              : !>        transforming the kpoint density matrix
    1910              : !> \param rho_ao_t ...
    1911              : !> \param rho_ao ...
    1912              : !> \param scale_prev_p ...
    1913              : !> \param ri_data ...
    1914              : !> \param qs_env ...
    1915              : ! **************************************************************************************************
    1916         1070 :    SUBROUTINE get_pmat_images(rho_ao_t, rho_ao, scale_prev_p, ri_data, qs_env)
    1917              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: rho_ao_t
    1918              :       TYPE(dbcsr_p_type), DIMENSION(:, :), INTENT(INOUT) :: rho_ao
    1919              :       REAL(dp), INTENT(IN)                               :: scale_prev_p
    1920              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    1921              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1922              : 
    1923              :       INTEGER                                            :: cell_j(3), i_img, i_spin, iatom, icol, &
    1924              :                                                             irow, j_img, jatom, mi_img, mj_img, &
    1925              :                                                             nimg, nspins
    1926         1070 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1927              :       LOGICAL                                            :: found
    1928              :       REAL(dp)                                           :: fac
    1929         1070 :       REAL(dp), DIMENSION(:, :), POINTER                 :: pblock, pblock_desymm
    1930         1070 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks, rho_desymm
    1931         9630 :       TYPE(dbt_type)                                     :: tmp
    1932              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1933              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1934              :       TYPE(neighbor_list_iterator_p_type), &
    1935         1070 :          DIMENSION(:), POINTER                           :: nl_iterator
    1936              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1937         1070 :          POINTER                                         :: sab_aux_fit, sab_aux_fit_asymm, sab_nl, &
    1938         1070 :                                                             sab_nl_nosym
    1939              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1940              : 
    1941         1070 :       NULLIFY (rho_desymm, kpoints, sab_nl_nosym, scf_env, matrix_ks, dft_control, &
    1942         1070 :                sab_nl, sab_aux_fit, sab_aux_fit_asymm, nl_iterator, cell_to_index, &
    1943         1070 :                pblock, pblock_desymm)
    1944              : 
    1945         1070 :       CALL get_qs_env(qs_env, kpoints=kpoints, scf_env=scf_env, matrix_ks_kp=matrix_ks, dft_control=dft_control)
    1946         1070 :       CALL get_kpoint_info(kpoints, sab_nl_nosym=sab_nl_nosym, cell_to_index=cell_to_index, sab_nl=sab_nl)
    1947              : 
    1948         1070 :       IF (dft_control%do_admm) THEN
    1949              :          CALL get_admm_env(qs_env%admm_env, matrix_ks_aux_fit_kp=matrix_ks, &
    1950          806 :                            sab_aux_fit=sab_aux_fit, sab_aux_fit_asymm=sab_aux_fit_asymm)
    1951          806 :          IF (ASSOCIATED(sab_aux_fit) .AND. ASSOCIATED(sab_aux_fit_asymm)) THEN
    1952          806 :             sab_nl => sab_aux_fit
    1953          806 :             sab_nl_nosym => sab_aux_fit_asymm
    1954              :          END IF
    1955              :       END IF
    1956              : 
    1957         1070 :       nspins = SIZE(matrix_ks, 1)
    1958         1070 :       nimg = ri_data%nimg
    1959              : 
    1960        77428 :       ALLOCATE (rho_desymm(nspins, nimg))
    1961        35852 :       DO i_img = 1, nimg
    1962        74218 :          DO i_spin = 1, nspins
    1963        38366 :             ALLOCATE (rho_desymm(i_spin, i_img)%matrix)
    1964              :             CALL dbcsr_create(rho_desymm(i_spin, i_img)%matrix, template=matrix_ks(i_spin, i_img)%matrix, &
    1965        38366 :                               matrix_type=dbcsr_type_no_symmetry)
    1966        73148 :             CALL cp_dbcsr_alloc_block_from_nbl(rho_desymm(i_spin, i_img)%matrix, sab_nl_nosym)
    1967              :          END DO
    1968              :       END DO
    1969         1070 :       CALL dbt_create(rho_desymm(1, 1)%matrix, tmp)
    1970              : 
    1971              :       !We transfor the symmtric typed (but not actually symmetric: P_ab^i = P_ba^-i) real-spaced density
    1972              :       !matrix into proper non-symemtric ones (using the same nl for consistency)
    1973         1070 :       CALL neighbor_list_iterator_create(nl_iterator, sab_nl)
    1974        55102 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    1975        54032 :          CALL get_iterator_info(nl_iterator, iatom=iatom, jatom=jatom, cell=cell_j)
    1976        54032 :          j_img = cell_to_index(cell_j(1), cell_j(2), cell_j(3))
    1977        54032 :          IF (j_img > nimg .OR. j_img < 1) CYCLE
    1978              : 
    1979        40729 :          fac = 1.0_dp
    1980        40729 :          IF (iatom == jatom) fac = 0.5_dp
    1981        40729 :          mj_img = get_opp_index(j_img, qs_env)
    1982              :          !if no opposite image, then no sum of P^j + P^-j => need full diag
    1983        40729 :          IF (mj_img == 0) fac = 1.0_dp
    1984              : 
    1985        40729 :          irow = iatom
    1986        40729 :          icol = jatom
    1987        40729 :          IF (iatom > jatom) THEN
    1988              :             !because symmetric nl. Value for atom pair i,j is actually stored in j,i if i > j
    1989        12959 :             irow = jatom
    1990        12959 :             icol = iatom
    1991              :          END IF
    1992              : 
    1993        87185 :          DO i_spin = 1, nspins
    1994        45386 :             CALL dbcsr_get_block_p(rho_ao(i_spin, j_img)%matrix, irow, icol, pblock, found)
    1995        45386 :             IF (.NOT. found) CYCLE
    1996              : 
    1997              :             !distribution of symm and non-symm matrix match in that way
    1998        45386 :             CALL dbcsr_get_block_p(rho_desymm(i_spin, j_img)%matrix, iatom, jatom, pblock_desymm, found)
    1999        45386 :             IF (.NOT. found) CYCLE
    2000              : 
    2001       190190 :             IF (iatom > jatom) THEN
    2002       991720 :                pblock_desymm(:, :) = fac*TRANSPOSE(pblock(:, :))
    2003              :             ELSE
    2004      2393948 :                pblock_desymm(:, :) = fac*pblock(:, :)
    2005              :             END IF
    2006              :          END DO
    2007              :       END DO
    2008         1070 :       CALL neighbor_list_iterator_release(nl_iterator)
    2009              : 
    2010        35852 :       DO i_img = 1, nimg
    2011        74218 :          DO i_spin = 1, nspins
    2012        38366 :             CALL dbt_scale(rho_ao_t(i_spin, i_img), scale_prev_p)
    2013              : 
    2014        38366 :             CALL dbt_copy_matrix_to_tensor(rho_desymm(i_spin, i_img)%matrix, tmp)
    2015        38366 :             CALL dbt_copy(tmp, rho_ao_t(i_spin, i_img), summation=.TRUE., move_data=.TRUE.)
    2016              : 
    2017              :             !symmetrize by addin transpose of opp img
    2018        38366 :             mi_img = get_opp_index(i_img, qs_env)
    2019        38366 :             IF (mi_img > 0 .AND. mi_img <= nimg) THEN
    2020        35874 :                CALL dbt_copy_matrix_to_tensor(rho_desymm(i_spin, mi_img)%matrix, tmp)
    2021        35874 :                CALL dbt_copy(tmp, rho_ao_t(i_spin, i_img), order=[2, 1], summation=.TRUE., move_data=.TRUE.)
    2022              :             END IF
    2023        73148 :             CALL dbt_filter(rho_ao_t(i_spin, i_img), ri_data%filter_eps)
    2024              :          END DO
    2025              :       END DO
    2026              : 
    2027        35852 :       DO i_img = 1, nimg
    2028        74218 :          DO i_spin = 1, nspins
    2029        38366 :             CALL dbcsr_release(rho_desymm(i_spin, i_img)%matrix)
    2030        73148 :             DEALLOCATE (rho_desymm(i_spin, i_img)%matrix)
    2031              :          END DO
    2032              :       END DO
    2033              : 
    2034         1070 :       CALL dbt_destroy(tmp)
    2035         1070 :       DEALLOCATE (rho_desymm)
    2036              : 
    2037         2140 :    END SUBROUTINE get_pmat_images
    2038              : 
    2039              : ! **************************************************************************************************
    2040              : !> \brief A routine that, given a cell index b and atom indices ij, returns a 2c tensor with the HFX
    2041              : !>        potential (P_i^0|Q_j^b), within the extended RI basis
    2042              : !> \param t_2c_pot ...
    2043              : !> \param mat_orig ...
    2044              : !> \param atom_i ...
    2045              : !> \param atom_j ...
    2046              : !> \param img_b ...
    2047              : !> \param ri_data ...
    2048              : !> \param qs_env ...
    2049              : !> \param do_inverse ...
    2050              : !> \param para_env_ext ...
    2051              : !> \param blacs_env_ext ...
    2052              : !> \param dbcsr_template ...
    2053              : !> \param off_diagonal ...
    2054              : !> \param skip_inverse ...
    2055              : ! **************************************************************************************************
    2056         5891 :    SUBROUTINE get_ext_2c_int(t_2c_pot, mat_orig, atom_i, atom_j, img_b, ri_data, qs_env, do_inverse, &
    2057              :                              para_env_ext, blacs_env_ext, dbcsr_template, off_diagonal, skip_inverse)
    2058              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_2c_pot
    2059              :       TYPE(dbcsr_type), DIMENSION(:), INTENT(INOUT)      :: mat_orig
    2060              :       INTEGER, INTENT(IN)                                :: atom_i, atom_j, img_b
    2061              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    2062              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2063              :       LOGICAL, INTENT(IN), OPTIONAL                      :: do_inverse
    2064              :       TYPE(mp_para_env_type), OPTIONAL, POINTER          :: para_env_ext
    2065              :       TYPE(cp_blacs_env_type), OPTIONAL, POINTER         :: blacs_env_ext
    2066              :       TYPE(dbcsr_type), OPTIONAL, POINTER                :: dbcsr_template
    2067              :       LOGICAL, INTENT(IN), OPTIONAL                      :: off_diagonal, skip_inverse
    2068              : 
    2069              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_ext_2c_int'
    2070              : 
    2071              :       INTEGER :: group, handle, handle2, i_img, i_RI, iatom, iblk, ikind, img_tot, j_img, j_RI, &
    2072              :          jatom, jblk, jkind, n_dependent, natom, nblks_RI, nimg, nkind
    2073         5891 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist1, dist2
    2074         5891 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: present_atoms_i, present_atoms_j
    2075         5891 :       INTEGER, CONTIGUOUS, DIMENSION(:), POINTER         :: col_dist, col_dist_ext, ri_blk_size_ext, &
    2076         5891 :                                                             row_dist, row_dist_ext
    2077              :       INTEGER, DIMENSION(3)                              :: cell_b, cell_i, cell_j, cell_tot
    2078         5891 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell, pgrid
    2079         5891 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    2080              :       LOGICAL                                            :: do_inverse_prv, found, my_offd, &
    2081              :                                                             skip_inverse_prv, use_template
    2082              :       REAL(dp)                                           :: bfac, dij, r0, r1, threshold
    2083              :       REAL(dp), DIMENSION(3)                             :: ri, rij, rj, rref, scoord
    2084         5891 :       REAL(dp), DIMENSION(:, :), POINTER                 :: pblock
    2085              :       TYPE(cell_type), POINTER                           :: cell
    2086              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    2087              :       TYPE(dbcsr_distribution_type)                      :: dbcsr_dist, dbcsr_dist_ext
    2088              :       TYPE(dbcsr_iterator_type)                          :: dbcsr_iter
    2089              :       TYPE(dbcsr_type)                                   :: work, work_tight, work_tight_inv
    2090        41237 :       TYPE(dbt_type)                                     :: t_2c_tmp
    2091              :       TYPE(distribution_2d_type), POINTER                :: dist_2d
    2092              :       TYPE(gto_basis_set_p_type), ALLOCATABLE, &
    2093         5891 :          DIMENSION(:), TARGET                            :: basis_set_RI
    2094              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2095              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2096              :       TYPE(neighbor_list_iterator_p_type), &
    2097         5891 :          DIMENSION(:), POINTER                           :: nl_iterator
    2098              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2099         5891 :          POINTER                                         :: nl_2c
    2100         5891 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2101         5891 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2102              : 
    2103         5891 :       NULLIFY (qs_kind_set, nl_2c, nl_iterator, cell, kpoints, cell_to_index, index_to_cell, dist_2d, &
    2104         5891 :                para_env, pblock, blacs_env, particle_set, col_dist, row_dist, pgrid, &
    2105         5891 :                col_dist_ext, row_dist_ext)
    2106              : 
    2107         5891 :       CALL timeset(routineN, handle)
    2108              : 
    2109              :       !Idea: run over the neighbor list once for i and once for j, and record in which cell the MIC
    2110              :       !      atoms are. Then loop over the atoms and only take the pairs the we need
    2111              : 
    2112              :       CALL get_qs_env(qs_env, natom=natom, nkind=nkind, qs_kind_set=qs_kind_set, cell=cell, &
    2113         5891 :                       kpoints=kpoints, para_env=para_env, blacs_env=blacs_env, particle_set=particle_set)
    2114         5891 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    2115              : 
    2116         5891 :       do_inverse_prv = .FALSE.
    2117         5891 :       IF (PRESENT(do_inverse)) do_inverse_prv = do_inverse
    2118          384 :       IF (do_inverse_prv) THEN
    2119          384 :          CPASSERT(atom_i == atom_j)
    2120              :       END IF
    2121              : 
    2122         5891 :       skip_inverse_prv = .FALSE.
    2123         5891 :       IF (PRESENT(skip_inverse)) skip_inverse_prv = skip_inverse
    2124              : 
    2125         5891 :       my_offd = .FALSE.
    2126         5891 :       IF (PRESENT(off_diagonal)) my_offd = off_diagonal
    2127              : 
    2128         5891 :       IF (PRESENT(para_env_ext)) para_env => para_env_ext
    2129         5891 :       IF (PRESENT(blacs_env_ext)) blacs_env => blacs_env_ext
    2130              : 
    2131         5891 :       nimg = SIZE(mat_orig)
    2132              : 
    2133         5891 :       CALL timeset(routineN//"_nl_iter", handle2)
    2134              : 
    2135              :       !create our own dist_2d in the subgroup
    2136        23564 :       ALLOCATE (dist1(natom), dist2(natom))
    2137        17673 :       DO iatom = 1, natom
    2138        11782 :          dist1(iatom) = MOD(iatom, blacs_env%num_pe(1))
    2139        17673 :          dist2(iatom) = MOD(iatom, blacs_env%num_pe(2))
    2140              :       END DO
    2141         5891 :       CALL distribution_2d_create(dist_2d, dist1, dist2, nkind, particle_set, blacs_env_ext=blacs_env)
    2142              : 
    2143        26665 :       ALLOCATE (basis_set_RI(nkind))
    2144         5891 :       CALL basis_set_list_setup(basis_set_RI, ri_data%ri_basis_type, qs_kind_set)
    2145              : 
    2146              :       CALL build_2c_neighbor_lists(nl_2c, basis_set_RI, basis_set_RI, ri_data%ri_metric, &
    2147         5891 :                                    "HFX_2c_nl_RI", qs_env, sym_ij=.FALSE., dist_2d=dist_2d)
    2148              : 
    2149        35346 :       ALLOCATE (present_atoms_i(natom, nimg), present_atoms_j(natom, nimg))
    2150         5891 :       present_atoms_i = 0
    2151         5891 :       present_atoms_j = 0
    2152              : 
    2153         5891 :       CALL neighbor_list_iterator_create(nl_iterator, nl_2c)
    2154       254385 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    2155              :          CALL get_iterator_info(nl_iterator, iatom=iatom, jatom=jatom, r=rij, cell=cell_j, &
    2156       248494 :                                 ikind=ikind, jkind=jkind)
    2157              : 
    2158       993976 :          dij = NORM2(rij)
    2159              : 
    2160       248494 :          j_img = cell_to_index(cell_j(1), cell_j(2), cell_j(3))
    2161       248494 :          IF (j_img > nimg .OR. j_img < 1) CYCLE
    2162              : 
    2163       246871 :          IF (iatom == atom_i .AND. dij <= ri_data%kp_RI_range) present_atoms_i(jatom, j_img) = 1
    2164       252762 :          IF (iatom == atom_j .AND. dij <= ri_data%kp_RI_range) present_atoms_j(jatom, j_img) = 1
    2165              :       END DO
    2166         5891 :       CALL neighbor_list_iterator_release(nl_iterator)
    2167         5891 :       CALL release_neighbor_list_sets(nl_2c)
    2168         5891 :       CALL distribution_2d_release(dist_2d)
    2169         5891 :       CALL timestop(handle2)
    2170              : 
    2171         5891 :       CALL para_env%sum(present_atoms_i)
    2172         5891 :       CALL para_env%sum(present_atoms_j)
    2173              : 
    2174              :       ! Retain the local RI basis used by the metric inverse for selecting G rows.
    2175         5891 :       IF (do_inverse_prv .AND. .NOT. skip_inverse_prv) THEN
    2176         5460 :          DO i_img = 1, nimg
    2177         5268 :             i_RI = ri_data%img_to_RI_cell(i_img)
    2178         5268 :             IF (i_RI == 0) CYCLE
    2179         3996 :             ri_data%kp_RI_neighbors((i_RI - 1)*natom + 1:i_RI*natom, atom_i) = present_atoms_i(:, i_img) > 0
    2180              :          END DO
    2181              :       END IF
    2182              : 
    2183              :       !Need to build a work matrix with matching distribution to mat_orig
    2184              :       !If template is provided, use it. If not, we create it.
    2185         5891 :       use_template = .FALSE.
    2186         5891 :       IF (PRESENT(dbcsr_template)) THEN
    2187         4991 :          IF (ASSOCIATED(dbcsr_template)) use_template = .TRUE.
    2188              :       END IF
    2189              : 
    2190              :       IF (use_template) THEN
    2191         4937 :          CALL dbcsr_create(work, template=dbcsr_template)
    2192              :       ELSE
    2193          954 :          CALL dbcsr_get_info(mat_orig(1), distribution=dbcsr_dist)
    2194          954 :          CALL dbcsr_distribution_get(dbcsr_dist, row_dist=row_dist, col_dist=col_dist, group=group, pgrid=pgrid)
    2195         3816 :          ALLOCATE (row_dist_ext(ri_data%ncell_RI*natom), col_dist_ext(ri_data%ncell_RI*natom))
    2196         1908 :          ALLOCATE (ri_blk_size_ext(ri_data%ncell_RI*natom))
    2197         7250 :          DO i_RI = 1, ri_data%ncell_RI
    2198        31480 :             row_dist_ext((i_RI - 1)*natom + 1:i_RI*natom) = row_dist(:)
    2199        31480 :             col_dist_ext((i_RI - 1)*natom + 1:i_RI*natom) = col_dist(:)
    2200        19842 :             RI_blk_size_ext((i_RI - 1)*natom + 1:i_RI*natom) = ri_data%bsizes_RI(:)
    2201              :          END DO
    2202              : 
    2203              :          CALL dbcsr_distribution_new(dbcsr_dist_ext, group=group, pgrid=pgrid, &
    2204          954 :                                      row_dist=row_dist_ext, col_dist=col_dist_ext)
    2205              :          CALL dbcsr_create(work, dist=dbcsr_dist_ext, name="RI_ext", matrix_type=dbcsr_type_no_symmetry, &
    2206          954 :                            row_blk_size=RI_blk_size_ext, col_blk_size=RI_blk_size_ext)
    2207          954 :          CALL dbcsr_distribution_release(dbcsr_dist_ext)
    2208          954 :          DEALLOCATE (col_dist_ext, row_dist_ext, RI_blk_size_ext)
    2209              : 
    2210         2862 :          IF (PRESENT(dbcsr_template)) THEN
    2211           54 :             ALLOCATE (dbcsr_template)
    2212           54 :             CALL dbcsr_create(dbcsr_template, template=work)
    2213              :          END IF
    2214              :       END IF !use_template
    2215              : 
    2216        23564 :       cell_b(:) = index_to_cell(:, img_b)
    2217       226845 :       DO i_img = 1, nimg
    2218       220954 :          i_RI = ri_data%img_to_RI_cell(i_img)
    2219       220954 :          IF (i_RI == 0) CYCLE
    2220       179896 :          cell_i(:) = index_to_cell(:, i_img)
    2221      2123679 :          DO j_img = 1, nimg
    2222      2072814 :             j_RI = ri_data%img_to_RI_cell(j_img)
    2223      2072814 :             IF (j_RI == 0) CYCLE
    2224      1834280 :             cell_j(:) = index_to_cell(:, j_img)
    2225      1834280 :             cell_tot = cell_j - cell_i + cell_b
    2226              : 
    2227      3175508 :             IF (ANY([cell_tot(1), cell_tot(2), cell_tot(3)] < LBOUND(cell_to_index)) .OR. &
    2228              :                 ANY([cell_tot(1), cell_tot(2), cell_tot(3)] > UBOUND(cell_to_index))) CYCLE
    2229       430335 :             img_tot = cell_to_index(cell_tot(1), cell_tot(2), cell_tot(3))
    2230       430335 :             IF (img_tot > nimg .OR. img_tot < 1) CYCLE
    2231              : 
    2232       282593 :             CALL dbcsr_iterator_start(dbcsr_iter, mat_orig(img_tot))
    2233       755135 :             DO WHILE (dbcsr_iterator_blocks_left(dbcsr_iter))
    2234       472542 :                CALL dbcsr_iterator_next_block(dbcsr_iter, row=iatom, column=jatom)
    2235       472542 :                IF (present_atoms_i(iatom, i_img) == 0) CYCLE
    2236       190017 :                IF (present_atoms_j(jatom, j_img) == 0) CYCLE
    2237        86447 :                IF (my_offd .AND. (i_RI - 1)*natom + iatom == (j_RI - 1)*natom + jatom) CYCLE
    2238              : 
    2239        86004 :                CALL dbcsr_get_block_p(mat_orig(img_tot), iatom, jatom, pblock, found)
    2240        86004 :                IF (.NOT. found) CYCLE
    2241              : 
    2242       755135 :                CALL dbcsr_put_block(work, (i_RI - 1)*natom + iatom, (j_RI - 1)*natom + jatom, pblock)
    2243              : 
    2244              :             END DO
    2245      2548126 :             CALL dbcsr_iterator_stop(dbcsr_iter)
    2246              : 
    2247              :          END DO !j_img
    2248              :       END DO !i_img
    2249         5891 :       CALL dbcsr_finalize(work)
    2250              : 
    2251         5891 :       IF (do_inverse_prv) THEN
    2252              : 
    2253          384 :          r1 = ri_data%kp_RI_range
    2254          384 :          r0 = ri_data%kp_bump_rad
    2255              : 
    2256              :          !Because there are a lot of empty rows/cols in work, we need to get rid of them for inversion
    2257        31992 :          nblks_RI = SUM(present_atoms_i)
    2258         1920 :          ALLOCATE (col_dist_ext(nblks_RI), row_dist_ext(nblks_RI), RI_blk_size_ext(nblks_RI))
    2259          384 :          iblk = 0
    2260        10920 :          DO i_img = 1, nimg
    2261        10536 :             i_RI = ri_data%img_to_RI_cell(i_img)
    2262        10536 :             IF (i_RI == 0) CYCLE
    2263         7992 :             DO iatom = 1, natom
    2264         5072 :                IF (present_atoms_i(iatom, i_img) == 0) CYCLE
    2265         1772 :                iblk = iblk + 1
    2266         1772 :                col_dist_ext(iblk) = col_dist(iatom)
    2267         1772 :                row_dist_ext(iblk) = row_dist(iatom)
    2268        15608 :                RI_blk_size_ext(iblk) = ri_data%bsizes_RI(iatom)
    2269              :             END DO
    2270              :          END DO
    2271              : 
    2272              :          CALL dbcsr_distribution_new(dbcsr_dist_ext, group=group, pgrid=pgrid, &
    2273          384 :                                      row_dist=row_dist_ext, col_dist=col_dist_ext)
    2274              :          CALL dbcsr_create(work_tight, dist=dbcsr_dist_ext, name="RI_ext", matrix_type=dbcsr_type_no_symmetry, &
    2275          384 :                            row_blk_size=RI_blk_size_ext, col_blk_size=RI_blk_size_ext)
    2276              :          CALL dbcsr_create(work_tight_inv, dist=dbcsr_dist_ext, name="RI_ext", matrix_type=dbcsr_type_no_symmetry, &
    2277          384 :                            row_blk_size=RI_blk_size_ext, col_blk_size=RI_blk_size_ext)
    2278          384 :          CALL dbcsr_distribution_release(dbcsr_dist_ext)
    2279          384 :          DEALLOCATE (col_dist_ext, row_dist_ext, RI_blk_size_ext)
    2280              : 
    2281              :          !We apply a bump function to the RI metric inverse for smooth RI basis extension:
    2282              :          ! S^-1 = B * ((P|Q)_D + B*(P|Q)_OD*B)^-1 * B, with D block-diagonal blocks and OD off-diagonal
    2283          384 :          rref = pbc(particle_set(atom_i)%r, cell)
    2284              : 
    2285          384 :          iblk = 0
    2286        10920 :          DO i_img = 1, nimg
    2287        10536 :             i_RI = ri_data%img_to_RI_cell(i_img)
    2288        10536 :             IF (i_RI == 0) CYCLE
    2289         7992 :             DO iatom = 1, natom
    2290         5072 :                IF (present_atoms_i(iatom, i_img) == 0) CYCLE
    2291         1772 :                iblk = iblk + 1
    2292              : 
    2293         1772 :                CALL real_to_scaled(scoord, pbc(particle_set(iatom)%r, cell), cell)
    2294         7088 :                CALL scaled_to_real(ri, scoord(:) + index_to_cell(:, i_img), cell)
    2295              : 
    2296         1772 :                jblk = 0
    2297        72212 :                DO j_img = 1, nimg
    2298        59904 :                   j_RI = ri_data%img_to_RI_cell(j_img)
    2299        59904 :                   IF (j_RI == 0) CYCLE
    2300        48680 :                   DO jatom = 1, natom
    2301        29072 :                      IF (present_atoms_j(jatom, j_img) == 0) CYCLE
    2302        10580 :                      jblk = jblk + 1
    2303              : 
    2304        10580 :                      CALL real_to_scaled(scoord, pbc(particle_set(jatom)%r, cell), cell)
    2305        42320 :                      CALL scaled_to_real(rj, scoord(:) + index_to_cell(:, j_img), cell)
    2306              : 
    2307        10580 :                      CALL dbcsr_get_block_p(work, (i_RI - 1)*natom + iatom, (j_RI - 1)*natom + jatom, pblock, found)
    2308        10580 :                      IF (.NOT. found) CYCLE
    2309              : 
    2310         4372 :                      bfac = 1.0_dp
    2311        25288 :                      IF (iblk /= jblk) bfac = bump(NORM2(ri - rref), r0, r1)*bump(NORM2(rj - rref), r0, r1)
    2312      6374048 :                      CALL dbcsr_put_block(work_tight, iblk, jblk, bfac*pblock(:, :))
    2313              :                   END DO
    2314              :                END DO
    2315              :             END DO
    2316              :          END DO
    2317          384 :          CALL dbcsr_finalize(work_tight)
    2318          384 :          CALL dbcsr_clear(work)
    2319              : 
    2320          384 :          IF (.NOT. skip_inverse_prv) THEN
    2321          192 :             SELECT CASE (ri_data%t2c_method)
    2322              :             CASE (hfx_ri_do_2c_iter)
    2323            0 :                threshold = MAX(ri_data%filter_eps, 1.0e-12_dp)
    2324            0 :                CALL invert_hotelling(work_tight_inv, work_tight, threshold=threshold, silent=.FALSE.)
    2325              :             CASE (hfx_ri_do_2c_cholesky)
    2326          192 :                CALL dbcsr_copy(work_tight_inv, work_tight)
    2327          192 :                CALL cp_dbcsr_cholesky_decompose(work_tight_inv, para_env=para_env, blacs_env=blacs_env)
    2328              :                CALL cp_dbcsr_cholesky_invert(work_tight_inv, para_env=para_env, blacs_env=blacs_env, &
    2329          192 :                                              uplo_to_full=.TRUE.)
    2330              :             CASE (hfx_ri_do_2c_diag)
    2331            0 :                CALL dbcsr_copy(work_tight_inv, work_tight)
    2332              :                CALL cp_dbcsr_power(work_tight_inv, -1.0_dp, ri_data%eps_eigval, n_dependent, &
    2333          192 :                                    para_env, blacs_env, verbose=ri_data%unit_nr_dbcsr > 0)
    2334              :             END SELECT
    2335              :          ELSE
    2336          192 :             CALL dbcsr_copy(work_tight_inv, work_tight)
    2337              :          END IF
    2338              : 
    2339              :          !move back data to standard extended RI pattern
    2340              :          !Note: we apply the external bump to ((P|Q)_D + B*(P|Q)_OD*B)^-1 later, because this matrix
    2341              :          !      is required for forces
    2342          384 :          iblk = 0
    2343        10920 :          DO i_img = 1, nimg
    2344        10536 :             i_RI = ri_data%img_to_RI_cell(i_img)
    2345        10536 :             IF (i_RI == 0) CYCLE
    2346         7992 :             DO iatom = 1, natom
    2347         5072 :                IF (present_atoms_i(iatom, i_img) == 0) CYCLE
    2348         1772 :                iblk = iblk + 1
    2349              : 
    2350         1772 :                jblk = 0
    2351        72212 :                DO j_img = 1, nimg
    2352        59904 :                   j_RI = ri_data%img_to_RI_cell(j_img)
    2353        59904 :                   IF (j_RI == 0) CYCLE
    2354        48680 :                   DO jatom = 1, natom
    2355        29072 :                      IF (present_atoms_j(jatom, j_img) == 0) CYCLE
    2356        10580 :                      jblk = jblk + 1
    2357              : 
    2358        10580 :                      CALL dbcsr_get_block_p(work_tight_inv, iblk, jblk, pblock, found)
    2359        10580 :                      IF (.NOT. found) CYCLE
    2360              : 
    2361        93807 :                      CALL dbcsr_put_block(work, (i_RI - 1)*natom + iatom, (j_RI - 1)*natom + jatom, pblock)
    2362              :                   END DO
    2363              :                END DO
    2364              :             END DO
    2365              :          END DO
    2366          384 :          CALL dbcsr_finalize(work)
    2367              : 
    2368          384 :          CALL dbcsr_release(work_tight)
    2369          768 :          CALL dbcsr_release(work_tight_inv)
    2370              :       END IF
    2371              : 
    2372         5891 :       CALL dbt_create(work, t_2c_tmp)
    2373         5891 :       CALL dbt_copy_matrix_to_tensor(work, t_2c_tmp)
    2374         5891 :       CALL dbt_copy(t_2c_tmp, t_2c_pot, move_data=.TRUE.)
    2375         5891 :       CALL dbt_filter(t_2c_pot, ri_data%filter_eps)
    2376              : 
    2377         5891 :       CALL dbt_destroy(t_2c_tmp)
    2378         5891 :       CALL dbcsr_release(work)
    2379              : 
    2380         5891 :       CALL timestop(handle)
    2381              : 
    2382        23564 :    END SUBROUTINE get_ext_2c_int
    2383              : 
    2384              : ! **************************************************************************************************
    2385              : !> \brief Build the unique, density-independent potential of the fitted AO pairs.
    2386              : !>        G_j(P^x; nu^0,lambda^l) = sum_Qq V_PQ(q-x) B_j(Q^q;nu^0,lambda^l).
    2387              : !>        A KS block (i,j,b) only selects rows x=p-b of this object. Requests
    2388              : !>        from overlapping local RI bases and different b images are combined.
    2389              : !> \param ri_data integral storage; G is invalidated together with the geometry
    2390              : !> \param qs_env simulation environment
    2391              : !> \param pattern selected KS atom pairs; negative entries are absent
    2392              : !> \param ngroups number of equal-sized contraction subgroups
    2393              : !> \param para_env_sub communicator of the local subgroup
    2394              : ! **************************************************************************************************
    2395           96 :    SUBROUTINE build_kp_exchange_integrals(ri_data, qs_env, pattern, ngroups, para_env_sub)
    2396              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    2397              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2398              :       INTEGER, INTENT(IN)                                :: pattern(:, :, :), ngroups
    2399              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env_sub
    2400              : 
    2401              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_kp_exchange_integrals'
    2402              : 
    2403              :       INTEGER :: b, batch_size, cell_p(3), cell_x(3), first, g, group, handle, hi(3), i, iatom, &
    2404              :          img, j, jatom, k, last, lo(3), nAO, natom, nblocks, nG, nimg, nRI, p, p_atom, pcoord(3), &
    2405              :          pdims(3), q, q_atom, slot
    2406              :       INTEGER(int_8)                                     :: nflop
    2407           96 :       INTEGER, ALLOCATABLE :: ao_pairs(:, :), cell_index(:, :, :), cells_G(:, :), dist1(:), &
    2408          288 :          dist2(:), dist3(:), idx_to_atom(:), indices(:), pairs(:, :), sizes_G_split(:), &
    2409           96 :          sizes_RI_split(:), sizes_stack(:), stack_dist(:)
    2410           96 :       INTEGER, CONTIGUOUS, POINTER :: blocks(:, :), cell_to_index(:, :, :), col_dist(:), &
    2411          288 :          col_ext(:), grid(:, :), index_to_cell(:, :), row_dist(:), row_ext(:), sizes_G(:), &
    2412           96 :          sizes_RI(:)
    2413              :       LOGICAL                                            :: found
    2414          192 :       LOGICAL, ALLOCATABLE                               :: needed(:, :), valid_images(:, :)
    2415           96 :       REAL(dp), POINTER                                  :: block(:, :)
    2416              :       TYPE(dbcsr_distribution_type)                      :: extended_dist, matrix_dist
    2417              :       TYPE(dbcsr_iterator_type)                          :: matrix_iter
    2418              :       TYPE(dbcsr_type)                                   :: potential
    2419          864 :       TYPE(dbt_distribution_type)                        :: tensor_dist
    2420          288 :       TYPE(dbt_pgrid_type)                               :: pgrid_sub
    2421         4128 :       TYPE(dbt_type)                                     :: B_stack, G_main, G_stack, V_atom, V_split
    2422              :       TYPE(kpoint_type), POINTER                         :: kp
    2423              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2424              : 
    2425           96 :       NULLIFY (block, blocks, cell_to_index, col_dist, col_ext, grid, index_to_cell, kp, &
    2426           96 :                para_env, row_dist, row_ext, sizes_G, sizes_RI)
    2427              : 
    2428           96 :       CALL timeset(routineN, handle)
    2429           96 :       CALL get_qs_env(qs_env, natom=natom, kpoints=kp, para_env=para_env)
    2430           96 :       CALL get_kpoint_info(kp, index_to_cell=index_to_cell, cell_to_index=cell_to_index)
    2431           96 :       nimg = ri_data%nimg
    2432           96 :       nAO = SIZE(ri_data%bsizes_AO_split)
    2433           96 :       nRI = SIZE(ri_data%bsizes_RI_split)
    2434           96 :       batch_size = ri_data%kp_stack_size
    2435              : 
    2436              :       ! get_ext_2c_int retained the exact RI basis used by each metric inverse.
    2437          288 :       ALLOCATE (ri_data%kp_RI_atom(nRI))
    2438           96 :       CALL get_idx_to_atom(ri_data%kp_RI_atom, ri_data%bsizes_RI_split, ri_data%bsizes_RI)
    2439              : 
    2440              :       ! Avoid ifx miscompilation of rank-reducing MINVAL/MAXVAL expressions
    2441              :       ! used to define allocation bounds. Each scalar reduction gives the same range.
    2442          384 :       DO i = 1, 3
    2443        11994 :          lo(i) = MINVAL(index_to_cell(i, ri_data%RI_cell_to_img)) - MAXVAL(index_to_cell(i, 1:nimg))
    2444        12378 :          hi(i) = MAXVAL(index_to_cell(i, ri_data%RI_cell_to_img)) - MINVAL(index_to_cell(i, 1:nimg))
    2445              :       END DO
    2446          480 :       ALLOCATE (cell_index(lo(1):hi(1), lo(2):hi(2), lo(3):hi(3)))
    2447           96 :       cell_index = 0
    2448         2730 :       DO b = 1, nimg
    2449         7998 :          DO iatom = 1, natom
    2450        11730 :             IF (ALL(pattern(iatom, :, b) < 0)) CYCLE
    2451        21680 :             DO p = 1, ri_data%ncell_RI
    2452        33906 :                IF (.NOT. ANY(ri_data%kp_RI_neighbors((p - 1)*natom + 1:p*natom, iatom))) CYCLE
    2453        40480 :                cell_x = index_to_cell(:, ri_data%RI_cell_to_img(p)) - index_to_cell(:, b)
    2454        22042 :                cell_index(cell_x(1), cell_x(2), cell_x(3)) = 1
    2455              :             END DO
    2456              :          END DO
    2457              :       END DO
    2458              :       ! Keep a valid empty tensor layout even if the exchange operator is zero.
    2459        22080 :       IF (COUNT(cell_index /= 0) == 0) cell_index(0, 0, 0) = 1
    2460        22080 :       nG = COUNT(cell_index /= 0)
    2461          576 :       ALLOCATE (cells_G(3, nG), ri_data%kp_G_to_RI(nG, nimg))
    2462           96 :       g = 0
    2463          512 :       DO k = lo(3), hi(3)
    2464         3132 :          DO j = lo(2), hi(2)
    2465        21984 :             DO i = lo(1), hi(1)
    2466        18948 :                IF (cell_index(i, j, k) == 0) CYCLE
    2467         3700 :                g = g + 1
    2468         3700 :                cell_index(i, j, k) = g
    2469        32668 :                cells_G(:, g) = [i, j, k]
    2470              :             END DO
    2471              :          END DO
    2472              :       END DO
    2473       156644 :       ri_data%kp_G_to_RI = 0
    2474         2730 :       DO b = 1, nimg
    2475       156644 :          DO g = 1, nG
    2476       615656 :             cell_p = cells_G(:, g) + index_to_cell(:, b)
    2477      1192612 :             IF (ANY(cell_p < LBOUND(cell_to_index)) .OR. ANY(cell_p > UBOUND(cell_to_index))) CYCLE
    2478       123792 :             img = cell_to_index(cell_p(1), cell_p(2), cell_p(3))
    2479       126426 :             IF (img > 0 .AND. img <= nimg) ri_data%kp_G_to_RI(g, b) = ri_data%img_to_RI_cell(img)
    2480              :          END DO
    2481              :       END DO
    2482              : 
    2483              :       ALLOCATE (sizes_G(nG*natom), sizes_G_split(nG*nRI), sizes_RI(ri_data%ncell_RI*natom), &
    2484          864 :                 sizes_RI_split(ri_data%ncell_RI*nRI))
    2485          192 :       sizes_G(:) = RESHAPE(SPREAD(ri_data%bsizes_RI, 2, nG), [nG*natom])
    2486          192 :       sizes_G_split(:) = RESHAPE(SPREAD(ri_data%bsizes_RI_split, 2, nG), [nG*nRI])
    2487          192 :       sizes_RI(:) = RESHAPE(SPREAD(ri_data%bsizes_RI, 2, ri_data%ncell_RI), [SIZE(sizes_RI)])
    2488          192 :       sizes_RI_split(:) = RESHAPE(SPREAD(ri_data%bsizes_RI_split, 2, ri_data%ncell_RI), [SIZE(sizes_RI_split)])
    2489              : 
    2490              :       ! V(P^x,Q^q) uses exactly the original finite set of potential images q-x.
    2491              :       ! Repeating the original atomic distribution keeps every inserted block local.
    2492           96 :       CALL dbcsr_get_info(ri_data%kp_mat_2c_pot(1, 1), distribution=matrix_dist)
    2493           96 :       CALL dbcsr_distribution_get(matrix_dist, row_dist=row_dist, col_dist=col_dist, group=group, pgrid=grid)
    2494          480 :       ALLOCATE (row_ext(nG*natom), col_ext(ri_data%ncell_RI*natom))
    2495          192 :       row_ext(:) = RESHAPE(SPREAD(row_dist, 2, nG), [nG*natom])
    2496          192 :       col_ext(:) = RESHAPE(SPREAD(col_dist, 2, ri_data%ncell_RI), [ri_data%ncell_RI*natom])
    2497           96 :       CALL dbcsr_distribution_new(extended_dist, group=group, pgrid=grid, row_dist=row_ext, col_dist=col_ext)
    2498              :       CALL dbcsr_create(potential, dist=extended_dist, name="V_G_RI", matrix_type=dbcsr_type_no_symmetry, &
    2499           96 :                         row_blk_size=sizes_G, col_blk_size=sizes_RI)
    2500           96 :       CALL dbcsr_distribution_release(extended_dist)
    2501           96 :       DEALLOCATE (row_ext, col_ext, sizes_G, sizes_RI)
    2502         2730 :       DO img = 1, nimg
    2503         2634 :          CALL dbcsr_iterator_start(matrix_iter, ri_data%kp_mat_2c_pot(1, img))
    2504         4859 :          DO WHILE (dbcsr_iterator_blocks_left(matrix_iter))
    2505         2225 :             CALL dbcsr_iterator_next_block(matrix_iter, row=p_atom, column=q_atom)
    2506         2225 :             CALL dbcsr_get_block_p(ri_data%kp_mat_2c_pot(1, img), p_atom, q_atom, block, found)
    2507         2225 :             IF (.NOT. found) CYCLE
    2508        20445 :             DO q = 1, ri_data%ncell_RI
    2509        62344 :                cell_x = index_to_cell(:, ri_data%RI_cell_to_img(q)) - index_to_cell(:, img)
    2510       124688 :                IF (ANY(cell_x < lo) .OR. ANY(cell_x > hi)) CYCLE
    2511        15586 :                g = cell_index(cell_x(1), cell_x(2), cell_x(3))
    2512        15586 :                IF (g == 0) CYCLE
    2513        17811 :                CALL dbcsr_put_block(potential, (g - 1)*natom + p_atom, (q - 1)*natom + q_atom, block)
    2514              :             END DO
    2515              :          END DO
    2516         5364 :          CALL dbcsr_iterator_stop(matrix_iter)
    2517              :       END DO
    2518           96 :       CALL dbcsr_finalize(potential)
    2519           96 :       CALL dbt_create(potential, V_atom)
    2520           96 :       CALL dbt_copy_matrix_to_tensor(potential, V_atom)
    2521           96 :       CALL dbcsr_release(potential)
    2522           96 :       CALL dbt_filter(V_atom, ri_data%filter_eps)
    2523           96 :       CALL create_2c_tensor(V_split, dist1, dist2, ri_data%pgrid_2d, sizes_G_split, sizes_RI_split, name="V_G_RI")
    2524           96 :       DEALLOCATE (dist1, dist2)
    2525           96 :       CALL dbt_copy(V_atom, V_split, move_data=.TRUE.)
    2526           96 :       CALL dbt_destroy(V_atom)
    2527           96 :       CALL dbt_filter(V_split, ri_data%filter_eps)
    2528              : 
    2529              :       ! Stack the fitted pairs, without adding any left-center or output-image label.
    2530          576 :       ALLOCATE (sizes_stack(batch_size*nAO), stack_dist(batch_size*nAO), indices(ri_data%nimg_nze))
    2531          192 :       sizes_stack(:) = RESHAPE(SPREAD(ri_data%bsizes_AO_split, 2, batch_size), [SIZE(sizes_stack)])
    2532         1902 :       DO i = 1, SIZE(indices)
    2533         1902 :          indices(i) = i
    2534              :       END DO
    2535          576 :       ALLOCATE (dist1(nAO), dist2(SIZE(sizes_RI_split)), dist3(nAO))
    2536           96 :       CALL dbt_get_info(ri_data%t_3c_int_ctr_1(1, 1), proc_dist_1=dist1, proc_dist_2=dist2, proc_dist_3=dist3)
    2537          192 :       stack_dist(:) = RESHAPE(SPREAD(dist3, 2, batch_size), [SIZE(stack_dist)])
    2538           96 :       CALL dbt_distribution_new(tensor_dist, ri_data%pgrid_1, dist1, dist2, stack_dist)
    2539              :       CALL dbt_create(B_stack, "B_stack", tensor_dist, [1, 2], [3], &
    2540           96 :                       ri_data%bsizes_AO_split, sizes_RI_split, sizes_stack)
    2541           96 :       CALL dbt_distribution_destroy(tensor_dist)
    2542           96 :       DEALLOCATE (dist1, dist2, dist3)
    2543              :       ! Only the subgroup G survives setup. Reuse one main-group tensor per image.
    2544         2862 :       ALLOCATE (ri_data%kp_t_3c_G_sub(ri_data%nimg_nze))
    2545           96 :       pdims = 0
    2546          384 :       CALL dbt_pgrid_create(para_env_sub, pdims, pgrid_sub, tensor_dims=[nAO, nG*nRI, nAO])
    2547              :       CALL create_3c_tensor(ri_data%kp_t_3c_G_sub(1), dist1, dist2, dist3, pgrid_sub, &
    2548           96 :                             ri_data%bsizes_AO_split, sizes_G_split, ri_data%bsizes_AO_split, [1], [2, 3], name="G")
    2549         1806 :       DO img = 2, ri_data%nimg_nze
    2550         1806 :          CALL dbt_create(ri_data%kp_t_3c_G_sub(1), ri_data%kp_t_3c_G_sub(img))
    2551              :       END DO
    2552           96 :       DEALLOCATE (dist1, dist2, dist3)
    2553           96 :       CALL dbt_pgrid_destroy(pgrid_sub)
    2554              :       CALL create_3c_tensor(G_main, dist1, dist2, dist3, ri_data%pgrid_1, &
    2555           96 :                             ri_data%bsizes_AO_split, sizes_G_split, ri_data%bsizes_AO_split, [1], [2, 3], name="G")
    2556          192 :       stack_dist(:) = RESHAPE(SPREAD(dist3, 2, batch_size), [SIZE(stack_dist)])
    2557           96 :       CALL dbt_distribution_new(tensor_dist, ri_data%pgrid_1, dist1, dist2, stack_dist)
    2558              :       CALL dbt_create(G_stack, "G_stack", tensor_dist, [1], [2, 3], &
    2559           96 :                       ri_data%bsizes_AO_split, sizes_G_split, sizes_stack)
    2560           96 :       CALL dbt_distribution_destroy(tensor_dist)
    2561           96 :       CALL dbt_mp_environ_pgrid(ri_data%pgrid_1, pdims, pcoord)
    2562          960 :       ALLOCATE (idx_to_atom(nAO), pairs(nimg, 2), ao_pairs(nAO, batch_size*nAO), needed(nG*natom, natom))
    2563           96 :       CALL get_idx_to_atom(idx_to_atom, ri_data%bsizes_AO_split, ri_data%bsizes_AO)
    2564              :       ! Image partners depend only on geometry, not on the count/pack traversal.
    2565          384 :       ALLOCATE (valid_images(ri_data%nimg_nze, nimg), blocks(0, 3))
    2566         2730 :       DO b = 1, nimg
    2567         2634 :          CALL get_iapc_pairs(pairs, b, ri_data, qs_env)
    2568        72172 :          valid_images(:, b) = pairs(:ri_data%nimg_nze, 2) >= 1 .AND. pairs(:ri_data%nimg_nze, 2) <= nimg
    2569              :       END DO
    2570              : 
    2571          240 :       DO first = 1, ri_data%nimg_nze, batch_size
    2572          144 :          last = MIN(first + batch_size, ri_data%nimg_nze + 1)
    2573          432 :          CALL fill_3c_stack(B_stack, ri_data%t_3c_int_ctr_1(1, :), indices, 3, ri_data, img_bounds=[first, last])
    2574          144 :          CALL dbt_filter(B_stack, ri_data%filter_eps)
    2575          144 :          CALL dbt_get_block_pattern(B_stack, [1, 3], ao_pairs)
    2576              : 
    2577              :          ! Reserve only requested RI-row/AO-pair blocks. No dense product space
    2578              :          ! is materialized, including for images that have no valid a+c partner.
    2579          144 :          nblocks = 0
    2580         1950 :          DO img = first, last - 1
    2581         1806 :             slot = img - first
    2582         1806 :             needed = .FALSE.
    2583        71248 :             DO b = 1, nimg
    2584        69442 :                IF (.NOT. valid_images(img, b)) CYCLE
    2585       108708 :                DO jatom = 1, natom
    2586       283246 :                   DO iatom = 1, natom
    2587       142536 :                      IF (pattern(iatom, jatom, b) < 0) CYCLE
    2588      3357584 :                      DO g = 1, nG
    2589      3237330 :                         p = ri_data%kp_G_to_RI(g, b)
    2590      3237330 :                         IF (p == 0) CYCLE
    2591              :                         needed((g - 1)*natom + 1:g*natom, jatom) = &
    2592              :                            needed((g - 1)*natom + 1:g*natom, jatom) .OR. &
    2593      1371240 :                            ri_data%kp_RI_neighbors((p - 1)*natom + 1:p*natom, iatom)
    2594              :                      END DO
    2595              :                   END DO
    2596              :                END DO
    2597              :             END DO
    2598       318514 :             DO j = 1, nG*nRI
    2599       316564 :                IF (dist2(j) /= pcoord(2)) CYCLE
    2600       311920 :                g = (j - 1)/nRI + 1
    2601       311920 :                p_atom = ri_data%kp_RI_atom(MODULO(j - 1, nRI) + 1)
    2602      1131938 :                DO i = 1, nAO
    2603       818212 :                   IF (dist1(i) /= pcoord(1)) CYCLE
    2604       420716 :                   IF (.NOT. needed((g - 1)*natom + p_atom, idx_to_atom(i))) CYCLE
    2605       943780 :                   DO k = slot*nAO + 1, (slot + 1)*nAO
    2606       475104 :                      IF (stack_dist(k) /= pcoord(3) .OR. ao_pairs(i, k) == 0) CYCLE
    2607       244550 :                      nblocks = nblocks + 1
    2608       244550 :                      IF (nblocks > SIZE(blocks, 1)) CALL reallocate(blocks, 1, MAX(1, 2*SIZE(blocks, 1)), 1, 3)
    2609      2026966 :                      blocks(nblocks, :) = [i, j, k]
    2610              :                   END DO
    2611              :                END DO
    2612              :             END DO
    2613              :          END DO
    2614          144 :          CALL dbt_reserve_blocks(G_stack, blocks(:nblocks, :))
    2615              :          CALL dbt_contract(1.0_dp, V_split, B_stack, 0.0_dp, G_stack, &
    2616              :                            contract_1=[2], notcontract_1=[1], contract_2=[2], notcontract_2=[1, 3], &
    2617          144 :                            map_1=[2], map_2=[1, 3], retain_sparsity=.TRUE., filter_eps=ri_data%filter_eps, flop=nflop)
    2618          144 :          ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    2619         1950 :          DO img = first, last - 1
    2620         1806 :             CALL unstack_t_3c_apc(G_main, G_stack, img - first + 1)
    2621         1806 :             CALL dbt_finalize(G_main)
    2622         1806 :             CALL dbt_filter(G_main, ri_data%filter_eps)
    2623         1806 :             CALL copy_3c_to_subgroup(ri_data%kp_t_3c_G_sub(img), G_main)
    2624         1950 :             CALL dbt_clear(G_main)
    2625              :          END DO
    2626          144 :          CALL dbt_clear(B_stack)
    2627          240 :          CALL dbt_clear(G_stack)
    2628              :       END DO
    2629           96 :       DEALLOCATE (blocks)
    2630           96 :       CALL dbt_destroy(B_stack)
    2631           96 :       CALL dbt_destroy(G_stack)
    2632           96 :       CALL dbt_destroy(G_main)
    2633           96 :       CALL dbt_destroy(V_split)
    2634           96 :       ri_data%kp_G_ngroups = ngroups
    2635           96 :       CALL timestop(handle)
    2636          672 :    END SUBROUTINE build_kp_exchange_integrals
    2637              : 
    2638              : ! **************************************************************************************************
    2639              : !> \brief Select and shift canonical G rows for an existing KS contraction batch.
    2640              : !>        The change x -> p=x+b can change the MPI owner. Route each retained
    2641              : !>        block to the destination tensor instead of assuming a local copy.
    2642              : !> \param stack output in the current contraction layout and distribution
    2643              : !> \param ri_data geometry-dependent G and local RI neighborhoods
    2644              : !> \param pairs image indices (l,a+c) from get_iapc_pairs
    2645              : !> \param iatom left AO center selecting the RI rows
    2646              : !> \param jatom right AO center selecting the fitted pairs
    2647              : !> \param b_img output KS image
    2648              : !> \param idx_to_at mapping of split AO blocks to atoms
    2649              : !> \param img_bounds half-open image batch
    2650              : ! **************************************************************************************************
    2651        22364 :    SUBROUTINE fill_kp_exchange_stack(stack, ri_data, pairs, iatom, jatom, b_img, idx_to_at, img_bounds)
    2652              :       TYPE(dbt_type), INTENT(INOUT)                      :: stack
    2653              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    2654              :       INTEGER, INTENT(IN)                                :: pairs(:, :), iatom, jatom, b_img, &
    2655              :                                                             idx_to_at(:), img_bounds(2)
    2656              : 
    2657              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'fill_kp_exchange_stack'
    2658              : 
    2659              :       INTEGER                                            :: g, handle, i, nAO, natom, nRI, p, r
    2660        22364 :       INTEGER, ALLOCATABLE                               :: images(:), index_map(:, :)
    2661              : 
    2662        22364 :       CALL timeset(routineN, handle)
    2663        22364 :       nAO = SIZE(ri_data%bsizes_AO_split)
    2664        22364 :       nRI = SIZE(ri_data%bsizes_RI_split)
    2665        22364 :       natom = SIZE(ri_data%bsizes_RI)
    2666        67092 :       ALLOCATE (index_map(MAX(nAO, SIZE(ri_data%kp_G_to_RI, 1)*nRI), 3))
    2667        22364 :       index_map = 0
    2668        73416 :       DO i = 1, nAO
    2669        51052 :          IF (idx_to_at(i) == jatom) index_map(i, 1) = i
    2670        73416 :          index_map(i, 3) = i
    2671              :       END DO
    2672              :       ! x -> p=x+b selects the original finite RI domain and the left-center neighborhood.
    2673      1833092 :       DO g = 1, SIZE(ri_data%kp_G_to_RI, 1)
    2674      1810728 :          p = ri_data%kp_G_to_RI(g, b_img)
    2675      1810728 :          IF (p == 0) CYCLE
    2676       987948 :          DO r = 1, nRI
    2677       743047 :             IF (.NOT. ri_data%kp_RI_neighbors((p - 1)*natom + ri_data%kp_RI_atom(r), iatom)) CYCLE
    2678      2553775 :             index_map((g - 1)*nRI + r, 2) = (p - 1)*nRI + r
    2679              :          END DO
    2680              :       END DO
    2681        67092 :       ALLOCATE (images(img_bounds(2) - img_bounds(1)))
    2682       308380 :       images(:) = pairs(img_bounds(1):img_bounds(2) - 1, 1)
    2683              :       WHERE (pairs(img_bounds(1):img_bounds(2) - 1, 2) < 1 .OR. &
    2684              :              pairs(img_bounds(1):img_bounds(2) - 1, 2) > ri_data%nimg .OR. &
    2685       308380 :              images < 1 .OR. images > SIZE(ri_data%kp_t_3c_G_sub)) images = 0
    2686        22364 :       CALL dbt_copy_indexed(ri_data%kp_t_3c_G_sub, stack, images, index_map, stack_dim=3)
    2687        22364 :       CALL timestop(handle)
    2688        44728 :    END SUBROUTINE fill_kp_exchange_stack
    2689              : 
    2690              : ! **************************************************************************************************
    2691              : !> \brief Pre-contract the density matrices with the 3-center integrals:
    2692              : !>        P_sigma^a,lambda^a+c (mu^0 sigma^a| P^0)
    2693              : !> \param t_3c_apc ...
    2694              : !> \param rho_ao_t ...
    2695              : !> \param ri_data ...
    2696              : !> \param qs_env ...
    2697              : ! **************************************************************************************************
    2698          562 :    SUBROUTINE contract_pmat_3c(t_3c_apc, rho_ao_t, ri_data, qs_env)
    2699              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_3c_apc, rho_ao_t
    2700              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    2701              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2702              : 
    2703              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'contract_pmat_3c'
    2704              : 
    2705              :       INTEGER                                            :: apc_img, b_img, batch_size, handle, &
    2706              :                                                             i_batch, i_img, i_spin, idx, j_batch, &
    2707              :                                                             n_batch_img, n_batch_nze, nimg, &
    2708              :                                                             nimg_nze, nspins
    2709              :       INTEGER(int_8)                                     :: nflop, nze
    2710          562 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: apc_filter, batch_ranges_img, &
    2711          562 :                                                             batch_ranges_nze, int_indices
    2712          562 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: ac_pairs, iapc_pairs, rho_images
    2713              :       REAL(dp)                                           :: occ, t1, t2
    2714          562 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:)          :: ints_stack, res_stack, rho_stack
    2715              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2716              : 
    2717          562 :       CALL timeset(routineN, handle)
    2718              : 
    2719          562 :       CALL get_qs_env(qs_env, dft_control=dft_control)
    2720              : 
    2721          562 :       nimg = ri_data%nimg
    2722          562 :       nimg_nze = ri_data%nimg_nze
    2723          562 :       nspins = dft_control%nspins
    2724              : 
    2725          562 :       batch_size = ri_data%kp_stack_size
    2726              : 
    2727         2810 :       ALLOCATE (apc_filter(nimg), iapc_pairs(nimg, 2))
    2728          562 :       apc_filter = 0
    2729        18710 :       DO b_img = 1, nimg
    2730        18148 :          CALL get_iapc_pairs(iapc_pairs, b_img, ri_data, qs_env)
    2731       495790 :          DO i_img = 1, nimg_nze
    2732       477080 :             idx = iapc_pairs(i_img, 2)
    2733       477080 :             IF (idx < 1 .OR. idx > nimg) CYCLE
    2734       495228 :             apc_filter(idx) = 1
    2735              :          END DO
    2736              :       END DO
    2737              : 
    2738              :       !batching over all images
    2739          562 :       n_batch_img = nimg/batch_size
    2740          562 :       IF (MODULO(nimg, batch_size) /= 0) n_batch_img = n_batch_img + 1
    2741         1686 :       ALLOCATE (batch_ranges_img(n_batch_img + 1))
    2742         1848 :       DO i_batch = 1, n_batch_img
    2743         1848 :          batch_ranges_img(i_batch) = (i_batch - 1)*batch_size + 1
    2744              :       END DO
    2745          562 :       batch_ranges_img(n_batch_img + 1) = nimg + 1
    2746              : 
    2747              :       !batching over images with non-zero 3c integrals
    2748          562 :       n_batch_nze = nimg_nze/batch_size
    2749          562 :       IF (MODULO(nimg_nze, batch_size) /= 0) n_batch_nze = n_batch_nze + 1
    2750         1686 :       ALLOCATE (batch_ranges_nze(n_batch_nze + 1))
    2751         1500 :       DO i_batch = 1, n_batch_nze
    2752         1500 :          batch_ranges_nze(i_batch) = (i_batch - 1)*batch_size + 1
    2753              :       END DO
    2754          562 :       batch_ranges_nze(n_batch_nze + 1) = nimg_nze + 1
    2755              : 
    2756              :       !Create the stack tensors in the approriate distribution
    2757        17422 :       ALLOCATE (rho_stack(2), ints_stack(2), res_stack(2))
    2758              :       CALL get_stack_tensors(res_stack, rho_stack, ints_stack, rho_ao_t(1, 1), &
    2759          562 :                              ri_data%t_3c_int_ctr_1(1, 1), batch_size, ri_data, qs_env)
    2760              : 
    2761         3934 :       ALLOCATE (ac_pairs(nimg, 2), int_indices(nimg_nze), rho_images(batch_size, batch_size))
    2762        12586 :       DO i_img = 1, nimg_nze
    2763        12586 :          int_indices(i_img) = i_img
    2764              :       END DO
    2765              : 
    2766          562 :       t1 = m_walltime()
    2767         1500 :       DO j_batch = 1, n_batch_nze
    2768              :          !First batch is over the integrals. They are always in the same order, consistent with get_ac_pairs
    2769              :          CALL fill_3c_stack(ints_stack(1), ri_data%t_3c_int_ctr_1(1, :), int_indices, 3, ri_data, &
    2770         2814 :                             img_bounds=[batch_ranges_nze(j_batch), batch_ranges_nze(j_batch + 1)])
    2771          938 :          CALL dbt_copy(ints_stack(1), ints_stack(2), move_data=.TRUE.)
    2772              : 
    2773         2580 :          DO i_spin = 1, nspins
    2774         4918 :             DO i_batch = 1, n_batch_img
    2775              :                !Collect the image pairs before filling the whole density-matrix stack.
    2776         2900 :                rho_images(:, :) = 0
    2777        42538 :                DO apc_img = batch_ranges_img(i_batch), batch_ranges_img(i_batch + 1) - 1
    2778        39638 :                   IF (apc_filter(apc_img) == 0) CYCLE
    2779        39638 :                   CALL get_ac_pairs(ac_pairs, apc_img, ri_data, qs_env)
    2780              :                   rho_images(1:batch_ranges_nze(j_batch + 1) - batch_ranges_nze(j_batch), &
    2781              :                              apc_img - batch_ranges_img(i_batch) + 1) = &
    2782       549444 :                      ac_pairs(batch_ranges_nze(j_batch):batch_ranges_nze(j_batch + 1) - 1, 2)
    2783              :                END DO !apc_img
    2784         2900 :                CALL fill_2c_stack(rho_stack(1), rho_ao_t(i_spin, :), rho_images, ri_data)
    2785         2900 :                CALL get_tensor_occupancy(rho_stack(1), nze, occ)
    2786         2900 :                IF (nze == 0) CYCLE
    2787         2836 :                CALL dbt_copy(rho_stack(1), rho_stack(2), move_data=.TRUE.)
    2788              : 
    2789              :                !The actual contraction
    2790         2836 :                CALL dbt_batched_contract_init(rho_stack(2))
    2791              :                CALL dbt_contract(1.0_dp, ints_stack(2), rho_stack(2), &
    2792              :                                  0.0_dp, res_stack(2), map_1=[1, 2], map_2=[3], &
    2793              :                                  contract_1=[3], notcontract_1=[1, 2], &
    2794              :                                  contract_2=[1], notcontract_2=[2], &
    2795         2836 :                                  filter_eps=ri_data%filter_eps, flop=nflop)
    2796         2836 :                ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    2797         2836 :                CALL dbt_batched_contract_finalize(rho_stack(2))
    2798         2836 :                CALL dbt_copy(res_stack(2), res_stack(1), move_data=.TRUE.)
    2799              : 
    2800              :                CALL accumulate_3c_stack(t_3c_apc(i_spin, batch_ranges_img(i_batch):batch_ranges_img(i_batch + 1) - 1), &
    2801              :                                         res_stack(1), &
    2802         6880 :                                         apc_filter(batch_ranges_img(i_batch):batch_ranges_img(i_batch + 1) - 1))
    2803              : 
    2804              :             END DO !i_batch
    2805              :          END DO !i_spin
    2806              :       END DO !j_batch
    2807          562 :       DEALLOCATE (batch_ranges_img)
    2808          562 :       DEALLOCATE (batch_ranges_nze)
    2809          562 :       t2 = m_walltime()
    2810          562 :       ri_data%dbcsr_time = ri_data%dbcsr_time + t2 - t1
    2811              : 
    2812          562 :       CALL dbt_destroy(rho_stack(1))
    2813          562 :       CALL dbt_destroy(rho_stack(2))
    2814          562 :       CALL dbt_destroy(ints_stack(1))
    2815          562 :       CALL dbt_destroy(ints_stack(2))
    2816          562 :       CALL dbt_destroy(res_stack(1))
    2817          562 :       CALL dbt_destroy(res_stack(2))
    2818              : 
    2819          562 :       CALL timestop(handle)
    2820              : 
    2821         6182 :    END SUBROUTINE contract_pmat_3c
    2822              : 
    2823              : ! **************************************************************************************************
    2824              : !> \brief Pre-contract 3-center integrals with the bumped invrse RI metric, for each atom
    2825              : !> \param t_3c_int ...
    2826              : !> \param ri_data ...
    2827              : !> \param qs_env ...
    2828              : ! **************************************************************************************************
    2829           96 :    SUBROUTINE precontract_3c_ints(t_3c_int, ri_data, qs_env)
    2830              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_3c_int
    2831              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    2832              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2833              : 
    2834              :       CHARACTER(len=*), PARAMETER :: routineN = 'precontract_3c_ints'
    2835              : 
    2836              :       INTEGER                                            :: batch_size, handle, i_batch, i_img, &
    2837              :                                                             i_RI, iatom, is, n_batch, natom, &
    2838              :                                                             nblks, nblks_3c(3), nimg
    2839              :       INTEGER(int_8)                                     :: nflop
    2840           96 :       INTEGER, ALLOCATABLE, DIMENSION(:) :: batch_ranges, bsizes_RI_ext, bsizes_RI_ext_split, &
    2841           96 :          bsizes_stack, dist1, dist2, dist3, dist_stack3, idx_to_at_AO, int_indices
    2842          864 :       TYPE(dbt_distribution_type)                        :: t_dist
    2843        20064 :       TYPE(dbt_type)                                     :: t_2c_RI_tmp(2), t_3c_tmp(3)
    2844              : 
    2845           96 :       CALL timeset(routineN, handle)
    2846              : 
    2847           96 :       CALL get_qs_env(qs_env, natom=natom)
    2848              : 
    2849           96 :       nimg = ri_data%nimg
    2850          288 :       ALLOCATE (int_indices(nimg))
    2851         2730 :       DO i_img = 1, nimg
    2852         2730 :          int_indices(i_img) = i_img
    2853              :       END DO
    2854              : 
    2855          288 :       ALLOCATE (idx_to_at_AO(SIZE(ri_data%bsizes_AO_split)))
    2856           96 :       CALL get_idx_to_atom(idx_to_at_AO, ri_data%bsizes_AO_split, ri_data%bsizes_AO)
    2857              : 
    2858           96 :       nblks = SIZE(ri_data%bsizes_RI_split)
    2859          288 :       ALLOCATE (bsizes_RI_ext(ri_data%ncell_RI*natom))
    2860          288 :       ALLOCATE (bsizes_RI_ext_split(ri_data%ncell_RI*nblks))
    2861          730 :       DO i_RI = 1, ri_data%ncell_RI
    2862         1902 :          bsizes_RI_ext((i_RI - 1)*natom + 1:i_RI*natom) = ri_data%bsizes_RI(:)
    2863         3606 :          bsizes_RI_ext_split((i_RI - 1)*nblks + 1:i_RI*nblks) = ri_data%bsizes_RI_split(:)
    2864              :       END DO
    2865              :       CALL create_2c_tensor(t_2c_RI_tmp(1), dist1, dist2, ri_data%pgrid_2d, &
    2866              :                             bsizes_RI_ext, bsizes_RI_ext, &
    2867           96 :                             name="(RI | RI)")
    2868           96 :       DEALLOCATE (dist1, dist2)
    2869              :       CALL create_2c_tensor(t_2c_RI_tmp(2), dist1, dist2, ri_data%pgrid_2d, &
    2870              :                             bsizes_RI_ext_split, bsizes_RI_ext_split, &
    2871           96 :                             name="(RI | RI)")
    2872           96 :       DEALLOCATE (dist1, dist2)
    2873              : 
    2874              :       !For more efficiency, we stack multiple images of the 3-center integrals into a single tensor
    2875           96 :       batch_size = ri_data%kp_stack_size
    2876           96 :       n_batch = nimg/batch_size
    2877           96 :       IF (MODULO(nimg, batch_size) /= 0) n_batch = n_batch + 1
    2878          288 :       ALLOCATE (batch_ranges(n_batch + 1))
    2879          294 :       DO i_batch = 1, n_batch
    2880          294 :          batch_ranges(i_batch) = (i_batch - 1)*batch_size + 1
    2881              :       END DO
    2882           96 :       batch_ranges(n_batch + 1) = nimg + 1
    2883              : 
    2884           96 :       nblks = SIZE(ri_data%bsizes_AO_split)
    2885          288 :       ALLOCATE (bsizes_stack(batch_size*nblks))
    2886         1728 :       DO is = 1, batch_size
    2887         7712 :          bsizes_stack((is - 1)*nblks + 1:is*nblks) = ri_data%bsizes_AO_split(:)
    2888              :       END DO
    2889              : 
    2890           96 :       CALL dbt_get_info(t_3c_int(1, 1), nblks_total=nblks_3c)
    2891          864 :       ALLOCATE (dist1(nblks_3c(1)), dist2(nblks_3c(2)), dist3(nblks_3c(3)), dist_stack3(batch_size*nblks_3c(3)))
    2892           96 :       CALL dbt_get_info(t_3c_int(1, 1), proc_dist_1=dist1, proc_dist_2=dist2, proc_dist_3=dist3)
    2893         1728 :       DO is = 1, batch_size
    2894         7712 :          dist_stack3((is - 1)*nblks_3c(3) + 1:is*nblks_3c(3)) = dist3(:)
    2895              :       END DO
    2896              : 
    2897           96 :       CALL dbt_distribution_new(t_dist, ri_data%pgrid, dist1, dist2, dist_stack3)
    2898              :       CALL dbt_create(t_3c_tmp(1), "ints_stack", t_dist, [1], [2, 3], bsizes_RI_ext_split, &
    2899           96 :                       ri_data%bsizes_AO_split, bsizes_stack)
    2900           96 :       CALL dbt_distribution_destroy(t_dist)
    2901           96 :       DEALLOCATE (dist1, dist2, dist3, dist_stack3)
    2902              : 
    2903           96 :       CALL dbt_create(t_3c_tmp(1), t_3c_tmp(2))
    2904           96 :       CALL dbt_create(t_3c_int(1, 1), t_3c_tmp(3))
    2905              : 
    2906          288 :       DO iatom = 1, natom
    2907          192 :          CALL dbt_copy(ri_data%t_2c_inv(1, iatom), t_2c_RI_tmp(1))
    2908          192 :          CALL apply_bump(t_2c_RI_tmp(1), iatom, ri_data, qs_env, from_left=.TRUE., from_right=.TRUE.)
    2909          192 :          CALL dbt_copy(t_2c_RI_tmp(1), t_2c_RI_tmp(2), move_data=.TRUE.)
    2910              : 
    2911          192 :          CALL dbt_batched_contract_init(t_2c_RI_tmp(2))
    2912          588 :          DO i_batch = 1, n_batch
    2913              : 
    2914              :             CALL fill_3c_stack(t_3c_tmp(1), t_3c_int(1, :), int_indices, 3, ri_data, &
    2915              :                                img_bounds=[batch_ranges(i_batch), batch_ranges(i_batch + 1)], &
    2916         1188 :                                filter_at=iatom, filter_dim=2, idx_to_at=idx_to_at_AO)
    2917              : 
    2918              :             CALL dbt_contract(1.0_dp, t_2c_RI_tmp(2), t_3c_tmp(1), &
    2919              :                               0.0_dp, t_3c_tmp(2), map_1=[1], map_2=[2, 3], &
    2920              :                               contract_1=[2], notcontract_1=[1], &
    2921              :                               contract_2=[1], notcontract_2=[2, 3], &
    2922          396 :                               filter_eps=ri_data%filter_eps, flop=nflop)
    2923          396 :             ri_data%dbcsr_nflop = ri_data%dbcsr_nflop + nflop
    2924              : 
    2925         5664 :             DO i_img = batch_ranges(i_batch), batch_ranges(i_batch + 1) - 1
    2926         5268 :                CALL unstack_t_3c_apc(t_3c_tmp(3), t_3c_tmp(2), i_img - batch_ranges(i_batch) + 1)
    2927              :                CALL dbt_copy(t_3c_tmp(3), ri_data%t_3c_int_ctr_1(1, i_img), summation=.TRUE., &
    2928         5664 :                              order=[2, 1, 3], move_data=.TRUE.)
    2929              :             END DO
    2930          588 :             CALL dbt_clear(t_3c_tmp(1))
    2931              :          END DO
    2932          288 :          CALL dbt_batched_contract_finalize(t_2c_RI_tmp(2))
    2933              : 
    2934              :       END DO
    2935           96 :       CALL dbt_destroy(t_2c_RI_tmp(1))
    2936           96 :       CALL dbt_destroy(t_2c_RI_tmp(2))
    2937           96 :       CALL dbt_destroy(t_3c_tmp(1))
    2938           96 :       CALL dbt_destroy(t_3c_tmp(2))
    2939           96 :       CALL dbt_destroy(t_3c_tmp(3))
    2940              : 
    2941         2730 :       DO i_img = 1, nimg
    2942         2730 :          CALL dbt_destroy(t_3c_int(1, i_img))
    2943              :       END DO
    2944              : 
    2945           96 :       CALL timestop(handle)
    2946              : 
    2947          288 :    END SUBROUTINE precontract_3c_ints
    2948              : 
    2949              : ! **************************************************************************************************
    2950              : !> \brief Copy the data of a 2D tensor living in the main MPI group to a sub-group, given the proc
    2951              : !>        mapping from one to the other (e.g. for a proc idx in the subgroup, we get the idx in the main)
    2952              : !> \param t2c_sub ...
    2953              : !> \param t2c_main ...
    2954              : !> \param group_size ...
    2955              : !> \param ngroups ...
    2956              : !> \param para_env ...
    2957              : ! **************************************************************************************************
    2958         6058 :    SUBROUTINE copy_2c_to_subgroup(t2c_sub, t2c_main, group_size, ngroups, para_env)
    2959              :       TYPE(dbt_type), INTENT(INOUT)                      :: t2c_sub, t2c_main
    2960              :       INTEGER, INTENT(IN)                                :: group_size, ngroups
    2961              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2962              : 
    2963              :       INTEGER                                            :: batch_size, i, i_batch, i_msg, iblk, &
    2964              :                                                             igroup, iproc, ir, is, jblk, n_batch, &
    2965              :                                                             nocc, tag
    2966         6058 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bsizes1, bsizes2
    2967         6058 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: block_dest, block_source
    2968         6058 :       INTEGER, ALLOCATABLE, DIMENSION(:, :, :)           :: current_dest
    2969              :       INTEGER, DIMENSION(2)                              :: ind, nblks
    2970              :       LOGICAL                                            :: found
    2971         6058 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :)             :: blk
    2972         6058 :       TYPE(cp_2d_r_p_type), ALLOCATABLE, DIMENSION(:)    :: recv_buff, send_buff
    2973              :       TYPE(dbt_iterator_type)                            :: iter
    2974         6058 :       TYPE(mp_request_type), ALLOCATABLE, DIMENSION(:)   :: recv_req, send_req
    2975              : 
    2976              :       !Stategy: we loop over the main tensor, and send all the data. Then we loop over the sub tensor
    2977              :       !         and receive it. We do all of it with async MPI communication. The sub tensor needs
    2978              :       !         to have blocks pre-reserved though
    2979              : 
    2980         6058 :       CALL dbt_get_info(t2c_main, nblks_total=nblks)
    2981              : 
    2982              :       !Loop over the main tensor, count how many blocks are there, which ones, and on which proc
    2983        24232 :       ALLOCATE (block_source(nblks(1), nblks(2)))
    2984       212922 :       block_source = -1
    2985         6058 :       nocc = 0
    2986         6058 : !$OMP PARALLEL DEFAULT(NONE) SHARED(t2c_main,para_env,nocc,block_source) PRIVATE(iter,ind,blk,found)
    2987              :       CALL dbt_iterator_start(iter, t2c_main)
    2988              :       DO WHILE (dbt_iterator_blocks_left(iter))
    2989              :          CALL dbt_iterator_next_block(iter, ind)
    2990              :          CALL dbt_get_block(t2c_main, ind, blk, found)
    2991              :          IF (.NOT. found) CYCLE
    2992              : 
    2993              :          block_source(ind(1), ind(2)) = para_env%mepos
    2994              : !$OMP ATOMIC
    2995              :          nocc = nocc + 1
    2996              :          DEALLOCATE (blk)
    2997              :       END DO
    2998              :       CALL dbt_iterator_stop(iter)
    2999              : !$OMP END PARALLEL
    3000              : 
    3001         6058 :       CALL para_env%sum(nocc)
    3002         6058 :       CALL para_env%sum(block_source)
    3003       212922 :       block_source = block_source + para_env%num_pe - 1
    3004         6058 :       IF (nocc == 0) RETURN
    3005              : 
    3006              :       !Loop over the sub tensor, get the block destination
    3007         5738 :       igroup = para_env%mepos/group_size
    3008        17214 :       ALLOCATE (block_dest(nblks(1), nblks(2)))
    3009       210682 :       block_dest = -1
    3010        25914 :       DO jblk = 1, nblks(2)
    3011       210682 :          DO iblk = 1, nblks(1)
    3012       184768 :             IF (block_source(iblk, jblk) == -1) CYCLE
    3013              : 
    3014       103620 :             CALL dbt_get_stored_coordinates(t2c_sub, [iblk, jblk], iproc)
    3015       204944 :             block_dest(iblk, jblk) = igroup*group_size + iproc !mapping of iproc in subgroup to main group idx
    3016              :          END DO
    3017              :       END DO
    3018              : 
    3019        28690 :       ALLOCATE (bsizes1(nblks(1)), bsizes2(nblks(2)))
    3020         5738 :       CALL dbt_get_info(t2c_main, blk_size_1=bsizes1, blk_size_2=bsizes2)
    3021              : 
    3022        28690 :       ALLOCATE (current_dest(nblks(1), nblks(2), 0:ngroups - 1))
    3023        17214 :       DO igroup = 0, ngroups - 1
    3024              :          !for a given subgroup, need to make the destination available to everyone in the main group
    3025       421364 :          current_dest(:, :, igroup) = block_dest(:, :)
    3026        17214 :          CALL para_env%bcast(current_dest(:, :, igroup), source=igroup*group_size) !bcast from first proc in sub-group
    3027              :       END DO
    3028              : 
    3029              :       !We go by batches, which cannot be larger than the maximum MPI tag value
    3030         5738 :       batch_size = MIN(para_env%get_tag_ub(), 128000, nocc*ngroups)
    3031         5738 :       n_batch = (nocc*ngroups)/batch_size
    3032         5738 :       IF (MODULO(nocc*ngroups, batch_size) /= 0) n_batch = n_batch + 1
    3033              : 
    3034        11476 :       DO i_batch = 1, n_batch
    3035              :          !Loop over groups, blocks and send/receive
    3036       161112 :          ALLOCATE (send_buff(batch_size), recv_buff(batch_size))
    3037       161112 :          ALLOCATE (send_req(batch_size), recv_req(batch_size))
    3038              :          ir = 0
    3039              :          is = 0
    3040              :          i_msg = 0
    3041        25914 :          DO jblk = 1, nblks(2)
    3042       210682 :             DO iblk = 1, nblks(1)
    3043       574480 :                DO igroup = 0, ngroups - 1
    3044       369536 :                   IF (block_source(iblk, jblk) == -1) CYCLE
    3045              : 
    3046        69080 :                   i_msg = i_msg + 1
    3047        69080 :                   IF (i_msg < (i_batch - 1)*batch_size + 1 .OR. i_msg > i_batch*batch_size) CYCLE
    3048              : 
    3049              :                   !a unique tag per block, within this batch
    3050        69080 :                   tag = i_msg - (i_batch - 1)*batch_size
    3051              : 
    3052        69080 :                   found = .FALSE.
    3053        69080 :                   IF (para_env%mepos == block_source(iblk, jblk)) THEN
    3054       103620 :                      CALL dbt_get_block(t2c_main, [iblk, jblk], blk, found)
    3055              :                   END IF
    3056              : 
    3057              :                   !If blocks live on same proc, simply copy. Else MPI send/recv
    3058        69080 :                   IF (block_source(iblk, jblk) == current_dest(iblk, jblk, igroup)) THEN
    3059       103620 :                      IF (found) CALL dbt_put_block(t2c_sub, [iblk, jblk], SHAPE(blk), blk)
    3060              :                   ELSE
    3061        34540 :                      IF (para_env%mepos == block_source(iblk, jblk) .AND. found) THEN
    3062        69080 :                         ALLOCATE (send_buff(tag)%array(bsizes1(iblk), bsizes2(jblk)))
    3063     14992892 :                         send_buff(tag)%array(:, :) = blk(:, :)
    3064        17270 :                         is = is + 1
    3065              :                         CALL para_env%isend(msgin=send_buff(tag)%array, dest=current_dest(iblk, jblk, igroup), &
    3066        17270 :                                             request=send_req(is), tag=tag)
    3067              :                      END IF
    3068              : 
    3069        34540 :                      IF (para_env%mepos == current_dest(iblk, jblk, igroup)) THEN
    3070        69080 :                         ALLOCATE (recv_buff(tag)%array(bsizes1(iblk), bsizes2(jblk)))
    3071        17270 :                         ir = ir + 1
    3072              :                         CALL para_env%irecv(msgout=recv_buff(tag)%array, source=block_source(iblk, jblk), &
    3073        17270 :                                             request=recv_req(ir), tag=tag)
    3074              :                      END IF
    3075              :                   END IF
    3076              : 
    3077       253848 :                   IF (found) DEALLOCATE (blk)
    3078              :                END DO
    3079              :             END DO
    3080              :          END DO
    3081              : 
    3082         5738 :          CALL mp_waitall(send_req(1:is))
    3083         5738 :          CALL mp_waitall(recv_req(1:ir))
    3084              :          !clean-up
    3085        74818 :          DO i = 1, batch_size
    3086        74818 :             IF (ASSOCIATED(send_buff(i)%array)) DEALLOCATE (send_buff(i)%array)
    3087              :          END DO
    3088              : 
    3089              :          !Finally copy the data from the buffer to the sub-tensor
    3090              :          i_msg = 0
    3091        25914 :          DO jblk = 1, nblks(2)
    3092       210682 :             DO iblk = 1, nblks(1)
    3093       574480 :                DO igroup = 0, ngroups - 1
    3094       369536 :                   IF (block_source(iblk, jblk) == -1) CYCLE
    3095              : 
    3096        69080 :                   i_msg = i_msg + 1
    3097        69080 :                   IF (i_msg < (i_batch - 1)*batch_size + 1 .OR. i_msg > i_batch*batch_size) CYCLE
    3098              : 
    3099              :                   !a unique tag per block, within this batch
    3100        69080 :                   tag = i_msg - (i_batch - 1)*batch_size
    3101              : 
    3102        69080 :                   IF (para_env%mepos == current_dest(iblk, jblk, igroup) .AND. &
    3103       184768 :                       block_source(iblk, jblk) /= current_dest(iblk, jblk, igroup)) THEN
    3104              : 
    3105        69080 :                      ALLOCATE (blk(bsizes1(iblk), bsizes2(jblk)))
    3106     14992892 :                      blk(:, :) = recv_buff(tag)%array(:, :)
    3107        86350 :                      CALL dbt_put_block(t2c_sub, [iblk, jblk], SHAPE(blk), blk)
    3108        17270 :                      DEALLOCATE (blk)
    3109              :                   END IF
    3110              :                END DO
    3111              :             END DO
    3112              :          END DO
    3113              : 
    3114              :          !clean-up
    3115        74818 :          DO i = 1, batch_size
    3116        74818 :             IF (ASSOCIATED(recv_buff(i)%array)) DEALLOCATE (recv_buff(i)%array)
    3117              :          END DO
    3118        11476 :          DEALLOCATE (send_buff, recv_buff, send_req, recv_req)
    3119              :       END DO !i_batch
    3120         5738 :       CALL dbt_finalize(t2c_sub)
    3121              : 
    3122        12116 :    END SUBROUTINE copy_2c_to_subgroup
    3123              : 
    3124              : ! **************************************************************************************************
    3125              : !> \brief Copy stored 3c blocks to subgroups with identical tensor layouts.
    3126              : !>        Route only existing blocks; destination ranks are relative to a subgroup.
    3127              : !> \param t3c_sub destination tensor in the local subgroup
    3128              : !> \param t3c_main source tensor in the main communicator
    3129              : !> \param iatom_to_subgroup optional atom-to-subgroup selection
    3130              : !> \param dim_at tensor dimension identifying the atom
    3131              : !> \param idx_to_at mapping of blocks in dim_at to atoms
    3132              : ! **************************************************************************************************
    3133        24568 :    SUBROUTINE copy_3c_to_subgroup(t3c_sub, t3c_main, iatom_to_subgroup, dim_at, idx_to_at)
    3134              :       TYPE(dbt_type), INTENT(INOUT)                      :: t3c_sub, t3c_main
    3135              :       TYPE(cp_1d_logical_p_type), INTENT(IN), OPTIONAL   :: iatom_to_subgroup(:)
    3136              :       INTEGER, INTENT(IN), OPTIONAL                      :: dim_at, idx_to_at(:)
    3137              : 
    3138              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'copy_3c_to_subgroup'
    3139              : 
    3140              :       INTEGER                                            :: handle, i
    3141        24568 :       LOGICAL, ALLOCATABLE                               :: group_mask(:, :)
    3142              : 
    3143        24568 :       CALL timeset(routineN, handle)
    3144        24568 :       IF (PRESENT(iatom_to_subgroup) .AND. PRESENT(dim_at) .AND. PRESENT(idx_to_at)) THEN
    3145        63448 :          ALLOCATE (group_mask(SIZE(iatom_to_subgroup(1)%array), SIZE(idx_to_at)))
    3146        47586 :          DO i = 1, SIZE(idx_to_at)
    3147       109410 :             group_mask(:, i) = iatom_to_subgroup(idx_to_at(i))%array(:)
    3148              :          END DO
    3149        15862 :          CALL dbt_copy_indexed(t3c_main, t3c_sub, group_mask=group_mask, group_dim=dim_at)
    3150              :       ELSE
    3151         8706 :          CALL dbt_copy_indexed(t3c_main, t3c_sub)
    3152              :       END IF
    3153        24568 :       CALL timestop(handle)
    3154        24568 :    END SUBROUTINE copy_3c_to_subgroup
    3155              : 
    3156              : ! **************************************************************************************************
    3157              : !> \brief A routine that gather the pieces of the KS matrix accross the subgroup and puts it in the
    3158              : !>        main group. Each b_img, iatom, jatom tuple is one a single CPU
    3159              : !> \param ks_t ...
    3160              : !> \param ks_t_sub ...
    3161              : !> \param group_size ...
    3162              : !> \param sparsity_pattern ...
    3163              : !> \param para_env ...
    3164              : !> \param ri_data ...
    3165              : ! **************************************************************************************************
    3166          508 :    SUBROUTINE gather_ks_matrix(ks_t, ks_t_sub, group_size, sparsity_pattern, para_env, ri_data)
    3167              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: ks_t, ks_t_sub
    3168              :       INTEGER, INTENT(IN)                                :: group_size
    3169              :       INTEGER, DIMENSION(:, :, :), INTENT(IN)            :: sparsity_pattern
    3170              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3171              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3172              : 
    3173              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'gather_ks_matrix'
    3174              : 
    3175              :       INTEGER                                            :: b_img, dest, handle, i, i_spin, iatom, &
    3176              :                                                             igroup, ir, is, jatom, n_mess, natom, &
    3177              :                                                             nimg, nspins, source, tag
    3178              :       LOGICAL                                            :: found
    3179          508 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :)             :: blk
    3180          508 :       TYPE(cp_2d_r_p_type), ALLOCATABLE, DIMENSION(:)    :: recv_buff, send_buff
    3181          508 :       TYPE(mp_request_type), ALLOCATABLE, DIMENSION(:)   :: recv_req, send_req
    3182              : 
    3183          508 :       CALL timeset(routineN, handle)
    3184              : 
    3185          508 :       nimg = SIZE(sparsity_pattern, 3)
    3186          508 :       natom = SIZE(sparsity_pattern, 2)
    3187          508 :       nspins = SIZE(ks_t, 1)
    3188              : 
    3189        17142 :       DO b_img = 1, nimg
    3190              :          n_mess = 0
    3191        34970 :          DO i_spin = 1, nspins
    3192        71642 :             DO jatom = 1, natom
    3193       128352 :                DO iatom = 1, natom
    3194       110016 :                   IF (sparsity_pattern(iatom, jatom, b_img) > -1) n_mess = n_mess + 1
    3195              :                END DO
    3196              :             END DO
    3197              :          END DO
    3198              : 
    3199       120850 :          ALLOCATE (send_buff(n_mess), recv_buff(n_mess))
    3200       137484 :          ALLOCATE (send_req(n_mess), recv_req(n_mess))
    3201        16634 :          ir = 0
    3202        16634 :          is = 0
    3203        16634 :          n_mess = 0
    3204        16634 :          tag = 0
    3205              : 
    3206        34970 :          DO i_spin = 1, nspins
    3207        71642 :             DO jatom = 1, natom
    3208       128352 :                DO iatom = 1, natom
    3209        73344 :                   IF (sparsity_pattern(iatom, jatom, b_img) < 0) CYCLE
    3210        26178 :                   n_mess = n_mess + 1
    3211        26178 :                   tag = tag + 1
    3212              : 
    3213              :                   !sending the message
    3214        78534 :                   CALL dbt_get_stored_coordinates(ks_t(i_spin, b_img), [iatom, jatom], dest)
    3215        78534 :                   CALL dbt_get_stored_coordinates(ks_t_sub(i_spin, b_img), [iatom, jatom], source) !source within sub
    3216        26178 :                   igroup = sparsity_pattern(iatom, jatom, b_img)
    3217        26178 :                   source = source + igroup*group_size
    3218        26178 :                   IF (para_env%mepos == source) THEN
    3219        39267 :                      CALL dbt_get_block(ks_t_sub(i_spin, b_img), [iatom, jatom], blk, found)
    3220        13089 :                      IF (source == dest) THEN
    3221         7819 :                         IF (found) CALL dbt_put_block(ks_t(i_spin, b_img), [iatom, jatom], SHAPE(blk), blk)
    3222              :                      ELSE
    3223        43064 :                         ALLOCATE (send_buff(n_mess)%array(ri_data%bsizes_AO(iatom), ri_data%bsizes_AO(jatom)))
    3224       431082 :                         send_buff(n_mess)%array(:, :) = 0.0_dp
    3225        10766 :                         IF (found) THEN
    3226       240649 :                            send_buff(n_mess)%array(:, :) = blk(:, :)
    3227              :                         END IF
    3228        10766 :                         is = is + 1
    3229              :                         CALL para_env%isend(msgin=send_buff(n_mess)%array, dest=dest, &
    3230        10766 :                                             request=send_req(is), tag=tag)
    3231              :                      END IF
    3232        13089 :                      DEALLOCATE (blk)
    3233              :                   END IF
    3234              : 
    3235              :                   !receiving the message
    3236        62850 :                   IF (para_env%mepos == dest .AND. source /= dest) THEN
    3237        43064 :                      ALLOCATE (recv_buff(n_mess)%array(ri_data%bsizes_AO(iatom), ri_data%bsizes_AO(jatom)))
    3238        10766 :                      ir = ir + 1
    3239              :                      CALL para_env%irecv(msgout=recv_buff(n_mess)%array, source=source, &
    3240        10766 :                                          request=recv_req(ir), tag=tag)
    3241              :                   END IF
    3242              :                END DO !iatom
    3243              :             END DO !jatom
    3244              :          END DO !ispin
    3245              : 
    3246        16634 :          CALL mp_waitall(send_req(1:is))
    3247        16634 :          CALL mp_waitall(recv_req(1:ir))
    3248              : 
    3249              :          !Copy the messages received into the KS matrix
    3250        16634 :          n_mess = 0
    3251        34970 :          DO i_spin = 1, nspins
    3252        71642 :             DO jatom = 1, natom
    3253       128352 :                DO iatom = 1, natom
    3254        73344 :                   IF (sparsity_pattern(iatom, jatom, b_img) < 0) CYCLE
    3255        26178 :                   n_mess = n_mess + 1
    3256              : 
    3257        78534 :                   CALL dbt_get_stored_coordinates(ks_t(i_spin, b_img), [iatom, jatom], dest)
    3258        62850 :                   IF (para_env%mepos == dest) THEN
    3259        13089 :                      IF (.NOT. ASSOCIATED(recv_buff(n_mess)%array)) CYCLE
    3260        43064 :                      ALLOCATE (blk(ri_data%bsizes_AO(iatom), ri_data%bsizes_AO(jatom)))
    3261       431082 :                      blk(:, :) = recv_buff(n_mess)%array(:, :)
    3262        53830 :                      CALL dbt_put_block(ks_t(i_spin, b_img), [iatom, jatom], SHAPE(blk), blk)
    3263        10766 :                      DEALLOCATE (blk)
    3264              :                   END IF
    3265              :                END DO
    3266              :             END DO
    3267              :          END DO
    3268              : 
    3269              :          !clean-up
    3270        42812 :          DO i = 1, n_mess
    3271        26178 :             IF (ASSOCIATED(send_buff(i)%array)) DEALLOCATE (send_buff(i)%array)
    3272        42812 :             IF (ASSOCIATED(recv_buff(i)%array)) DEALLOCATE (recv_buff(i)%array)
    3273              :          END DO
    3274        17142 :          DEALLOCATE (send_buff, recv_buff, send_req, recv_req)
    3275              :       END DO !b_img
    3276              : 
    3277          508 :       CALL timestop(handle)
    3278              : 
    3279          508 :    END SUBROUTINE gather_ks_matrix
    3280              : 
    3281              : ! **************************************************************************************************
    3282              : !> \brief copy all required 2c tensors from the main MPI group to the subgroups
    3283              : !> \param t_2c_ao_tmp ...
    3284              : !> \param ks_t_split ...
    3285              : !> \param ks_t_sub ...
    3286              : !> \param para_env_sub ...
    3287              : !> \param ri_data ...
    3288              : ! **************************************************************************************************
    3289          508 :    SUBROUTINE get_subgroup_ks_tensors(t_2c_ao_tmp, ks_t_split, ks_t_sub, para_env_sub, ri_data)
    3290              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_2c_ao_tmp, ks_t_split
    3291              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: ks_t_sub
    3292              :       TYPE(mp_para_env_type), POINTER                    :: para_env_sub
    3293              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3294              : 
    3295              :       CHARACTER(len=*), PARAMETER :: routineN = 'get_subgroup_ks_tensors'
    3296              : 
    3297              :       INTEGER                                            :: handle, i_img, i_spin, nimg, nspins
    3298          508 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist1, dist2
    3299              :       INTEGER, DIMENSION(2)                              :: pdims_2d
    3300         1524 :       TYPE(dbt_pgrid_type)                               :: pgrid_2d
    3301              : 
    3302          508 :       CALL timeset(routineN, handle)
    3303              : 
    3304              :       !Create the 2d pgrid
    3305          508 :       pdims_2d = 0
    3306          508 :       CALL dbt_pgrid_create(para_env_sub, pdims_2d, pgrid_2d)
    3307              : 
    3308              :       !the AO based tensors
    3309              :       CALL create_2c_tensor(ks_t_split(1), dist1, dist2, pgrid_2d, &
    3310              :                             ri_data%bsizes_AO_split, ri_data%bsizes_AO_split, &
    3311          508 :                             name="(AO | AO)")
    3312          508 :       DEALLOCATE (dist1, dist2)
    3313          508 :       CALL dbt_create(ks_t_split(1), ks_t_split(2))
    3314              : 
    3315              :       CALL create_2c_tensor(t_2c_ao_tmp(1), dist1, dist2, pgrid_2d, &
    3316              :                             ri_data%bsizes_AO, ri_data%bsizes_AO, &
    3317          508 :                             name="(AO | AO)")
    3318          508 :       DEALLOCATE (dist1, dist2)
    3319              : 
    3320          508 :       nspins = SIZE(ks_t_sub, 1)
    3321          508 :       nimg = SIZE(ks_t_sub, 2)
    3322        17142 :       DO i_img = 1, nimg
    3323        35478 :          DO i_spin = 1, nspins
    3324        34970 :             CALL dbt_create(t_2c_ao_tmp(1), ks_t_sub(i_spin, i_img))
    3325              :          END DO
    3326              :       END DO
    3327              : 
    3328          508 :       CALL dbt_pgrid_destroy(pgrid_2d)
    3329          508 :       CALL timestop(handle)
    3330              : 
    3331          508 :    END SUBROUTINE get_subgroup_ks_tensors
    3332              : 
    3333              : ! **************************************************************************************************
    3334              : !> \brief copy all required 3c tensors from the main MPI group to the subgroups
    3335              : !> \param t_3c_work_2 ...
    3336              : !> \param t_3c_apc ...
    3337              : !> \param t_3c_apc_sub ...
    3338              : !> \param para_env_sub ...
    3339              : !> \param ri_data ...
    3340              : ! **************************************************************************************************
    3341          508 :    SUBROUTINE get_subgroup_3c_tensors(t_3c_work_2, t_3c_apc, t_3c_apc_sub, &
    3342              :                                       para_env_sub, ri_data)
    3343              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_3c_work_2
    3344              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_3c_apc, t_3c_apc_sub
    3345              :       TYPE(mp_para_env_type), POINTER                    :: para_env_sub
    3346              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3347              : 
    3348              :       CHARACTER(len=*), PARAMETER :: routineN = 'get_subgroup_3c_tensors'
    3349              : 
    3350              :       INTEGER                                            :: batch_size, handle, handle2, i_img, &
    3351              :                                                             i_RI, i_spin, ib, natom, nblks_AO, &
    3352              :                                                             nblks_RI, nimg, nspins
    3353              :       INTEGER(int_8)                                     :: nze
    3354          508 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bsizes_RI_ext, bsizes_RI_ext_split, &
    3355          508 :                                                             bsizes_stack, dist1, dist2, dist3, &
    3356          508 :                                                             dist_stack, idx_to_at
    3357              :       INTEGER, DIMENSION(3)                              :: pdims
    3358              :       REAL(dp)                                           :: occ
    3359         4572 :       TYPE(dbt_distribution_type)                        :: t_dist
    3360         1524 :       TYPE(dbt_pgrid_type)                               :: pgrid
    3361        12700 :       TYPE(dbt_type)                                     :: tmp, work_atom_block, work_atom_block_sub
    3362              : 
    3363          508 :       CALL timeset(routineN, handle)
    3364              : 
    3365          508 :       nblks_RI = SIZE(ri_data%bsizes_RI_split)
    3366         1524 :       ALLOCATE (bsizes_RI_ext_split(ri_data%ncell_RI*nblks_RI))
    3367         4282 :       DO i_RI = 1, ri_data%ncell_RI
    3368        18272 :          bsizes_RI_ext_split((i_RI - 1)*nblks_RI + 1:i_RI*nblks_RI) = ri_data%bsizes_RI_split(:)
    3369              :       END DO
    3370              : 
    3371          508 :       natom = SIZE(ri_data%bsizes_RI)
    3372         1524 :       ALLOCATE (bsizes_RI_ext(ri_data%ncell_RI*natom))
    3373         4282 :       DO i_RI = 1, ri_data%ncell_RI
    3374        11830 :          bsizes_RI_ext((i_RI - 1)*natom + 1:i_RI*natom) = ri_data%bsizes_RI(:)
    3375              :       END DO
    3376              : 
    3377          508 :       batch_size = ri_data%kp_stack_size
    3378          508 :       nblks_AO = SIZE(ri_data%bsizes_AO_split)
    3379         1524 :       ALLOCATE (bsizes_stack(batch_size*nblks_AO))
    3380         9564 :       DO ib = 1, batch_size
    3381        34364 :          bsizes_stack((ib - 1)*nblks_AO + 1:ib*nblks_AO) = ri_data%bsizes_AO_split(:)
    3382              :       END DO
    3383              : 
    3384              :       !Do the same for the t_3c_ctr_2 configuration
    3385          508 :       pdims = 0
    3386              :       CALL dbt_pgrid_create(para_env_sub, pdims, pgrid, &
    3387         2032 :                             tensor_dims=[1, SIZE(bsizes_RI_ext_split), batch_size*SIZE(ri_data%bsizes_AO_split)])
    3388              : 
    3389              :       !For more efficient communication, we use intermediate tensors with larger block size
    3390              :       CALL create_3c_tensor(work_atom_block_sub, dist1, dist2, dist3, &
    3391              :                             pgrid, ri_data%bsizes_AO, bsizes_RI_ext, &
    3392          508 :                             ri_data%bsizes_AO, [1], [2, 3], name="(AO RI | AO)")
    3393          508 :       DEALLOCATE (dist1, dist2, dist3)
    3394              : 
    3395              :       CALL create_3c_tensor(work_atom_block, dist1, dist2, dist3, &
    3396              :                             ri_data%pgrid_1, ri_data%bsizes_AO, bsizes_RI_ext, &
    3397          508 :                             ri_data%bsizes_AO, [1], [2, 3], name="(AO RI | AO)")
    3398          508 :       DEALLOCATE (dist1, dist2, dist3)
    3399              : 
    3400              :       !template for t_3c_apc_sub
    3401              :       CALL create_3c_tensor(tmp, dist1, dist2, dist3, &
    3402              :                             pgrid, ri_data%bsizes_AO_split, bsizes_RI_ext_split, &
    3403          508 :                             ri_data%bsizes_AO_split, [1], [2, 3], name="(AO RI | AO)")
    3404              : 
    3405              :       !create t_3c_work_2 tensors in a distribution that matches the above
    3406         1016 :       ALLOCATE (dist_stack(batch_size*nblks_AO))
    3407         9564 :       DO ib = 1, batch_size
    3408        34364 :          dist_stack((ib - 1)*nblks_AO + 1:ib*nblks_AO) = dist3(:)
    3409              :       END DO
    3410              : 
    3411          508 :       CALL dbt_distribution_new(t_dist, pgrid, dist1, dist2, dist_stack)
    3412              :       CALL dbt_create(t_3c_work_2(1), "work_2_stack", t_dist, [1], [2, 3], &
    3413          508 :                       ri_data%bsizes_AO_split, bsizes_RI_ext_split, bsizes_stack)
    3414          508 :       CALL dbt_create(t_3c_work_2(1), t_3c_work_2(2))
    3415          508 :       CALL dbt_create(t_3c_work_2(1), t_3c_work_2(3))
    3416          508 :       CALL dbt_distribution_destroy(t_dist)
    3417          508 :       DEALLOCATE (dist1, dist2, dist3, dist_stack)
    3418              : 
    3419              :       !Finally copy data from t_3c_apc to the subgroups
    3420         1524 :       ALLOCATE (idx_to_at(SIZE(ri_data%bsizes_AO)))
    3421          508 :       CALL get_idx_to_atom(idx_to_at, ri_data%bsizes_AO, ri_data%bsizes_AO)
    3422          508 :       nspins = SIZE(t_3c_apc, 1)
    3423          508 :       nimg = SIZE(t_3c_apc, 2)
    3424          508 :       CALL timeset(routineN//"_apc", handle2)
    3425        17142 :       DO i_img = 1, nimg
    3426        34970 :          DO i_spin = 1, nspins
    3427        18336 :             CALL dbt_create(tmp, t_3c_apc_sub(i_spin, i_img))
    3428        18336 :             CALL get_tensor_occupancy(t_3c_apc(i_spin, i_img), nze, occ)
    3429        18336 :             IF (nze == 0) CYCLE
    3430        14192 :             CALL dbt_copy(t_3c_apc(i_spin, i_img), work_atom_block, move_data=.TRUE.)
    3431              :             CALL copy_3c_to_subgroup(work_atom_block_sub, work_atom_block, &
    3432        14192 :                                      ri_data%iatom_to_subgroup, 1, idx_to_at)
    3433        14192 :             CALL dbt_copy(work_atom_block_sub, t_3c_apc_sub(i_spin, i_img), move_data=.TRUE.)
    3434        49162 :             CALL dbt_filter(t_3c_apc_sub(i_spin, i_img), ri_data%filter_eps)
    3435              :          END DO
    3436        35478 :          DO i_spin = 1, nspins
    3437        34970 :             CALL dbt_destroy(t_3c_apc(i_spin, i_img))
    3438              :          END DO
    3439              :       END DO
    3440          508 :       CALL timestop(handle2)
    3441          508 :       CALL dbt_pgrid_destroy(pgrid)
    3442          508 :       CALL dbt_destroy(tmp)
    3443          508 :       CALL dbt_destroy(work_atom_block)
    3444          508 :       CALL dbt_destroy(work_atom_block_sub)
    3445              : 
    3446          508 :       CALL timestop(handle)
    3447              : 
    3448         1524 :    END SUBROUTINE get_subgroup_3c_tensors
    3449              : 
    3450              : ! **************************************************************************************************
    3451              : !> \brief copy all required 2c force tensors from the main MPI group to the subgroups
    3452              : !> \param t_2c_inv ...
    3453              : !> \param t_2c_bint ...
    3454              : !> \param t_2c_metric ...
    3455              : !> \param mat_2c_pot ...
    3456              : !> \param t_2c_work ...
    3457              : !> \param rho_ao_t ...
    3458              : !> \param rho_ao_t_sub ...
    3459              : !> \param t_2c_der_metric ...
    3460              : !> \param t_2c_der_metric_sub ...
    3461              : !> \param mat_der_pot ...
    3462              : !> \param mat_der_pot_sub ...
    3463              : !> \param group_size ...
    3464              : !> \param ngroups ...
    3465              : !> \param para_env ...
    3466              : !> \param para_env_sub ...
    3467              : !> \param ri_data ...
    3468              : !> \note Main MPI group tensors are deleted within this routine, for memory optimization
    3469              : ! **************************************************************************************************
    3470          108 :    SUBROUTINE get_subgroup_2c_derivs(t_2c_inv, t_2c_bint, t_2c_metric, mat_2c_pot, t_2c_work, rho_ao_t, &
    3471           54 :                                      rho_ao_t_sub, t_2c_der_metric, t_2c_der_metric_sub, mat_der_pot, &
    3472           54 :                                      mat_der_pot_sub, group_size, ngroups, para_env, para_env_sub, ri_data)
    3473              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_2c_inv, t_2c_bint, t_2c_metric
    3474              :       TYPE(dbcsr_type), DIMENSION(:), INTENT(INOUT)      :: mat_2c_pot
    3475              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_2c_work
    3476              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: rho_ao_t, rho_ao_t_sub, t_2c_der_metric, &
    3477              :                                                             t_2c_der_metric_sub
    3478              :       TYPE(dbcsr_type), DIMENSION(:, :), INTENT(INOUT)   :: mat_der_pot, mat_der_pot_sub
    3479              :       INTEGER, INTENT(IN)                                :: group_size, ngroups
    3480              :       TYPE(mp_para_env_type), POINTER                    :: para_env, para_env_sub
    3481              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3482              : 
    3483              :       CHARACTER(len=*), PARAMETER :: routineN = 'get_subgroup_2c_derivs'
    3484              : 
    3485              :       INTEGER                                            :: handle, i, i_img, i_RI, i_spin, i_xyz, &
    3486              :                                                             iatom, iproc, j, natom, nblks, nimg, &
    3487              :                                                             nspins
    3488              :       INTEGER(int_8)                                     :: nze
    3489              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bsizes_RI_ext, bsizes_RI_ext_split, &
    3490           54 :                                                             dist1, dist2
    3491          108 :       INTEGER, CONTIGUOUS, DIMENSION(:), POINTER         :: col_dist, RI_blk_size, row_dist
    3492              :       INTEGER, DIMENSION(2)                              :: pdims_2d
    3493           54 :       INTEGER, DIMENSION(:, :), POINTER                  :: dbcsr_pgrid
    3494              :       REAL(dp)                                           :: occ
    3495              :       TYPE(dbcsr_distribution_type)                      :: dbcsr_dist_sub
    3496          162 :       TYPE(dbt_pgrid_type)                               :: pgrid_2d
    3497          702 :       TYPE(dbt_type)                                     :: work, work_sub
    3498              : 
    3499           54 :       CALL timeset(routineN, handle)
    3500              : 
    3501              :       !Note: a fair portion of this routine is copied from the energy version of it
    3502              :       !Create the 2d pgrid
    3503           54 :       pdims_2d = 0
    3504           54 :       CALL dbt_pgrid_create(para_env_sub, pdims_2d, pgrid_2d)
    3505              : 
    3506           54 :       natom = SIZE(ri_data%bsizes_RI)
    3507           54 :       nblks = SIZE(ri_data%bsizes_RI_split)
    3508          162 :       ALLOCATE (bsizes_RI_ext(ri_data%ncell_RI*natom))
    3509          162 :       ALLOCATE (bsizes_RI_ext_split(ri_data%ncell_RI*nblks))
    3510          410 :       DO i_RI = 1, ri_data%ncell_RI
    3511         1068 :          bsizes_RI_ext((i_RI - 1)*natom + 1:i_RI*natom) = ri_data%bsizes_RI(:)
    3512         1994 :          bsizes_RI_ext_split((i_RI - 1)*nblks + 1:i_RI*nblks) = ri_data%bsizes_RI_split(:)
    3513              :       END DO
    3514              : 
    3515              :       !nRI x nRI 2c tensors
    3516              :       CALL create_2c_tensor(t_2c_inv(1), dist1, dist2, pgrid_2d, &
    3517              :                             bsizes_RI_ext, bsizes_RI_ext, &
    3518           54 :                             name="(RI | RI)")
    3519           54 :       DEALLOCATE (dist1, dist2)
    3520              : 
    3521           54 :       CALL dbt_create(t_2c_inv(1), t_2c_bint(1))
    3522           54 :       CALL dbt_create(t_2c_inv(1), t_2c_metric(1))
    3523          108 :       DO iatom = 2, natom
    3524           54 :          CALL dbt_create(t_2c_inv(1), t_2c_inv(iatom))
    3525           54 :          CALL dbt_create(t_2c_inv(1), t_2c_bint(iatom))
    3526          108 :          CALL dbt_create(t_2c_inv(1), t_2c_metric(iatom))
    3527              :       END DO
    3528           54 :       CALL dbt_create(t_2c_inv(1), t_2c_work(1))
    3529           54 :       CALL dbt_create(t_2c_inv(1), t_2c_work(2))
    3530           54 :       CALL dbt_create(t_2c_inv(1), t_2c_work(3))
    3531           54 :       CALL dbt_create(t_2c_inv(1), t_2c_work(4))
    3532              : 
    3533              :       CALL create_2c_tensor(t_2c_work(5), dist1, dist2, pgrid_2d, &
    3534              :                             bsizes_RI_ext_split, bsizes_RI_ext_split, &
    3535           54 :                             name="(RI | RI)")
    3536           54 :       DEALLOCATE (dist1, dist2)
    3537              : 
    3538              :       !copy the data from the main group.
    3539          162 :       DO iatom = 1, natom
    3540          108 :          CALL copy_2c_to_subgroup(t_2c_inv(iatom), ri_data%t_2c_inv(1, iatom), group_size, ngroups, para_env)
    3541          108 :          CALL copy_2c_to_subgroup(t_2c_bint(iatom), ri_data%t_2c_int(1, iatom), group_size, ngroups, para_env)
    3542          162 :          CALL copy_2c_to_subgroup(t_2c_metric(iatom), ri_data%t_2c_pot(1, iatom), group_size, ngroups, para_env)
    3543              :       END DO
    3544              : 
    3545              :       !This includes the derivatives of the RI metric, for which there is one per atom
    3546          216 :       DO i_xyz = 1, 3
    3547          540 :          DO iatom = 1, natom
    3548          324 :             CALL dbt_create(t_2c_inv(1), t_2c_der_metric_sub(iatom, i_xyz))
    3549              :             CALL copy_2c_to_subgroup(t_2c_der_metric_sub(iatom, i_xyz), t_2c_der_metric(iatom, i_xyz), &
    3550          324 :                                      group_size, ngroups, para_env)
    3551          486 :             CALL dbt_destroy(t_2c_der_metric(iatom, i_xyz))
    3552              :          END DO
    3553              :       END DO
    3554              : 
    3555              :       !AO x AO 2c tensors
    3556              :       CALL create_2c_tensor(rho_ao_t_sub(1, 1), dist1, dist2, pgrid_2d, &
    3557              :                             ri_data%bsizes_AO_split, ri_data%bsizes_AO_split, &
    3558           54 :                             name="(AO | AO)")
    3559           54 :       DEALLOCATE (dist1, dist2)
    3560           54 :       nspins = SIZE(rho_ao_t, 1)
    3561           54 :       nimg = SIZE(rho_ao_t, 2)
    3562              : 
    3563         1568 :       DO i_img = 1, nimg
    3564         3262 :          DO i_spin = 1, nspins
    3565         1694 :             IF (.NOT. (i_img == 1 .AND. i_spin == 1)) THEN
    3566         1640 :                CALL dbt_create(rho_ao_t_sub(1, 1), rho_ao_t_sub(i_spin, i_img))
    3567              :             END IF
    3568              :             CALL copy_2c_to_subgroup(rho_ao_t_sub(i_spin, i_img), rho_ao_t(i_spin, i_img), &
    3569         1694 :                                      group_size, ngroups, para_env)
    3570         3208 :             CALL dbt_destroy(rho_ao_t(i_spin, i_img))
    3571              :          END DO
    3572              :       END DO
    3573              : 
    3574              :       !The RIxRI matrices, going through tensors
    3575              :       CALL create_2c_tensor(work_sub, dist1, dist2, pgrid_2d, &
    3576              :                             ri_data%bsizes_RI, ri_data%bsizes_RI, &
    3577           54 :                             name="(RI | RI)")
    3578           54 :       CALL dbt_create(ri_data%kp_mat_2c_pot(1, 1), work)
    3579              : 
    3580          216 :       ALLOCATE (dbcsr_pgrid(0:pdims_2d(1) - 1, 0:pdims_2d(2) - 1))
    3581           54 :       iproc = 0
    3582          108 :       DO i = 0, pdims_2d(1) - 1
    3583          162 :          DO j = 0, pdims_2d(2) - 1
    3584           54 :             dbcsr_pgrid(i, j) = iproc
    3585          108 :             iproc = iproc + 1
    3586              :          END DO
    3587              :       END DO
    3588              : 
    3589              :       !We need to have the same exact 2d block dist as the tensors
    3590          216 :       ALLOCATE (col_dist(natom), row_dist(natom))
    3591          162 :       row_dist(:) = dist1(:)
    3592          162 :       col_dist(:) = dist2(:)
    3593              : 
    3594          108 :       ALLOCATE (RI_blk_size(natom))
    3595          162 :       RI_blk_size(:) = ri_data%bsizes_RI(:)
    3596              : 
    3597              :       CALL dbcsr_distribution_new(dbcsr_dist_sub, group=para_env_sub%get_handle(), pgrid=dbcsr_pgrid, &
    3598           54 :                                   row_dist=row_dist, col_dist=col_dist)
    3599              :       CALL dbcsr_create(mat_2c_pot(1), dist=dbcsr_dist_sub, name="sub", matrix_type=dbcsr_type_no_symmetry, &
    3600           54 :                         row_blk_size=RI_blk_size, col_blk_size=RI_blk_size)
    3601              : 
    3602              :       !The HFX potential
    3603         1568 :       DO i_img = 1, nimg
    3604         1514 :          IF (i_img > 1) CALL dbcsr_create(mat_2c_pot(i_img), template=mat_2c_pot(1))
    3605         1514 :          CALL dbt_copy_matrix_to_tensor(ri_data%kp_mat_2c_pot(1, i_img), work)
    3606         1514 :          CALL get_tensor_occupancy(work, nze, occ)
    3607         1514 :          IF (nze == 0) CYCLE
    3608              : 
    3609          944 :          CALL copy_2c_to_subgroup(work_sub, work, group_size, ngroups, para_env)
    3610          944 :          CALL dbt_copy_tensor_to_matrix(work_sub, mat_2c_pot(i_img))
    3611          944 :          CALL dbcsr_filter(mat_2c_pot(i_img), ri_data%filter_eps)
    3612         2512 :          CALL dbt_clear(work_sub)
    3613              :       END DO
    3614              : 
    3615              :       !The derivatives of the HFX potential
    3616          216 :       DO i_xyz = 1, 3
    3617         4758 :          DO i_img = 1, nimg
    3618         4542 :             CALL dbcsr_create(mat_der_pot_sub(i_img, i_xyz), template=mat_2c_pot(1))
    3619         4542 :             CALL dbt_copy_matrix_to_tensor(mat_der_pot(i_img, i_xyz), work)
    3620         4542 :             CALL dbcsr_release(mat_der_pot(i_img, i_xyz))
    3621         4542 :             CALL get_tensor_occupancy(work, nze, occ)
    3622         4542 :             IF (nze == 0) CYCLE
    3623              : 
    3624         2772 :             CALL copy_2c_to_subgroup(work_sub, work, group_size, ngroups, para_env)
    3625         2772 :             CALL dbt_copy_tensor_to_matrix(work_sub, mat_der_pot_sub(i_img, i_xyz))
    3626         2772 :             CALL dbcsr_filter(mat_der_pot_sub(i_img, i_xyz), ri_data%filter_eps)
    3627         7476 :             CALL dbt_clear(work_sub)
    3628              :          END DO
    3629              :       END DO
    3630              : 
    3631           54 :       CALL dbt_destroy(work)
    3632           54 :       CALL dbt_destroy(work_sub)
    3633           54 :       CALL dbt_pgrid_destroy(pgrid_2d)
    3634           54 :       CALL dbcsr_distribution_release(dbcsr_dist_sub)
    3635           54 :       DEALLOCATE (col_dist, row_dist, RI_blk_size, dbcsr_pgrid)
    3636              : 
    3637           54 :       CALL timestop(handle)
    3638              : 
    3639          216 :    END SUBROUTINE get_subgroup_2c_derivs
    3640              : 
    3641              : ! **************************************************************************************************
    3642              : !> \brief copy all required 3c derivative tensors from the main MPI group to the subgroups
    3643              : !> \param t_3c_work_2 ...
    3644              : !> \param t_3c_work_3 ...
    3645              : !> \param t_3c_der_AO ...
    3646              : !> \param t_3c_der_AO_sub ...
    3647              : !> \param t_3c_der_RI ...
    3648              : !> \param t_3c_der_RI_sub ...
    3649              : !> \param t_3c_apc ...
    3650              : !> \param t_3c_apc_sub ...
    3651              : !> \param t_3c_der_stack ...
    3652              : !> \param para_env_sub ...
    3653              : !> \param ri_data ...
    3654              : !> \note the tensor containing the derivatives in the main MPI group are deleted for memory
    3655              : ! **************************************************************************************************
    3656           54 :    SUBROUTINE get_subgroup_3c_derivs(t_3c_work_2, t_3c_work_3, t_3c_der_AO, t_3c_der_AO_sub, &
    3657           54 :                                      t_3c_der_RI, t_3c_der_RI_sub, t_3c_apc, t_3c_apc_sub, &
    3658           54 :                                      t_3c_der_stack, para_env_sub, &
    3659              :                                      ri_data)
    3660              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_3c_work_2, t_3c_work_3
    3661              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_3c_der_AO, t_3c_der_AO_sub, &
    3662              :                                                             t_3c_der_RI, t_3c_der_RI_sub, &
    3663              :                                                             t_3c_apc, t_3c_apc_sub
    3664              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_3c_der_stack
    3665              :       TYPE(mp_para_env_type), POINTER                    :: para_env_sub
    3666              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3667              : 
    3668              :       CHARACTER(len=*), PARAMETER :: routineN = 'get_subgroup_3c_derivs'
    3669              : 
    3670              :       INTEGER                                            :: batch_size, handle, i_img, i_RI, i_spin, &
    3671              :                                                             i_xyz, ib, nblks_AO, nblks_RI, nimg, &
    3672              :                                                             nspins, pdims(3)
    3673              :       INTEGER(int_8)                                     :: nze
    3674           54 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bsizes_RI_ext, bsizes_RI_ext_split, &
    3675           54 :                                                             bsizes_stack, dist1, dist2, dist3, &
    3676           54 :                                                             dist_stack, idx_to_at
    3677              :       REAL(dp)                                           :: occ
    3678          486 :       TYPE(dbt_distribution_type)                        :: t_dist
    3679          162 :       TYPE(dbt_pgrid_type)                               :: pgrid
    3680         1350 :       TYPE(dbt_type)                                     :: tmp, work_atom_block, work_atom_block_sub
    3681              : 
    3682           54 :       CALL timeset(routineN, handle)
    3683              : 
    3684              :       !We use intermediate tensors with larger block size for more optimized communication
    3685           54 :       nimg = ri_data%nimg
    3686           54 :       batch_size = ri_data%kp_stack_size
    3687           54 :       nblks_RI = SIZE(ri_data%bsizes_RI)
    3688          162 :       ALLOCATE (bsizes_RI_ext(ri_data%ncell_RI*nblks_RI))
    3689          410 :       DO i_RI = 1, ri_data%ncell_RI
    3690         1122 :          bsizes_RI_ext((i_RI - 1)*nblks_RI + 1:i_RI*nblks_RI) = ri_data%bsizes_RI(:)
    3691              :       END DO
    3692              : 
    3693           54 :       nblks_RI = SIZE(ri_data%bsizes_RI_split)
    3694          162 :       ALLOCATE (bsizes_RI_ext_split(ri_data%ncell_RI*nblks_RI))
    3695          410 :       DO i_RI = 1, ri_data%ncell_RI
    3696         1994 :          bsizes_RI_ext_split((i_RI - 1)*nblks_RI + 1:i_RI*nblks_RI) = ri_data%bsizes_RI_split(:)
    3697              :       END DO
    3698           54 :       pdims = 0
    3699              :       CALL dbt_pgrid_create(para_env_sub, pdims, pgrid, &
    3700          216 :                             tensor_dims=[SIZE(bsizes_RI_ext_split), 1, batch_size*SIZE(ri_data%bsizes_AO_split)])
    3701              : 
    3702              :       CALL create_3c_tensor(tmp, dist1, dist2, dist3, pgrid, bsizes_RI_ext_split, &
    3703           54 :                             ri_data%bsizes_AO_split, ri_data%bsizes_AO_split, [1], [2, 3], name="(RI | AO AO)")
    3704           54 :       DEALLOCATE (dist1, dist2, dist3)
    3705              : 
    3706              :       CALL create_3c_tensor(work_atom_block_sub, dist1, dist2, dist3, &
    3707              :                             pgrid, bsizes_RI_ext, ri_data%bsizes_AO, &
    3708           54 :                             ri_data%bsizes_AO, [1], [2, 3], name="(RI | AO AO)")
    3709           54 :       DEALLOCATE (dist1, dist2, dist3)
    3710              : 
    3711              :       CALL create_3c_tensor(work_atom_block, dist1, dist2, dist3, &
    3712              :                             ri_data%pgrid_2, bsizes_RI_ext, ri_data%bsizes_AO, &
    3713           54 :                             ri_data%bsizes_AO, [1], [2, 3], name="(RI | AO AO)")
    3714           54 :       DEALLOCATE (dist1, dist2, dist3)
    3715           54 :       CALL dbt_pgrid_destroy(pgrid)
    3716              : 
    3717              :       ! SCF retains G=VB. The force contractions also need B itself, so build
    3718              :       ! its subgroup copy only when forces are requested, using the original layout.
    3719           54 :       IF (.NOT. ALLOCATED(ri_data%kp_t_3c_int)) THEN
    3720         2108 :          ALLOCATE (ri_data%kp_t_3c_int(nimg))
    3721         1568 :          DO i_img = 1, nimg
    3722         1514 :             CALL dbt_create(tmp, ri_data%kp_t_3c_int(i_img))
    3723         1514 :             CALL get_tensor_occupancy(ri_data%t_3c_int_ctr_1(1, i_img), nze, occ)
    3724         1514 :             IF (nze == 0) CYCLE
    3725         1390 :             CALL dbt_copy(ri_data%t_3c_int_ctr_1(1, i_img), work_atom_block, order=[2, 1, 3])
    3726         1390 :             CALL copy_3c_to_subgroup(work_atom_block_sub, work_atom_block)
    3727         1390 :             CALL dbt_copy(work_atom_block_sub, ri_data%kp_t_3c_int(i_img), move_data=.TRUE.)
    3728         2958 :             CALL dbt_filter(ri_data%kp_t_3c_int(i_img), ri_data%filter_eps)
    3729              :          END DO
    3730              :       END IF
    3731           54 :       CALL dbt_destroy(tmp)
    3732              : 
    3733              :       !We use the 3c integrals on the subgroup as template for the derivatives
    3734          216 :       DO i_xyz = 1, 3
    3735         4704 :          DO i_img = 1, nimg
    3736         4542 :             CALL dbt_create(ri_data%kp_t_3c_int(1), t_3c_der_AO_sub(i_img, i_xyz))
    3737         4542 :             CALL get_tensor_occupancy(t_3c_der_AO(i_img, i_xyz), nze, occ)
    3738         4542 :             IF (nze == 0) CYCLE
    3739              : 
    3740         2784 :             CALL dbt_copy(t_3c_der_AO(i_img, i_xyz), work_atom_block, move_data=.TRUE.)
    3741         2784 :             CALL copy_3c_to_subgroup(work_atom_block_sub, work_atom_block)
    3742         2784 :             CALL dbt_copy(work_atom_block_sub, t_3c_der_AO_sub(i_img, i_xyz), move_data=.TRUE.)
    3743         7488 :             CALL dbt_filter(t_3c_der_AO_sub(i_img, i_xyz), ri_data%filter_eps)
    3744              :          END DO
    3745              : 
    3746         4704 :          DO i_img = 1, nimg
    3747         4542 :             CALL dbt_create(ri_data%kp_t_3c_int(1), t_3c_der_RI_sub(i_img, i_xyz))
    3748         4542 :             CALL get_tensor_occupancy(t_3c_der_RI(i_img, i_xyz), nze, occ)
    3749         4542 :             IF (nze == 0) CYCLE
    3750              : 
    3751         2726 :             CALL dbt_copy(t_3c_der_RI(i_img, i_xyz), work_atom_block, move_data=.TRUE.)
    3752         2726 :             CALL copy_3c_to_subgroup(work_atom_block_sub, work_atom_block)
    3753         2726 :             CALL dbt_copy(work_atom_block_sub, t_3c_der_RI_sub(i_img, i_xyz), move_data=.TRUE.)
    3754         7430 :             CALL dbt_filter(t_3c_der_RI_sub(i_img, i_xyz), ri_data%filter_eps)
    3755              :          END DO
    3756              : 
    3757         4758 :          DO i_img = 1, nimg
    3758         4542 :             CALL dbt_destroy(t_3c_der_RI(i_img, i_xyz))
    3759         4704 :             CALL dbt_destroy(t_3c_der_AO(i_img, i_xyz))
    3760              :          END DO
    3761              :       END DO
    3762           54 :       CALL dbt_destroy(work_atom_block_sub)
    3763           54 :       CALL dbt_destroy(work_atom_block)
    3764              : 
    3765              :       !Deal with t_3c_apc
    3766           54 :       pdims = 0
    3767              :       CALL dbt_pgrid_create(para_env_sub, pdims, pgrid, &
    3768          216 :                             tensor_dims=[1, SIZE(bsizes_RI_ext_split), batch_size*SIZE(ri_data%bsizes_AO_split)])
    3769              : 
    3770              :       CALL create_3c_tensor(work_atom_block_sub, dist1, dist2, dist3, &
    3771              :                             pgrid, ri_data%bsizes_AO, bsizes_RI_ext, &
    3772           54 :                             ri_data%bsizes_AO, [1], [2, 3], name="(AO RI | AO)")
    3773           54 :       DEALLOCATE (dist1, dist2, dist3)
    3774              : 
    3775              :       CALL create_3c_tensor(work_atom_block, dist1, dist2, dist3, &
    3776              :                             ri_data%pgrid_1, ri_data%bsizes_AO, bsizes_RI_ext, &
    3777           54 :                             ri_data%bsizes_AO, [1], [2, 3], name="(AO RI | AO)")
    3778           54 :       DEALLOCATE (dist1, dist2, dist3)
    3779              : 
    3780              :       CALL create_3c_tensor(tmp, dist1, dist2, dist3, &
    3781              :                             pgrid, ri_data%bsizes_AO_split, bsizes_RI_ext_split, &
    3782           54 :                             ri_data%bsizes_AO_split, [1], [2, 3], name="(AO RI | AO)")
    3783           54 :       DEALLOCATE (dist1, dist2, dist3)
    3784              : 
    3785          162 :       ALLOCATE (idx_to_at(SIZE(ri_data%bsizes_AO)))
    3786           54 :       CALL get_idx_to_atom(idx_to_at, ri_data%bsizes_AO, ri_data%bsizes_AO)
    3787           54 :       nspins = SIZE(t_3c_apc, 1)
    3788         1568 :       DO i_img = 1, nimg
    3789         3208 :          DO i_spin = 1, nspins
    3790         1694 :             CALL dbt_create(tmp, t_3c_apc_sub(i_spin, i_img))
    3791         1694 :             CALL get_tensor_occupancy(t_3c_apc(i_spin, i_img), nze, occ)
    3792         1694 :             IF (nze == 0) CYCLE
    3793         1670 :             CALL dbt_copy(t_3c_apc(i_spin, i_img), work_atom_block, move_data=.TRUE.)
    3794              :             CALL copy_3c_to_subgroup(work_atom_block_sub, work_atom_block, &
    3795         1670 :                                      ri_data%iatom_to_subgroup, 1, idx_to_at)
    3796         1670 :             CALL dbt_copy(work_atom_block_sub, t_3c_apc_sub(i_spin, i_img), move_data=.TRUE.)
    3797         4878 :             CALL dbt_filter(t_3c_apc_sub(i_spin, i_img), ri_data%filter_eps)
    3798              :          END DO
    3799         3262 :          DO i_spin = 1, nspins
    3800         3208 :             CALL dbt_destroy(t_3c_apc(i_spin, i_img))
    3801              :          END DO
    3802              :       END DO
    3803           54 :       CALL dbt_destroy(tmp)
    3804           54 :       CALL dbt_destroy(work_atom_block)
    3805           54 :       CALL dbt_destroy(work_atom_block_sub)
    3806           54 :       CALL dbt_pgrid_destroy(pgrid)
    3807              : 
    3808              :       !t_3c_work_3 based on structure of 3c integrals/derivs
    3809           54 :       batch_size = ri_data%kp_stack_size
    3810           54 :       nblks_AO = SIZE(ri_data%bsizes_AO_split)
    3811          162 :       ALLOCATE (bsizes_stack(batch_size*nblks_AO))
    3812          950 :       DO ib = 1, batch_size
    3813         4246 :          bsizes_stack((ib - 1)*nblks_AO + 1:ib*nblks_AO) = ri_data%bsizes_AO_split(:)
    3814              :       END DO
    3815              : 
    3816          324 :       ALLOCATE (dist1(ri_data%ncell_RI*nblks_RI), dist2(nblks_AO), dist3(nblks_AO))
    3817              :       CALL dbt_get_info(ri_data%kp_t_3c_int(1), proc_dist_1=dist1, proc_dist_2=dist2, &
    3818           54 :                         proc_dist_3=dist3, pdims=pdims)
    3819              : 
    3820          108 :       ALLOCATE (dist_stack(batch_size*nblks_AO))
    3821          950 :       DO ib = 1, batch_size
    3822         4246 :          dist_stack((ib - 1)*nblks_AO + 1:ib*nblks_AO) = dist3(:)
    3823              :       END DO
    3824              : 
    3825           54 :       CALL dbt_pgrid_create(para_env_sub, pdims, pgrid)
    3826           54 :       CALL dbt_distribution_new(t_dist, pgrid, dist1, dist2, dist_stack)
    3827              :       CALL dbt_create(t_3c_work_3(1), "work_3_stack", t_dist, [1], [2, 3], &
    3828           54 :                       bsizes_RI_ext_split, ri_data%bsizes_AO_split, bsizes_stack)
    3829           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_work_3(2))
    3830           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_work_3(3))
    3831           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_work_3(4))
    3832           54 :       CALL dbt_distribution_destroy(t_dist)
    3833           54 :       CALL dbt_pgrid_destroy(pgrid)
    3834           54 :       DEALLOCATE (dist1, dist2, dist3, dist_stack)
    3835              : 
    3836              :       !the derivatives are stacked in the same way
    3837           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_der_stack(1))
    3838           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_der_stack(2))
    3839           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_der_stack(3))
    3840           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_der_stack(4))
    3841           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_der_stack(5))
    3842           54 :       CALL dbt_create(t_3c_work_3(1), t_3c_der_stack(6))
    3843              : 
    3844              :       !t_3c_work_2 based on structure of t_3c_apc
    3845          270 :       ALLOCATE (dist1(nblks_AO), dist2(ri_data%ncell_RI*nblks_RI), dist3(nblks_AO))
    3846              :       CALL dbt_get_info(t_3c_apc_sub(1, 1), proc_dist_1=dist1, proc_dist_2=dist2, &
    3847           54 :                         proc_dist_3=dist3, pdims=pdims)
    3848              : 
    3849          108 :       ALLOCATE (dist_stack(batch_size*nblks_AO))
    3850          950 :       DO ib = 1, batch_size
    3851         4246 :          dist_stack((ib - 1)*nblks_AO + 1:ib*nblks_AO) = dist3(:)
    3852              :       END DO
    3853              : 
    3854           54 :       CALL dbt_pgrid_create(para_env_sub, pdims, pgrid)
    3855           54 :       CALL dbt_distribution_new(t_dist, pgrid, dist1, dist2, dist_stack)
    3856              :       CALL dbt_create(t_3c_work_2(1), "work_3_stack", t_dist, [1], [2, 3], &
    3857           54 :                       ri_data%bsizes_AO_split, bsizes_RI_ext_split, bsizes_stack)
    3858           54 :       CALL dbt_create(t_3c_work_2(1), t_3c_work_2(2))
    3859           54 :       CALL dbt_create(t_3c_work_2(1), t_3c_work_2(3))
    3860           54 :       CALL dbt_distribution_destroy(t_dist)
    3861           54 :       CALL dbt_pgrid_destroy(pgrid)
    3862           54 :       DEALLOCATE (dist1, dist2, dist3, dist_stack)
    3863              : 
    3864           54 :       CALL timestop(handle)
    3865              : 
    3866          108 :    END SUBROUTINE get_subgroup_3c_derivs
    3867              : 
    3868              : ! **************************************************************************************************
    3869              : !> \brief A routine that reorders the t_3c_int tensors such that all items which are fully empty
    3870              : !>        are bunched together. This way, we can get much more efficient screening based on NZE
    3871              : !> \param t_3c_ints ...
    3872              : !> \param ri_data ...
    3873              : ! **************************************************************************************************
    3874           96 :    SUBROUTINE reorder_3c_ints(t_3c_ints, ri_data)
    3875              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_3c_ints
    3876              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3877              : 
    3878              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'reorder_3c_ints'
    3879              : 
    3880              :       INTEGER                                            :: handle, i_img, idx, idx_empty, idx_full, &
    3881              :                                                             nimg
    3882              :       INTEGER(int_8)                                     :: nze
    3883              :       REAL(dp)                                           :: occ
    3884           96 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:)          :: t_3c_tmp
    3885              : 
    3886           96 :       CALL timeset(routineN, handle)
    3887              : 
    3888           96 :       nimg = ri_data%nimg
    3889         3690 :       ALLOCATE (t_3c_tmp(nimg))
    3890         2730 :       DO i_img = 1, nimg
    3891         2634 :          CALL dbt_create(t_3c_ints(i_img), t_3c_tmp(i_img))
    3892         2730 :          CALL dbt_copy(t_3c_ints(i_img), t_3c_tmp(i_img), move_data=.TRUE.)
    3893              :       END DO
    3894              : 
    3895              :       !Loop over the images, check if ints have NZE == 0, and put them at the start or end of the
    3896              :       !initial tensor array. Keep the mapping in an array
    3897          288 :       ALLOCATE (ri_data%idx_to_img(nimg))
    3898           96 :       idx_full = 0
    3899           96 :       idx_empty = nimg + 1
    3900              : 
    3901         2730 :       DO i_img = 1, nimg
    3902         2634 :          CALL get_tensor_occupancy(t_3c_tmp(i_img), nze, occ)
    3903         2634 :          IF (nze == 0) THEN
    3904          828 :             idx_empty = idx_empty - 1
    3905          828 :             CALL dbt_copy(t_3c_tmp(i_img), t_3c_ints(idx_empty), move_data=.TRUE.)
    3906          828 :             ri_data%idx_to_img(idx_empty) = i_img
    3907              :          ELSE
    3908         1806 :             idx_full = idx_full + 1
    3909         1806 :             CALL dbt_copy(t_3c_tmp(i_img), t_3c_ints(idx_full), move_data=.TRUE.)
    3910         1806 :             ri_data%idx_to_img(idx_full) = i_img
    3911              :          END IF
    3912         5364 :          CALL dbt_destroy(t_3c_tmp(i_img))
    3913              :       END DO
    3914              : 
    3915              :       !store the highest image index with non-zero integrals
    3916           96 :       ri_data%nimg_nze = idx_full
    3917              : 
    3918          192 :       ALLOCATE (ri_data%img_to_idx(nimg))
    3919         2730 :       DO idx = 1, nimg
    3920         2730 :          ri_data%img_to_idx(ri_data%idx_to_img(idx)) = idx
    3921              :       END DO
    3922              : 
    3923           96 :       CALL timestop(handle)
    3924              : 
    3925         2826 :    END SUBROUTINE reorder_3c_ints
    3926              : 
    3927              : ! **************************************************************************************************
    3928              : !> \brief A routine that reorders the 3c derivatives, the same way that the integrals are, also to
    3929              : !>        increase efficiency of screening
    3930              : !> \param t_3c_derivs ...
    3931              : !> \param ri_data ...
    3932              : ! **************************************************************************************************
    3933          108 :    SUBROUTINE reorder_3c_derivs(t_3c_derivs, ri_data)
    3934              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_3c_derivs
    3935              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3936              : 
    3937              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'reorder_3c_derivs'
    3938              : 
    3939              :       INTEGER                                            :: handle, i_img, i_xyz, idx, nimg
    3940              :       INTEGER(int_8)                                     :: nze
    3941              :       REAL(dp)                                           :: occ
    3942          108 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:)          :: t_3c_tmp
    3943              : 
    3944          108 :       CALL timeset(routineN, handle)
    3945              : 
    3946          108 :       nimg = ri_data%nimg
    3947         4216 :       ALLOCATE (t_3c_tmp(nimg))
    3948         3136 :       DO i_img = 1, nimg
    3949         3136 :          CALL dbt_create(t_3c_derivs(1, 1), t_3c_tmp(i_img))
    3950              :       END DO
    3951              : 
    3952          432 :       DO i_xyz = 1, 3
    3953         9408 :          DO i_img = 1, nimg
    3954         9408 :             CALL dbt_copy(t_3c_derivs(i_img, i_xyz), t_3c_tmp(i_img), move_data=.TRUE.)
    3955              :          END DO
    3956         9516 :          DO i_img = 1, nimg
    3957         9084 :             idx = ri_data%img_to_idx(i_img)
    3958         9084 :             CALL dbt_copy(t_3c_tmp(i_img), t_3c_derivs(idx, i_xyz), move_data=.TRUE.)
    3959         9084 :             CALL get_tensor_occupancy(t_3c_derivs(idx, i_xyz), nze, occ)
    3960         9408 :             IF (nze > 0) ri_data%nimg_nze = MAX(idx, ri_data%nimg_nze)
    3961              :          END DO
    3962              :       END DO
    3963              : 
    3964         3136 :       DO i_img = 1, nimg
    3965         3136 :          CALL dbt_destroy(t_3c_tmp(i_img))
    3966              :       END DO
    3967              : 
    3968          108 :       CALL timestop(handle)
    3969              : 
    3970         3244 :    END SUBROUTINE reorder_3c_derivs
    3971              : 
    3972              : ! **************************************************************************************************
    3973              : !> \brief Get the sparsity pattern related to the non-symmetric AO basis overlap neighbor list
    3974              : !> \param pattern ...
    3975              : !> \param ri_data ...
    3976              : !> \param qs_env ...
    3977              : ! **************************************************************************************************
    3978          562 :    SUBROUTINE get_sparsity_pattern(pattern, ri_data, qs_env)
    3979              :       INTEGER, DIMENSION(:, :, :), INTENT(INOUT)         :: pattern
    3980              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    3981              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3982              : 
    3983              :       INTEGER                                            :: iatom, j_img, jatom, mj_img, natom, nimg
    3984          562 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bins
    3985          562 :       INTEGER, ALLOCATABLE, DIMENSION(:, :, :)           :: tmp_pattern
    3986              :       INTEGER, DIMENSION(3)                              :: cell_j
    3987          562 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    3988          562 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    3989              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3990              :       TYPE(kpoint_type), POINTER                         :: kpoints
    3991              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3992              :       TYPE(neighbor_list_iterator_p_type), &
    3993          562 :          DIMENSION(:), POINTER                           :: nl_iterator
    3994              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3995          562 :          POINTER                                         :: nl_2c
    3996              : 
    3997          562 :       NULLIFY (nl_2c, nl_iterator, kpoints, cell_to_index, dft_control, index_to_cell, para_env)
    3998              : 
    3999          562 :       CALL get_qs_env(qs_env, kpoints=kpoints, dft_control=dft_control, para_env=para_env, natom=natom)
    4000          562 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index, index_to_cell=index_to_cell, sab_nl=nl_2c)
    4001              : 
    4002          562 :       nimg = ri_data%nimg
    4003       127598 :       pattern(:, :, :) = 0
    4004              : 
    4005              :       !We use the symmetric nl for all images that have an opposite cell
    4006          562 :       CALL neighbor_list_iterator_create(nl_iterator, nl_2c)
    4007        38694 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    4008        38132 :          CALL get_iterator_info(nl_iterator, iatom=iatom, jatom=jatom, cell=cell_j)
    4009              : 
    4010        38132 :          j_img = cell_to_index(cell_j(1), cell_j(2), cell_j(3))
    4011        38132 :          IF (j_img > nimg .OR. j_img < 1) CYCLE
    4012              : 
    4013        22901 :          mj_img = get_opp_index(j_img, qs_env)
    4014        22901 :          IF (mj_img > nimg .OR. mj_img < 1) CYCLE
    4015              : 
    4016        22318 :          IF (ri_data%present_images(j_img) == 0) CYCLE
    4017              : 
    4018        38132 :          pattern(iatom, jatom, j_img) = 1
    4019              :       END DO
    4020          562 :       CALL neighbor_list_iterator_release(nl_iterator)
    4021              : 
    4022              :       !If there is no opposite cell present, then we take into account the non-symmetric nl
    4023          562 :       CALL get_kpoint_info(kpoints, sab_nl_nosym=nl_2c)
    4024              : 
    4025          562 :       CALL neighbor_list_iterator_create(nl_iterator, nl_2c)
    4026        50760 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    4027        50198 :          CALL get_iterator_info(nl_iterator, iatom=iatom, jatom=jatom, cell=cell_j)
    4028              : 
    4029        50198 :          j_img = cell_to_index(cell_j(1), cell_j(2), cell_j(3))
    4030        50198 :          IF (j_img > nimg .OR. j_img < 1) CYCLE
    4031              : 
    4032        29693 :          mj_img = get_opp_index(j_img, qs_env)
    4033        29693 :          IF (mj_img <= nimg .AND. mj_img > 0) CYCLE
    4034              : 
    4035          607 :          IF (ri_data%present_images(j_img) == 0) CYCLE
    4036              : 
    4037        50198 :          pattern(iatom, jatom, j_img) = 1
    4038              :       END DO
    4039          562 :       CALL neighbor_list_iterator_release(nl_iterator)
    4040              : 
    4041       254634 :       CALL para_env%sum(pattern)
    4042              : 
    4043              :       !If the opposite image is considered, then there is no need to compute diagonal twice
    4044        18148 :       DO j_img = 2, nimg
    4045        53320 :          DO iatom = 1, natom
    4046        52758 :             IF (pattern(iatom, iatom, j_img) /= 0) THEN
    4047        12552 :                mj_img = get_opp_index(j_img, qs_env)
    4048        12552 :                IF (mj_img > nimg .OR. mj_img < 1) CYCLE
    4049        12552 :                pattern(iatom, iatom, mj_img) = 0
    4050              :             END IF
    4051              :          END DO
    4052              :       END DO
    4053              : 
    4054              :       ! We want to equilibrate the sparsity pattern such that there are same amount of blocks
    4055              :       ! for each atom i of i,j pairs
    4056         1686 :       ALLOCATE (bins(natom))
    4057          562 :       bins(:) = 0
    4058              : 
    4059         2810 :       ALLOCATE (tmp_pattern(natom, natom, nimg))
    4060          562 :       tmp_pattern(:, :, :) = 0
    4061        18710 :       DO j_img = 1, nimg
    4062        55006 :          DO jatom = 1, natom
    4063       127036 :             DO iatom = 1, natom
    4064        72592 :                IF (pattern(iatom, jatom, j_img) == 0) CYCLE
    4065        25278 :                mj_img = get_opp_index(j_img, qs_env)
    4066              : 
    4067              :                !Should we take the i,j,b or th j,i,-b atomic block?
    4068        61574 :                IF (mj_img > nimg .OR. mj_img < 1) THEN
    4069              :                   !No opposite image, no choice
    4070          290 :                   bins(iatom) = bins(iatom) + 1
    4071          290 :                   tmp_pattern(iatom, jatom, j_img) = 1
    4072              :                ELSE
    4073              : 
    4074        24988 :                   IF (bins(iatom) > bins(jatom)) THEN
    4075         5308 :                      bins(jatom) = bins(jatom) + 1
    4076         5308 :                      tmp_pattern(jatom, iatom, mj_img) = 1
    4077              :                   ELSE
    4078        19680 :                      bins(iatom) = bins(iatom) + 1
    4079        19680 :                      tmp_pattern(iatom, jatom, j_img) = 1
    4080              :                   END IF
    4081              :                END IF
    4082              :             END DO
    4083              :          END DO
    4084              :       END DO
    4085              : 
    4086              :       ! -1 => unoccupied, 0 => occupied
    4087       127598 :       pattern(:, :, :) = tmp_pattern(:, :, :) - 1
    4088              : 
    4089         1124 :    END SUBROUTINE get_sparsity_pattern
    4090              : 
    4091              : ! **************************************************************************************************
    4092              : !> \brief Distribute the iatom, jatom, b_img triplet over the subgroupd to spread the load
    4093              : !>        the group id for each triplet is passed as the value of sparsity_pattern(i, j, b),
    4094              : !>        with -1 being an unoccupied block
    4095              : !> \param sparsity_pattern ...
    4096              : !> \param ngroups ...
    4097              : !> \param ri_data ...
    4098              : ! **************************************************************************************************
    4099          562 :    SUBROUTINE get_sub_dist(sparsity_pattern, ngroups, ri_data)
    4100              :       INTEGER, DIMENSION(:, :, :), INTENT(INOUT)         :: sparsity_pattern
    4101              :       INTEGER, INTENT(IN)                                :: ngroups
    4102              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4103              : 
    4104              :       INTEGER                                            :: b_img, ctr, iat, iatom, igroup, jatom, &
    4105              :                                                             natom, nimg, ub
    4106          562 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: max_at_per_group
    4107              :       REAL(dp)                                           :: cost
    4108          562 :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: bins
    4109              : 
    4110          562 :       natom = SIZE(sparsity_pattern, 2)
    4111          562 :       nimg = SIZE(sparsity_pattern, 3)
    4112              : 
    4113              :       !To avoid unnecessary data replication accross the subgroups, we want to have a limited number
    4114              :       !of subgroup with the data of a given iatom. At the minimum, all groups have 1 atom
    4115              :       !We assume that the cost associated to each iatom is roughly the same
    4116          562 :       IF (.NOT. ALLOCATED(ri_data%iatom_to_subgroup)) THEN
    4117          476 :          ALLOCATE (ri_data%iatom_to_subgroup(natom), max_at_per_group(ngroups))
    4118          204 :          DO iatom = 1, natom
    4119          136 :             NULLIFY (ri_data%iatom_to_subgroup(iatom)%array)
    4120          272 :             ALLOCATE (ri_data%iatom_to_subgroup(iatom)%array(ngroups))
    4121          472 :             ri_data%iatom_to_subgroup(iatom)%array(:) = .FALSE.
    4122              :          END DO
    4123              : 
    4124           68 :          ub = natom/ngroups
    4125           68 :          IF (ub*ngroups < natom) ub = ub + 1
    4126          202 :          max_at_per_group(:) = MAX(1, ub)
    4127              : 
    4128              :          !We want each atom to be present the same amount of times. Some groups might have more atoms
    4129              :          !than other to achieve this.
    4130              :          ctr = 0
    4131          202 :          DO WHILE (MODULO(SUM(max_at_per_group), natom) /= 0)
    4132            0 :             igroup = MODULO(ctr, ngroups) + 1
    4133            0 :             max_at_per_group(igroup) = max_at_per_group(igroup) + 1
    4134           68 :             ctr = ctr + 1
    4135              :          END DO
    4136              : 
    4137              :          ctr = 0
    4138          202 :          DO igroup = 1, ngroups
    4139          338 :             DO iat = 1, max_at_per_group(igroup)
    4140          136 :                iatom = MODULO(ctr, natom) + 1
    4141          136 :                ri_data%iatom_to_subgroup(iatom)%array(igroup) = .TRUE.
    4142          270 :                ctr = ctr + 1
    4143              :             END DO
    4144              :          END DO
    4145              :       END IF
    4146              : 
    4147         1686 :       ALLOCATE (bins(ngroups))
    4148          562 :       bins = 0.0_dp
    4149        18710 :       DO b_img = 1, nimg
    4150        55006 :          DO jatom = 1, natom
    4151       127036 :             DO iatom = 1, natom
    4152        72592 :                IF (sparsity_pattern(iatom, jatom, b_img) == -1) CYCLE
    4153       121576 :                igroup = MINLOC(bins, 1, MASK=ri_data%iatom_to_subgroup(iatom)%array) - 1
    4154              : 
    4155              :                !Use cost information from previous SCF if available
    4156       917050 :                IF (ANY(ri_data%kp_cost > EPSILON(0.0_dp))) THEN
    4157        21928 :                   cost = ri_data%kp_cost(iatom, jatom, b_img)
    4158              :                ELSE
    4159         3350 :                   cost = REAL(ri_data%bsizes_AO(iatom)*ri_data%bsizes_AO(jatom), dp)
    4160              :                END IF
    4161        25278 :                bins(igroup + 1) = bins(igroup + 1) + cost
    4162       108888 :                sparsity_pattern(iatom, jatom, b_img) = igroup
    4163              :             END DO
    4164              :          END DO
    4165              :       END DO
    4166              : 
    4167          562 :    END SUBROUTINE get_sub_dist
    4168              : 
    4169              : ! **************************************************************************************************
    4170              : !> \brief A rouine that updates the sparsity pattern for force calculation, where all i,j,b combinations
    4171              : !>        are visited.
    4172              : !> \param force_pattern ...
    4173              : !> \param scf_pattern ...
    4174              : !> \param ngroups ...
    4175              : !> \param ri_data ...
    4176              : !> \param qs_env ...
    4177              : ! **************************************************************************************************
    4178           54 :    SUBROUTINE update_pattern_to_forces(force_pattern, scf_pattern, ngroups, ri_data, qs_env)
    4179              :       INTEGER, DIMENSION(:, :, :), INTENT(INOUT)         :: force_pattern, scf_pattern
    4180              :       INTEGER, INTENT(IN)                                :: ngroups
    4181              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4182              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4183              : 
    4184              :       INTEGER                                            :: b_img, iatom, igroup, jatom, mb_img, &
    4185              :                                                             natom, nimg
    4186           54 :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: bins
    4187              : 
    4188           54 :       natom = SIZE(scf_pattern, 2)
    4189           54 :       nimg = SIZE(scf_pattern, 3)
    4190              : 
    4191          162 :       ALLOCATE (bins(ngroups))
    4192           54 :       bins = 0.0_dp
    4193              : 
    4194         1568 :       DO b_img = 1, nimg
    4195         1514 :          mb_img = get_opp_index(b_img, qs_env)
    4196         4596 :          DO jatom = 1, natom
    4197        10598 :             DO iatom = 1, natom
    4198              :                !Important: same distribution as KS matrix, because reuse t_3c_apc
    4199        30280 :                igroup = MINLOC(bins, 1, MASK=ri_data%iatom_to_subgroup(iatom)%array) - 1
    4200              : 
    4201              :                !check that block not already treated
    4202         6056 :                IF (scf_pattern(iatom, jatom, b_img) > -1) CYCLE
    4203              : 
    4204              :                !If not, take the cost of block j, i, -b (same energy contribution)
    4205         7396 :                IF (mb_img > 0 .AND. mb_img <= nimg) THEN
    4206         3862 :                   IF (scf_pattern(jatom, iatom, mb_img) == -1) CYCLE
    4207         1542 :                   bins(igroup + 1) = bins(igroup + 1) + ri_data%kp_cost(jatom, iatom, mb_img)
    4208         1542 :                   force_pattern(iatom, jatom, b_img) = igroup
    4209              :                END IF
    4210              :             END DO
    4211              :          END DO
    4212              :       END DO
    4213              : 
    4214           54 :    END SUBROUTINE update_pattern_to_forces
    4215              : 
    4216              : ! **************************************************************************************************
    4217              : !> \brief A routine that determines the extend of the KP RI-HFX periodic images, including for the
    4218              : !>        extension of the RI basis
    4219              : !> \param ri_data ...
    4220              : !> \param qs_env ...
    4221              : ! **************************************************************************************************
    4222           96 :    SUBROUTINE get_kp_and_ri_images(ri_data, qs_env)
    4223              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4224              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4225              : 
    4226              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_kp_and_ri_images'
    4227              : 
    4228              :       CHARACTER(LEN=512)                                 :: warning_msg
    4229              :       INTEGER :: cell_j(3), cell_k(3), handle, i_img, iatom, ikind, j_img, jatom, jcell, katom, &
    4230              :          kcell, kp_index_lbounds(3), kp_index_ubounds(3), natom, ngroups, nimg, nkind, pcoord(3), &
    4231              :          pdims(3)
    4232           96 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist_AO_1, dist_AO_2, dist_RI, &
    4233           96 :                                                             nRI_per_atom, present_img, RI_cells
    4234           96 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    4235              :       REAL(dp)                                           :: bump_fact, dij, dik, image_range, &
    4236              :                                                             RI_range, rij(3), rik(3)
    4237          672 :       TYPE(dbt_type)                                     :: t_dummy
    4238              :       TYPE(dft_control_type), POINTER                    :: dft_control
    4239              :       TYPE(distribution_2d_type), POINTER                :: dist_2d
    4240              :       TYPE(distribution_3d_type)                         :: dist_3d
    4241              :       TYPE(gto_basis_set_p_type), ALLOCATABLE, &
    4242           96 :          DIMENSION(:), TARGET                            :: basis_set_AO, basis_set_RI
    4243              :       TYPE(kpoint_type), POINTER                         :: kpoints
    4244           96 :       TYPE(mp_cart_type)                                 :: mp_comm_t3c
    4245              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    4246              :       TYPE(neighbor_list_3c_iterator_type)               :: nl_3c_iter
    4247              :       TYPE(neighbor_list_3c_type)                        :: nl_3c
    4248              :       TYPE(neighbor_list_iterator_p_type), &
    4249           96 :          DIMENSION(:), POINTER                           :: nl_iterator
    4250              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    4251           96 :          POINTER                                         :: nl_2c
    4252           96 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    4253           96 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    4254              :       TYPE(section_vals_type), POINTER                   :: hfx_section
    4255              : 
    4256           96 :       NULLIFY (qs_kind_set, dist_2d, nl_2c, nl_iterator, dft_control, &
    4257           96 :                particle_set, kpoints, para_env, cell_to_index, hfx_section)
    4258              : 
    4259           96 :       CALL timeset(routineN, handle)
    4260              : 
    4261              :       CALL get_qs_env(qs_env, nkind=nkind, qs_kind_set=qs_kind_set, distribution_2d=dist_2d, &
    4262              :                       dft_control=dft_control, particle_set=particle_set, kpoints=kpoints, &
    4263           96 :                       para_env=para_env, natom=natom)
    4264           96 :       nimg = dft_control%nimages
    4265           96 :       CALL get_kpoint_info(kpoints, cell_to_index=cell_to_index)
    4266          384 :       kp_index_lbounds = LBOUND(cell_to_index)
    4267          384 :       kp_index_ubounds = UBOUND(cell_to_index)
    4268              : 
    4269           96 :       hfx_section => section_vals_get_subs_vals(qs_env%input, "DFT%XC%HF%RI")
    4270           96 :       CALL section_vals_val_get(hfx_section, "KP_NGROUPS", i_val=ngroups)
    4271              : 
    4272          672 :       ALLOCATE (basis_set_RI(nkind), basis_set_AO(nkind))
    4273           96 :       CALL basis_set_list_setup(basis_set_RI, ri_data%ri_basis_type, qs_kind_set)
    4274           96 :       CALL basis_set_list_setup(basis_set_AO, ri_data%orb_basis_type, qs_kind_set)
    4275              : 
    4276           96 :       IF (ri_data%hfx_pot%potential_type == do_potential_short) THEN
    4277              :          ! Use the same default screening range as the rest of the k-point code.
    4278            0 :          IF (.NOT. ri_data%explicit_hfx_cutoff) THEN
    4279            0 :             CALL erfc_cutoff(ri_data%eps_schwarz, ri_data%hfx_pot%omega, ri_data%hfx_pot%cutoff_radius)
    4280              :          END IF
    4281              :          WRITE (warning_msg, '(A)') &
    4282              :             "The SHORTRANGE HFX potential typically extends over many periodic images, "// &
    4283              :             "possibly slowing down the calculation. Consider using the TRUNCATED "// &
    4284            0 :             "potential for better computational performance."
    4285            0 :          CPWARN(warning_msg)
    4286              :       END IF
    4287              : 
    4288              :       !Determine the range for contributing periodic images, and for the RI basis extension
    4289           96 :       ri_data%kp_RI_range = 0.0_dp
    4290           96 :       ri_data%kp_image_range = 0.0_dp
    4291          240 :       DO ikind = 1, nkind
    4292              : 
    4293          144 :          CALL init_interaction_radii_orb_basis(basis_set_AO(ikind)%gto_basis_set, ri_data%eps_pgf_orb)
    4294          144 :          CALL get_gto_basis_set(basis_set_AO(ikind)%gto_basis_set, kind_radius=RI_range)
    4295          144 :          ri_data%kp_RI_range = MAX(RI_range, ri_data%kp_RI_range)
    4296              : 
    4297          144 :          CALL init_interaction_radii_orb_basis(basis_set_AO(ikind)%gto_basis_set, ri_data%eps_pgf_orb)
    4298          144 :          CALL init_interaction_radii_orb_basis(basis_set_RI(ikind)%gto_basis_set, ri_data%eps_pgf_orb)
    4299          144 :          CALL get_gto_basis_set(basis_set_RI(ikind)%gto_basis_set, kind_radius=image_range)
    4300              : 
    4301          144 :          image_range = 2.0_dp*image_range + cutoff_screen_factor*ri_data%hfx_pot%cutoff_radius
    4302          384 :          ri_data%kp_image_range = MAX(image_range, ri_data%kp_image_range)
    4303              :       END DO
    4304              : 
    4305           96 :       CALL section_vals_val_get(hfx_section, "KP_RI_BUMP_FACTOR", r_val=bump_fact)
    4306           96 :       ri_data%kp_bump_rad = bump_fact*ri_data%kp_RI_range
    4307              : 
    4308              :       !For the extent of the KP RI-HFX images, we are limited by the RI-HFX potential in
    4309              :       !(mu^0 sigma^a|P^0) (P^0|Q^b) (Q^b|nu^b lambda^a+c), if there is no contact between
    4310              :       !any P^0 and Q^b, then image b does not contribute
    4311              :       CALL build_2c_neighbor_lists(nl_2c, basis_set_RI, basis_set_RI, ri_data%hfx_pot, &
    4312           96 :                                    "HFX_2c_nl_RI", qs_env, sym_ij=.FALSE., dist_2d=dist_2d)
    4313              : 
    4314          288 :       ALLOCATE (present_img(nimg))
    4315           96 :       present_img = 0
    4316           96 :       ri_data%nimg = 0
    4317           96 :       CALL neighbor_list_iterator_create(nl_iterator, nl_2c)
    4318         2412 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    4319         2316 :          CALL get_iterator_info(nl_iterator, r=rij, cell=cell_j)
    4320              : 
    4321         9264 :          dij = NORM2(rij)
    4322              : 
    4323         2316 :          j_img = cell_to_index(cell_j(1), cell_j(2), cell_j(3))
    4324         2316 :          IF (j_img > nimg .OR. j_img < 1) CYCLE
    4325              : 
    4326         2277 :          IF (dij > ri_data%kp_image_range) CYCLE
    4327              : 
    4328         2277 :          ri_data%nimg = MAX(j_img, ri_data%nimg)
    4329         2316 :          present_img(j_img) = 1
    4330              : 
    4331              :       END DO
    4332           96 :       CALL neighbor_list_iterator_release(nl_iterator)
    4333           96 :       CALL release_neighbor_list_sets(nl_2c)
    4334           96 :       CALL para_env%max(ri_data%nimg)
    4335           96 :       IF (ri_data%nimg > nimg) THEN
    4336            0 :          CPABORT("Make sure the smallest exponent of the RI-HFX basis is larger than that of the ORB basis.")
    4337              :       END IF
    4338              : 
    4339              :       !Keep track of which images will not contribute, so that can be ignored before calculation
    4340           96 :       CALL para_env%sum(present_img)
    4341          288 :       ALLOCATE (ri_data%present_images(ri_data%nimg))
    4342         2730 :       ri_data%present_images = 0
    4343         2730 :       DO i_img = 1, ri_data%nimg
    4344         2730 :          IF (present_img(i_img) > 0) ri_data%present_images(i_img) = 1
    4345              :       END DO
    4346              : 
    4347              :       CALL create_3c_tensor(t_dummy, dist_AO_1, dist_AO_2, dist_RI, &
    4348              :                             ri_data%pgrid, ri_data%bsizes_AO, ri_data%bsizes_AO, ri_data%bsizes_RI, &
    4349           96 :                             map1=[1, 2], map2=[3], name="(AO AO | RI)")
    4350              : 
    4351           96 :       CALL dbt_mp_environ_pgrid(ri_data%pgrid, pdims, pcoord)
    4352           96 :       CALL mp_comm_t3c%create(ri_data%pgrid%mp_comm_2d, 3, pdims)
    4353              :       CALL distribution_3d_create(dist_3d, dist_AO_1, dist_AO_2, dist_RI, &
    4354           96 :                                   nkind, particle_set, mp_comm_t3c, own_comm=.TRUE.)
    4355           96 :       DEALLOCATE (dist_RI, dist_AO_1, dist_AO_2)
    4356           96 :       CALL dbt_destroy(t_dummy)
    4357              : 
    4358              :       !For the extension of the RI basis P in (mu^0 sigma^a |P^i), we consider an atom if the distance,
    4359              :       !between mu^0 and P^i if smaller or equal to the kind radius of mu^0
    4360              :       CALL build_3c_neighbor_lists(nl_3c, basis_set_AO, basis_set_AO, basis_set_RI, dist_3d, &
    4361              :                                    ri_data%ri_metric, "HFX_3c_nl", qs_env, op_pos=2, sym_ij=.FALSE., &
    4362           96 :                                    own_dist=.TRUE.)
    4363              : 
    4364          192 :       ALLOCATE (RI_cells(nimg))
    4365           96 :       RI_cells = 0
    4366              : 
    4367          288 :       ALLOCATE (nRI_per_atom(natom))
    4368           96 :       nRI_per_atom = 0
    4369              : 
    4370           96 :       CALL neighbor_list_3c_iterator_create(nl_3c_iter, nl_3c)
    4371       112830 :       DO WHILE (neighbor_list_3c_iterate(nl_3c_iter) == 0)
    4372              :          CALL get_3c_iterator_info(nl_3c_iter, cell_k=cell_k, rik=rik, cell_j=cell_j, &
    4373       112734 :                                    iatom=iatom, jatom=jatom, katom=katom)
    4374       450936 :          dik = NORM2(rik)
    4375              : 
    4376       789138 :          IF (ANY([cell_j(1), cell_j(2), cell_j(3)] < kp_index_lbounds) .OR. &
    4377              :              ANY([cell_j(1), cell_j(2), cell_j(3)] > kp_index_ubounds)) CYCLE
    4378              : 
    4379       112734 :          jcell = cell_to_index(cell_j(1), cell_j(2), cell_j(3))
    4380       112734 :          IF (jcell > nimg .OR. jcell < 1) CYCLE
    4381              : 
    4382       748457 :          IF (ANY([cell_k(1), cell_k(2), cell_k(3)] < kp_index_lbounds) .OR. &
    4383              :              ANY([cell_k(1), cell_k(2), cell_k(3)] > kp_index_ubounds)) CYCLE
    4384              : 
    4385       100328 :          kcell = cell_to_index(cell_k(1), cell_k(2), cell_k(3))
    4386       100328 :          IF (kcell > nimg .OR. kcell < 1) CYCLE
    4387              : 
    4388        82177 :          IF (dik > ri_data%kp_RI_range) CYCLE
    4389        10845 :          RI_cells(kcell) = 1
    4390              : 
    4391        10941 :          IF (jcell == 1 .AND. iatom == jatom) nRI_per_atom(iatom) = nRI_per_atom(iatom) + ri_data%bsizes_RI(katom)
    4392              :       END DO
    4393           96 :       CALL neighbor_list_3c_iterator_destroy(nl_3c_iter)
    4394           96 :       CALL neighbor_list_3c_destroy(nl_3c)
    4395           96 :       CALL para_env%sum(RI_cells)
    4396           96 :       CALL para_env%sum(nRI_per_atom)
    4397              : 
    4398          192 :       ALLOCATE (ri_data%img_to_RI_cell(nimg))
    4399           96 :       ri_data%ncell_RI = 0
    4400         5274 :       ri_data%img_to_RI_cell = 0
    4401         5274 :       DO i_img = 1, nimg
    4402         5274 :          IF (RI_cells(i_img) > 0) THEN
    4403          634 :             ri_data%ncell_RI = ri_data%ncell_RI + 1
    4404          634 :             ri_data%img_to_RI_cell(i_img) = ri_data%ncell_RI
    4405              :          END IF
    4406              :       END DO
    4407              : 
    4408          288 :       ALLOCATE (ri_data%RI_cell_to_img(ri_data%ncell_RI))
    4409         5274 :       DO i_img = 1, nimg
    4410         5274 :          IF (ri_data%img_to_RI_cell(i_img) > 0) ri_data%RI_cell_to_img(ri_data%img_to_RI_cell(i_img)) = i_img
    4411              :       END DO
    4412              : 
    4413              :       !Print some info
    4414           96 :       IF (ri_data%unit_nr > 0) THEN
    4415              :          WRITE (ri_data%unit_nr, FMT="(/T3,A,I29)") &
    4416           45 :             "KP-HFX_RI_INFO| Number of RI-KP parallel groups:", ngroups
    4417              :          WRITE (ri_data%unit_nr, FMT="(T3,A,I29)") &
    4418           45 :             "KP-HFX_RI_INFO| Tensor stack size:              ", ri_data%kp_stack_size
    4419              :          WRITE (ri_data%unit_nr, FMT="(T3,A,F31.3,A)") &
    4420           45 :             "KP-HFX_RI_INFO| RI basis extension radius:", ri_data%kp_RI_range*angstrom, " Ang"
    4421              :          WRITE (ri_data%unit_nr, FMT="(T3,A,F12.3,A, F6.3, A)") &
    4422           45 :             "KP-HFX_RI_INFO| RI basis bump factor and bump radius:", bump_fact, " /", &
    4423           90 :             ri_data%kp_bump_rad*angstrom, " Ang"
    4424              :          WRITE (ri_data%unit_nr, FMT="(T3,A,I16,A)") &
    4425           45 :             "KP-HFX_RI_INFO| The extended RI bases cover up to ", ri_data%ncell_RI, " unit cells"
    4426              :          WRITE (ri_data%unit_nr, FMT="(T3,A,I18)") &
    4427          135 :             "KP-HFX_RI_INFO| Average number of sgf in extended RI bases:", SUM(nRI_per_atom)/natom
    4428              :          WRITE (ri_data%unit_nr, FMT="(T3,A,F13.3,A)") &
    4429           45 :             "KP-HFX_RI_INFO| Consider all image cells within a radius of ", ri_data%kp_image_range*angstrom, " Ang"
    4430              :          WRITE (ri_data%unit_nr, FMT="(T3,A,I27/)") &
    4431           45 :             "KP-HFX_RI_INFO| Number of image cells considered: ", ri_data%nimg
    4432           45 :          CALL m_flush(ri_data%unit_nr)
    4433              :       END IF
    4434              : 
    4435           96 :       CALL timestop(handle)
    4436              : 
    4437         1152 :    END SUBROUTINE get_kp_and_ri_images
    4438              : 
    4439              : ! **************************************************************************************************
    4440              : !> \brief A routine that creates tensors structure for rho_ao and 3c_ints in a stacked format for
    4441              : !>        the efficient contractions of rho_sigma^0,lambda^c * (mu^0 sigam^a | P) => TAS tensors
    4442              : !> \param res_stack ...
    4443              : !> \param rho_stack ...
    4444              : !> \param ints_stack ...
    4445              : !> \param rho_template ...
    4446              : !> \param ints_template ...
    4447              : !> \param stack_size ...
    4448              : !> \param ri_data ...
    4449              : !> \param qs_env ...
    4450              : !> \note The result tensor has the exact same shape and distribution as the integral tensor
    4451              : ! **************************************************************************************************
    4452          562 :    SUBROUTINE get_stack_tensors(res_stack, rho_stack, ints_stack, rho_template, ints_template, &
    4453              :                                 stack_size, ri_data, qs_env)
    4454              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: res_stack, rho_stack, ints_stack
    4455              :       TYPE(dbt_type), INTENT(INOUT)                      :: rho_template, ints_template
    4456              :       INTEGER, INTENT(IN)                                :: stack_size
    4457              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4458              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4459              : 
    4460              :       INTEGER                                            :: is, nblks, nblks_3c(3), pdims_3d(3)
    4461          562 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bsizes_RI_ext, bsizes_stack, dist1, &
    4462          562 :                                                             dist2, dist3, dist_stack1, &
    4463          562 :                                                             dist_stack2, dist_stack3
    4464         5058 :       TYPE(dbt_distribution_type)                        :: t_dist
    4465         1686 :       TYPE(dbt_pgrid_type)                               :: pgrid
    4466              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    4467              : 
    4468          562 :       NULLIFY (para_env)
    4469              : 
    4470          562 :       CALL get_qs_env(qs_env, para_env=para_env)
    4471              : 
    4472          562 :       nblks = SIZE(ri_data%bsizes_AO_split)
    4473         1686 :       ALLOCATE (bsizes_stack(stack_size*nblks))
    4474        10514 :       DO is = 1, stack_size
    4475        38610 :          bsizes_stack((is - 1)*nblks + 1:is*nblks) = ri_data%bsizes_AO_split(:)
    4476              :       END DO
    4477              : 
    4478         3372 :       ALLOCATE (dist1(nblks), dist2(nblks), dist_stack1(stack_size*nblks), dist_stack2(stack_size*nblks))
    4479          562 :       CALL dbt_get_info(rho_template, proc_dist_1=dist1, proc_dist_2=dist2)
    4480        10514 :       DO is = 1, stack_size
    4481        38048 :          dist_stack1((is - 1)*nblks + 1:is*nblks) = dist1(:)
    4482        38610 :          dist_stack2((is - 1)*nblks + 1:is*nblks) = dist2(:)
    4483              :       END DO
    4484              : 
    4485              :       !First 2c tensor matches the distribution of template
    4486              :       !It is stacked in both directions
    4487          562 :       CALL dbt_distribution_new(t_dist, ri_data%pgrid_2d, dist_stack1, dist_stack2)
    4488          562 :       CALL dbt_create(rho_stack(1), "RHO_stack", t_dist, [1], [2], bsizes_stack, bsizes_stack)
    4489          562 :       CALL dbt_distribution_destroy(t_dist)
    4490          562 :       DEALLOCATE (dist1, dist2, dist_stack1, dist_stack2)
    4491              : 
    4492              :       !Second 2c tensor has optimal distribution on the 2d pgrid
    4493          562 :       CALL create_2c_tensor(rho_stack(2), dist1, dist2, ri_data%pgrid_2d, bsizes_stack, bsizes_stack, name="RHO_stack")
    4494          562 :       DEALLOCATE (dist1, dist2)
    4495              : 
    4496          562 :       CALL dbt_get_info(ints_template, nblks_total=nblks_3c)
    4497         3934 :       ALLOCATE (dist1(nblks_3c(1)), dist2(nblks_3c(2)), dist3(nblks_3c(3)))
    4498         2248 :       ALLOCATE (dist_stack3(stack_size*nblks_3c(3)), bsizes_RI_ext(nblks_3c(2)))
    4499              :       CALL dbt_get_info(ints_template, proc_dist_1=dist1, proc_dist_2=dist2, &
    4500          562 :                         proc_dist_3=dist3, blk_size_2=bsizes_RI_ext)
    4501        10514 :       DO is = 1, stack_size
    4502        38610 :          dist_stack3((is - 1)*nblks_3c(3) + 1:is*nblks_3c(3)) = dist3(:)
    4503              :       END DO
    4504              : 
    4505              :       !First 3c tensor matches the distribution of template
    4506          562 :       CALL dbt_distribution_new(t_dist, ri_data%pgrid_1, dist1, dist2, dist_stack3)
    4507              :       CALL dbt_create(ints_stack(1), "ints_stack", t_dist, [1, 2], [3], ri_data%bsizes_AO_split, &
    4508          562 :                       bsizes_RI_ext, bsizes_stack)
    4509          562 :       CALL dbt_distribution_destroy(t_dist)
    4510          562 :       DEALLOCATE (dist1, dist2, dist3, dist_stack3)
    4511              : 
    4512              :       !Second 3c tensor has optimal pgrid
    4513          562 :       pdims_3d = 0
    4514         2248 :       CALL dbt_pgrid_create(para_env, pdims_3d, pgrid, tensor_dims=[nblks_3c(1), nblks_3c(2), stack_size*nblks_3c(3)])
    4515              :       CALL create_3c_tensor(ints_stack(2), dist1, dist2, dist3, pgrid, ri_data%bsizes_AO_split, &
    4516          562 :                             bsizes_RI_ext, bsizes_stack, [1, 2], [3], name="ints_stack")
    4517          562 :       DEALLOCATE (dist1, dist2, dist3)
    4518          562 :       CALL dbt_pgrid_destroy(pgrid)
    4519              : 
    4520              :       !The result tensor has the same shape and dist as the integral tensor
    4521          562 :       CALL dbt_create(ints_stack(1), res_stack(1))
    4522          562 :       CALL dbt_create(ints_stack(2), res_stack(2))
    4523              : 
    4524          562 :    END SUBROUTINE get_stack_tensors
    4525              : 
    4526              : ! **************************************************************************************************
    4527              : !> \brief Fill the stack of 3c tensors accrding to the order in the images input
    4528              : !> \param t_3c_stack ...
    4529              : !> \param t_3c_in ...
    4530              : !> \param images ...
    4531              : !> \param stack_dim ...
    4532              : !> \param ri_data ...
    4533              : !> \param filter_at ...
    4534              : !> \param filter_dim ...
    4535              : !> \param idx_to_at ...
    4536              : !> \param img_bounds ...
    4537              : ! **************************************************************************************************
    4538        55310 :    SUBROUTINE fill_3c_stack(t_3c_stack, t_3c_in, images, stack_dim, ri_data, filter_at, filter_dim, &
    4539        55310 :                             idx_to_at, img_bounds)
    4540              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_3c_stack
    4541              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_3c_in
    4542              :       INTEGER, DIMENSION(:), INTENT(INOUT)               :: images
    4543              :       INTEGER, INTENT(IN)                                :: stack_dim
    4544              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4545              :       INTEGER, INTENT(IN), OPTIONAL                      :: filter_at, filter_dim
    4546              :       INTEGER, DIMENSION(:), INTENT(INOUT), OPTIONAL     :: idx_to_at
    4547              :       INTEGER, INTENT(IN), OPTIONAL                      :: img_bounds(2)
    4548              : 
    4549              :       INTEGER                                            :: dest(3), i_img, idx, ind(3), lb, nblks, &
    4550              :                                                             nimg, offset, ub
    4551              :       LOGICAL                                            :: do_filter
    4552              :       TYPE(dbt_iterator_type)                            :: iter
    4553              : 
    4554              :       ! Source and stack have matching block layouts and MPI owners by construction.
    4555        55310 :       nimg = ri_data%nimg
    4556        55310 :       nblks = SIZE(ri_data%bsizes_AO_split)
    4557              : 
    4558        55310 :       do_filter = .FALSE.
    4559        54228 :       IF (PRESENT(filter_at) .AND. PRESENT(filter_dim) .AND. PRESENT(idx_to_at)) do_filter = .TRUE.
    4560              : 
    4561        55310 :       lb = 1
    4562        55310 :       ub = nimg
    4563        55310 :       offset = 0
    4564        55310 :       IF (PRESENT(img_bounds)) THEN
    4565        55310 :          lb = img_bounds(1)
    4566        55310 :          ub = img_bounds(2) - 1
    4567        55310 :          offset = lb - 1
    4568              :       END IF
    4569              : 
    4570              :       ! Each image fills a distinct stack slice, so the team can span the whole batch.
    4571              : !$OMP PARALLEL DEFAULT(NONE) &
    4572              : !$OMP SHARED(images,t_3c_in,t_3c_stack,nblks,nimg,lb,ub,stack_dim,filter_at,filter_dim,idx_to_at,do_filter,offset) &
    4573        55310 : !$OMP PRIVATE(iter,ind,dest,i_img,idx)
    4574              :       DO idx = lb, ub
    4575              :          i_img = images(idx)
    4576              :          IF (i_img == 0 .OR. i_img > nimg) CYCLE
    4577              :          CALL dbt_iterator_start(iter, t_3c_in(i_img))
    4578              :          DO WHILE (dbt_iterator_blocks_left(iter))
    4579              :             CALL dbt_iterator_next_block(iter, ind)
    4580              :             IF (do_filter) THEN
    4581              :                IF (.NOT. idx_to_at(ind(filter_dim)) == filter_at) CYCLE
    4582              :             END IF
    4583              :             dest(:) = ind(:)
    4584              :             dest(stack_dim) = ind(stack_dim) + (idx - offset - 1)*nblks
    4585              :             CALL dbt_copy_block(t_3c_in(i_img), t_3c_stack, ind, ind_out=dest)
    4586              :          END DO
    4587              :          CALL dbt_iterator_stop(iter)
    4588              :       END DO
    4589              : !$OMP END PARALLEL
    4590        55310 :       CALL dbt_finalize(t_3c_stack)
    4591              : 
    4592        55310 :    END SUBROUTINE fill_3c_stack
    4593              : 
    4594              : ! **************************************************************************************************
    4595              : !> \brief Fill a density-matrix stack, with images indexing both stack dimensions
    4596              : !> \param t_2c_stack ...
    4597              : !> \param t_2c_in ...
    4598              : !> \param images ...
    4599              : !> \param ri_data ...
    4600              : ! **************************************************************************************************
    4601         2900 :    SUBROUTINE fill_2c_stack(t_2c_stack, t_2c_in, images, ri_data)
    4602              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_2c_stack
    4603              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_2c_in
    4604              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: images
    4605              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4606              : 
    4607              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'fill_2c_stack'
    4608              : 
    4609              :       INTEGER                                            :: dest(2), handle, i_img, icol, ind(2), &
    4610              :                                                             irow, nblks, nimg
    4611              :       TYPE(dbt_iterator_type)                            :: iter
    4612              : 
    4613         2900 :       CALL timeset(routineN, handle)
    4614              : 
    4615              :       ! Source and stack have matching block layouts and MPI owners by construction.
    4616         2900 :       nimg = ri_data%nimg
    4617         2900 :       nblks = SIZE(ri_data%bsizes_AO_split)
    4618              : 
    4619              :       ! Each image pair fills a distinct slice; keep one team for the whole batch.
    4620              : !$OMP PARALLEL DEFAULT(NONE) SHARED(images,t_2c_in,t_2c_stack,nblks,nimg) &
    4621         2900 : !$OMP PRIVATE(iter,ind,dest,i_img,irow,icol)
    4622              :       DO icol = 1, SIZE(images, 2)
    4623              :          DO irow = 1, SIZE(images, 1)
    4624              :             i_img = images(irow, icol)
    4625              :             IF (i_img < 1 .OR. i_img > nimg) CYCLE
    4626              :             CALL dbt_iterator_start(iter, t_2c_in(i_img))
    4627              :             DO WHILE (dbt_iterator_blocks_left(iter))
    4628              :                CALL dbt_iterator_next_block(iter, ind)
    4629              :                dest(:) = [(irow - 1)*nblks + ind(1), (icol - 1)*nblks + ind(2)]
    4630              :                CALL dbt_copy_block(t_2c_in(i_img), t_2c_stack, ind, ind_out=dest)
    4631              :             END DO
    4632              :             CALL dbt_iterator_stop(iter)
    4633              :          END DO
    4634              :       END DO
    4635              : !$OMP END PARALLEL
    4636         2900 :       CALL dbt_finalize(t_2c_stack)
    4637         2900 :       CALL timestop(handle)
    4638              : 
    4639         2900 :    END SUBROUTINE fill_2c_stack
    4640              : 
    4641              : ! **************************************************************************************************
    4642              : !> \brief Accumulate a result stack into its image tensors in a single traversal
    4643              : !> \param t_3c_apc Destination images in stack order, with matching blocks and MPI owners
    4644              : !> \param t_stacked Result tensor stacked along the third dimension
    4645              : !> \param img_filter Zero entries skip the corresponding destination image
    4646              : ! **************************************************************************************************
    4647         2836 :    SUBROUTINE accumulate_3c_stack(t_3c_apc, t_stacked, img_filter)
    4648              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_3c_apc
    4649              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_stacked
    4650              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: img_filter
    4651              : 
    4652              :       CHARACTER(len=*), PARAMETER :: routineN = 'accumulate_3c_stack'
    4653              : 
    4654              :       INTEGER                                            :: handle, idx, ndata
    4655              :       INTEGER, DIMENSION(3)                              :: dest, ind, nblks_3c, sizes
    4656              :       LOGICAL                                            :: found
    4657         2836 :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: blk
    4658              :       TYPE(dbt_iterator_type)                            :: iter
    4659              : 
    4660         2836 :       CALL timeset(routineN, handle)
    4661         2836 :       CALL dbt_get_info(t_3c_apc(1), nblks_total=nblks_3c)
    4662              : 
    4663              :       ! get_stack_tensors repeats the image distribution. Buffer reuse also supports
    4664              :       ! the different matrix layouts of res_stack(1) and t_3c_apc.
    4665              : !$OMP PARALLEL DEFAULT(NONE) SHARED(t_3c_apc,t_stacked,img_filter,nblks_3c) &
    4666         2836 : !$OMP PRIVATE(iter,ind,dest,sizes,blk,found,idx,ndata)
    4667              :       ALLOCATE (blk(0))
    4668              :       CALL dbt_iterator_start(iter, t_stacked)
    4669              :       DO WHILE (dbt_iterator_blocks_left(iter))
    4670              :          CALL dbt_iterator_next_block(iter, ind, blk_size=sizes)
    4671              :          idx = (ind(3) - 1)/nblks_3c(3) + 1
    4672              :          IF (idx > SIZE(t_3c_apc)) CYCLE
    4673              :          IF (img_filter(idx) == 0) CYCLE
    4674              :          ndata = PRODUCT(sizes)
    4675              :          IF (SIZE(blk) < ndata) THEN
    4676              :             DEALLOCATE (blk)
    4677              :             ALLOCATE (blk(ndata))
    4678              :          END IF
    4679              :          CALL dbt_get_block_data(t_stacked, ind, sizes, blk(:ndata), found)
    4680              :          IF (.NOT. found) CYCLE
    4681              :          dest(:) = [ind(1), ind(2), ind(3) - (idx - 1)*nblks_3c(3)]
    4682              :          CALL dbt_put_block_data(t_3c_apc(idx), dest, sizes, blk(:ndata), summation=.TRUE.)
    4683              :       END DO
    4684              :       CALL dbt_iterator_stop(iter)
    4685              :       DEALLOCATE (blk)
    4686              : !$OMP END PARALLEL
    4687        41658 :       DO idx = 1, SIZE(t_3c_apc)
    4688        41658 :          IF (img_filter(idx) /= 0) CALL dbt_finalize(t_3c_apc(idx))
    4689              :       END DO
    4690         2836 :       CALL timestop(handle)
    4691              : 
    4692         5672 :    END SUBROUTINE accumulate_3c_stack
    4693              : 
    4694              : ! **************************************************************************************************
    4695              : !> \brief Unstacks a stacked 3c tensor containing t_3c_apc
    4696              : !> \param t_3c_apc ...
    4697              : !> \param t_stacked ...
    4698              : !> \param idx ...
    4699              : ! **************************************************************************************************
    4700         7074 :    SUBROUTINE unstack_t_3c_apc(t_3c_apc, t_stacked, idx)
    4701              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_3c_apc, t_stacked
    4702              :       INTEGER, INTENT(IN)                                :: idx
    4703              : 
    4704              :       INTEGER                                            :: current_idx
    4705              :       INTEGER, DIMENSION(3)                              :: ind, nblks_3c
    4706              :       LOGICAL                                            :: found
    4707         7074 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :, :)          :: blk
    4708              :       TYPE(dbt_iterator_type)                            :: iter
    4709              : 
    4710              :       !Note: t_3c_apc and t_stacked must have the same ditribution
    4711         7074 :       CALL dbt_get_info(t_3c_apc, nblks_total=nblks_3c)
    4712              : 
    4713         7074 : !$OMP PARALLEL DEFAULT(NONE) SHARED(t_3c_apc,t_stacked,idx,nblks_3c) PRIVATE(iter,ind,blk,found,current_idx)
    4714              :       CALL dbt_iterator_start(iter, t_stacked)
    4715              :       DO WHILE (dbt_iterator_blocks_left(iter))
    4716              :          CALL dbt_iterator_next_block(iter, ind)
    4717              : 
    4718              :          !tensor is stacked along the 3rd dimension
    4719              :          current_idx = (ind(3) - 1)/nblks_3c(3) + 1
    4720              :          IF (.NOT. idx == current_idx) CYCLE
    4721              : 
    4722              :          CALL dbt_get_block(t_stacked, ind, blk, found)
    4723              :          IF (.NOT. found) CYCLE
    4724              : 
    4725              :          CALL dbt_put_block(t_3c_apc, [ind(1), ind(2), ind(3) - (idx - 1)*nblks_3c(3)], SHAPE(blk), blk)
    4726              :          DEALLOCATE (blk)
    4727              :       END DO
    4728              :       CALL dbt_iterator_stop(iter)
    4729              : !$OMP END PARALLEL
    4730              : 
    4731         7074 :    END SUBROUTINE unstack_t_3c_apc
    4732              : 
    4733              : ! **************************************************************************************************
    4734              : !> \brief copies the 3c integrals correspoinding to a single atom mu from the general (P^0| mu^0 sigam^a)
    4735              : !> \param t_3c_at ...
    4736              : !> \param t_3c_ints ...
    4737              : !> \param iatom ...
    4738              : !> \param dim_at ...
    4739              : !> \param idx_to_at ...
    4740              : ! **************************************************************************************************
    4741            0 :    SUBROUTINE get_atom_3c_ints(t_3c_at, t_3c_ints, iatom, dim_at, idx_to_at)
    4742              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_3c_at, t_3c_ints
    4743              :       INTEGER, INTENT(IN)                                :: iatom, dim_at
    4744              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: idx_to_at
    4745              : 
    4746              :       INTEGER, DIMENSION(3)                              :: ind
    4747              :       LOGICAL                                            :: found
    4748            0 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :, :)          :: blk
    4749              :       TYPE(dbt_iterator_type)                            :: iter
    4750              : 
    4751            0 : !$OMP PARALLEL DEFAULT(NONE) SHARED(t_3c_ints,t_3c_at,iatom,idx_to_at,dim_at) PRIVATE(iter,ind,blk,found)
    4752              :       CALL dbt_iterator_start(iter, t_3c_ints)
    4753              :       DO WHILE (dbt_iterator_blocks_left(iter))
    4754              :          CALL dbt_iterator_next_block(iter, ind)
    4755              :          IF (.NOT. idx_to_at(ind(dim_at)) == iatom) CYCLE
    4756              : 
    4757              :          CALL dbt_get_block(t_3c_ints, ind, blk, found)
    4758              :          IF (.NOT. found) CYCLE
    4759              : 
    4760              :          CALL dbt_put_block(t_3c_at, ind, SHAPE(blk), blk)
    4761              :          DEALLOCATE (blk)
    4762              :       END DO
    4763              :       CALL dbt_iterator_stop(iter)
    4764              : !$OMP END PARALLEL
    4765            0 :       CALL dbt_finalize(t_3c_at)
    4766              : 
    4767            0 :    END SUBROUTINE get_atom_3c_ints
    4768              : 
    4769              : ! **************************************************************************************************
    4770              : !> \brief Precalculate the 3c and 2c derivatives tensors
    4771              : !> \param t_3c_der_RI ...
    4772              : !> \param t_3c_der_AO ...
    4773              : !> \param mat_der_pot ...
    4774              : !> \param t_2c_der_metric ...
    4775              : !> \param ri_data ...
    4776              : !> \param qs_env ...
    4777              : ! **************************************************************************************************
    4778           54 :    SUBROUTINE precalc_derivatives(t_3c_der_RI, t_3c_der_AO, mat_der_pot, t_2c_der_metric, ri_data, qs_env)
    4779              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_3c_der_RI, t_3c_der_AO
    4780              :       TYPE(dbcsr_type), DIMENSION(:, :), INTENT(INOUT)   :: mat_der_pot
    4781              :       TYPE(dbt_type), DIMENSION(:, :), INTENT(INOUT)     :: t_2c_der_metric
    4782              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    4783              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4784              : 
    4785              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'precalc_derivatives'
    4786              : 
    4787              :       INTEGER                                            :: handle, handle2, i_img, i_mem, i_RI, &
    4788              :                                                             i_xyz, iatom, n_mem, natom, nblks_RI, &
    4789              :                                                             ncell_RI, nimg, nkind, nthreads
    4790              :       INTEGER(int_8)                                     :: nze
    4791           54 :       INTEGER, ALLOCATABLE, DIMENSION(:) :: bsizes_RI_ext, bsizes_RI_ext_split, dist_AO_1, &
    4792          108 :          dist_AO_2, dist_RI, dist_RI_ext, dummy_end, dummy_start, end_blocks, start_blocks
    4793          108 :       INTEGER, CONTIGUOUS, DIMENSION(:), POINTER         :: col_bsize, row_bsize
    4794              :       INTEGER, DIMENSION(3)                              :: pcoord, pdims
    4795              :       REAL(dp)                                           :: occ
    4796              :       TYPE(dbcsr_distribution_type)                      :: dbcsr_dist
    4797              :       TYPE(dbcsr_type)                                   :: dbcsr_template
    4798           54 :       TYPE(dbcsr_type), ALLOCATABLE, DIMENSION(:, :)     :: mat_der_metric
    4799          486 :       TYPE(dbt_distribution_type)                        :: t_dist
    4800          162 :       TYPE(dbt_pgrid_type)                               :: pgrid
    4801          486 :       TYPE(dbt_type)                                     :: t_3c_template
    4802           54 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:, :, :)    :: t_3c_der_AO_prv, t_3c_der_RI_prv
    4803              :       TYPE(dft_control_type), POINTER                    :: dft_control
    4804              :       TYPE(distribution_2d_type), POINTER                :: dist_2d
    4805              :       TYPE(distribution_3d_type)                         :: dist_3d
    4806              :       TYPE(gto_basis_set_p_type), ALLOCATABLE, &
    4807           54 :          DIMENSION(:), TARGET                            :: basis_set_AO, basis_set_RI
    4808           54 :       TYPE(mp_cart_type)                                 :: mp_comm_t3c
    4809              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    4810              :       TYPE(neighbor_list_3c_type)                        :: nl_3c
    4811              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    4812           54 :          POINTER                                         :: nl_2c
    4813           54 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    4814           54 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    4815              : 
    4816           54 :       NULLIFY (qs_kind_set, dist_2d, nl_2c, particle_set, dft_control, para_env, row_bsize, col_bsize)
    4817              : 
    4818           54 :       CALL timeset(routineN, handle)
    4819              : 
    4820              :       CALL get_qs_env(qs_env, nkind=nkind, qs_kind_set=qs_kind_set, distribution_2d=dist_2d, natom=natom, &
    4821           54 :                       particle_set=particle_set, dft_control=dft_control, para_env=para_env)
    4822              : 
    4823           54 :       nimg = ri_data%nimg
    4824           54 :       ncell_RI = ri_data%ncell_RI
    4825              : 
    4826          380 :       ALLOCATE (basis_set_RI(nkind), basis_set_AO(nkind))
    4827           54 :       CALL basis_set_list_setup(basis_set_RI, ri_data%ri_basis_type, qs_kind_set)
    4828           54 :       CALL get_particle_set(particle_set, qs_kind_set, basis=basis_set_RI)
    4829           54 :       CALL basis_set_list_setup(basis_set_AO, ri_data%orb_basis_type, qs_kind_set)
    4830           54 :       CALL get_particle_set(particle_set, qs_kind_set, basis=basis_set_AO)
    4831              : 
    4832              :       !Dealing with the 3c derivatives
    4833           54 :       nthreads = 1
    4834           54 : !$    nthreads = omp_get_num_threads()
    4835           54 :       pdims = 0
    4836          216 :       CALL dbt_pgrid_create(para_env, pdims, pgrid, tensor_dims=[MAX(1, natom/(ri_data%n_mem*nthreads)), natom, natom])
    4837              : 
    4838              :       CALL create_3c_tensor(t_3c_template, dist_AO_1, dist_AO_2, dist_RI, pgrid, &
    4839              :                             ri_data%bsizes_AO, ri_data%bsizes_AO, ri_data%bsizes_RI, &
    4840           54 :                             map1=[1, 2], map2=[3], name="tmp")
    4841           54 :       CALL dbt_destroy(t_3c_template)
    4842              : 
    4843              :       !We stack the RI basis images. Keep consistent distribution
    4844           54 :       nblks_RI = SIZE(ri_data%bsizes_RI_split)
    4845          162 :       ALLOCATE (dist_RI_ext(natom*ncell_RI))
    4846          108 :       ALLOCATE (bsizes_RI_ext(natom*ncell_RI))
    4847          162 :       ALLOCATE (bsizes_RI_ext_split(nblks_RI*ncell_RI))
    4848          410 :       DO i_RI = 1, ncell_RI
    4849         1068 :          bsizes_RI_ext((i_RI - 1)*natom + 1:i_RI*natom) = ri_data%bsizes_RI(:)
    4850         1068 :          dist_RI_ext((i_RI - 1)*natom + 1:i_RI*natom) = dist_RI(:)
    4851         1994 :          bsizes_RI_ext_split((i_RI - 1)*nblks_RI + 1:i_RI*nblks_RI) = ri_data%bsizes_RI_split(:)
    4852              :       END DO
    4853              : 
    4854           54 :       CALL dbt_distribution_new(t_dist, pgrid, dist_AO_1, dist_AO_2, dist_RI_ext)
    4855              :       CALL dbt_create(t_3c_template, "KP_3c_der", t_dist, [1, 2], [3], &
    4856           54 :                       ri_data%bsizes_AO, ri_data%bsizes_AO, bsizes_RI_ext)
    4857           54 :       CALL dbt_distribution_destroy(t_dist)
    4858              : 
    4859        10812 :       ALLOCATE (t_3c_der_RI_prv(nimg, 1, 3), t_3c_der_AO_prv(nimg, 1, 3))
    4860          216 :       DO i_xyz = 1, 3
    4861         4758 :          DO i_img = 1, nimg
    4862         4542 :             CALL dbt_create(t_3c_template, t_3c_der_RI_prv(i_img, 1, i_xyz))
    4863         4704 :             CALL dbt_create(t_3c_template, t_3c_der_AO_prv(i_img, 1, i_xyz))
    4864              :          END DO
    4865              :       END DO
    4866           54 :       CALL dbt_destroy(t_3c_template)
    4867              : 
    4868           54 :       CALL dbt_mp_environ_pgrid(pgrid, pdims, pcoord)
    4869           54 :       CALL mp_comm_t3c%create(pgrid%mp_comm_2d, 3, pdims)
    4870              :       CALL distribution_3d_create(dist_3d, dist_AO_1, dist_AO_2, dist_RI, &
    4871           54 :                                   nkind, particle_set, mp_comm_t3c, own_comm=.TRUE.)
    4872           54 :       DEALLOCATE (dist_RI, dist_AO_1, dist_AO_2)
    4873           54 :       CALL dbt_pgrid_destroy(pgrid)
    4874              : 
    4875              :       CALL build_3c_neighbor_lists(nl_3c, basis_set_AO, basis_set_AO, basis_set_RI, dist_3d, ri_data%ri_metric, &
    4876           54 :                                    "HFX_3c_nl", qs_env, op_pos=2, sym_jk=.FALSE., own_dist=.TRUE.)
    4877              : 
    4878           54 :       n_mem = ri_data%n_mem
    4879              :       CALL create_tensor_batches(ri_data%bsizes_RI, n_mem, dummy_start, dummy_end, &
    4880           54 :                                  start_blocks, end_blocks)
    4881           54 :       DEALLOCATE (dummy_start, dummy_end)
    4882              : 
    4883              :       CALL create_3c_tensor(t_3c_template, dist_RI, dist_AO_1, dist_AO_2, ri_data%pgrid_2, &
    4884              :                             bsizes_RI_ext_split, ri_data%bsizes_AO_split, ri_data%bsizes_AO_split, &
    4885           54 :                             map1=[1], map2=[2, 3], name="der (RI | AO AO)")
    4886          216 :       DO i_xyz = 1, 3
    4887         4758 :          DO i_img = 1, nimg
    4888         4542 :             CALL dbt_create(t_3c_template, t_3c_der_RI(i_img, i_xyz))
    4889         4704 :             CALL dbt_create(t_3c_template, t_3c_der_AO(i_img, i_xyz))
    4890              :          END DO
    4891              :       END DO
    4892              : 
    4893          152 :       DO i_mem = 1, n_mem
    4894              :          CALL build_3c_derivatives(t_3c_der_AO_prv, t_3c_der_RI_prv, ri_data%filter_eps, qs_env, &
    4895              :                                    nl_3c, basis_set_AO, basis_set_AO, basis_set_RI, &
    4896              :                                    ri_data%ri_metric, der_eps=ri_data%eps_schwarz_forces, op_pos=2, &
    4897              :                                    do_kpoints=.TRUE., do_hfx_kpoints=.TRUE., &
    4898              :                                    bounds_k=[start_blocks(i_mem), end_blocks(i_mem)], &
    4899          294 :                                    RI_range=ri_data%kp_RI_range, img_to_RI_cell=ri_data%img_to_RI_cell)
    4900              : 
    4901           98 :          CALL timeset(routineN//"_cpy", handle2)
    4902              :          !We go from (mu^0 sigma^i | P^j) to (P^i| sigma^j mu^0) and finally to (P^i| mu^0 sigma^j)
    4903         3026 :          DO i_img = 1, nimg
    4904        11810 :             DO i_xyz = 1, 3
    4905              :                !derivative wrt to mu^0
    4906         8784 :                CALL get_tensor_occupancy(t_3c_der_AO_prv(i_img, 1, i_xyz), nze, occ)
    4907         8784 :                IF (nze > 0) THEN
    4908              :                   CALL dbt_copy(t_3c_der_AO_prv(i_img, 1, i_xyz), t_3c_template, &
    4909         5056 :                                 order=[3, 2, 1], move_data=.TRUE.)
    4910         5056 :                   CALL dbt_filter(t_3c_template, ri_data%filter_eps)
    4911              :                   CALL dbt_copy(t_3c_template, t_3c_der_AO(i_img, i_xyz), &
    4912         5056 :                                 order=[1, 3, 2], move_data=.TRUE., summation=.TRUE.)
    4913              :                END IF
    4914              : 
    4915              :                !derivative wrt to P^i
    4916         8784 :                CALL get_tensor_occupancy(t_3c_der_RI_prv(i_img, 1, i_xyz), nze, occ)
    4917        20496 :                IF (nze > 0) THEN
    4918              :                   CALL dbt_copy(t_3c_der_RI_prv(i_img, 1, i_xyz), t_3c_template, &
    4919         5006 :                                 order=[3, 2, 1], move_data=.TRUE.)
    4920         5006 :                   CALL dbt_filter(t_3c_template, ri_data%filter_eps)
    4921              :                   CALL dbt_copy(t_3c_template, t_3c_der_RI(i_img, i_xyz), &
    4922         5006 :                                 order=[1, 3, 2], move_data=.TRUE., summation=.TRUE.)
    4923              :                END IF
    4924              :             END DO
    4925              :          END DO
    4926          250 :          CALL timestop(handle2)
    4927              :       END DO
    4928           54 :       CALL dbt_destroy(t_3c_template)
    4929              : 
    4930           54 :       CALL neighbor_list_3c_destroy(nl_3c)
    4931          216 :       DO i_xyz = 1, 3
    4932         4758 :          DO i_img = 1, nimg
    4933         4542 :             CALL dbt_destroy(t_3c_der_RI_prv(i_img, 1, i_xyz))
    4934         4704 :             CALL dbt_destroy(t_3c_der_AO_prv(i_img, 1, i_xyz))
    4935              :          END DO
    4936              :       END DO
    4937         9138 :       DEALLOCATE (t_3c_der_RI_prv, t_3c_der_AO_prv)
    4938              : 
    4939              :       !Reorder 3c derivatives to be consistant with ints
    4940           54 :       CALL reorder_3c_derivs(t_3c_der_RI, ri_data)
    4941           54 :       CALL reorder_3c_derivs(t_3c_der_AO, ri_data)
    4942              : 
    4943           54 :       CALL timeset(routineN//"_2c", handle2)
    4944              :       !The 2-center derivatives
    4945           54 :       CALL cp_dbcsr_dist2d_to_dist(dist_2d, dbcsr_dist)
    4946          162 :       ALLOCATE (row_bsize(SIZE(ri_data%bsizes_RI)))
    4947          108 :       ALLOCATE (col_bsize(SIZE(ri_data%bsizes_RI)))
    4948          162 :       row_bsize(:) = ri_data%bsizes_RI
    4949          162 :       col_bsize(:) = ri_data%bsizes_RI
    4950              : 
    4951              :       CALL dbcsr_create(dbcsr_template, "2c_der", dbcsr_dist, dbcsr_type_no_symmetry, &
    4952           54 :                         row_bsize, col_bsize)
    4953           54 :       CALL dbcsr_distribution_release(dbcsr_dist)
    4954           54 :       DEALLOCATE (col_bsize, row_bsize)
    4955              : 
    4956         4866 :       ALLOCATE (mat_der_metric(nimg, 3))
    4957          216 :       DO i_xyz = 1, 3
    4958         4758 :          DO i_img = 1, nimg
    4959         4542 :             CALL dbcsr_create(mat_der_pot(i_img, i_xyz), template=dbcsr_template)
    4960         4704 :             CALL dbcsr_create(mat_der_metric(i_img, i_xyz), template=dbcsr_template)
    4961              :          END DO
    4962              :       END DO
    4963           54 :       CALL dbcsr_release(dbcsr_template)
    4964              : 
    4965              :       !HFX potential derivatives
    4966              :       CALL build_2c_neighbor_lists(nl_2c, basis_set_RI, basis_set_RI, ri_data%hfx_pot, &
    4967           54 :                                    "HFX_2c_nl_pot", qs_env, sym_ij=.FALSE., dist_2d=dist_2d)
    4968              :       CALL build_2c_derivatives(mat_der_pot, ri_data%filter_eps_2c, qs_env, nl_2c, &
    4969           54 :                                 basis_set_RI, basis_set_RI, ri_data%hfx_pot, do_kpoints=.TRUE.)
    4970           54 :       CALL release_neighbor_list_sets(nl_2c)
    4971              : 
    4972              :       !RI metric derivatives
    4973              :       CALL build_2c_neighbor_lists(nl_2c, basis_set_RI, basis_set_RI, ri_data%ri_metric, &
    4974           54 :                                    "HFX_2c_nl_pot", qs_env, sym_ij=.FALSE., dist_2d=dist_2d)
    4975              :       CALL build_2c_derivatives(mat_der_metric, ri_data%filter_eps_2c, qs_env, nl_2c, &
    4976           54 :                                 basis_set_RI, basis_set_RI, ri_data%ri_metric, do_kpoints=.TRUE.)
    4977           54 :       CALL release_neighbor_list_sets(nl_2c)
    4978              : 
    4979              :       !Get into extended RI basis and tensor format
    4980          216 :       DO i_xyz = 1, 3
    4981          486 :          DO iatom = 1, natom
    4982          324 :             CALL dbt_create(ri_data%t_2c_inv(1, 1), t_2c_der_metric(iatom, i_xyz))
    4983              :             CALL get_ext_2c_int(t_2c_der_metric(iatom, i_xyz), mat_der_metric(:, i_xyz), &
    4984          486 :                                 iatom, iatom, 1, ri_data, qs_env)
    4985              :          END DO
    4986         4758 :          DO i_img = 1, nimg
    4987         4704 :             CALL dbcsr_release(mat_der_metric(i_img, i_xyz))
    4988              :          END DO
    4989              :       END DO
    4990           54 :       CALL timestop(handle2)
    4991              : 
    4992           54 :       CALL timestop(handle)
    4993              : 
    4994          270 :    END SUBROUTINE precalc_derivatives
    4995              : 
    4996              : ! **************************************************************************************************
    4997              : !> \brief Update the forces due to the derivative of the a 2-center product d/dR (Q|R)
    4998              : !> \param force ...
    4999              : !> \param t_2c_contr A precontracted tensor containing sum_abcdPS (ab|P)(P|Q)^-1 (R|S)^-1 (S|cd) P_ac P_bd
    5000              : !> \param t_2c_der the d/dR (Q|R) tensor, in all 3 cartesian directions
    5001              : !> \param atom_of_kind ...
    5002              : !> \param kind_of ...
    5003              : !> \param img in which periodic image the second center of the tensor is
    5004              : !> \param pref ...
    5005              : !> \param ri_data ...
    5006              : !> \param qs_env ...
    5007              : !> \param work_virial ...
    5008              : !> \param cell ...
    5009              : !> \param particle_set ...
    5010              : !> \param diag ...
    5011              : !> \param offdiag ...
    5012              : !> \note IMPORTANT: t_tc_contr and t_2c_der need to have the same distribution. Atomic block sizes are
    5013              : !>                  assumed
    5014              : ! **************************************************************************************************
    5015         4220 :    SUBROUTINE get_2c_der_force(force, t_2c_contr, t_2c_der, atom_of_kind, kind_of, img, pref, &
    5016              :                                ri_data, qs_env, work_virial, cell, particle_set, diag, offdiag)
    5017              : 
    5018              :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
    5019              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_2c_contr
    5020              :       TYPE(dbt_type), DIMENSION(:), INTENT(INOUT)        :: t_2c_der
    5021              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: atom_of_kind, kind_of
    5022              :       INTEGER, INTENT(IN)                                :: img
    5023              :       REAL(dp), INTENT(IN)                               :: pref
    5024              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    5025              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    5026              :       REAL(dp), DIMENSION(3, 3), INTENT(INOUT), OPTIONAL :: work_virial
    5027              :       TYPE(cell_type), OPTIONAL, POINTER                 :: cell
    5028              :       TYPE(particle_type), DIMENSION(:), OPTIONAL, &
    5029              :          POINTER                                         :: particle_set
    5030              :       LOGICAL, INTENT(IN), OPTIONAL                      :: diag, offdiag
    5031              : 
    5032              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_2c_der_force'
    5033              : 
    5034              :       INTEGER                                            :: handle, i_img, i_RI, i_xyz, iat, &
    5035              :                                                             iat_of_kind, ikind, j_img, j_RI, &
    5036              :                                                             j_xyz, jat, jat_of_kind, jkind, natom
    5037              :       INTEGER, DIMENSION(2)                              :: ind
    5038         4220 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    5039              :       LOGICAL                                            :: found, my_diag, my_offdiag, use_virial
    5040              :       REAL(dp)                                           :: new_force
    5041         4220 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :), TARGET     :: contr_blk, der_blk
    5042              :       REAL(dp), DIMENSION(3)                             :: scoord
    5043              :       TYPE(dbt_iterator_type)                            :: iter
    5044              :       TYPE(kpoint_type), POINTER                         :: kpoints
    5045              : 
    5046         4220 :       NULLIFY (kpoints, index_to_cell)
    5047              : 
    5048              :       !Loop over the blocks of d/dR (Q|R), contract with the corresponding block of t_2c_contr and
    5049              :       !update the relevant force
    5050              : 
    5051         4220 :       CALL timeset(routineN, handle)
    5052              : 
    5053         4220 :       use_virial = .FALSE.
    5054         4220 :       IF (PRESENT(work_virial) .AND. PRESENT(cell) .AND. PRESENT(particle_set)) use_virial = .TRUE.
    5055              : 
    5056         4220 :       my_diag = .FALSE.
    5057         4220 :       IF (PRESENT(diag)) my_diag = diag
    5058              : 
    5059         3376 :       my_offdiag = .FALSE.
    5060         3376 :       IF (PRESENT(diag)) my_offdiag = offdiag
    5061              : 
    5062         4220 :       CALL get_qs_env(qs_env, kpoints=kpoints, natom=natom)
    5063         4220 :       CALL get_kpoint_info(kpoints, index_to_cell=index_to_cell)
    5064              : 
    5065              : !$OMP PARALLEL DEFAULT(NONE) &
    5066              : !$OMP SHARED(t_2c_der,t_2c_contr,work_virial,force,use_virial,natom,index_to_cell,ri_data,img) &
    5067              : !$OMP SHARED(pref,atom_of_kind,kind_of,particle_set,cell,my_diag,my_offdiag) &
    5068              : !$OMP PRIVATE(i_xyz,j_xyz,iter,ind,der_blk,contr_blk,found,new_force,i_RI,i_img,j_RI,j_img) &
    5069         4220 : !$OMP PRIVATE(iat,jat,iat_of_kind,jat_of_kind,ikind,jkind,scoord)
    5070              :       DO i_xyz = 1, 3
    5071              :          CALL dbt_iterator_start(iter, t_2c_der(i_xyz))
    5072              :          DO WHILE (dbt_iterator_blocks_left(iter))
    5073              :             CALL dbt_iterator_next_block(iter, ind)
    5074              : 
    5075              :             !Only take forecs due to block diagonal or block off-diagonal, depending on arguments
    5076              :             IF ((my_diag .AND. .NOT. my_offdiag) .OR. (.NOT. my_diag .AND. my_offdiag)) THEN
    5077              :                IF (my_diag .AND. (ind(1) /= ind(2))) CYCLE
    5078              :                IF (my_offdiag .AND. (ind(1) == ind(2))) CYCLE
    5079              :             END IF
    5080              : 
    5081              :             CALL dbt_get_block(t_2c_der(i_xyz), ind, der_blk, found)
    5082              :             CPASSERT(found)
    5083              :             CALL dbt_get_block(t_2c_contr, ind, contr_blk, found)
    5084              : 
    5085              :             IF (found) THEN
    5086              : 
    5087              :                !an element of d/dR (Q|R) corresponds to 2 things because of translational invariance
    5088              :                !(Q'| R) = - (Q| R'), once wrt the center on Q, and once on R
    5089              :                new_force = pref*SUM(der_blk(:, :)*contr_blk(:, :))
    5090              : 
    5091              :                i_RI = (ind(1) - 1)/natom + 1
    5092              :                i_img = ri_data%RI_cell_to_img(i_RI)
    5093              :                iat = ind(1) - (i_RI - 1)*natom
    5094              :                iat_of_kind = atom_of_kind(iat)
    5095              :                ikind = kind_of(iat)
    5096              : 
    5097              :                j_RI = (ind(2) - 1)/natom + 1
    5098              :                j_img = ri_data%RI_cell_to_img(j_RI)
    5099              :                jat = ind(2) - (j_RI - 1)*natom
    5100              :                jat_of_kind = atom_of_kind(jat)
    5101              :                jkind = kind_of(jat)
    5102              : 
    5103              :                !Force on iatom (first center)
    5104              : !$OMP ATOMIC
    5105              :                force(ikind)%fock_4c(i_xyz, iat_of_kind) = force(ikind)%fock_4c(i_xyz, iat_of_kind) &
    5106              :                                                           + new_force
    5107              : 
    5108              :                IF (use_virial) THEN
    5109              : 
    5110              :                   CALL real_to_scaled(scoord, pbc(particle_set(iat)%r, cell), cell)
    5111              :                   scoord(:) = scoord(:) + REAL(index_to_cell(:, i_img), dp)
    5112              : 
    5113              :                   DO j_xyz = 1, 3
    5114              : !$OMP ATOMIC
    5115              :                      work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) + new_force*scoord(j_xyz)
    5116              :                   END DO
    5117              :                END IF
    5118              : 
    5119              :                !Force on jatom (second center)
    5120              : !$OMP ATOMIC
    5121              :                force(jkind)%fock_4c(i_xyz, jat_of_kind) = force(jkind)%fock_4c(i_xyz, jat_of_kind) &
    5122              :                                                           - new_force
    5123              : 
    5124              :                IF (use_virial) THEN
    5125              : 
    5126              :                   CALL real_to_scaled(scoord, pbc(particle_set(jat)%r, cell), cell)
    5127              :                   scoord(:) = scoord(:) + REAL(index_to_cell(:, j_img) + index_to_cell(:, img), dp)
    5128              : 
    5129              :                   DO j_xyz = 1, 3
    5130              : !$OMP ATOMIC
    5131              :                      work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) - new_force*scoord(j_xyz)
    5132              :                   END DO
    5133              :                END IF
    5134              : 
    5135              :                DEALLOCATE (contr_blk)
    5136              :             END IF
    5137              : 
    5138              :             DEALLOCATE (der_blk)
    5139              :          END DO !iter
    5140              :          CALL dbt_iterator_stop(iter)
    5141              : 
    5142              :       END DO !i_xyz
    5143              : !$OMP END PARALLEL
    5144         4220 :       CALL timestop(handle)
    5145              : 
    5146         8440 :    END SUBROUTINE get_2c_der_force
    5147              : 
    5148              : ! **************************************************************************************************
    5149              : !> \brief This routines calculates the force contribution from a trace over 3D tensors, i.e.
    5150              : !>        force = sum_ijk A_ijk B_ijk., the B tensor is (P^0| sigma^0 lambda^img), with P in the
    5151              : !>        extended RI basis. Note that all tensors are stacked along the 3rd dimension
    5152              : !> \param force ...
    5153              : !> \param t_3c_contr ...
    5154              : !> \param t_3c_der_1 ...
    5155              : !> \param t_3c_der_2 ...
    5156              : !> \param atom_of_kind ...
    5157              : !> \param kind_of ...
    5158              : !> \param idx_to_at_RI ...
    5159              : !> \param idx_to_at_AO ...
    5160              : !> \param i_images ...
    5161              : !> \param lb_img ...
    5162              : !> \param pref ...
    5163              : !> \param ri_data ...
    5164              : !> \param qs_env ...
    5165              : !> \param work_virial ...
    5166              : !> \param cell ...
    5167              : !> \param particle_set ...
    5168              : ! **************************************************************************************************
    5169         3172 :    SUBROUTINE get_force_from_3c_trace(force, t_3c_contr, t_3c_der_1, t_3c_der_2, atom_of_kind, kind_of, &
    5170         6344 :                                       idx_to_at_RI, idx_to_at_AO, i_images, lb_img, pref, &
    5171              :                                       ri_data, qs_env, work_virial, cell, particle_set)
    5172              : 
    5173              :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
    5174              :       TYPE(dbt_type), INTENT(INOUT)                      :: t_3c_contr
    5175              :       TYPE(dbt_type), DIMENSION(3), INTENT(INOUT)        :: t_3c_der_1, t_3c_der_2
    5176              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: atom_of_kind, kind_of, idx_to_at_RI, &
    5177              :                                                             idx_to_at_AO, i_images
    5178              :       INTEGER, INTENT(IN)                                :: lb_img
    5179              :       REAL(dp), INTENT(IN)                               :: pref
    5180              :       TYPE(hfx_ri_type), INTENT(INOUT)                   :: ri_data
    5181              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    5182              :       REAL(dp), DIMENSION(3, 3), INTENT(INOUT), OPTIONAL :: work_virial
    5183              :       TYPE(cell_type), OPTIONAL, POINTER                 :: cell
    5184              :       TYPE(particle_type), DIMENSION(:), OPTIONAL, &
    5185              :          POINTER                                         :: particle_set
    5186              : 
    5187              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_force_from_3c_trace'
    5188              : 
    5189              :       INTEGER :: handle, i_RI, i_xyz, iat, iat_of_kind, idx, ikind, j_xyz, jat, jat_of_kind, &
    5190              :          jkind, kat, kat_of_kind, kkind, nblks_AO, nblks_RI, RI_img
    5191              :       INTEGER, DIMENSION(3)                              :: ind
    5192         3172 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    5193              :       LOGICAL                                            :: found, found_1, found_2, use_virial
    5194              :       REAL(dp)                                           :: new_force
    5195         3172 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :, :), TARGET  :: contr_blk, der_blk_1, der_blk_2, &
    5196         3172 :                                                             der_blk_3
    5197              :       REAL(dp), DIMENSION(3)                             :: scoord
    5198              :       TYPE(dbt_iterator_type)                            :: iter
    5199              :       TYPE(kpoint_type), POINTER                         :: kpoints
    5200              : 
    5201         3172 :       NULLIFY (kpoints, index_to_cell)
    5202              : 
    5203         3172 :       CALL timeset(routineN, handle)
    5204              : 
    5205         3172 :       CALL get_qs_env(qs_env, kpoints=kpoints)
    5206         3172 :       CALL get_kpoint_info(kpoints, index_to_cell=index_to_cell)
    5207              : 
    5208         3172 :       nblks_RI = SIZE(ri_data%bsizes_RI_split)
    5209         3172 :       nblks_AO = SIZE(ri_data%bsizes_AO_split)
    5210              : 
    5211         3172 :       use_virial = .FALSE.
    5212         3172 :       IF (PRESENT(work_virial) .AND. PRESENT(cell) .AND. PRESENT(particle_set)) use_virial = .TRUE.
    5213              : 
    5214              : !$OMP PARALLEL DEFAULT(NONE) &
    5215              : !$OMP SHARED(t_3c_der_1, t_3c_der_2,t_3c_contr,work_virial,force,use_virial,index_to_cell,i_images,lb_img) &
    5216              : !$OMP SHARED(pref,idx_to_at_AO,atom_of_kind,kind_of,particle_set,cell,idx_to_at_RI,ri_data,nblks_RI,nblks_AO) &
    5217              : !$OMP PRIVATE(i_xyz,j_xyz,iter,ind,der_blk_1,contr_blk,found,new_force,iat,iat_of_kind,ikind,scoord) &
    5218         3172 : !$OMP PRIVATE(jat,kat,jat_of_kind,kat_of_kind,jkind,kkind,i_RI,RI_img,der_blk_2,der_blk_3,found_1,found_2,idx)
    5219              :       CALL dbt_iterator_start(iter, t_3c_contr)
    5220              :       DO WHILE (dbt_iterator_blocks_left(iter))
    5221              :          CALL dbt_iterator_next_block(iter, ind)
    5222              : 
    5223              :          CALL dbt_get_block(t_3c_contr, ind, contr_blk, found)
    5224              :          IF (found) THEN
    5225              : 
    5226              :             DO i_xyz = 1, 3
    5227              :                CALL dbt_get_block(t_3c_der_1(i_xyz), ind, der_blk_1, found_1)
    5228              :                IF (.NOT. found_1) THEN
    5229              :                   DEALLOCATE (der_blk_1)
    5230              :                   ALLOCATE (der_blk_1(SIZE(contr_blk, 1), SIZE(contr_blk, 2), SIZE(contr_blk, 3)))
    5231              :                   der_blk_1(:, :, :) = 0.0_dp
    5232              :                END IF
    5233              :                CALL dbt_get_block(t_3c_der_2(i_xyz), ind, der_blk_2, found_2)
    5234              :                IF (.NOT. found_2) THEN
    5235              :                   DEALLOCATE (der_blk_2)
    5236              :                   ALLOCATE (der_blk_2(SIZE(contr_blk, 1), SIZE(contr_blk, 2), SIZE(contr_blk, 3)))
    5237              :                   der_blk_2(:, :, :) = 0.0_dp
    5238              :                END IF
    5239              : 
    5240              :                ALLOCATE (der_blk_3(SIZE(contr_blk, 1), SIZE(contr_blk, 2), SIZE(contr_blk, 3)))
    5241              :                der_blk_3(:, :, :) = -(der_blk_1(:, :, :) + der_blk_2(:, :, :))
    5242              : 
    5243              :                !We assume the tensors are in the format (P^0| sigma^0 mu^a+c-b), with P a member of the
    5244              :                !extended RI basis set
    5245              : 
    5246              :                !Force for the first center (RI extended basis, zero cell)
    5247              :                new_force = pref*SUM(der_blk_1(:, :, :)*contr_blk(:, :, :))
    5248              : 
    5249              :                i_RI = (ind(1) - 1)/nblks_RI + 1
    5250              :                RI_img = ri_data%RI_cell_to_img(i_RI)
    5251              :                iat = idx_to_at_RI(ind(1) - (i_RI - 1)*nblks_RI)
    5252              :                iat_of_kind = atom_of_kind(iat)
    5253              :                ikind = kind_of(iat)
    5254              : 
    5255              : !$OMP ATOMIC
    5256              :                force(ikind)%fock_4c(i_xyz, iat_of_kind) = force(ikind)%fock_4c(i_xyz, iat_of_kind) &
    5257              :                                                           + new_force
    5258              : 
    5259              :                IF (use_virial) THEN
    5260              : 
    5261              :                   CALL real_to_scaled(scoord, pbc(particle_set(iat)%r, cell), cell)
    5262              :                   scoord(:) = scoord(:) + REAL(index_to_cell(:, RI_img), dp)
    5263              : 
    5264              :                   DO j_xyz = 1, 3
    5265              : !$OMP ATOMIC
    5266              :                      work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) + new_force*scoord(j_xyz)
    5267              :                   END DO
    5268              :                END IF
    5269              : 
    5270              :                !Force with respect to the second center (AO basis, zero cell)
    5271              :                new_force = pref*SUM(der_blk_2(:, :, :)*contr_blk(:, :, :))
    5272              :                jat = idx_to_at_AO(ind(2))
    5273              :                jat_of_kind = atom_of_kind(jat)
    5274              :                jkind = kind_of(jat)
    5275              : 
    5276              : !$OMP ATOMIC
    5277              :                force(jkind)%fock_4c(i_xyz, jat_of_kind) = force(jkind)%fock_4c(i_xyz, jat_of_kind) &
    5278              :                                                           + new_force
    5279              : 
    5280              :                IF (use_virial) THEN
    5281              : 
    5282              :                   CALL real_to_scaled(scoord, pbc(particle_set(jat)%r, cell), cell)
    5283              : 
    5284              :                   DO j_xyz = 1, 3
    5285              : !$OMP ATOMIC
    5286              :                      work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) + new_force*scoord(j_xyz)
    5287              :                   END DO
    5288              :                END IF
    5289              : 
    5290              :                !Force with respect to the third center (AO basis, apc_img - b_img)
    5291              :                !Note: tensors are stacked along the 3rd direction
    5292              :                new_force = pref*SUM(der_blk_3(:, :, :)*contr_blk(:, :, :))
    5293              :                idx = (ind(3) - 1)/nblks_AO + 1
    5294              :                kat = idx_to_at_AO(ind(3) - (idx - 1)*nblks_AO)
    5295              :                kat_of_kind = atom_of_kind(kat)
    5296              :                kkind = kind_of(kat)
    5297              : 
    5298              : !$OMP ATOMIC
    5299              :                force(kkind)%fock_4c(i_xyz, kat_of_kind) = force(kkind)%fock_4c(i_xyz, kat_of_kind) &
    5300              :                                                           + new_force
    5301              : 
    5302              :                IF (use_virial) THEN
    5303              :                   CALL real_to_scaled(scoord, pbc(particle_set(kat)%r, cell), cell)
    5304              :                   scoord(:) = scoord(:) + REAL(index_to_cell(:, i_images(lb_img - 1 + idx)), dp)
    5305              : 
    5306              :                   DO j_xyz = 1, 3
    5307              : !$OMP ATOMIC
    5308              :                      work_virial(i_xyz, j_xyz) = work_virial(i_xyz, j_xyz) + new_force*scoord(j_xyz)
    5309              :                   END DO
    5310              :                END IF
    5311              : 
    5312              :                DEALLOCATE (der_blk_1, der_blk_2, der_blk_3)
    5313              :             END DO !i_xyz
    5314              :             DEALLOCATE (contr_blk)
    5315              :          END IF !found
    5316              :       END DO !iter
    5317              :       CALL dbt_iterator_stop(iter)
    5318              : !$OMP END PARALLEL
    5319         3172 :       CALL timestop(handle)
    5320              : 
    5321         6344 :    END SUBROUTINE get_force_from_3c_trace
    5322              : 
    5323              : END MODULE hfx_ri_kp
        

Generated by: LCOV version 2.0-1