LCOV - code coverage report
Current view: top level - src - hfx_energy_potential.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 85.6 % 348 298
Test Date: 2026-11-24 01:22:08 Functions: 80.0 % 5 4

            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 Routines to calculate HFX energy and potential
      10              : !> \par History
      11              : !>      11.2006 created [Manuel Guidon]
      12              : !>      10.2025 added libGint interface [M Puligheddu]
      13              : !> \author Manuel Guidon
      14              : ! **************************************************************************************************
      15              : MODULE hfx_energy_potential
      16              :    USE r12_fundamentals, ONLY: r12_fundamentals_init
      17              :    USE admm_types, ONLY: get_admm_env
      18              :    USE atomic_kind_types, ONLY: atomic_kind_type, &
      19              :                                 get_atomic_kind_set
      20              :    USE bibliography, ONLY: cite_reference, &
      21              :                            guidon2008, &
      22              :                            guidon2009
      23              :    USE cell_types, ONLY: cell_type, &
      24              :                          pbc
      25              :    USE cp_control_types, ONLY: dft_control_type
      26              :    USE cp_files, ONLY: close_file, &
      27              :                        open_file
      28              :    USE cp_log_handling, ONLY: cp_get_default_logger, &
      29              :                               cp_logger_type
      30              :    USE cp_output_handling, ONLY: cp_p_file, &
      31              :                                  cp_print_key_finished_output, &
      32              :                                  cp_print_key_should_output, &
      33              :                                  cp_print_key_unit_nr
      34              :    USE message_passing, ONLY: mp_para_env_type
      35              :    USE cp_dbcsr_api, ONLY: dbcsr_copy, &
      36              :                            dbcsr_get_matrix_type, &
      37              :                            dbcsr_p_type, &
      38              :                            dbcsr_type_antisymmetric, &
      39              :                            dbcsr_dot_threadsafe
      40              :    USE four_center_integral_methods, ONLY: coulomb4
      41              :    USE hfx_communication, ONLY: distribute_ks_matrix, &
      42              :                                 get_atomic_block_maps, &
      43              :                                 get_full_density
      44              :    USE hfx_compression_methods, ONLY: hfx_add_mult_cache_elements, &
      45              :                                       hfx_add_single_cache_element, &
      46              :                                       hfx_decompress_first_cache, &
      47              :                                       hfx_flush_last_cache, &
      48              :                                       hfx_get_mult_cache_elements, &
      49              :                                       hfx_get_single_cache_element, &
      50              :                                       hfx_reset_cache_and_container
      51              :    USE hfx_contract_block, ONLY: contract_block
      52              :    USE hfx_load_balance_methods, ONLY: collect_load_balance_info, &
      53              :                                        hfx_load_balance, &
      54              :                                        hfx_update_load_balance
      55              :    USE hfx_pair_list_methods, ONLY: build_atomic_pair_list, &
      56              :                                     build_pair_list
      57              :    USE hfx_screening_methods, ONLY: calc_pair_dist_radii, &
      58              :                                     calc_screening_functions, &
      59              :                                     update_pmax_mat
      60              :    USE hfx_types, ONLY: &
      61              :       alloc_containers, dealloc_containers, hfx_basis_info_type, hfx_basis_type, hfx_cache_type, &
      62              :       hfx_cell_type, hfx_container_type, hfx_create_neighbor_cells, hfx_distribution, &
      63              :       hfx_general_type, hfx_init_container, hfx_load_balance_type, hfx_memory_type, hfx_p_kind, &
      64              :       hfx_pgf_list, hfx_potential_type, hfx_reset_memory_usage_counter, &
      65              :       hfx_screen_coeff_type, hfx_screening_type, hfx_task_list_type, hfx_type, &
      66              :       log_zero, pair_list_type, pair_set_list_type
      67              : 
      68              :    USE input_constants, ONLY: do_potential_mix_cl_trunc, &
      69              :                               do_potential_truncated, &
      70              :                               do_potential_short, &
      71              :                               do_potential_coulomb, &
      72              :                               hfx_do_eval_energy, &
      73              :                               hfx_library_is_libint, hfx_library_is_libGint, hfx_library_is_both
      74              : 
      75              :    USE input_section_types, ONLY: section_vals_type
      76              :    USE kinds, ONLY: default_string_length, &
      77              :                     dp, &
      78              :                     int_8
      79              :    USE kpoint_types, ONLY: get_kpoint_info, &
      80              :                            kpoint_type
      81              :    USE machine, ONLY: m_flush, &
      82              :                       m_memory, &
      83              :                       m_walltime
      84              :    USE mathconstants, ONLY: fac
      85              :    USE orbital_pointers, ONLY: nco, &
      86              :                                ncoset, &
      87              :                                nso
      88              :    USE particle_types, ONLY: particle_type
      89              :    USE qs_environment_types, ONLY: get_qs_env, &
      90              :                                    qs_environment_type
      91              :    USE qs_ks_types, ONLY: get_ks_env, &
      92              :                           qs_ks_env_type
      93              :    USE util, ONLY: sort
      94              :    use, intrinsic :: iso_c_binding, only: c_ptr
      95              : 
      96              :    use cp2k_info, only: cp2k_flags
      97              :    use offload_api, only: offload_get_chosen_device, offload_set_chosen_device, offload_activate_chosen_device
      98              :    use libGint_wrapper, only: cp_libGint_init, libGint_update_env, libGint_set_density, libGint_coulomb4, &
      99              :                               libGint_update_fock_matrix, libGint_get_fock_matrix
     100              : 
     101              : !$ USE OMP_LIB, ONLY: omp_get_max_threads, omp_get_thread_num, omp_get_num_threads
     102              : 
     103              : #include "./base/base_uses.f90"
     104              : 
     105              :    IMPLICIT NONE
     106              :    PRIVATE
     107              : 
     108              :    PUBLIC :: integrate_four_center
     109              : 
     110              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'hfx_energy_potential'
     111              : 
     112              : !***
     113              : 
     114              : CONTAINS
     115              : 
     116              : ! **************************************************************************************************
     117              : !> \brief computes four center integrals for a full basis set and updates the
     118              : !>      Kohn-Sham-Matrix and energy. Uses all 8 eri symmetries
     119              : !> \param qs_env ...
     120              : !> \param x_data ...
     121              : !> \param ks_matrix ...
     122              : !> \param ehfx energy calculated with the updated HFX matrix
     123              : !> \param rho_ao density matrix in ao basis
     124              : !> \param hfx_section input_section HFX
     125              : !> \param para_env ...
     126              : !> \param geometry_did_change flag that indicates we have to recalc integrals
     127              : !> \param irep Index for the HFX replica
     128              : !> \param distribute_fock_matrix Flag that indicates whether to communicate the
     129              : !>        new fock matrix or not
     130              : !> \param ispin ...
     131              : !> \par History
     132              : !>      06.2007 created [Manuel Guidon]
     133              : !>      08.2007 optimized load balance [Manuel Guidon]
     134              : !>      09.2007 new parallelization [Manuel Guidon]
     135              : !>      02.2009 completely rewritten screening part [Manuel Guidon]
     136              : !>      12.2017 major bug fix. removed wrong cycle that was caussing segfault.
     137              : !>              see https://groups.google.com/forum/#!topic/cp2k/pc6B14XOALY
     138              : !>              [Tobias Binninger + Valery Weber]
     139              : !> \author Manuel Guidon
     140              : ! **************************************************************************************************
     141        43303 :    SUBROUTINE integrate_four_center(qs_env, x_data, ks_matrix, ehfx, rho_ao, hfx_section, para_env, &
     142              :                                     geometry_did_change, irep, distribute_fock_matrix, &
     143              :                                     ispin, nspins)
     144              : 
     145              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     146              :       TYPE(hfx_type), DIMENSION(:, :), POINTER           :: x_data
     147              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_matrix
     148              :       REAL(KIND=dp), INTENT(OUT)                         :: ehfx
     149              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao
     150              :       TYPE(section_vals_type), POINTER                   :: hfx_section
     151              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     152              :       LOGICAL                                            :: geometry_did_change
     153              :       INTEGER                                            :: irep
     154              :       LOGICAL, INTENT(IN)                                :: distribute_fock_matrix
     155              :       INTEGER, INTENT(IN)                                :: ispin
     156              :       INTEGER, INTENT(IN), OPTIONAL                      :: nspins
     157              : 
     158              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'integrate_four_center'
     159              : 
     160              :       CHARACTER(len=default_string_length)               :: eps_scaling_str, eps_schwarz_min_str
     161              :       INTEGER :: act_atomic_block_offset, act_set_offset, atomic_offset_ac, atomic_offset_ad, &
     162              :                  atomic_offset_bc, atomic_offset_bd, bin, bits_max_val, buffer_left, buffer_size, &
     163              :                  buffer_start, cache_size, current_counter, handle, handle_bin, handle_dist_ks, &
     164              :                  handle_getP, handle_load, handle_main, i, inla, nla, i_list_ij, i_list_kl, i_set_list_ij, &
     165              :                  i_set_list_ij_start, i_set_list_ij_stop, i_set_list_kl, i_set_list_kl_start, &
     166              :                  i_set_list_kl_stop, i_thread, iatom, iatom_block, iatom_end, iatom_start, ikind, img, &
     167              :                  iset, iw, j, jatom, jatom_block, jatom_end, jatom_start, jkind, jset, katom, katom_block, &
     168              :                  katom_end
     169              :       INTEGER :: katom_start, kind_kind_idx, kkind, kset, l_max, latom, latom_block, latom_end, &
     170              :                  latom_start, lkind, lset, ma, max_am, max_pgf, max_set, mb, my_bin_id, my_bin_size, &
     171              :                  my_thread_id, n_threads, natom, nbits, ncob, ncos_max, nints, nkimages, nkind, nneighbors, &
     172              :                  nseta, nsetb, nsgf_max, my_nspins, pa, sgfb, shm_task_counter, shm_total_bins, &
     173              :                  swap_id, tmp_i4
     174              :       INTEGER(int_8) :: atom_block, counter, estimate_to_store_int, max_val_memory, &
     175              :                         mb_size_buffers, mb_size_f, mb_size_p, mem_compression_counter, &
     176              :                         mem_compression_counter_disk, mem_eris, mem_eris_disk, mem_max_val, memsize_after, &
     177              :                         memsize_before, my_current_counter, my_istart, n_processes, nblocks, ncpu, neris_disk, &
     178              :                         neris_incore, neris_onthefly, neris_tmp, neris_total, nprim_ints, &
     179              :                         shm_mem_compression_counter, shm_neris_disk, shm_neris_incore, shm_neris_onthefly, &
     180              :                         shm_neris_total, shm_nprim_ints, shm_stor_count_int_disk, shm_stor_count_max_val, &
     181              :                         shm_storage_counter_integrals, stor_count_int_disk
     182              :       INTEGER(int_8) :: stor_count_max_val, storage_counter_integrals, subtr_size_mb, tmp_block, tmp_i8(8)
     183        43303 :       INTEGER(int_8), ALLOCATABLE, DIMENSION(:)          :: tmp_task_list_cost
     184        86606 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: kind_of, last_sgf_global, nimages, &
     185        86606 :                                                             tmp_index, first_set_of_atom
     186        43303 :       INTEGER, DIMENSION(:), POINTER :: la_max, la_min, lb_max, lb_min, lc_max, lc_min, ld_max, &
     187        86606 :                                         ld_min, npgfa, npgfb, npgfc, npgfd, nsgfa, nsgfb, nsgfc, nsgfd, shm_block_offset
     188        86606 :       INTEGER, DIMENSION(:, :), POINTER :: first_sgfb, nsgfl_a, nsgfl_b, nsgfl_c, nsgfl_d, &
     189        43303 :                                            offset_ac_set, offset_ad_set, offset_bc_set, offset_bd_set, shm_atomic_block_offset
     190              :       INTEGER, DIMENSION(:, :), POINTER, SAVE            :: shm_is_assoc_atomic_block
     191        43303 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
     192        43303 :       INTEGER, DIMENSION(:, :, :, :), POINTER            :: shm_set_offset
     193              :       INTEGER, SAVE                                      :: shm_number_of_p_entries
     194              :       LOGICAL :: bins_left, buffer_overflow, do_disk_storage, do_dynamic_load_balancing, do_it, &
     195              :                  do_kpoints, do_p_screening, do_periodic, do_print_load_balance_info, is_anti_symmetric, &
     196              :                  ks_fully_occ, my_geo_change, treat_lsd_in_core, use_disk_storage
     197        43303 :       LOGICAL, DIMENSION(:, :), POINTER                  :: shm_atomic_pair_list
     198              :       REAL(dp) :: afac, bintime_start, bintime_stop, cartesian_estimate, compression_factor, &
     199              :                   compression_factor_disk, ene_x_aa, ene_x_aa_diag, ene_x_bb, ene_x_bb_diag, eps_schwarz, &
     200              :                   eps_storage, etmp, fac, hf_fraction, ln_10, log10_eps_schwarz, log10_pmax, &
     201              :                   max_contraction_val, max_val1, max_val2, max_val2_set, pmax_atom, pmax_blocks, &
     202              :                   pmax_entry, ra(3), rab2, rb(3), rc(3), rcd2, rd(3), screen_kind_ij, screen_kind_kl, &
     203              :                   spherical_estimate, symm_fac
     204        43303 :       REAL(dp), ALLOCATABLE, DIMENSION(:) :: ee_buffer1, ee_buffer2, ee_work2, &
     205        86606 :                                          kac_buf, kad_buf, kbc_buf, kbd_buf, pac_buf, pad_buf, pbc_buf, pbd_buf, primitive_integrals
     206              : 
     207        43303 :       REAL(dp), DIMENSION(:, :), POINTER :: full_density_alpha, full_density_beta, full_ks_alpha, &
     208        86606 :                                             full_ks_beta, max_contraction, ptr_p_1, ptr_p_2, ptr_p_3, ptr_p_4, shm_pmax_atom, &
     209        43303 :                                             shm_pmax_block, sphi_b, zeta, zetb, zetc, zetd, &
     210        43303 :                                             full_ks_alpha_from_gpu, full_ks_beta_from_gpu
     211        43303 :       REAL(dp), DIMENSION(:, :, :), POINTER             :: gcc
     212              :       REAL(KIND=dp)                                      :: coeffs_kind_max0
     213        43303 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     214              :       TYPE(cell_type), POINTER                           :: cell
     215              :       TYPE(cp_logger_type), POINTER                      :: logger
     216        43303 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_ks_aux_fit_hfx
     217              :       TYPE(dft_control_type), POINTER                    :: dft_control
     218              :       TYPE(hfx_basis_info_type), POINTER                 :: basis_info
     219        43303 :       TYPE(hfx_basis_type), DIMENSION(:), POINTER        :: basis_parameter
     220        43303 :       TYPE(hfx_cache_type), DIMENSION(:), POINTER        :: integral_caches, integral_caches_disk
     221              :       TYPE(hfx_cache_type), POINTER                      :: maxval_cache, maxval_cache_disk
     222        43303 :       TYPE(hfx_container_type), DIMENSION(:), POINTER    :: integral_containers, &
     223        43303 :                                                             integral_containers_disk
     224              :       TYPE(hfx_container_type), POINTER                  :: maxval_container, maxval_container_disk
     225              :       TYPE(hfx_distribution), POINTER                    :: distribution_energy
     226              :       TYPE(hfx_general_type)                             :: general_parameter
     227              :       TYPE(hfx_load_balance_type), POINTER               :: load_balance_parameter
     228              :       TYPE(hfx_memory_type), POINTER                     :: memory_parameter
     229        43303 :       TYPE(hfx_p_kind), DIMENSION(:), POINTER            :: shm_initial_p
     230        43303 :       TYPE(hfx_pgf_list), ALLOCATABLE, DIMENSION(:)      :: pgf_list_ij, pgf_list_kl
     231              :       TYPE(hfx_potential_type)                           :: potential_parameter
     232              :       TYPE(hfx_screen_coeff_type), DIMENSION(:, :), &
     233        43303 :          POINTER                                         :: screen_coeffs_kind, tmp_R_1, tmp_R_2, &
     234        43303 :                                                             tmp_screen_pgf1, tmp_screen_pgf2
     235              :       TYPE(hfx_screen_coeff_type), &
     236        43303 :          DIMENSION(:, :, :, :), POINTER                  :: screen_coeffs_set
     237              :       TYPE(hfx_screen_coeff_type), &
     238        43303 :          DIMENSION(:, :, :, :, :, :), POINTER            :: radii_pgf, screen_coeffs_pgf
     239              :       TYPE(hfx_screening_type)                           :: screening_parameter
     240        43303 :       TYPE(hfx_task_list_type), DIMENSION(:), POINTER    :: shm_task_list, tmp_task_list
     241              :       TYPE(hfx_type), POINTER                            :: actual_x_data, shm_master_x_data
     242              :       TYPE(kpoint_type), POINTER                         :: kpoints
     243              :       TYPE(pair_list_type)                               :: list_ij, list_kl
     244              :       TYPE(pair_set_list_type), ALLOCATABLE, &
     245        43303 :          DIMENSION(:)                                    :: set_list_ij, set_list_kl
     246        43303 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     247              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
     248              : 
     249              :       logical :: screened
     250              :       real(dp) :: max_abs_delta_KS
     251              :       integer :: iatom_set, jatom_set, katom_set, latom_set, shared_dev
     252              :       logical :: use_libint, use_libgint, use_only_alpha_spin
     253              :       logical :: cp2k_was_compiled_with_cuda_offload, cp2k_was_compiled_with_libint
     254              :       logical :: cp2k_was_compiled_with_libGint
     255              : 
     256        43303 :       NULLIFY (dft_control, matrix_ks_aux_fit_hfx)
     257              : 
     258        43303 :       CALL timeset(routineN, handle)
     259              : 
     260        43303 :       CALL cite_reference(Guidon2008)
     261        43303 :       CALL cite_reference(Guidon2009)
     262              : 
     263        43303 :       ehfx = 0.0_dp
     264              : 
     265              :       ! This is not very clean, but effective. ispin can only be 2 if we do the beta spin part in core
     266        43303 :       my_geo_change = geometry_did_change
     267        43303 :       IF (ispin == 2) my_geo_change = .FALSE.
     268              : 
     269        43303 :       logger => cp_get_default_logger()
     270              : 
     271        43303 :       is_anti_symmetric = dbcsr_get_matrix_type(rho_ao(1, 1)%matrix) == dbcsr_type_antisymmetric
     272              : 
     273              :       iw = -1
     274              : 
     275        43303 :       IF (my_geo_change) THEN
     276         2598 :          CALL m_memory(memsize_before)
     277         2598 :          CALL para_env%max(memsize_before)
     278              :          iw = cp_print_key_unit_nr(logger, hfx_section, "HF_INFO", &
     279         2598 :                                    extension=".scfLog")
     280         2598 :          IF (iw > 0) THEN
     281              :             WRITE (UNIT=iw, FMT="(/,(T3,A,T60,I21))") &
     282          478 :                "HFX_MEM_INFO| Est. max. program size before HFX [MiB]:", memsize_before/(1024*1024)
     283          478 :             CALL m_flush(iw)
     284              :          END IF
     285              :          CALL cp_print_key_finished_output(iw, logger, hfx_section, &
     286         2598 :                                            "HF_INFO")
     287              :       END IF
     288              : 
     289        43303 :       CALL get_qs_env(qs_env=qs_env, atomic_kind_set=atomic_kind_set, cell=cell)
     290              : 
     291        43303 :       NULLIFY (cell_to_index)
     292        43303 :       CALL get_qs_env(qs_env=qs_env, do_kpoints=do_kpoints)
     293        43303 :       IF (do_kpoints) THEN
     294            0 :          CALL get_qs_env(qs_env=qs_env, ks_env=ks_env)
     295            0 :          CALL get_ks_env(ks_env=ks_env, kpoints=kpoints)
     296            0 :          CALL get_kpoint_info(kpoint=kpoints, cell_to_index=cell_to_index)
     297              :       END IF
     298              : 
     299              :       !! Calculate l_max used in fgamma , because init_md_ftable is definitely not thread safe
     300        43303 :       nkind = SIZE(atomic_kind_set, 1)
     301        43303 :       l_max = 0
     302       123017 :       DO ikind = 1, nkind
     303       360673 :          l_max = MAX(l_max, MAXVAL(x_data(1, 1)%basis_parameter(ikind)%lmax))
     304              :       END DO
     305        43303 :       l_max = 4*l_max
     306        43303 :       CALL r12_fundamentals_init(l_max, x_data(1, 1)%potential_parameter, para_env)
     307              : 
     308        43303 :       n_threads = 1
     309        43303 : !$    n_threads = omp_get_max_threads()
     310              : 
     311              :       ! This initialization is needed to prevent a segmentation fault. The correct assigment is done below
     312        43303 :       my_nspins = 0
     313        43303 :       IF (PRESENT(nspins)) my_nspins = nspins
     314              : 
     315        43303 :       shm_neris_total = 0
     316        43303 :       shm_nprim_ints = 0
     317        43303 :       shm_neris_onthefly = 0
     318        43303 :       shm_storage_counter_integrals = 0
     319        43303 :       shm_stor_count_int_disk = 0
     320        43303 :       shm_neris_incore = 0
     321        43303 :       shm_neris_disk = 0
     322        43303 :       shm_stor_count_max_val = 0
     323              : 
     324              : !$OMP PARALLEL DEFAULT(NONE) &
     325              : !$OMP SHARED(qs_env,&
     326              : !$OMP                                  x_data,&
     327              : !$OMP                                  ks_matrix,&
     328              : !$OMP                                  ehfx,&
     329              : !$OMP                                  rho_ao,&
     330              : !$OMP                                  matrix_ks_aux_fit_hfx,&
     331              : !$OMP                                  hfx_section,&
     332              : !$OMP                                  para_env,&
     333              : !$OMP                                  my_geo_change,&
     334              : !$OMP                                  irep,&
     335              : !$OMP                                  distribute_fock_matrix,&
     336              : !$OMP                                  cell_to_index,&
     337              : !$OMP                                  ncoset,&
     338              : !$OMP                                  nso,&
     339              : !$OMP                                  nco,&
     340              : !$OMP                                  full_ks_alpha,&
     341              : !$OMP                                  full_ks_alpha_from_gpu,&
     342              : !$OMP                                  full_ks_beta_from_gpu,&
     343              : !$OMP                                  full_ks_beta,&
     344              : !$OMP                                  n_threads,&
     345              : !$OMP                                  full_density_alpha,&
     346              : !$OMP                                  full_density_beta,&
     347              : !$OMP                                  shm_initial_p,&
     348              : !$OMP                                  shm_is_assoc_atomic_block,&
     349              : !$OMP                                  shm_number_of_p_entries,&
     350              : !$OMP                                  shm_neris_total,&
     351              : !$OMP                                  shm_neris_onthefly,&
     352              : !$OMP                                  shm_storage_counter_integrals,&
     353              : !$OMP                                  shm_stor_count_int_disk,&
     354              : !$OMP                                  shm_neris_incore,&
     355              : !$OMP                                  shm_neris_disk,&
     356              : !$OMP                                  shm_nprim_ints,&
     357              : !$OMP                                  shm_stor_count_max_val,&
     358              : !$OMP                                  cell,&
     359              : !$OMP                                  screen_coeffs_set,&
     360              : !$OMP                                  screen_coeffs_kind,&
     361              : !$OMP                                  screen_coeffs_pgf,&
     362              : !$OMP                                  radii_pgf,&
     363              : !$OMP                                  nkind,&
     364              : !$OMP                                  ispin,&
     365              : !$OMP                                  is_anti_symmetric,&
     366              : !$OMP                                  shm_atomic_block_offset,&
     367              : !$OMP                                  shm_set_offset,&
     368              : !$OMP                                  shm_block_offset,&
     369              : !$OMP                                  shm_task_counter,&
     370              : !$OMP                                  shm_task_list,&
     371              : !$OMP                                  shm_total_bins,&
     372              : !$OMP                                  shm_master_x_data,&
     373              : !$OMP                                  shm_pmax_atom,&
     374              : !$OMP                                  shm_pmax_block,&
     375              : !$OMP                                  shm_atomic_pair_list,&
     376              : !$OMP                                  shm_mem_compression_counter,&
     377              : !$OMP                                  shared_dev, &
     378              : !$OMP                                  do_print_load_balance_info,use_libgint,use_libint, &
     379              : !$OMP                                  cp2k_was_compiled_with_cuda_offload, &
     380              : !$OMP                                  cp2k_was_compiled_with_libint, &
     381              : !$OMP                                  cp2k_was_compiled_with_libGint, &
     382              : !$OMP                                  my_nspins) &
     383              : !$OMP PRIVATE(ln_10,i_thread,actual_x_data,do_periodic,screening_parameter,potential_parameter,&
     384              : !$OMP         general_parameter,load_balance_parameter,memory_parameter,cache_size,bits_max_val,&
     385              : !$OMP         basis_parameter,basis_info,treat_lsd_in_core,ncpu,n_processes,neris_total,neris_incore,&
     386              : !$OMP         neris_disk,neris_onthefly,mem_eris,mem_eris_disk,mem_max_val,compression_factor,&
     387              : !$OMP         compression_factor_disk,nprim_ints,neris_tmp,max_val_memory,max_am,do_p_screening,&
     388              : !$OMP         max_set,particle_set,atomic_kind_set,natom,kind_of,ncos_max,nsgf_max,ikind,&
     389              : !$OMP         nseta,npgfa,la_max,nsgfa,primitive_integrals,pbd_buf,pbc_buf,pad_buf,pac_buf,kbd_buf,kbc_buf,&
     390              : !$OMP         kad_buf,kac_buf,ee_work2,ee_buffer1,ee_buffer2,max_contraction,&
     391              : !$OMP         max_pgf,jkind,lb_max,nsetb,npgfb,first_sgfb,sphi_b,nsgfb,ncob,sgfb,nneighbors,pgf_list_ij,pgf_list_kl,&
     392              : !$OMP         nimages,ks_fully_occ,subtr_size_mb,use_disk_storage,counter,do_disk_storage,&
     393              : !$OMP         maxval_container_disk,maxval_cache_disk,integral_containers_disk,integral_caches_disk,eps_schwarz,&
     394              : !$OMP         log10_eps_schwarz,eps_storage,hf_fraction,buffer_overflow,logger,last_sgf_global,handle_getp,&
     395              : !$OMP         fac,handle_load,do_dynamic_load_balancing,my_bin_size,maxval_container,integral_containers,maxval_cache,&
     396              : !$OMP         integral_caches,tmp_task_list,tmp_task_list_cost,tmp_index,handle_main,coeffs_kind_max0,set_list_ij,&
     397              : !$OMP         set_list_kl,iatom_start,iatom_end,jatom_start,jatom_end,nblocks,bins_left,do_it,distribution_energy,&
     398              : !$OMP         my_thread_id,my_bin_id,handle_bin,bintime_start,my_istart,my_current_counter,latom_block,tmp_block,&
     399              : !$OMP         katom_block,katom_start,katom_end,latom_start,latom_end,pmax_blocks,list_ij,list_kl,i_set_list_ij_start,&
     400              : !$OMP         i_set_list_ij_stop,ra,rb,rab2,la_min,zeta,nsgfl_a,&
     401              : !$OMP         lb_min,zetb,nsgfl_b,katom,latom,i_set_list_kl_start,i_set_list_kl_stop,&
     402              : !$OMP         kkind,lkind,rc,rd,rcd2,pmax_atom,screen_kind_ij,screen_kind_kl,symm_fac,lc_max,lc_min,npgfc,zetc,nsgfc,&
     403              : !$OMP         nsgfl_c,ld_max,ld_min,npgfd,zetd,nsgfd,nsgfl_d,&
     404              : !$OMP         atomic_offset_bd,atomic_offset_bc,atomic_offset_ad,atomic_offset_ac,offset_bd_set,offset_bc_set,&
     405              : !$OMP         offset_ad_set,offset_ac_set,swap_id,kind_kind_idx,ptr_p_1,ptr_p_2,ptr_p_3,ptr_p_4,mem_compression_counter,&
     406              : !$OMP         mem_compression_counter_disk,max_val1,kset,lset,max_val2_set,max_val2,&
     407              : !$OMP         pmax_entry,log10_pmax,current_counter,nints,estimate_to_store_int,&
     408              : !$OMP         spherical_estimate,nbits,buffer_left,buffer_start,buffer_size,max_contraction_val,tmp_r_1,tmp_r_2,&
     409              : !$OMP         tmp_screen_pgf1,tmp_screen_pgf2,cartesian_estimate,bintime_stop,iw,memsize_after,storage_counter_integrals,&
     410              : !$OMP         stor_count_int_disk,stor_count_max_val,ene_x_aa,ene_x_bb,mb_size_p,mb_size_f,mb_size_buffers,afac,ene_x_aa_diag,&
     411              : !$OMP         ene_x_bb_diag,act_atomic_block_offset,act_set_offset,j,handle_dist_ks,tmp_i8,tmp_i4,dft_control,&
     412              : !$OMP         etmp,nkimages,img,bin,eps_scaling_str,eps_schwarz_min_str, &
     413              : !$OMP         i,inla,nla,gcc,first_set_of_atom,max_abs_delta_KS, screened, &
     414        43303 : !$OMP         iatom_set,jatom_set,katom_set,latom_set,use_only_alpha_spin)
     415              : 
     416              :       ln_10 = LOG(10.0_dp)
     417              :       i_thread = 0
     418              : !$    i_thread = omp_get_thread_num()
     419              : 
     420              :       actual_x_data => x_data(irep, i_thread + 1)
     421              : !$OMP MASTER
     422              :       shm_master_x_data => x_data(irep, 1)
     423              : !$OMP END MASTER
     424              : !$OMP BARRIER
     425              : 
     426              :       do_periodic = actual_x_data%periodic_parameter%do_periodic
     427              : 
     428              :       IF (do_periodic) THEN
     429              :          ! ** Rebuild neighbor lists in case the cell has changed (i.e. NPT MD)
     430              :          actual_x_data%periodic_parameter%number_of_shells = actual_x_data%periodic_parameter%mode
     431              :          CALL hfx_create_neighbor_cells(actual_x_data, actual_x_data%periodic_parameter%number_of_shells_from_input, &
     432              :                                         cell, i_thread)
     433              :       END IF
     434              : 
     435              :       screening_parameter = actual_x_data%screening_parameter
     436              :       potential_parameter = actual_x_data%potential_parameter
     437              : 
     438              :       general_parameter = actual_x_data%general_parameter
     439              :       load_balance_parameter => actual_x_data%load_balance_parameter
     440              :       memory_parameter => actual_x_data%memory_parameter
     441              : 
     442              :       cache_size = memory_parameter%cache_size
     443              :       bits_max_val = memory_parameter%bits_max_val
     444              : 
     445              :       basis_parameter => actual_x_data%basis_parameter
     446              :       basis_info => actual_x_data%basis_info
     447              : 
     448              :       treat_lsd_in_core = general_parameter%treat_lsd_in_core
     449              : 
     450              :       ncpu = para_env%num_pe
     451              :       n_processes = ncpu*n_threads
     452              : 
     453              :       !! initialize some counters
     454              :       neris_total = 0_int_8
     455              :       neris_incore = 0_int_8
     456              :       neris_disk = 0_int_8
     457              :       neris_onthefly = 0_int_8
     458              :       mem_eris = 0_int_8
     459              :       mem_eris_disk = 0_int_8
     460              :       mem_max_val = 0_int_8
     461              :       compression_factor = 0.0_dp
     462              :       compression_factor_disk = 0.0_dp
     463              :       nprim_ints = 0_int_8
     464              :       neris_tmp = 0_int_8
     465              :       max_val_memory = 1_int_8
     466              : 
     467              :       ! Set the integral engine
     468              :       IF (general_parameter%hfx_library == hfx_library_is_libint) THEN
     469              :          use_libint = .true.
     470              :          use_libGint = .false.
     471              :       END IF
     472              :       IF (general_parameter%hfx_library == hfx_library_is_libGint) THEN
     473              :          use_libint = .false.
     474              :          use_libGint = .true.
     475              :       END IF
     476              :       IF (general_parameter%hfx_library == hfx_library_is_both) THEN
     477              :          use_libint = .true.
     478              :          use_libGint = .true.
     479              :       END IF
     480              : 
     481              :       max_am = basis_info%max_am
     482              : 
     483              :       CALL get_qs_env(qs_env=qs_env, &
     484              :                       atomic_kind_set=atomic_kind_set, &
     485              :                       particle_set=particle_set, &
     486              :                       dft_control=dft_control)
     487              :       IF (dft_control%do_admm) CALL get_admm_env(qs_env%admm_env, matrix_ks_aux_fit_hfx=matrix_ks_aux_fit_hfx)
     488              : 
     489              :       do_p_screening = screening_parameter%do_initial_p_screening
     490              :       ! Special treatment for MP2 with initial density screening
     491              :       IF (do_p_screening) THEN
     492              :          IF (ASSOCIATED(qs_env%mp2_env)) THEN
     493              :             IF ((qs_env%mp2_env%ri_grad%free_hfx_buffer)) THEN
     494              :                do_p_screening = ((qs_env%mp2_env%p_screen) .AND. (qs_env%mp2_env%not_last_hfx))
     495              :             ELSE
     496              :                do_p_screening = .FALSE.
     497              :             END IF
     498              :          END IF
     499              :       END IF
     500              :       max_set = basis_info%max_set
     501              :       natom = SIZE(particle_set, 1)
     502              : 
     503              :       ! Number of image matrices in k-point calculations (nkimages==1 -> no kpoints)
     504              :       nkimages = dft_control%nimages
     505              :       CPASSERT(nkimages == 1)
     506              : 
     507              :       CALL get_atomic_kind_set(atomic_kind_set=atomic_kind_set, kind_of=kind_of)
     508              : 
     509              :       !! precompute maximum nco and allocate scratch
     510              :       ncos_max = 0
     511              :       nsgf_max = 0
     512              :       DO iatom = 1, natom
     513              :          ikind = kind_of(iatom)
     514              :          nseta = basis_parameter(ikind)%nset
     515              :          npgfa => basis_parameter(ikind)%npgf
     516              :          la_max => basis_parameter(ikind)%lmax
     517              :          nsgfa => basis_parameter(ikind)%nsgf
     518              :          DO iset = 1, nseta
     519              :             ncos_max = MAX(ncos_max, ncoset(la_max(iset)))
     520              :             nsgf_max = MAX(nsgf_max, nsgfa(iset))
     521              :          END DO
     522              :       END DO
     523              :       !! Allocate the arrays for the integrals.
     524              :       ALLOCATE (primitive_integrals(nsgf_max**4))
     525              :       primitive_integrals = 0.0_dp
     526              : 
     527              :       ALLOCATE (pbd_buf(nsgf_max**2))
     528              :       ALLOCATE (pbc_buf(nsgf_max**2))
     529              :       ALLOCATE (pad_buf(nsgf_max**2))
     530              :       ALLOCATE (pac_buf(nsgf_max**2))
     531              :       ALLOCATE (kbd_buf(nsgf_max**2))
     532              :       ALLOCATE (kbc_buf(nsgf_max**2))
     533              :       ALLOCATE (kad_buf(nsgf_max**2))
     534              :       ALLOCATE (kac_buf(nsgf_max**2))
     535              :       ALLOCATE (ee_work2(ncos_max**4))
     536              :       ALLOCATE (ee_buffer1(ncos_max**4))
     537              :       ALLOCATE (ee_buffer2(ncos_max**4))
     538              : 
     539              :       IF (my_nspins == 0) my_nspins = dft_control%nspins
     540              : 
     541              :       ALLOCATE (max_contraction(max_set, natom))
     542              : 
     543              :       max_contraction = 0.0_dp
     544              :       max_pgf = 0
     545              :       DO jatom = 1, natom
     546              :          jkind = kind_of(jatom)
     547              :          lb_max => basis_parameter(jkind)%lmax
     548              :          nsetb = basis_parameter(jkind)%nset
     549              :          npgfb => basis_parameter(jkind)%npgf
     550              :          first_sgfb => basis_parameter(jkind)%first_sgf
     551              :          sphi_b => basis_parameter(jkind)%sphi
     552              :          nsgfb => basis_parameter(jkind)%nsgf
     553              :          DO jset = 1, nsetb
     554              :             ! takes the primitive to contracted transformation into account
     555              :             ncob = npgfb(jset)*ncoset(lb_max(jset))
     556              :             sgfb = first_sgfb(1, jset)
     557              :             ! if the primitives are assumed to be all of max_val2, max_val2*p2s_b becomes
     558              :             ! the maximum value after multiplication with sphi_b
     559              :             max_contraction(jset, jatom) = MAXVAL([(SUM(ABS(sphi_b(1:ncob, i))), i=sgfb, sgfb + nsgfb(jset) - 1)])
     560              :             max_pgf = MAX(max_pgf, npgfb(jset))
     561              :          END DO
     562              :       END DO
     563              : 
     564              :       ! ** Allocate buffers for pgf_lists
     565              :       nneighbors = SIZE(actual_x_data%neighbor_cells)
     566              :       ALLOCATE (pgf_list_ij(max_pgf**2))
     567              :       ALLOCATE (pgf_list_kl(max_pgf**2))
     568              :       ALLOCATE (nimages(max_pgf**2))
     569              : 
     570              :       DO i = 1, max_pgf**2
     571              :          ALLOCATE (pgf_list_ij(i)%image_list(nneighbors))
     572              :          ALLOCATE (pgf_list_kl(i)%image_list(nneighbors))
     573              :       END DO
     574              : !$OMP BARRIER
     575              : !$OMP MASTER
     576              :       !! Calculate helper array that stores if a certain atomic pair is associated in the KS matrix
     577              :       IF (my_geo_change) THEN
     578              :          CALL get_atomic_block_maps(ks_matrix(1, 1)%matrix, basis_parameter, kind_of, &
     579              :                                     shm_master_x_data%is_assoc_atomic_block, &
     580              :                                     shm_master_x_data%number_of_p_entries, &
     581              :                                     para_env, &
     582              :                                     shm_master_x_data%atomic_block_offset, &
     583              :                                     shm_master_x_data%set_offset, &
     584              :                                     shm_master_x_data%block_offset, &
     585              :                                     shm_master_x_data%map_atoms_to_cpus, &
     586              :                                     nkind)
     587              : 
     588              :          shm_is_assoc_atomic_block => shm_master_x_data%is_assoc_atomic_block
     589              : 
     590              :          !! Get occupation of KS-matrix
     591              :          ks_fully_occ = .TRUE.
     592              :          outer: DO iatom = 1, natom
     593              :             DO jatom = iatom, natom
     594              :                IF (shm_is_assoc_atomic_block(jatom, iatom) == 0) THEN
     595              :                   ks_fully_occ = .FALSE.
     596              :                   EXIT outer
     597              :                END IF
     598              :             END DO
     599              :          END DO outer
     600              : 
     601              :          IF (.NOT. ks_fully_occ) THEN
     602              :             CALL cp_warn(__LOCATION__, &
     603              :                          "The Kohn Sham matrix is not 100% occupied. This "// &
     604              :                          "may result in incorrect Hartree-Fock results. Setting "// &
     605              :                          "MIN_PAIR_LIST_RADIUS to -1 in the QS section ensures a "// &
     606              :                          "fully occupied KS matrix. For more information "// &
     607              :                          "see FAQ: https://www.cp2k.org/faq:hfx_eps_warning")
     608              :          END IF
     609              :       END IF
     610              : 
     611              :       ! ** Set pointers
     612              :       shm_number_of_p_entries = shm_master_x_data%number_of_p_entries
     613              :       shm_is_assoc_atomic_block => shm_master_x_data%is_assoc_atomic_block
     614              :       shm_atomic_block_offset => shm_master_x_data%atomic_block_offset
     615              :       shm_set_offset => shm_master_x_data%set_offset
     616              :       shm_block_offset => shm_master_x_data%block_offset
     617              : !$OMP END MASTER
     618              : !$OMP BARRIER
     619              : 
     620              :       ! ** Reset storage counter given by MAX_MEMORY by subtracting all buffers
     621              :       ! ** Fock and density Matrices (shared)
     622              :       subtr_size_mb = 2_int_8*shm_block_offset(ncpu + 1)
     623              :       ! ** if non restricted ==> alpha/beta spin
     624              :       IF (.NOT. treat_lsd_in_core) THEN
     625              :          IF (my_nspins == 2) subtr_size_mb = subtr_size_mb*2_int_8
     626              :       END IF
     627              :       ! ** Initial P only MAX(alpha,beta) (shared)
     628              :       IF (do_p_screening .OR. screening_parameter%do_p_screening_forces) THEN
     629              :          subtr_size_mb = subtr_size_mb + memory_parameter%size_p_screen
     630              :       END IF
     631              :       ! ** In core forces require their own initial P
     632              :       IF (screening_parameter%do_p_screening_forces) THEN
     633              :          IF (memory_parameter%treat_forces_in_core) THEN
     634              :             subtr_size_mb = subtr_size_mb + memory_parameter%size_p_screen
     635              :          END IF
     636              :       END IF
     637              :       ! ** primitive buffer (not shared by the threads)
     638              :       subtr_size_mb = subtr_size_mb + nsgf_max**4*n_threads
     639              :       ! ** density + fock buffers
     640              :       subtr_size_mb = subtr_size_mb + 8_int_8*nsgf_max**2*n_threads
     641              :       ! ** screening functions (shared)
     642              :       ! ** coeffs_pgf
     643              :       subtr_size_mb = subtr_size_mb + max_pgf**2*max_set**2*nkind**2
     644              :       ! ** coeffs_set
     645              :       subtr_size_mb = subtr_size_mb + max_set**2*nkind**2
     646              :       ! ** coeffs_kind
     647              :       subtr_size_mb = subtr_size_mb + nkind**2
     648              :       ! ** radii_pgf
     649              :       subtr_size_mb = subtr_size_mb + max_pgf**2*max_set**2*nkind**2
     650              : 
     651              :       ! ** is_assoc (shared)
     652              :       subtr_size_mb = subtr_size_mb + natom**2
     653              : 
     654              :       ! ** pmax_atom (shared)
     655              :       IF (do_p_screening) THEN
     656              :          subtr_size_mb = subtr_size_mb + natom**2
     657              :       END IF
     658              :       IF (screening_parameter%do_p_screening_forces) THEN
     659              :          IF (memory_parameter%treat_forces_in_core) THEN
     660              :             subtr_size_mb = subtr_size_mb + natom**2
     661              :          END IF
     662              :       END IF
     663              : 
     664              :       ! ** Convert into MiB's
     665              :       subtr_size_mb = subtr_size_mb*8_int_8/1024_int_8/1024_int_8
     666              : 
     667              :       ! ** Subtracting all these buffers from MAX_MEMORY yields the amount
     668              :       ! ** of RAM that is left for the compressed integrals. When using threads
     669              :       ! ** all the available memory is shared among all n_threads. i.e. the faster
     670              :       ! ** ones can steal from the slower ones
     671              : 
     672              :       CALL hfx_reset_memory_usage_counter(memory_parameter, subtr_size_mb)
     673              : 
     674              :       use_disk_storage = .FALSE.
     675              :       counter = 0_int_8
     676              :       do_disk_storage = memory_parameter%do_disk_storage
     677              :       IF (do_disk_storage) THEN
     678              :          maxval_container_disk => actual_x_data%store_ints%maxval_container_disk
     679              :          maxval_cache_disk => actual_x_data%store_ints%maxval_cache_disk
     680              : 
     681              :          integral_containers_disk => actual_x_data%store_ints%integral_containers_disk
     682              :          integral_caches_disk => actual_x_data%store_ints%integral_caches_disk
     683              :       END IF
     684              : 
     685              :       IF (my_geo_change) THEN
     686              :          memory_parameter%ram_counter = HUGE(memory_parameter%ram_counter)
     687              :       END IF
     688              : 
     689              :       IF (my_geo_change) THEN
     690              :          memory_parameter%recalc_forces = .TRUE.
     691              :       ELSE
     692              :          IF (.NOT. memory_parameter%treat_forces_in_core) memory_parameter%recalc_forces = .TRUE.
     693              :       END IF
     694              : 
     695              :       !! Get screening parameter
     696              :       eps_schwarz = screening_parameter%eps_schwarz
     697              :       IF (eps_schwarz <= 0.0_dp) THEN
     698              :          log10_eps_schwarz = log_zero
     699              :       ELSE
     700              :          log10_eps_schwarz = LOG10(eps_schwarz)
     701              :       END IF
     702              :       !! get storage epsilon
     703              :       eps_storage = eps_schwarz*memory_parameter%eps_storage_scaling
     704              : 
     705              :       !! If we have a hybrid functional, we may need only a fraction of exact exchange
     706              :       hf_fraction = general_parameter%fraction
     707              : 
     708              :       !! The number of integrals that fit into the given MAX_MEMORY
     709              : 
     710              :       !! Parameters related to the potential 1/r, erf(wr)/r, erfc(wr/r)
     711              :       potential_parameter = actual_x_data%potential_parameter
     712              : 
     713              :       !! Variable to check if we calculate the integrals in-core or on the fly
     714              :       !! If TRUE -> on the fly
     715              :       IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
     716              :          buffer_overflow = .FALSE.
     717              :       ELSE
     718              :          buffer_overflow = .TRUE.
     719              :       END IF
     720              :       logger => cp_get_default_logger()
     721              : 
     722              :       !! Helper array to map local basis function indices to global ones
     723              :       ALLOCATE (last_sgf_global(0:natom))
     724              :       last_sgf_global(0) = 0
     725              :       DO iatom = 1, natom
     726              :          ikind = kind_of(iatom)
     727              :          last_sgf_global(iatom) = last_sgf_global(iatom - 1) + basis_parameter(ikind)%nsgf_total
     728              :       END DO
     729              : !$OMP BARRIER
     730              : !$OMP MASTER
     731              :       !! Let master thread get the density (avoid problems with MPI)
     732              :       !! Get the full density from all the processors
     733              :       NULLIFY (full_density_alpha, full_density_beta)
     734              :       ALLOCATE (full_density_alpha(shm_block_offset(ncpu + 1), nkimages))
     735              :       IF (.NOT. treat_lsd_in_core .OR. my_nspins == 1) THEN
     736              :          CALL timeset(routineN//"_getP", handle_getP)
     737              :          DO img = 1, nkimages
     738              :             CALL get_full_density(para_env, full_density_alpha(:, img), rho_ao(ispin, img)%matrix, shm_number_of_p_entries, &
     739              :                                   shm_master_x_data%block_offset, &
     740              :                                   kind_of, basis_parameter, get_max_vals_spin=.FALSE., antisymmetric=is_anti_symmetric)
     741              :          END DO
     742              : 
     743              :          IF (my_nspins == 2) THEN
     744              :             ALLOCATE (full_density_beta(shm_block_offset(ncpu + 1), nkimages))
     745              :             DO img = 1, nkimages
     746              :                CALL get_full_density(para_env, full_density_beta(:, img), rho_ao(2, img)%matrix, shm_number_of_p_entries, &
     747              :                                      shm_master_x_data%block_offset, &
     748              :                                      kind_of, basis_parameter, get_max_vals_spin=.FALSE., antisymmetric=is_anti_symmetric)
     749              :             END DO
     750              :          END IF
     751              :          CALL timestop(handle_getP)
     752              : 
     753              :          !! Calculate the max values of the density matrix actual_pmax stores the data from the actual density matrix
     754              :          !! and x_data%initial_p stores the same for the initial guess. The initial guess is updated only in the case of
     755              :          !! a changed geometry
     756              :          NULLIFY (shm_initial_p)
     757              :          IF (do_p_screening) THEN
     758              :             shm_initial_p => shm_master_x_data%initial_p
     759              :             shm_pmax_atom => shm_master_x_data%pmax_atom
     760              :             IF (my_geo_change) THEN
     761              :                CALL update_pmax_mat(shm_master_x_data%initial_p, &
     762              :                                     shm_master_x_data%map_atom_to_kind_atom, &
     763              :                                     shm_master_x_data%set_offset, &
     764              :                                     shm_master_x_data%atomic_block_offset, &
     765              :                                     shm_pmax_atom, &
     766              :                                     full_density_alpha, full_density_beta, &
     767              :                                     natom, kind_of, basis_parameter, &
     768              :                                     nkind, shm_master_x_data%is_assoc_atomic_block, my_nspins)
     769              :             END IF
     770              :          END IF
     771              :       ELSE
     772              :          IF (do_p_screening) THEN
     773              :             CALL timeset(routineN//"_getP", handle_getP)
     774              :             DO img = 1, nkimages
     775              :                CALL get_full_density(para_env, full_density_alpha(:, img), rho_ao(1, img)%matrix, shm_number_of_p_entries, &
     776              :                                      shm_master_x_data%block_offset, &
     777              :                                      kind_of, basis_parameter, get_max_vals_spin=.TRUE., &
     778              :                                      rho_beta=rho_ao(2, img)%matrix, antisymmetric=is_anti_symmetric)
     779              :             END DO
     780              :             CALL timestop(handle_getP)
     781              : 
     782              :             !! Calculate the max values of the density matrix actual_pmax stores the data from the actual density matrix
     783              :             !! and x_data%initial_p stores the same for the initial guess. The initial guess is updated only in the case of
     784              :             !! a changed geometry
     785              :             NULLIFY (shm_initial_p)
     786              :             shm_initial_p => actual_x_data%initial_p
     787              :             shm_pmax_atom => shm_master_x_data%pmax_atom
     788              :             IF (my_geo_change) THEN
     789              :                CALL update_pmax_mat(shm_master_x_data%initial_p, &
     790              :                                     shm_master_x_data%map_atom_to_kind_atom, &
     791              :                                     shm_master_x_data%set_offset, &
     792              :                                     shm_master_x_data%atomic_block_offset, &
     793              :                                     shm_pmax_atom, &
     794              :                                     full_density_alpha, full_density_beta, &
     795              :                                     natom, kind_of, basis_parameter, &
     796              :                                     nkind, shm_master_x_data%is_assoc_atomic_block, my_nspins)
     797              :             END IF
     798              :          END IF
     799              :          ! ** Now get the density(ispin)
     800              :          DO img = 1, nkimages
     801              :             CALL get_full_density(para_env, full_density_alpha(:, img), rho_ao(ispin, img)%matrix, shm_number_of_p_entries, &
     802              :                                   shm_master_x_data%block_offset, &
     803              :                                   kind_of, basis_parameter, get_max_vals_spin=.FALSE., &
     804              :                                   antisymmetric=is_anti_symmetric)
     805              :          END DO
     806              :       END IF
     807              : 
     808              :       NULLIFY (full_ks_alpha, full_ks_beta)
     809              :       ALLOCATE (shm_master_x_data%full_ks_alpha(shm_block_offset(ncpu + 1), nkimages))
     810              :       full_ks_alpha => shm_master_x_data%full_ks_alpha
     811              :       full_ks_alpha = 0.0_dp
     812              : 
     813              :       IF (.NOT. treat_lsd_in_core) THEN
     814              :          IF (my_nspins == 2) THEN
     815              :             ALLOCATE (shm_master_x_data%full_ks_beta(shm_block_offset(ncpu + 1), nkimages))
     816              :             full_ks_beta => shm_master_x_data%full_ks_beta
     817              :             full_ks_beta = 0.0_dp
     818              :          END IF
     819              :       END IF
     820              : 
     821              : !$OMP END MASTER
     822              : !$OMP BARRIER
     823              : 
     824              :       !! Initialize schwarz screening matrices for near field estimates and boxing screening matrices
     825              :       !! for far field estimates. The update is only performed if the geomtry of the system changed.
     826              :       !! If the system is periodic, then the corresponding routines are called and some variables
     827              :       !! are initialized
     828              : 
     829              :       IF (.NOT. shm_master_x_data%screen_funct_is_initialized) THEN
     830              :          CALL calc_pair_dist_radii(qs_env, basis_parameter, &
     831              :                                    shm_master_x_data%pair_dist_radii_pgf, max_set, max_pgf, eps_schwarz, &
     832              :                                    n_threads, i_thread)
     833              : !$OMP BARRIER
     834              :          CALL calc_screening_functions(qs_env, basis_parameter, actual_x_data%eri4_context, shm_master_x_data%potential_parameter, &
     835              :                                        shm_master_x_data%screen_funct_coeffs_set, &
     836              :                                        shm_master_x_data%screen_funct_coeffs_kind, &
     837              :                                        shm_master_x_data%screen_funct_coeffs_pgf, &
     838              :                                        shm_master_x_data%pair_dist_radii_pgf, &
     839              :                                        max_set, max_pgf, n_threads, i_thread)
     840              : 
     841              : !$OMP MASTER
     842              :          shm_master_x_data%screen_funct_is_initialized = .TRUE.
     843              : !$OMP END MASTER
     844              :       END IF
     845              : !$OMP BARRIER
     846              : 
     847              : !$OMP MASTER
     848              :       screen_coeffs_set => shm_master_x_data%screen_funct_coeffs_set
     849              :       screen_coeffs_kind => shm_master_x_data%screen_funct_coeffs_kind
     850              :       screen_coeffs_pgf => shm_master_x_data%screen_funct_coeffs_pgf
     851              :       radii_pgf => shm_master_x_data%pair_dist_radii_pgf
     852              : !$OMP END MASTER
     853              : !$OMP BARRIER
     854              : 
     855              :       !! Initialize a prefactor depending on the fraction and the number of spins
     856              :       IF (my_nspins == 1) THEN
     857              :          fac = 0.5_dp*hf_fraction
     858              :       ELSE
     859              :          fac = 1.0_dp*hf_fraction
     860              :       END IF
     861              : 
     862              :       !! Call routines that distribute the load on all processes. If we want to screen on a initial density matrix, there is
     863              :       !! an optional parameter. Of course, this is only done if the geometry did change
     864              : !$OMP BARRIER
     865              : !$OMP MASTER
     866              :       CALL timeset(routineN//"_load", handle_load)
     867              : !$OMP END MASTER
     868              : !$OMP BARRIER
     869              :       IF (my_geo_change) THEN
     870              :          IF (actual_x_data%b_first_load_balance_energy) THEN
     871              :             CALL hfx_load_balance(actual_x_data, eps_schwarz, particle_set, max_set, para_env, &
     872              :                                   screen_coeffs_set, screen_coeffs_kind, &
     873              :                                   shm_is_assoc_atomic_block, do_periodic, load_balance_parameter, &
     874              :                                   kind_of, basis_parameter, shm_initial_p, shm_pmax_atom, i_thread, n_threads, &
     875              :                                   cell, do_p_screening, actual_x_data%map_atom_to_kind_atom, &
     876              :                                   nkind, hfx_do_eval_energy, shm_pmax_block, use_virial=.FALSE.)
     877              :             actual_x_data%b_first_load_balance_energy = .FALSE.
     878              :          ELSE
     879              :             CALL hfx_update_load_balance(actual_x_data, para_env, &
     880              :                                          load_balance_parameter, &
     881              :                                          i_thread, n_threads, hfx_do_eval_energy)
     882              :          END IF
     883              :       END IF
     884              : !$OMP BARRIER
     885              : !$OMP MASTER
     886              :       CALL timestop(handle_load)
     887              : !$OMP END MASTER
     888              : !$OMP BARRIER
     889              : 
     890              :       use_only_alpha_spin = treat_lsd_in_core .or. .not. my_nspins == 2
     891              : 
     892              :       ! Set up the gpu enviroment for libGint
     893              :       if (use_libGint) then
     894              : 
     895              :          call offload_activate_chosen_device()
     896              : 
     897              :          ! At least once, and before any other call from all OMP threads
     898              :          call cp_libGint_init(actual_x_data)
     899              : 
     900              :          ! At least at geo change
     901              :          call libGint_update_env(fac, memory_parameter, do_periodic, cell, actual_x_data, &
     902              :                                  nneighbors, max_pgf, natom, kind_of, particle_set, basis_parameter)
     903              : 
     904              :          ! Every cycle, comunicate the updated density to libGint
     905              :          if (use_only_alpha_spin) then
     906              :             call libGint_set_density(full_density_alpha)
     907              :          else
     908              :             call libGint_set_density(full_density_alpha, full_density_beta)
     909              :          end if
     910              :       end if
     911              :       !!!
     912              : 
     913              :       !! Start calculating integrals of the form (ab|cd) or (ij|kl)
     914              :       !! In order to do so, there is a main four-loop structure that takes into account the two symmetries
     915              :       !!
     916              :       !!   (ab|cd) = (ba|cd) = (ab|dc) = (ba|dc)
     917              :       !!
     918              :       !! by iterating in the following way
     919              :       !!
     920              :       !! DO iatom=1,natom               and       DO katom=1,natom
     921              :       !!   DO jatom=iatom,natom                     DO latom=katom,natom
     922              :       !!
     923              :       !! The third symmetry
     924              :       !!
     925              :       !!  (ab|cd) = (cd|ab)
     926              :       !!
     927              :       !! is taken into account by the following criterion:
     928              :       !!
     929              :       !! IF(katom+latom<=iatom+jatom)  THEN
     930              :       !!   IF( ((iatom+jatom)==(katom+latom) ) .AND.(katom<iatom)) CYCLE
     931              :       !!
     932              :       !! Depending on the degeneracy of an integral the exchange contribution is multiplied by a corresponding
     933              :       !! factor ( symm_fac ).
     934              :       !!
     935              :       !! If one quartet does not pass the screening we CYCLE on the outer most possible loop. Thats why we use
     936              :       !! different hierarchies of short range screening matrices.
     937              :       !!
     938              :       !! If we do a parallel run, each process owns a unique array of workloads. Here, a workload is
     939              :       !! defined as :
     940              :       !!
     941              :       !! istart, jstart, kstart, lstart, number_of_atom_quartets, initial_cpu_id
     942              :       !!
     943              :       !! This tells the process where to start the main loops and how many bunches of integrals it has to
     944              :       !! calculate. The original parallelization is a simple modulo distribution that is binned and
     945              :       !! optimized in the load_balance routines. Since the Monte Carlo routines can swap processors,
     946              :       !! we need to know which was the initial cpu_id.
     947              :       !! Furthermore, the indices iatom, jatom, katom, latom have to be set to istart, jstart, kstart and
     948              :       !! lstart only the first time the loop is executed. All subsequent loops have to start with one or
     949              :       !! iatom and katom respectively. Therefore, we use flags like first_j_loop etc.
     950              : 
     951              :       !! LibGint follows the same patter, distributing integrals over mpi and openmp with a shared-over-mpi
     952              :       !! density and fock matrix. The main differences are that the fock matrix is not in a valid state
     953              :       !! until after the libGint_get_fock_matrix has returned -in approximately a thousand lines-,
     954              :       !! and the integrals are not saved in memory, but recomputed each cycle
     955              : 
     956              :       do_dynamic_load_balancing = .TRUE.
     957              : 
     958              :       IF (n_threads == 1 .OR. do_disk_storage) do_dynamic_load_balancing = .FALSE.
     959              : 
     960              :       IF (do_dynamic_load_balancing) THEN
     961              :          my_bin_size = SIZE(actual_x_data%distribution_energy)
     962              :       ELSE
     963              :          my_bin_size = 1
     964              :       END IF
     965              :       !! We do not need the containers if MAX_MEM = 0
     966              :       IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
     967              :          !! IF new md step -> reinitialize containers
     968              :          IF (my_geo_change) THEN
     969              :             CALL dealloc_containers(actual_x_data%store_ints, memory_parameter%actual_memory_usage)
     970              :             CALL alloc_containers(actual_x_data%store_ints, my_bin_size)
     971              : 
     972              :             DO bin = 1, my_bin_size
     973              :                maxval_container => actual_x_data%store_ints%maxval_container(bin)
     974              :                integral_containers => actual_x_data%store_ints%integral_containers(:, bin)
     975              :                CALL hfx_init_container(maxval_container, memory_parameter%actual_memory_usage, .FALSE.)
     976              :                DO i = 1, 64
     977              :                   CALL hfx_init_container(integral_containers(i), memory_parameter%actual_memory_usage, .FALSE.)
     978              :                END DO
     979              :             END DO
     980              :          END IF
     981              : 
     982              :          !! Decompress the first cache for maxvals and integrals
     983              :          IF (.NOT. my_geo_change) THEN
     984              :             DO bin = 1, my_bin_size
     985              :                maxval_cache => actual_x_data%store_ints%maxval_cache(bin)
     986              :                maxval_container => actual_x_data%store_ints%maxval_container(bin)
     987              :                integral_caches => actual_x_data%store_ints%integral_caches(:, bin)
     988              :                integral_containers => actual_x_data%store_ints%integral_containers(:, bin)
     989              :                CALL hfx_decompress_first_cache(bits_max_val, maxval_cache, maxval_container, &
     990              :                                                memory_parameter%actual_memory_usage, .FALSE.)
     991              :                DO i = 1, 64
     992              :                   CALL hfx_decompress_first_cache(i, integral_caches(i), integral_containers(i), &
     993              :                                                   memory_parameter%actual_memory_usage, .FALSE.)
     994              :                END DO
     995              :             END DO
     996              :          END IF
     997              :       END IF
     998              : 
     999              :       !! Since the I/O routines are no thread-safe, i.e. the procedure to get the unit number, put a lock here
    1000              : !$OMP CRITICAL(hfxenergy_io_critical)
    1001              :       !! If we do disk storage, we have to initialize the containers/caches
    1002              :       IF (do_disk_storage) THEN
    1003              :          !! IF new md step -> reinitialize containers
    1004              :          IF (my_geo_change) THEN
    1005              :             CALL hfx_init_container(maxval_container_disk, memory_parameter%actual_memory_usage_disk, do_disk_storage)
    1006              :             DO i = 1, 64
    1007              :                CALL hfx_init_container(integral_containers_disk(i), memory_parameter%actual_memory_usage_disk, do_disk_storage)
    1008              :             END DO
    1009              :          END IF
    1010              :          !! Decompress the first cache for maxvals and integrals
    1011              :          IF (.NOT. my_geo_change) THEN
    1012              :             CALL hfx_decompress_first_cache(bits_max_val, maxval_cache_disk, maxval_container_disk, &
    1013              :                                             memory_parameter%actual_memory_usage_disk, .TRUE.)
    1014              :             DO i = 1, 64
    1015              :                CALL hfx_decompress_first_cache(i, integral_caches_disk(i), integral_containers_disk(i), &
    1016              :                                                memory_parameter%actual_memory_usage_disk, .TRUE.)
    1017              :             END DO
    1018              :          END IF
    1019              :       END IF
    1020              : !$OMP END CRITICAL(hfxenergy_io_critical)
    1021              : 
    1022              : !$OMP BARRIER
    1023              : !$OMP MASTER
    1024              : 
    1025              :       IF (do_dynamic_load_balancing) THEN
    1026              :          ! ** Lets construct the task list
    1027              :          shm_total_bins = 0
    1028              :          DO i = 1, n_threads
    1029              :             shm_total_bins = shm_total_bins + SIZE(x_data(irep, i)%distribution_energy)
    1030              :          END DO
    1031              :          ALLOCATE (tmp_task_list(shm_total_bins))
    1032              :          shm_task_counter = 0
    1033              :          DO i = 1, n_threads
    1034              :             DO bin = 1, SIZE(x_data(irep, i)%distribution_energy)
    1035              :                shm_task_counter = shm_task_counter + 1
    1036              :                tmp_task_list(shm_task_counter)%thread_id = i
    1037              :                tmp_task_list(shm_task_counter)%bin_id = bin
    1038              :                tmp_task_list(shm_task_counter)%cost = x_data(irep, i)%distribution_energy(bin)%cost
    1039              :             END DO
    1040              :          END DO
    1041              : 
    1042              :          ! ** Now sort the task list
    1043              :          ALLOCATE (tmp_task_list_cost(shm_total_bins))
    1044              :          ALLOCATE (tmp_index(shm_total_bins))
    1045              : 
    1046              :          DO i = 1, shm_total_bins
    1047              :             tmp_task_list_cost(i) = tmp_task_list(i)%cost
    1048              :          END DO
    1049              : 
    1050              :          CALL sort(tmp_task_list_cost, shm_total_bins, tmp_index)
    1051              : 
    1052              :          ALLOCATE (shm_master_x_data%task_list(shm_total_bins))
    1053              : 
    1054              :          DO i = 1, shm_total_bins
    1055              :             shm_master_x_data%task_list(i) = tmp_task_list(tmp_index(shm_total_bins - i + 1))
    1056              :          END DO
    1057              : 
    1058              :          shm_task_list => shm_master_x_data%task_list
    1059              :          shm_task_counter = 0
    1060              : 
    1061              :          DEALLOCATE (tmp_task_list_cost, tmp_index, tmp_task_list)
    1062              :       END IF
    1063              : !$OMP END MASTER
    1064              : !$OMP BARRIER
    1065              : 
    1066              :       IF (my_bin_size > 0) THEN
    1067              :          maxval_container => actual_x_data%store_ints%maxval_container(1)
    1068              :          maxval_cache => actual_x_data%store_ints%maxval_cache(1)
    1069              : 
    1070              :          integral_containers => actual_x_data%store_ints%integral_containers(:, 1)
    1071              :          integral_caches => actual_x_data%store_ints%integral_caches(:, 1)
    1072              :       END IF
    1073              : 
    1074              : !$OMP BARRIER
    1075              : !$OMP MASTER
    1076              :       CALL timeset(routineN//"_main", handle_main)
    1077              : !$OMP END MASTER
    1078              : !$OMP BARRIER
    1079              : 
    1080              :       coeffs_kind_max0 = MAXVAL(screen_coeffs_kind(:, :)%x(2))
    1081              :       ALLOCATE (set_list_ij((max_set*load_balance_parameter%block_size)**2))
    1082              :       ALLOCATE (set_list_kl((max_set*load_balance_parameter%block_size)**2))
    1083              : 
    1084              : !$OMP BARRIER
    1085              : !$OMP MASTER
    1086              : 
    1087              :       !! precalculate maximum density matrix elements in blocks
    1088              :       actual_x_data%pmax_block = 0.0_dp
    1089              :       shm_pmax_block => actual_x_data%pmax_block
    1090              :       IF (do_p_screening) THEN
    1091              :          DO iatom_block = 1, SIZE(actual_x_data%blocks)
    1092              :             iatom_start = actual_x_data%blocks(iatom_block)%istart
    1093              :             iatom_end = actual_x_data%blocks(iatom_block)%iend
    1094              :             DO jatom_block = 1, SIZE(actual_x_data%blocks)
    1095              :                jatom_start = actual_x_data%blocks(jatom_block)%istart
    1096              :                jatom_end = actual_x_data%blocks(jatom_block)%iend
    1097              :                shm_pmax_block(iatom_block, jatom_block) = MAXVAL(shm_pmax_atom(iatom_start:iatom_end, jatom_start:jatom_end))
    1098              :             END DO
    1099              :          END DO
    1100              :       END IF
    1101              :       shm_atomic_pair_list => actual_x_data%atomic_pair_list
    1102              :       IF (my_geo_change) THEN
    1103              :          CALL build_atomic_pair_list(natom, shm_atomic_pair_list, kind_of, basis_parameter, particle_set, &
    1104              :                                      do_periodic, screen_coeffs_kind, coeffs_kind_max0, log10_eps_schwarz, cell, &
    1105              :                                      actual_x_data%blocks)
    1106              :       END IF
    1107              : 
    1108              :       my_bin_size = SIZE(actual_x_data%distribution_energy)
    1109              :       ! reset timings for the new SCF round
    1110              :       IF (my_geo_change) THEN
    1111              :          DO bin = 1, my_bin_size
    1112              :             actual_x_data%distribution_energy(bin)%time_first_scf = 0.0_dp
    1113              :             actual_x_data%distribution_energy(bin)%time_other_scf = 0.0_dp
    1114              :             actual_x_data%distribution_energy(bin)%time_forces = 0.0_dp
    1115              :          END DO
    1116              :       END IF
    1117              : !$OMP END MASTER
    1118              : !$OMP BARRIER
    1119              : 
    1120              :       my_bin_size = SIZE(actual_x_data%distribution_energy)
    1121              :       nblocks = load_balance_parameter%nblocks
    1122              : 
    1123              :       bins_left = .TRUE.
    1124              :       do_it = .TRUE.
    1125              :       bin = 0
    1126              :       ! Main cycle starts here
    1127              :       DO WHILE (bins_left)
    1128              :          ! Check if this thread can run this bin
    1129              :          IF (.NOT. do_dynamic_load_balancing) THEN
    1130              :             bin = bin + 1
    1131              :             IF (bin > my_bin_size) THEN
    1132              :                do_it = .FALSE.
    1133              :                bins_left = .FALSE.
    1134              :             ELSE
    1135              :                do_it = .TRUE.
    1136              :                bins_left = .TRUE.
    1137              :                distribution_energy => actual_x_data%distribution_energy(bin)
    1138              :             END IF
    1139              :          ELSE
    1140              : !$OMP CRITICAL(hfxenergy_critical)
    1141              :             shm_task_counter = shm_task_counter + 1
    1142              :             IF (shm_task_counter <= shm_total_bins) THEN
    1143              :                my_thread_id = shm_task_list(shm_task_counter)%thread_id
    1144              :                my_bin_id = shm_task_list(shm_task_counter)%bin_id
    1145              :                IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
    1146              :                   maxval_cache => x_data(irep, my_thread_id)%store_ints%maxval_cache(my_bin_id)
    1147              :                   maxval_container => x_data(irep, my_thread_id)%store_ints%maxval_container(my_bin_id)
    1148              :                   integral_caches => x_data(irep, my_thread_id)%store_ints%integral_caches(:, my_bin_id)
    1149              :                   integral_containers => x_data(irep, my_thread_id)%store_ints%integral_containers(:, my_bin_id)
    1150              :                END IF
    1151              :                distribution_energy => x_data(irep, my_thread_id)%distribution_energy(my_bin_id)
    1152              :                do_it = .TRUE.
    1153              :                bins_left = .TRUE.
    1154              :                IF (my_geo_change) THEN
    1155              :                   distribution_energy%ram_counter = HUGE(distribution_energy%ram_counter)
    1156              :                END IF
    1157              :                counter = 0_Int_8
    1158              :             ELSE
    1159              :                do_it = .FALSE.
    1160              :                bins_left = .FALSE.
    1161              :             END IF
    1162              : !$OMP END CRITICAL(hfxenergy_critical)
    1163              :          END IF
    1164              :          IF (.NOT. do_it) CYCLE
    1165              : 
    1166              : !$OMP MASTER
    1167              :          CALL timeset(routineN//"_bin", handle_bin)
    1168              : !$OMP END MASTER
    1169              : 
    1170              :          bintime_start = m_walltime()
    1171              :          my_istart = distribution_energy%istart
    1172              :          my_current_counter = 0
    1173              :          IF (distribution_energy%number_of_atom_quartets == 0 .OR. &
    1174              :              my_istart == -1_int_8) my_istart = nblocks**4
    1175              :          atomic_blocks: DO atom_block = my_istart, nblocks**4 - 1, n_processes
    1176              :             latom_block = INT(MODULO(atom_block, nblocks)) + 1
    1177              :             tmp_block = atom_block/nblocks
    1178              :             katom_block = INT(MODULO(tmp_block, nblocks)) + 1
    1179              :             IF (latom_block < katom_block) CYCLE atomic_blocks
    1180              :             tmp_block = tmp_block/nblocks
    1181              :             jatom_block = INT(MODULO(tmp_block, nblocks)) + 1
    1182              :             tmp_block = tmp_block/nblocks
    1183              :             iatom_block = INT(MODULO(tmp_block, nblocks)) + 1
    1184              :             IF (jatom_block < iatom_block) CYCLE atomic_blocks
    1185              :             my_current_counter = my_current_counter + 1
    1186              :             IF (my_current_counter > distribution_energy%number_of_atom_quartets) EXIT atomic_blocks
    1187              : 
    1188              :             iatom_start = actual_x_data%blocks(iatom_block)%istart
    1189              :             iatom_end = actual_x_data%blocks(iatom_block)%iend
    1190              :             jatom_start = actual_x_data%blocks(jatom_block)%istart
    1191              :             jatom_end = actual_x_data%blocks(jatom_block)%iend
    1192              :             katom_start = actual_x_data%blocks(katom_block)%istart
    1193              :             katom_end = actual_x_data%blocks(katom_block)%iend
    1194              :             latom_start = actual_x_data%blocks(latom_block)%istart
    1195              :             latom_end = actual_x_data%blocks(latom_block)%iend
    1196              : 
    1197              :             pmax_blocks = MAX(shm_pmax_block(katom_block, iatom_block), &
    1198              :                               shm_pmax_block(latom_block, jatom_block), &
    1199              :                               shm_pmax_block(latom_block, iatom_block), &
    1200              :                               shm_pmax_block(katom_block, jatom_block))
    1201              : 
    1202              :             IF (2.0_dp*coeffs_kind_max0 + pmax_blocks < log10_eps_schwarz) CYCLE atomic_blocks
    1203              : 
    1204              :             CALL build_pair_list(natom, list_ij, set_list_ij, iatom_start, iatom_end, &
    1205              :                                  jatom_start, jatom_end, &
    1206              :                                  kind_of, basis_parameter, particle_set, &
    1207              :                                  do_periodic, screen_coeffs_set, screen_coeffs_kind, &
    1208              :                                  coeffs_kind_max0, log10_eps_schwarz, cell, pmax_blocks, &
    1209              :                                  shm_atomic_pair_list)
    1210              : 
    1211              :             CALL build_pair_list(natom, list_kl, set_list_kl, katom_start, katom_end, &
    1212              :                                  latom_start, latom_end, &
    1213              :                                  kind_of, basis_parameter, particle_set, &
    1214              :                                  do_periodic, screen_coeffs_set, screen_coeffs_kind, &
    1215              :                                  coeffs_kind_max0, log10_eps_schwarz, cell, pmax_blocks, &
    1216              :                                  shm_atomic_pair_list)
    1217              : 
    1218              :             DO i_list_ij = 1, list_ij%n_element
    1219              : 
    1220              :                iatom = list_ij%elements(i_list_ij)%pair(1)
    1221              :                jatom = list_ij%elements(i_list_ij)%pair(2)
    1222              :                i_set_list_ij_start = list_ij%elements(i_list_ij)%set_bounds(1)
    1223              :                i_set_list_ij_stop = list_ij%elements(i_list_ij)%set_bounds(2)
    1224              :                ikind = list_ij%elements(i_list_ij)%kind_pair(1)
    1225              :                jkind = list_ij%elements(i_list_ij)%kind_pair(2)
    1226              :                ra = list_ij%elements(i_list_ij)%r1
    1227              :                rb = list_ij%elements(i_list_ij)%r2
    1228              :                rab2 = list_ij%elements(i_list_ij)%dist2
    1229              : 
    1230              :                la_max => basis_parameter(ikind)%lmax
    1231              :                la_min => basis_parameter(ikind)%lmin
    1232              :                npgfa => basis_parameter(ikind)%npgf
    1233              :                nseta = basis_parameter(ikind)%nset
    1234              :                zeta => basis_parameter(ikind)%zet
    1235              :                nsgfa => basis_parameter(ikind)%nsgf
    1236              :                nsgfl_a => basis_parameter(ikind)%nsgfl
    1237              : 
    1238              :                lb_max => basis_parameter(jkind)%lmax
    1239              :                lb_min => basis_parameter(jkind)%lmin
    1240              :                npgfb => basis_parameter(jkind)%npgf
    1241              :                nsetb = basis_parameter(jkind)%nset
    1242              :                zetb => basis_parameter(jkind)%zet
    1243              :                nsgfb => basis_parameter(jkind)%nsgf
    1244              :                nsgfl_b => basis_parameter(jkind)%nsgfl
    1245              : 
    1246              :                DO i_list_kl = 1, list_kl%n_element
    1247              :                   katom = list_kl%elements(i_list_kl)%pair(1)
    1248              :                   latom = list_kl%elements(i_list_kl)%pair(2)
    1249              : 
    1250              :                   IF (.NOT. (katom + latom <= iatom + jatom)) CYCLE
    1251              :                   IF (((iatom + jatom) == (katom + latom)) .AND. (katom < iatom)) CYCLE
    1252              :                   i_set_list_kl_start = list_kl%elements(i_list_kl)%set_bounds(1)
    1253              :                   i_set_list_kl_stop = list_kl%elements(i_list_kl)%set_bounds(2)
    1254              :                   kkind = list_kl%elements(i_list_kl)%kind_pair(1)
    1255              :                   lkind = list_kl%elements(i_list_kl)%kind_pair(2)
    1256              :                   rc = list_kl%elements(i_list_kl)%r1
    1257              :                   rd = list_kl%elements(i_list_kl)%r2
    1258              :                   rcd2 = list_kl%elements(i_list_kl)%dist2
    1259              : 
    1260              :                   IF (do_p_screening) THEN
    1261              :                      pmax_atom = MAX(shm_pmax_atom(katom, iatom), &
    1262              :                                      shm_pmax_atom(latom, jatom), &
    1263              :                                      shm_pmax_atom(latom, iatom), &
    1264              :                                      shm_pmax_atom(katom, jatom))
    1265              :                   ELSE
    1266              :                      pmax_atom = 0.0_dp
    1267              :                   END IF
    1268              : 
    1269              :                   screen_kind_ij = screen_coeffs_kind(jkind, ikind)%x(1)*rab2 + &
    1270              :                                    screen_coeffs_kind(jkind, ikind)%x(2)
    1271              :                   screen_kind_kl = screen_coeffs_kind(lkind, kkind)%x(1)*rcd2 + &
    1272              :                                    screen_coeffs_kind(lkind, kkind)%x(2)
    1273              : 
    1274              :                   IF (screen_kind_ij + screen_kind_kl + pmax_atom < log10_eps_schwarz) CYCLE
    1275              : 
    1276              :                   !! we want to be consistent with the KS matrix. If none of the atomic indices
    1277              :                   !! is associated cycle
    1278              :                   IF (.NOT. (shm_is_assoc_atomic_block(latom, iatom) >= 1 .AND. &
    1279              :                              shm_is_assoc_atomic_block(katom, iatom) >= 1 .AND. &
    1280              :                              shm_is_assoc_atomic_block(katom, jatom) >= 1 .AND. &
    1281              :                              shm_is_assoc_atomic_block(latom, jatom) >= 1)) CYCLE
    1282              : 
    1283              :                   !! calculate symmetry_factor according to degeneracy of atomic quartet
    1284              :                   symm_fac = 0.5_dp
    1285              :                   IF (iatom == jatom) symm_fac = symm_fac*2.0_dp
    1286              :                   IF (katom == latom) symm_fac = symm_fac*2.0_dp
    1287              :                   IF (iatom == katom .AND. jatom == latom .AND. iatom /= jatom .AND. katom /= latom) symm_fac = symm_fac*2.0_dp
    1288              :                   IF (iatom == katom .AND. iatom == jatom .AND. katom == latom) symm_fac = symm_fac*2.0_dp
    1289              :                   symm_fac = 1.0_dp/symm_fac
    1290              : 
    1291              :                   lc_max => basis_parameter(kkind)%lmax
    1292              :                   lc_min => basis_parameter(kkind)%lmin
    1293              :                   npgfc => basis_parameter(kkind)%npgf
    1294              :                   zetc => basis_parameter(kkind)%zet
    1295              :                   nsgfc => basis_parameter(kkind)%nsgf
    1296              :                   nsgfl_c => basis_parameter(kkind)%nsgfl
    1297              : 
    1298              :                   ld_max => basis_parameter(lkind)%lmax
    1299              :                   ld_min => basis_parameter(lkind)%lmin
    1300              :                   npgfd => basis_parameter(lkind)%npgf
    1301              :                   zetd => basis_parameter(lkind)%zet
    1302              :                   nsgfd => basis_parameter(lkind)%nsgf
    1303              :                   nsgfl_d => basis_parameter(lkind)%nsgfl
    1304              : 
    1305              :                   ! Note: shm_atomic_block_offset is already symmetric
    1306              :                   ! see get_atomic_block_maps in hfx_communication.F
    1307              :                   atomic_offset_bd = shm_atomic_block_offset(jatom, latom)
    1308              :                   atomic_offset_bc = shm_atomic_block_offset(jatom, katom)
    1309              :                   atomic_offset_ad = shm_atomic_block_offset(iatom, latom)
    1310              :                   atomic_offset_ac = shm_atomic_block_offset(iatom, katom)
    1311              : 
    1312              :                   IF (jatom < latom) THEN
    1313              :                      offset_bd_set => shm_set_offset(:, :, lkind, jkind)
    1314              :                   ELSE
    1315              :                      offset_bd_set => shm_set_offset(:, :, jkind, lkind)
    1316              :                   END IF
    1317              :                   IF (jatom < katom) THEN
    1318              :                      offset_bc_set => shm_set_offset(:, :, kkind, jkind)
    1319              :                   ELSE
    1320              :                      offset_bc_set => shm_set_offset(:, :, jkind, kkind)
    1321              :                   END IF
    1322              :                   IF (iatom < latom) THEN
    1323              :                      offset_ad_set => shm_set_offset(:, :, lkind, ikind)
    1324              :                   ELSE
    1325              :                      offset_ad_set => shm_set_offset(:, :, ikind, lkind)
    1326              :                   END IF
    1327              :                   IF (iatom < katom) THEN
    1328              :                      offset_ac_set => shm_set_offset(:, :, kkind, ikind)
    1329              :                   ELSE
    1330              :                      offset_ac_set => shm_set_offset(:, :, ikind, kkind)
    1331              :                   END IF
    1332              : 
    1333              :                   IF (do_p_screening) THEN
    1334              :                      swap_id = 0
    1335              :                      kind_kind_idx = INT(get_1D_idx(kkind, ikind, INT(nkind, int_8)))
    1336              :                      IF (ikind >= kkind) THEN
    1337              :                         ptr_p_1 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1338              :                                                                        actual_x_data%map_atom_to_kind_atom(katom), &
    1339              :                                                                        actual_x_data%map_atom_to_kind_atom(iatom))
    1340              :                      ELSE
    1341              :                         ptr_p_1 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1342              :                                                                        actual_x_data%map_atom_to_kind_atom(iatom), &
    1343              :                                                                        actual_x_data%map_atom_to_kind_atom(katom))
    1344              :                         swap_id = swap_id + 1
    1345              :                      END IF
    1346              :                      kind_kind_idx = INT(get_1D_idx(lkind, jkind, INT(nkind, int_8)))
    1347              :                      IF (jkind >= lkind) THEN
    1348              :                         ptr_p_2 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1349              :                                                                        actual_x_data%map_atom_to_kind_atom(latom), &
    1350              :                                                                        actual_x_data%map_atom_to_kind_atom(jatom))
    1351              :                      ELSE
    1352              :                         ptr_p_2 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1353              :                                                                        actual_x_data%map_atom_to_kind_atom(jatom), &
    1354              :                                                                        actual_x_data%map_atom_to_kind_atom(latom))
    1355              :                         swap_id = swap_id + 2
    1356              :                      END IF
    1357              :                      kind_kind_idx = INT(get_1D_idx(lkind, ikind, INT(nkind, int_8)))
    1358              :                      IF (ikind >= lkind) THEN
    1359              :                         ptr_p_3 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1360              :                                                                        actual_x_data%map_atom_to_kind_atom(latom), &
    1361              :                                                                        actual_x_data%map_atom_to_kind_atom(iatom))
    1362              :                      ELSE
    1363              :                         ptr_p_3 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1364              :                                                                        actual_x_data%map_atom_to_kind_atom(iatom), &
    1365              :                                                                        actual_x_data%map_atom_to_kind_atom(latom))
    1366              :                         swap_id = swap_id + 4
    1367              :                      END IF
    1368              :                      kind_kind_idx = INT(get_1D_idx(kkind, jkind, INT(nkind, int_8)))
    1369              :                      IF (jkind >= kkind) THEN
    1370              :                         ptr_p_4 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1371              :                                                                        actual_x_data%map_atom_to_kind_atom(katom), &
    1372              :                                                                        actual_x_data%map_atom_to_kind_atom(jatom))
    1373              :                      ELSE
    1374              :                         ptr_p_4 => shm_initial_p(kind_kind_idx)%p_kind(:, :, &
    1375              :                                                                        actual_x_data%map_atom_to_kind_atom(jatom), &
    1376              :                                                                        actual_x_data%map_atom_to_kind_atom(katom))
    1377              :                         swap_id = swap_id + 8
    1378              :                      END IF
    1379              :                   END IF
    1380              : 
    1381              :                   !! At this stage, check for memory used in compression
    1382              :                   IF (my_geo_change) THEN
    1383              :                      IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
    1384              :                         ! ** We know the maximum amount of integrals that we can store per MPI-process
    1385              :                         ! ** Now we need to sum the current memory usage among all openMP threads
    1386              :                         ! ** We can just read what is currently stored on the corresponding x_data type
    1387              :                         ! ** If this is thread i and it tries to read the data from thread j, that is
    1388              :                         ! ** currently writing that data, we just dont care, because the possible error
    1389              :                         ! ** is of the order of CACHE_SIZE
    1390              :                         mem_compression_counter = 0
    1391              :                         DO i = 1, n_threads
    1392              : !$OMP                   ATOMIC READ
    1393              :                            tmp_i4 = x_data(irep, i)%memory_parameter%actual_memory_usage
    1394              :                            mem_compression_counter = mem_compression_counter + &
    1395              :                                                      tmp_i4*memory_parameter%cache_size
    1396              :                         END DO
    1397              :                         IF (mem_compression_counter > memory_parameter%max_compression_counter) THEN
    1398              :                            buffer_overflow = .TRUE.
    1399              :                            IF (do_dynamic_load_balancing) THEN
    1400              :                               distribution_energy%ram_counter = counter
    1401              :                            ELSE
    1402              :                               memory_parameter%ram_counter = counter
    1403              :                            END IF
    1404              :                         ELSE
    1405              :                            counter = counter + 1
    1406              :                            buffer_overflow = .FALSE.
    1407              :                         END IF
    1408              :                      END IF
    1409              :                   ELSE
    1410              :                      IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
    1411              :                         IF (do_dynamic_load_balancing) THEN
    1412              :                            IF (distribution_energy%ram_counter == counter) THEN
    1413              :                               buffer_overflow = .TRUE.
    1414              :                            ELSE
    1415              :                               counter = counter + 1
    1416              :                               buffer_overflow = .FALSE.
    1417              :                            END IF
    1418              : 
    1419              :                         ELSE
    1420              :                            IF (memory_parameter%ram_counter == counter) THEN
    1421              :                               buffer_overflow = .TRUE.
    1422              :                            ELSE
    1423              :                               counter = counter + 1
    1424              :                               buffer_overflow = .FALSE.
    1425              :                            END IF
    1426              :                         END IF
    1427              :                      END IF
    1428              :                   END IF
    1429              : 
    1430              :                   IF (buffer_overflow .AND. do_disk_storage) THEN
    1431              :                      use_disk_storage = .TRUE.
    1432              :                      buffer_overflow = .FALSE.
    1433              :                   END IF
    1434              : 
    1435              :                   IF (use_disk_storage) THEN
    1436              : !$OMP               ATOMIC READ
    1437              :                      tmp_i4 = memory_parameter%actual_memory_usage_disk
    1438              :                      mem_compression_counter_disk = tmp_i4*memory_parameter%cache_size
    1439              :                      IF (mem_compression_counter_disk > memory_parameter%max_compression_counter_disk) THEN
    1440              :                         buffer_overflow = .TRUE.
    1441              :                         use_disk_storage = .FALSE.
    1442              :                      END IF
    1443              :                   END IF
    1444              : 
    1445              :                   DO i_set_list_ij = i_set_list_ij_start, i_set_list_ij_stop
    1446              :                      iset = set_list_ij(i_set_list_ij)%pair(1)
    1447              :                      jset = set_list_ij(i_set_list_ij)%pair(2)
    1448              : 
    1449              :                      ncob = npgfb(jset)*ncoset(lb_max(jset))
    1450              :                      max_val1 = screen_coeffs_set(jset, iset, jkind, ikind)%x(1)*rab2 + &
    1451              :                                 screen_coeffs_set(jset, iset, jkind, ikind)%x(2)
    1452              : 
    1453              :                      IF (max_val1 + screen_kind_kl + pmax_atom < log10_eps_schwarz) CYCLE
    1454              : 
    1455              :                      DO i_set_list_kl = i_set_list_kl_start, i_set_list_kl_stop
    1456              :                         kset = set_list_kl(i_set_list_kl)%pair(1)
    1457              :                         lset = set_list_kl(i_set_list_kl)%pair(2)
    1458              : 
    1459              :                         max_val2_set = (screen_coeffs_set(lset, kset, lkind, kkind)%x(1)*rcd2 + &
    1460              :                                         screen_coeffs_set(lset, kset, lkind, kkind)%x(2))
    1461              :                         max_val2 = max_val1 + max_val2_set
    1462              : 
    1463              :                         !! Near field screening
    1464              :                         IF (max_val2 + pmax_atom < log10_eps_schwarz) CYCLE
    1465              :                         !! get max_vals if we screen on initial density
    1466              :                         IF (do_p_screening) THEN
    1467              :                            CALL get_pmax_val(ptr_p_1, ptr_p_2, ptr_p_3, ptr_p_4, &
    1468              :                                              iset, jset, kset, lset, &
    1469              :                                              pmax_entry, swap_id)
    1470              :                         ELSE
    1471              :                            pmax_entry = 0.0_dp
    1472              :                         END IF
    1473              :                         log10_pmax = pmax_entry
    1474              :                         max_val2 = max_val2 + log10_pmax
    1475              :                         IF (max_val2 < log10_eps_schwarz) CYCLE
    1476              :                         pmax_entry = EXP(log10_pmax*ln_10)
    1477              : 
    1478              :                         ! libGint can only run in direct mode at the moment
    1479              :                         ! so there is no need to check the buffers
    1480              :                         if (use_libGint) then
    1481              :                            tmp_screen_pgf1 => screen_coeffs_pgf(:, :, jset, iset, jkind, ikind)
    1482              :                            tmp_screen_pgf2 => screen_coeffs_pgf(:, :, lset, kset, lkind, kkind)
    1483              :                            ! TODO a more modern approach in which the call is more like
    1484              :                            ! call coulom_4_gpu( HFX_data, iset, jset, kset, lset )
    1485              :                            call libGint_coulomb4( &
    1486              :                               iatom, jatom, katom, latom, iset, jset, kset, lset, &
    1487              :                               ra, rb, rc, rd, &
    1488              :                               npgfa(iset), npgfb(jset), npgfc(kset), npgfd(lset), &
    1489              :                               potential_parameter, &
    1490              :                               screen_coeffs_set(jset, iset, jkind, ikind)%x, &
    1491              :                               screen_coeffs_set(lset, kset, lkind, kkind)%x, &
    1492              :                               log10_pmax, log10_eps_schwarz, &
    1493              :                               tmp_screen_pgf1, tmp_screen_pgf2, &
    1494              :                               actual_x_data%neighbor_cells, cell, do_periodic, screened)
    1495              : 
    1496              :                            if (.not. screened) then
    1497              : 
    1498              :                               ! TODO a more modern approach in which the call is more like
    1499              :                               ! call update_fock_matrix_gpu( HFX_data, iset, jset, kset, lset )
    1500              :                               call libGint_update_fock_matrix( &
    1501              :                                  symm_fac, &
    1502              :                                  iatom, jatom, katom, latom, &
    1503              :                                  iset, jset, kset, lset, &
    1504              :                                  atomic_offset_ac, atomic_offset_ad, atomic_offset_bc, atomic_offset_bd, &
    1505              :                                  offset_ac_set, offset_ad_set, offset_bc_set, offset_bd_set, &
    1506              :                                  nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), &
    1507              :                                  la_min(iset), la_max(iset), lb_min(jset), lb_max(jset), &
    1508              :                                  lc_min(kset), lc_max(kset), ld_min(lset), ld_max(lset), &
    1509              :                                  nsgfl_a, nsgfl_b, nsgfl_c, nsgfl_d)
    1510              : 
    1511              :                            end if
    1512              :                         end if
    1513              :                         ! Run using libint as integral engine
    1514              :                         if_use_libint: if (use_libint) then
    1515              :                            !! store current number of integrals, update total number and number of integrals in buffer
    1516              :                            current_counter = nsgfa(iset)*nsgfb(jset)*nsgfc(kset)*nsgfd(lset)
    1517              :                            IF (buffer_overflow) THEN
    1518              :                               neris_onthefly = neris_onthefly + current_counter
    1519              :                            END IF
    1520              : 
    1521              :                            !! Get integrals from buffer and update Kohn-Sham matrix
    1522              :                            IF (.NOT. buffer_overflow .AND. .NOT. my_geo_change) THEN
    1523              :                               nints = current_counter
    1524              :                               IF (.NOT. use_disk_storage) THEN
    1525              :                                  CALL hfx_get_single_cache_element( &
    1526              :                                     estimate_to_store_int, 6, &
    1527              :                                     maxval_cache, maxval_container, memory_parameter%actual_memory_usage, &
    1528              :                                     use_disk_storage)
    1529              :                               ELSE
    1530              :                                  CALL hfx_get_single_cache_element( &
    1531              :                                     estimate_to_store_int, 6, &
    1532              :                                     maxval_cache_disk, maxval_container_disk, memory_parameter%actual_memory_usage_disk, &
    1533              :                                     use_disk_storage)
    1534              :                               END IF
    1535              :                               spherical_estimate = SET_EXPONENT(1.0_dp, estimate_to_store_int + 1)
    1536              :                               IF (spherical_estimate*pmax_entry < eps_schwarz) CYCLE
    1537              :                               nbits = EXPONENT(ANINT(spherical_estimate*pmax_entry/eps_storage)) + 1
    1538              :                               buffer_left = nints
    1539              :                               buffer_start = 1
    1540              :                               IF (.NOT. use_disk_storage) THEN
    1541              :                                  neris_incore = neris_incore + INT(nints, int_8)
    1542              :                               ELSE
    1543              :                                  neris_disk = neris_disk + INT(nints, int_8)
    1544              :                               END IF
    1545              :                               DO WHILE (buffer_left > 0)
    1546              :                                  buffer_size = MIN(buffer_left, cache_size)
    1547              :                                  IF (.NOT. use_disk_storage) THEN
    1548              :                                     CALL hfx_get_mult_cache_elements(primitive_integrals(buffer_start), &
    1549              :                                                                      buffer_size, nbits, &
    1550              :                                                                      integral_caches(nbits), &
    1551              :                                                                      integral_containers(nbits), &
    1552              :                                                                      eps_storage, pmax_entry, &
    1553              :                                                                      memory_parameter%actual_memory_usage, &
    1554              :                                                                      use_disk_storage)
    1555              :                                  ELSE
    1556              :                                     CALL hfx_get_mult_cache_elements(primitive_integrals(buffer_start), &
    1557              :                                                                      buffer_size, nbits, &
    1558              :                                                                      integral_caches_disk(nbits), &
    1559              :                                                                      integral_containers_disk(nbits), &
    1560              :                                                                      eps_storage, pmax_entry, &
    1561              :                                                                      memory_parameter%actual_memory_usage_disk, &
    1562              :                                                                      use_disk_storage)
    1563              :                                  END IF
    1564              :                                  buffer_left = buffer_left - buffer_size
    1565              :                                  buffer_start = buffer_start + buffer_size
    1566              :                               END DO
    1567              :                            END IF
    1568              :                            !! Calculate integrals if we run out of buffer or the geometry did change
    1569              :                            IF (my_geo_change .OR. buffer_overflow) THEN
    1570              : 
    1571              :                               max_contraction_val = max_contraction(iset, iatom)* &
    1572              :                                                     max_contraction(jset, jatom)* &
    1573              :                                                     max_contraction(kset, katom)* &
    1574              :                                                     max_contraction(lset, latom)*pmax_entry
    1575              :                               tmp_R_1 => radii_pgf(:, :, jset, iset, jkind, ikind)
    1576              :                               tmp_R_2 => radii_pgf(:, :, lset, kset, lkind, kkind)
    1577              :                               tmp_screen_pgf1 => screen_coeffs_pgf(:, :, jset, iset, jkind, ikind)
    1578              :                               tmp_screen_pgf2 => screen_coeffs_pgf(:, :, lset, kset, lkind, kkind)
    1579              : 
    1580              :                               CALL coulomb4(actual_x_data%eri4_context, ra, rb, rc, rd, &
    1581              :                                             npgfa(iset), npgfb(jset), npgfc(kset), npgfd(lset), &
    1582              :                                             la_min(iset), la_max(iset), lb_min(jset), lb_max(jset), &
    1583              :                                             lc_min(kset), lc_max(kset), ld_min(lset), ld_max(lset), &
    1584              :                                             nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), &
    1585              :                                             zeta(1:npgfa(iset), iset), zetb(1:npgfb(jset), jset), &
    1586              :                                             zetc(1:npgfc(kset), kset), zetd(1:npgfd(lset), lset), &
    1587              :                                             primitive_integrals, &
    1588              :                                             potential_parameter, &
    1589              :                                             actual_x_data%neighbor_cells, screen_coeffs_set(jset, iset, jkind, ikind)%x, &
    1590              :                                             screen_coeffs_set(lset, kset, lkind, kkind)%x, eps_schwarz, &
    1591              :                                             max_contraction_val, cartesian_estimate, cell, neris_tmp, &
    1592              :                                             log10_pmax, log10_eps_schwarz, &
    1593              :                                             tmp_R_1, tmp_R_2, tmp_screen_pgf1, tmp_screen_pgf2, &
    1594              :                                             pgf_list_ij, pgf_list_kl, &
    1595              :                                             basis_parameter(ikind)%contraction(:, iset), &
    1596              :                                             basis_parameter(jkind)%contraction(:, jset), &
    1597              :                                             basis_parameter(kkind)%contraction(:, kset), &
    1598              :                                             basis_parameter(lkind)%contraction(:, lset), &
    1599              :                                             ee_work2, ee_buffer1, ee_buffer2, &
    1600              :                                             nimages, do_periodic)
    1601              : 
    1602              :                               nints = nsgfa(iset)*nsgfb(jset)*nsgfc(kset)*nsgfd(lset)
    1603              :                               neris_total = neris_total + nints
    1604              :                               nprim_ints = nprim_ints + neris_tmp
    1605              : 
    1606              :                               !! Compress the array for storage
    1607              :                               spherical_estimate = 0.0_dp
    1608              :                               IF (cartesian_estimate /= 0.0_dp) THEN
    1609              :                                  DO i = 1, nints
    1610              :                                     spherical_estimate = MAX(spherical_estimate, ABS(primitive_integrals(i)))
    1611              :                                  END DO
    1612              :                               ELSE IF (buffer_overflow) THEN
    1613              :                                  CYCLE
    1614              :                               END IF
    1615              : 
    1616              :                               IF (spherical_estimate == 0.0_dp) spherical_estimate = TINY(spherical_estimate)
    1617              :                               estimate_to_store_int = EXPONENT(spherical_estimate)
    1618              :                               estimate_to_store_int = MAX(estimate_to_store_int, -15_int_8)
    1619              : 
    1620              :                               IF (.NOT. buffer_overflow .AND. my_geo_change) THEN
    1621              :                                  IF (.NOT. use_disk_storage) THEN
    1622              :                                     CALL hfx_add_single_cache_element( &
    1623              :                                        estimate_to_store_int, 6, &
    1624              :                                        maxval_cache, maxval_container, memory_parameter%actual_memory_usage, &
    1625              :                                        use_disk_storage, max_val_memory)
    1626              :                                  ELSE
    1627              :                                     CALL hfx_add_single_cache_element( &
    1628              :                                        estimate_to_store_int, 6, &
    1629              :                                        maxval_cache_disk, maxval_container_disk, memory_parameter%actual_memory_usage_disk, &
    1630              :                                        use_disk_storage)
    1631              :                                  END IF
    1632              :                               END IF
    1633              :                               spherical_estimate = SET_EXPONENT(1.0_dp, estimate_to_store_int + 1)
    1634              :                               IF (spherical_estimate*pmax_entry < eps_schwarz) CYCLE
    1635              :                               IF (.NOT. buffer_overflow) THEN
    1636              :                                  nbits = EXPONENT(ANINT(spherical_estimate*pmax_entry/eps_storage)) + 1
    1637              : 
    1638              :                                  ! In case of a tight eps_storage threshold the number of significant
    1639              :                                  ! bits in the integer number NINT(value*pmax_entry/eps_storage) may
    1640              :                                  ! exceed the width of the storage element. As the compression algorithm
    1641              :                                  ! is designed for IEEE 754 double precision numbers, a 64-bit signed
    1642              :                                  ! integer variable which is used to store the result of this float-to-
    1643              :                                  ! integer conversion (we have no wish to use more memory for storing
    1644              :                                  ! compressed ERIs than it is needed for uncompressed ERIs) may overflow.
    1645              :                                  ! Abort with a meaningful message when it happens.
    1646              :                                  !
    1647              :                                  ! The magic number 63 stands for the number of magnitude bits
    1648              :                                  ! (64 bits minus one sign bit).
    1649              :                                  IF (nbits > 63) THEN
    1650              :                                     WRITE (eps_schwarz_min_str, '(ES10.3E2)') &
    1651              :                                        spherical_estimate*pmax_entry/ &
    1652              :                                        (SET_EXPONENT(1.0_dp, 63)*memory_parameter%eps_storage_scaling)
    1653              : 
    1654              :                                     WRITE (eps_scaling_str, '(ES10.3E2)') &
    1655              :                                        spherical_estimate*pmax_entry/(SET_EXPONENT(1.0_dp, 63)*eps_schwarz)
    1656              : 
    1657              :                                     CALL cp_abort(__LOCATION__, &
    1658              :                                                   "Overflow during ERI's compression. Please use a larger "// &
    1659              :                                                   "EPS_SCHWARZ threshold (above "//TRIM(ADJUSTL(eps_schwarz_min_str))// &
    1660              :                                                   ") or increase the EPS_STORAGE_SCALING factor above "// &
    1661              :                                                   TRIM(ADJUSTL(eps_scaling_str))//".")
    1662              :                                  END IF
    1663              : 
    1664              :                                  buffer_left = nints
    1665              :                                  buffer_start = 1
    1666              :                                  IF (.NOT. use_disk_storage) THEN
    1667              :                                     neris_incore = neris_incore + INT(nints, int_8)
    1668              :                                  ELSE
    1669              :                                     neris_disk = neris_disk + INT(nints, int_8)
    1670              :                                  END IF
    1671              :                                  DO WHILE (buffer_left > 0)
    1672              :                                     buffer_size = MIN(buffer_left, CACHE_SIZE)
    1673              :                                     IF (.NOT. use_disk_storage) THEN
    1674              :                                        CALL hfx_add_mult_cache_elements(primitive_integrals(buffer_start), &
    1675              :                                                                         buffer_size, nbits, &
    1676              :                                                                         integral_caches(nbits), &
    1677              :                                                                         integral_containers(nbits), &
    1678              :                                                                         eps_storage, pmax_entry, &
    1679              :                                                                         memory_parameter%actual_memory_usage, &
    1680              :                                                                         use_disk_storage)
    1681              :                                     ELSE
    1682              :                                        CALL hfx_add_mult_cache_elements(primitive_integrals(buffer_start), &
    1683              :                                                                         buffer_size, nbits, &
    1684              :                                                                         integral_caches_disk(nbits), &
    1685              :                                                                         integral_containers_disk(nbits), &
    1686              :                                                                         eps_storage, pmax_entry, &
    1687              :                                                                         memory_parameter%actual_memory_usage_disk, &
    1688              :                                                                         use_disk_storage)
    1689              :                                     END IF
    1690              :                                     buffer_left = buffer_left - buffer_size
    1691              :                                     buffer_start = buffer_start + buffer_size
    1692              :                                  END DO
    1693              :                               ELSE
    1694              :                                  !! In order to be consistent with in-core part, round all the eris wrt. eps_schwarz
    1695              :                                  DO i = 1, nints
    1696              :                                     primitive_integrals(i) = primitive_integrals(i)*pmax_entry
    1697              :                                     IF (ABS(primitive_integrals(i)) > eps_storage) THEN
    1698              :                                        primitive_integrals(i) = ANINT(primitive_integrals(i)/eps_storage, dp)*eps_storage/pmax_entry
    1699              :                                     ELSE
    1700              :                                        primitive_integrals(i) = 0.0_dp
    1701              :                                     END IF
    1702              :                                  END DO
    1703              :                               END IF
    1704              :                               IF (cartesian_estimate == 0.0_dp) CYCLE
    1705              :                            END IF
    1706              :                            !!!  DEBUG, print out primitive integrals and indices. Only works serial no OMP  !!!
    1707              :                            IF (.FALSE.) THEN
    1708              :                               CALL print_integrals( &
    1709              :                                  iatom, jatom, katom, latom, shm_set_offset, shm_atomic_block_offset, &
    1710              :                                  iset, jset, kset, lset, nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), primitive_integrals)
    1711              :                            END IF
    1712              :                            IF (.NOT. is_anti_symmetric) THEN
    1713              :                               !! Update Kohn-Sham matrix
    1714              :                               CALL update_fock_matrix( &
    1715              :                                  nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), &
    1716              :                                  fac, symm_fac, full_density_alpha(:, 1), full_ks_alpha(:, 1), &
    1717              :                                  primitive_integrals, pbd_buf, pbc_buf, pad_buf, pac_buf, kbd_buf, &
    1718              :                                  kbc_buf, kad_buf, kac_buf, iatom, jatom, katom, latom, &
    1719              :                                  iset, jset, kset, lset, offset_bd_set, offset_bc_set, offset_ad_set, offset_ac_set, &
    1720              :                                  atomic_offset_bd, atomic_offset_bc, atomic_offset_ad, atomic_offset_ac)
    1721              :                               IF (.NOT. treat_lsd_in_core) THEN
    1722              :                                  IF (my_nspins == 2) THEN
    1723              :                                     CALL update_fock_matrix( &
    1724              :                                        nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), &
    1725              :                                        fac, symm_fac, full_density_beta(:, 1), full_ks_beta(:, 1), &
    1726              :                                        primitive_integrals, pbd_buf, pbc_buf, pad_buf, pac_buf, kbd_buf, &
    1727              :                                        kbc_buf, kad_buf, kac_buf, iatom, jatom, katom, latom, &
    1728              :                                        iset, jset, kset, lset, offset_bd_set, offset_bc_set, offset_ad_set, offset_ac_set, &
    1729              :                                        atomic_offset_bd, atomic_offset_bc, atomic_offset_ad, atomic_offset_ac)
    1730              :                                  END IF
    1731              :                               END IF
    1732              :                            ELSE
    1733              :                               !! Update Kohn-Sham matrix
    1734              :                               CALL update_fock_matrix_as( &
    1735              :                                  nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), &
    1736              :                                  fac, symm_fac, full_density_alpha(:, 1), full_ks_alpha(:, 1), &
    1737              :                                  primitive_integrals, pbd_buf, pbc_buf, pad_buf, pac_buf, kbd_buf, &
    1738              :                                  kbc_buf, kad_buf, kac_buf, iatom, jatom, katom, latom, &
    1739              :                                  iset, jset, kset, lset, offset_bd_set, offset_bc_set, offset_ad_set, offset_ac_set, &
    1740              :                                  atomic_offset_bd, atomic_offset_bc, atomic_offset_ad, atomic_offset_ac)
    1741              :                               IF (.NOT. treat_lsd_in_core) THEN
    1742              :                                  IF (my_nspins == 2) THEN
    1743              :                                     CALL update_fock_matrix_as( &
    1744              :                                        nsgfa(iset), nsgfb(jset), nsgfc(kset), nsgfd(lset), &
    1745              :                                        fac, symm_fac, full_density_beta(:, 1), full_ks_beta(:, 1), &
    1746              :                                        primitive_integrals, pbd_buf, pbc_buf, pad_buf, pac_buf, kbd_buf, &
    1747              :                                        kbc_buf, kad_buf, kac_buf, iatom, jatom, katom, latom, &
    1748              :                                        iset, jset, kset, lset, offset_bd_set, offset_bc_set, offset_ad_set, offset_ac_set, &
    1749              :                                        atomic_offset_bd, atomic_offset_bc, atomic_offset_ad, atomic_offset_ac)
    1750              :                                  END IF
    1751              :                               END IF
    1752              :                            END IF
    1753              :                         END IF if_use_libint
    1754              :                      END DO ! i_set_list_kl
    1755              :                   END DO ! i_set_list_ij
    1756              :                   IF (do_disk_storage) THEN
    1757              :                      buffer_overflow = .TRUE.
    1758              :                   END IF
    1759              :                END DO !i_list_ij
    1760              :             END DO !i_list_kl
    1761              :          END DO atomic_blocks
    1762              :          bintime_stop = m_walltime()
    1763              :          IF (my_geo_change) THEN
    1764              :             distribution_energy%time_first_scf = bintime_stop - bintime_start
    1765              :          ELSE
    1766              :             distribution_energy%time_other_scf = &
    1767              :                distribution_energy%time_other_scf + bintime_stop - bintime_start
    1768              :          END IF
    1769              : !$OMP MASTER
    1770              :          CALL timestop(handle_bin)
    1771              : !$OMP END MASTER
    1772              :       END DO !bin
    1773              : 
    1774              :       !!!
    1775              :       ! IF running both libint and libGint, uses the values from libint to check libGint values
    1776              :       IF (use_libGint .and. use_libint) THEN
    1777              :          ! barrier needed after allocate  full_ks_alpha(beta)_from_gpu before libGint get K
    1778              :          ! to feed libgint a valid position for full_ks_alpha(beta)_from_gpu
    1779              :          ALLOCATE (full_ks_alpha_from_gpu, Mold=full_ks_alpha)
    1780              :          !$OMP BARRIER
    1781              :          IF (use_only_alpha_spin) THEN
    1782              :             call libGint_get_fock_matrix(full_ks_alpha_from_gpu)
    1783              :          ELSE
    1784              :             ALLOCATE (full_ks_beta_from_gpu, Mold=full_ks_beta)
    1785              :             !$OMP BARRIER
    1786              :             CALL libGint_get_fock_matrix(full_ks_alpha_from_gpu, full_ks_beta_from_gpu)
    1787              :          END IF
    1788              : 
    1789              :          !$OMP BARRIER
    1790              :          !$omp single
    1791              :          max_abs_delta_KS = 0.0_dp
    1792              :          DO i = 1, SIZE(full_ks_alpha)
    1793              :             max_abs_delta_KS = MAX(max_abs_delta_ks, ABS(full_ks_alpha(i, 1) - full_ks_alpha_from_gpu(i, 1)))
    1794              :          END DO
    1795              :          IF (iw > 0) THEN
    1796              :             WRITE (UNIT=iw, FMT=*) " ------------------------------------ "
    1797              :             WRITE (UNIT=iw, FMT=*) " | rank ", para_env%mepos
    1798              :             WRITE (UNIT=iw, FMT=*) " |  max abs dif: ", max_abs_delta_KS
    1799              :             WRITE (UNIT=iw, FMT=*) " ------------------------------------ "
    1800              :          END IF
    1801              : 
    1802              :          ! Print all F if delta is too large or (suspiciously) too small
    1803              :          IF (iw > 0) THEN
    1804              :             if (max_abs_delta_KS > 100.0_dp*eps_schwarz .or. max_abs_delta_KS < 1.0E-20_dp) THEN
    1805              :                WRITE (UNIT=iw, FMT=*) " K from CPU  |  K from GPU  |  Delta | Ratio "
    1806              :                DO i = 1, SIZE(full_ks_alpha)
    1807              :                   write (UNIT=iw, FMT=*) i, full_ks_alpha(i, 1), full_ks_alpha_from_gpu(i, 1), &
    1808              :                      full_ks_alpha(i, 1) - full_ks_alpha_from_gpu(i, 1), &
    1809              :                      full_ks_alpha(i, 1)/full_ks_alpha_from_gpu(i, 1)
    1810              :                END DO
    1811              :             END IF
    1812              :          END IF
    1813              : 
    1814              :          IF (.NOT. use_only_alpha_spin) THEN
    1815              :             max_abs_delta_KS = 0.0_dp
    1816              :             DO i = 1, size(full_ks_beta)
    1817              :                max_abs_delta_KS = max(max_abs_delta_ks, abs(full_ks_beta(i, 1) - full_ks_beta_from_gpu(i, 1)))
    1818              :             END DO
    1819              :             IF (iw > 0) THEN
    1820              :                WRITE (UNIT=iw, FMT=*) " ------------------------------------ "
    1821              :                WRITE (UNIT=iw, FMT=*) " | rank ", para_env%mepos
    1822              :                WRITE (UNIT=iw, FMT=*) " |  max abs dif B: ", max_abs_delta_KS
    1823              :                WRITE (UNIT=iw, FMT=*) " ------------------------------------ "
    1824              :             END IF
    1825              : 
    1826              :             ! Print all F if delta is too large or (suspiciously) too small
    1827              :             IF (max_abs_delta_KS > 100.0_dp*eps_schwarz .or. max_abs_delta_KS < 1.0E-18_dp) THEN
    1828              :                IF (iw > 0) THEN
    1829              :                   WRITE (UNIT=iw, FMT=*) " BETA K from CPU  |  K from GPU  |  Delta | Ratio "
    1830              :                   DO i = 1, size(full_ks_beta)
    1831              :                      WRITE (UNIT=iw, FMT=*) i, full_ks_beta(i, 1), full_ks_beta_from_gpu(i, 1), &
    1832              :                         full_ks_beta(i, 1) - full_ks_beta_from_gpu(i, 1), &
    1833              :                         full_ks_beta(i, 1)/full_ks_beta_from_gpu(i, 1)
    1834              :                   END DO
    1835              :                END IF
    1836              :             END IF
    1837              :          END IF
    1838              :          !$omp end single
    1839              :       END IF
    1840              : 
    1841              :       ! Copy the KS matrix from device to host.
    1842              :       IF (use_libGint .AND. (.NOT. use_libint)) THEN
    1843              :          IF (use_only_alpha_spin) THEN
    1844              :             CALL libGint_get_fock_matrix(full_ks_alpha)
    1845              :          ELSE
    1846              :             CALL libGint_get_fock_matrix(full_ks_alpha, full_ks_beta)
    1847              :          END IF
    1848              :       END IF
    1849              : 
    1850              : !$OMP MASTER
    1851              :       logger => cp_get_default_logger()
    1852              :       do_print_load_balance_info = .FALSE.
    1853              :       do_print_load_balance_info = BTEST(cp_print_key_should_output(logger%iter_info, hfx_section, &
    1854              :                                                                     "LOAD_BALANCE%PRINT/LOAD_BALANCE_INFO"), cp_p_file)
    1855              : !$OMP END MASTER
    1856              : !$OMP BARRIER
    1857              :       IF (do_print_load_balance_info) THEN
    1858              :          iw = -1
    1859              : !$OMP MASTER
    1860              :          iw = cp_print_key_unit_nr(logger, hfx_section, "LOAD_BALANCE%PRINT/LOAD_BALANCE_INFO", &
    1861              :                                    extension=".scfLog")
    1862              : !$OMP END MASTER
    1863              : 
    1864              :          CALL collect_load_balance_info(para_env, actual_x_data, iw, n_threads, i_thread, &
    1865              :                                         hfx_do_eval_energy)
    1866              : 
    1867              : !$OMP MASTER
    1868              :          CALL cp_print_key_finished_output(iw, logger, hfx_section, &
    1869              :                                            "LOAD_BALANCE%PRINT/LOAD_BALANCE_INFO")
    1870              : !$OMP END MASTER
    1871              :       END IF
    1872              : 
    1873              : !$OMP BARRIER
    1874              : !$OMP MASTER
    1875              :       CALL m_memory(memsize_after)
    1876              : !$OMP END MASTER
    1877              : !$OMP BARRIER
    1878              : 
    1879              :       DEALLOCATE (primitive_integrals)
    1880              : !$OMP BARRIER
    1881              :       !! Get some number about ERIS
    1882              : !$OMP ATOMIC
    1883              :       shm_neris_total = shm_neris_total + neris_total
    1884              : !$OMP ATOMIC
    1885              :       shm_neris_onthefly = shm_neris_onthefly + neris_onthefly
    1886              : !$OMP ATOMIC
    1887              :       shm_nprim_ints = shm_nprim_ints + nprim_ints
    1888              : 
    1889              :       storage_counter_integrals = memory_parameter%actual_memory_usage* &
    1890              :                                   memory_parameter%cache_size
    1891              :       stor_count_int_disk = memory_parameter%actual_memory_usage_disk* &
    1892              :                             memory_parameter%cache_size
    1893              :       stor_count_max_val = max_val_memory*memory_parameter%cache_size
    1894              : !$OMP ATOMIC
    1895              :       shm_storage_counter_integrals = shm_storage_counter_integrals + storage_counter_integrals
    1896              : !$OMP ATOMIC
    1897              :       shm_stor_count_int_disk = shm_stor_count_int_disk + stor_count_int_disk
    1898              : !$OMP ATOMIC
    1899              :       shm_neris_incore = shm_neris_incore + neris_incore
    1900              : !$OMP ATOMIC
    1901              :       shm_neris_disk = shm_neris_disk + neris_disk
    1902              : !$OMP ATOMIC
    1903              :       shm_stor_count_max_val = shm_stor_count_max_val + stor_count_max_val
    1904              : !$OMP BARRIER
    1905              : 
    1906              :       ! ** Calculate how much memory has already been used (might be needed for in-core forces
    1907              : !$OMP MASTER
    1908              :       shm_mem_compression_counter = 0
    1909              :       DO i = 1, n_threads
    1910              : !$OMP       ATOMIC READ
    1911              :          tmp_i4 = x_data(irep, i)%memory_parameter%actual_memory_usage
    1912              :          shm_mem_compression_counter = shm_mem_compression_counter + &
    1913              :                                        tmp_i4*memory_parameter%cache_size
    1914              :       END DO
    1915              : !$OMP END MASTER
    1916              : !$OMP BARRIER
    1917              :       actual_x_data%memory_parameter%final_comp_counter_energy = shm_mem_compression_counter
    1918              : 
    1919              : !$OMP MASTER
    1920              :       !! Calculate the exchange energies from the Kohn-Sham matrix. Before we can go on, we have to symmetrize.
    1921              :       ene_x_aa = 0.0_dp
    1922              :       ene_x_bb = 0.0_dp
    1923              : 
    1924              :       mb_size_p = shm_block_offset(ncpu + 1)/1024/128
    1925              :       mb_size_f = shm_block_offset(ncpu + 1)/1024/128
    1926              :       IF (.NOT. treat_lsd_in_core) THEN
    1927              :          IF (my_nspins == 2) THEN
    1928              :             mb_size_f = mb_size_f*2
    1929              :             mb_size_p = mb_size_p*2
    1930              :          END IF
    1931              :       END IF
    1932              :       !! size of primitive_integrals(not shared)
    1933              :       mb_size_buffers = INT(nsgf_max, int_8)**4*n_threads
    1934              :       !! fock density buffers (not shared)
    1935              :       mb_size_buffers = mb_size_buffers + INT(nsgf_max, int_8)**2*n_threads
    1936              :       subtr_size_mb = subtr_size_mb + 8_int_8*nsgf_max**2*n_threads
    1937              :       !! size of screening functions (shared)
    1938              :       mb_size_buffers = mb_size_buffers + max_pgf**2*max_set**2*nkind**2 &
    1939              :                         + max_set**2*nkind**2 &
    1940              :                         + nkind**2 &
    1941              :                         + max_pgf**2*max_set**2*nkind**2
    1942              :       !! is_assoc (shared)
    1943              :       mb_size_buffers = mb_size_buffers + natom**2
    1944              :       ! ** pmax_atom (shared)
    1945              :       IF (do_p_screening) THEN
    1946              :          mb_size_buffers = mb_size_buffers + natom**2
    1947              :       END IF
    1948              :       IF (screening_parameter%do_p_screening_forces) THEN
    1949              :          IF (memory_parameter%treat_forces_in_core) THEN
    1950              :             mb_size_buffers = mb_size_buffers + natom**2
    1951              :          END IF
    1952              :       END IF
    1953              :       ! ** Initial P only MAX(alpha,beta) (shared)
    1954              :       IF (do_p_screening .OR. screening_parameter%do_p_screening_forces) THEN
    1955              :          mb_size_buffers = mb_size_buffers + memory_parameter%size_p_screen
    1956              :       END IF
    1957              :       ! ** In core forces require their own initial P
    1958              :       IF (screening_parameter%do_p_screening_forces) THEN
    1959              :          IF (memory_parameter%treat_forces_in_core) THEN
    1960              :             mb_size_buffers = mb_size_buffers + memory_parameter%size_p_screen
    1961              :          END IF
    1962              :       END IF
    1963              : 
    1964              :       !! mb
    1965              :       mb_size_buffers = mb_size_buffers/1024/128
    1966              : 
    1967              :       afac = 1.0_dp
    1968              :       IF (is_anti_symmetric) afac = -1.0_dp
    1969              :       CALL timestop(handle_main)
    1970              :       ene_x_aa_diag = 0.0_dp
    1971              :       ene_x_bb_diag = 0.0_dp
    1972              :       DO iatom = 1, natom
    1973              :          ikind = kind_of(iatom)
    1974              :          nseta = basis_parameter(ikind)%nset
    1975              :          nsgfa => basis_parameter(ikind)%nsgf
    1976              :          jatom = iatom
    1977              :          jkind = kind_of(jatom)
    1978              :          nsetb = basis_parameter(jkind)%nset
    1979              :          nsgfb => basis_parameter(jkind)%nsgf
    1980              :          act_atomic_block_offset = shm_atomic_block_offset(jatom, iatom)
    1981              :          DO img = 1, nkimages
    1982              :             DO iset = 1, nseta
    1983              :                DO jset = 1, nsetb
    1984              :                   act_set_offset = shm_set_offset(jset, iset, jkind, ikind)
    1985              :                   i = act_set_offset + act_atomic_block_offset - 1
    1986              :                   DO ma = 1, nsgfa(iset)
    1987              :                      j = shm_set_offset(iset, jset, jkind, ikind) + act_atomic_block_offset - 1 + ma - 1
    1988              :                      DO mb = 1, nsgfb(jset)
    1989              :                         IF (i > j) THEN
    1990              :                            full_ks_alpha(i, img) = (full_ks_alpha(i, img) + full_ks_alpha(j, img)*afac)
    1991              :                            full_ks_alpha(j, img) = full_ks_alpha(i, img)*afac
    1992              :                            IF (.NOT. treat_lsd_in_core .AND. my_nspins == 2) THEN
    1993              :                               full_ks_beta(i, img) = (full_ks_beta(i, img) + full_ks_beta(j, img)*afac)
    1994              :                               full_ks_beta(j, img) = full_ks_beta(i, img)*afac
    1995              :                            END IF
    1996              :                         END IF
    1997              :                         ! ** For adiabatically rescaled functionals we need the energy coming from the diagonal elements
    1998              :                         IF (i == j) THEN
    1999              :                            ene_x_aa_diag = ene_x_aa_diag + full_ks_alpha(i, img)*full_density_alpha(i, img)
    2000              :                            IF (.NOT. treat_lsd_in_core .AND. my_nspins == 2) THEN
    2001              :                               ene_x_bb_diag = ene_x_bb_diag + full_ks_beta(i, img)*full_density_beta(i, img)
    2002              :                            END IF
    2003              :                         END IF
    2004              :                         i = i + 1
    2005              :                         j = j + nsgfa(iset)
    2006              :                      END DO
    2007              :                   END DO
    2008              :                END DO
    2009              :             END DO
    2010              :          END DO
    2011              :       END DO
    2012              : 
    2013              :       CALL para_env%sync()
    2014              :       afac = 1.0_dp
    2015              :       IF (is_anti_symmetric) afac = 0._dp
    2016              :       IF (distribute_fock_matrix) THEN
    2017              :          !! Distribute the current KS-matrix to all the processes
    2018              :          CALL timeset(routineN//"_dist_KS", handle_dist_ks)
    2019              :          DO img = 1, nkimages
    2020              :             CALL distribute_ks_matrix(para_env, full_ks_alpha(:, img), ks_matrix(ispin, img)%matrix, shm_number_of_p_entries, &
    2021              :                                       shm_block_offset, kind_of, basis_parameter, &
    2022              :                                       off_diag_fac=0.5_dp, diag_fac=afac)
    2023              :          END DO
    2024              : 
    2025              :          NULLIFY (full_ks_alpha)
    2026              :          DEALLOCATE (shm_master_x_data%full_ks_alpha)
    2027              :          IF (.NOT. treat_lsd_in_core) THEN
    2028              :             IF (my_nspins == 2) THEN
    2029              :                DO img = 1, nkimages
    2030              :                   CALL distribute_ks_matrix(para_env, full_ks_beta(:, img), ks_matrix(2, img)%matrix, shm_number_of_p_entries, &
    2031              :                                             shm_block_offset, kind_of, basis_parameter, &
    2032              :                                             off_diag_fac=0.5_dp, diag_fac=afac)
    2033              :                END DO
    2034              :                NULLIFY (full_ks_beta)
    2035              :                DEALLOCATE (shm_master_x_data%full_ks_beta)
    2036              :             END IF
    2037              :          END IF
    2038              :          CALL timestop(handle_dist_ks)
    2039              :       END IF
    2040              : 
    2041              :       IF (distribute_fock_matrix) THEN
    2042              :          !! ** Calculate the exchange energy
    2043              :          ene_x_aa = 0.0_dp
    2044              :          DO img = 1, nkimages
    2045              :             CALL dbcsr_dot_threadsafe(ks_matrix(ispin, img)%matrix, rho_ao(ispin, img)%matrix, etmp)
    2046              :             ene_x_aa = ene_x_aa + etmp
    2047              :          END DO
    2048              :          !for ADMMS, we need the exchange matrix k(d) for both spins
    2049              :          IF (dft_control%do_admm) THEN
    2050              :             CPASSERT(nkimages == 1)
    2051              :             CALL dbcsr_copy(matrix_ks_aux_fit_hfx(ispin)%matrix, ks_matrix(ispin, 1)%matrix, &
    2052              :                             name="HF exch. part of matrix_ks_aux_fit for ADMMS")
    2053              :          END IF
    2054              : 
    2055              :          ene_x_bb = 0.0_dp
    2056              :          IF (my_nspins == 2 .AND. .NOT. treat_lsd_in_core) THEN
    2057              :             DO img = 1, nkimages
    2058              :                CALL dbcsr_dot_threadsafe(ks_matrix(2, img)%matrix, rho_ao(2, img)%matrix, etmp)
    2059              :                ene_x_bb = ene_x_bb + etmp
    2060              :             END DO
    2061              :             !for ADMMS, we need the exchange matrix k(d) for both spins
    2062              :             IF (dft_control%do_admm) THEN
    2063              :                CPASSERT(nkimages == 1)
    2064              :                CALL dbcsr_copy(matrix_ks_aux_fit_hfx(2)%matrix, ks_matrix(2, 1)%matrix, &
    2065              :                                name="HF exch. part of matrix_ks_aux_fit for ADMMS")
    2066              :             END IF
    2067              :          END IF
    2068              : 
    2069              :          !! Update energy type
    2070              :          ehfx = 0.5_dp*(ene_x_aa + ene_x_bb)
    2071              :       ELSE
    2072              :          ! ** It is easier to correct the following expression by the diagonal energy contribution,
    2073              :          ! ** than explicitly going throuhg the diagonal elements
    2074              :          DO img = 1, nkimages
    2075              :             DO pa = 1, SIZE(full_ks_alpha, 1)
    2076              :                ene_x_aa = ene_x_aa + full_ks_alpha(pa, img)*full_density_alpha(pa, img)
    2077              :             END DO
    2078              :          END DO
    2079              :          ! ** Now correct
    2080              :          ene_x_aa = (ene_x_aa + ene_x_aa_diag)*0.5_dp
    2081              :          IF (my_nspins == 2) THEN
    2082              :             DO img = 1, nkimages
    2083              :                DO pa = 1, SIZE(full_ks_beta, 1)
    2084              :                   ene_x_bb = ene_x_bb + full_ks_beta(pa, img)*full_density_beta(pa, img)
    2085              :                END DO
    2086              :             END DO
    2087              :             ! ** Now correct
    2088              :             ene_x_bb = (ene_x_bb + ene_x_bb_diag)*0.5_dp
    2089              :          END IF
    2090              :          CALL para_env%sum(ene_x_aa)
    2091              :          IF (my_nspins == 2) CALL para_env%sum(ene_x_bb)
    2092              :          ehfx = 0.5_dp*(ene_x_aa + ene_x_bb)
    2093              :       END IF
    2094              : 
    2095              :       !! Print some memeory information if this is the first step
    2096              :       IF (my_geo_change) THEN
    2097              :          tmp_i8(1:8) = [shm_storage_counter_integrals, shm_neris_onthefly, shm_neris_incore, shm_neris_disk, &
    2098              :                         shm_neris_total, shm_stor_count_int_disk, shm_nprim_ints, shm_stor_count_max_val]
    2099              :          CALL para_env%sum(tmp_i8)
    2100              :          shm_storage_counter_integrals = tmp_i8(1)
    2101              :          shm_neris_onthefly = tmp_i8(2)
    2102              :          shm_neris_incore = tmp_i8(3)
    2103              :          shm_neris_disk = tmp_i8(4)
    2104              :          shm_neris_total = tmp_i8(5)
    2105              :          shm_stor_count_int_disk = tmp_i8(6)
    2106              :          shm_nprim_ints = tmp_i8(7)
    2107              :          shm_stor_count_max_val = tmp_i8(8)
    2108              :          CALL para_env%max(memsize_after)
    2109              :          mem_eris = (shm_storage_counter_integrals + 128*1024 - 1)/1024/128
    2110              :          compression_factor = REAL(shm_neris_incore, dp)/REAL(shm_storage_counter_integrals, dp)
    2111              :          mem_eris_disk = (shm_stor_count_int_disk + 128*1024 - 1)/1024/128
    2112              :          compression_factor_disk = REAL(shm_neris_disk, dp)/REAL(shm_stor_count_int_disk, dp)
    2113              :          mem_max_val = (shm_stor_count_max_val + 128*1024 - 1)/1024/128
    2114              : 
    2115              :          IF (shm_neris_incore == 0) THEN
    2116              :             mem_eris = 0
    2117              :             compression_factor = 0.0_dp
    2118              :          END IF
    2119              :          IF (shm_neris_disk == 0) THEN
    2120              :             mem_eris_disk = 0
    2121              :             compression_factor_disk = 0.0_dp
    2122              :          END IF
    2123              : 
    2124              :          iw = cp_print_key_unit_nr(logger, hfx_section, "HF_INFO", &
    2125              :                                    extension=".scfLog")
    2126              :          IF (iw > 0) THEN
    2127              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2128              :                "HFX_MEM_INFO| Number of cart. primitive ERI's calculated:      ", shm_nprim_ints
    2129              : 
    2130              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2131              :                "HFX_MEM_INFO| Number of sph. ERI's calculated:           ", shm_neris_total
    2132              : 
    2133              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2134              :                "HFX_MEM_INFO| Number of sph. ERI's stored in-core:        ", shm_neris_incore
    2135              : 
    2136              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2137              :                "HFX_MEM_INFO| Number of sph. ERI's stored on disk:        ", shm_neris_disk
    2138              : 
    2139              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2140              :                "HFX_MEM_INFO| Number of sph. ERI's calculated on the fly: ", shm_neris_onthefly
    2141              : 
    2142              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2143              :                "HFX_MEM_INFO| Total memory consumption ERI's RAM [MiB]:            ", mem_eris
    2144              : 
    2145              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2146              :                "HFX_MEM_INFO| Whereof max-vals [MiB]:            ", mem_max_val
    2147              : 
    2148              :             WRITE (UNIT=iw, FMT="((T3,A,T60,F21.2))") &
    2149              :                "HFX_MEM_INFO| Total compression factor ERI's RAM:                  ", compression_factor
    2150              : 
    2151              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2152              :                "HFX_MEM_INFO| Total memory consumption ERI's disk [MiB]:       ", mem_eris_disk
    2153              : 
    2154              :             WRITE (UNIT=iw, FMT="((T3,A,T60,F21.2))") &
    2155              :                "HFX_MEM_INFO| Total compression factor ERI's disk:             ", compression_factor_disk
    2156              : 
    2157              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2158              :                "HFX_MEM_INFO| Size of density/Fock matrix [MiB]:             ", 2_int_8*mb_size_p
    2159              : 
    2160              :             IF (do_periodic) THEN
    2161              :                WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2162              :                   "HFX_MEM_INFO| Size of buffers [MiB]:             ", mb_size_buffers
    2163              :                WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2164              :                   "HFX_MEM_INFO| Number of periodic image cells considered: ", SIZE(shm_master_x_data%neighbor_cells)
    2165              :             ELSE
    2166              :                WRITE (UNIT=iw, FMT="((T3,A,T60,I21))") &
    2167              :                   "HFX_MEM_INFO| Size of buffers [MiB]:             ", mb_size_buffers
    2168              :             END IF
    2169              :             WRITE (UNIT=iw, FMT="((T3,A,T60,I21),/)") &
    2170              :                "HFX_MEM_INFO| Est. max. program size after HFX  [MiB]:", memsize_after/(1024*1024)
    2171              :             CALL m_flush(iw)
    2172              :          END IF
    2173              : 
    2174              :          CALL cp_print_key_finished_output(iw, logger, hfx_section, &
    2175              :                                            "HF_INFO")
    2176              :       END IF
    2177              : !$OMP END MASTER
    2178              : 
    2179              :       !! flush caches if the geometry changed
    2180              :       IF (do_dynamic_load_balancing) THEN
    2181              :          my_bin_size = SIZE(actual_x_data%distribution_energy)
    2182              :       ELSE
    2183              :          my_bin_size = 1
    2184              :       END IF
    2185              : 
    2186              :       IF (my_geo_change) THEN
    2187              :          IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
    2188              :             DO bin = 1, my_bin_size
    2189              :                maxval_cache => actual_x_data%store_ints%maxval_cache(bin)
    2190              :                maxval_container => actual_x_data%store_ints%maxval_container(bin)
    2191              :                integral_caches => actual_x_data%store_ints%integral_caches(:, bin)
    2192              :                integral_containers => actual_x_data%store_ints%integral_containers(:, bin)
    2193              :                CALL hfx_flush_last_cache(bits_max_val, maxval_cache, maxval_container, memory_parameter%actual_memory_usage, &
    2194              :                                          .FALSE.)
    2195              :                DO i = 1, 64
    2196              :                   CALL hfx_flush_last_cache(i, integral_caches(i), integral_containers(i), &
    2197              :                                             memory_parameter%actual_memory_usage, .FALSE.)
    2198              :                END DO
    2199              :             END DO
    2200              :          END IF
    2201              :       END IF
    2202              :       !! reset all caches except we calculate all on the fly
    2203              :       IF (.NOT. memory_parameter%do_all_on_the_fly) THEN
    2204              :          DO bin = 1, my_bin_size
    2205              :             maxval_cache => actual_x_data%store_ints%maxval_cache(bin)
    2206              :             maxval_container => actual_x_data%store_ints%maxval_container(bin)
    2207              :             integral_caches => actual_x_data%store_ints%integral_caches(:, bin)
    2208              :             integral_containers => actual_x_data%store_ints%integral_containers(:, bin)
    2209              : 
    2210              :             CALL hfx_reset_cache_and_container(maxval_cache, maxval_container, memory_parameter%actual_memory_usage, .FALSE.)
    2211              :             DO i = 1, 64
    2212              :                CALL hfx_reset_cache_and_container(integral_caches(i), integral_containers(i), &
    2213              :                                                   memory_parameter%actual_memory_usage, &
    2214              :                                                   .FALSE.)
    2215              :             END DO
    2216              :          END DO
    2217              :       END IF
    2218              : 
    2219              :       !! Since the I/O routines are no thread-safe, i.e. the procedure to get the unit number, put a lock here
    2220              : !$OMP CRITICAL(hfxenergy_out_critical)
    2221              :       IF (do_disk_storage) THEN
    2222              :          !! flush caches if the geometry changed
    2223              :          IF (my_geo_change) THEN
    2224              :             CALL hfx_flush_last_cache(bits_max_val, maxval_cache_disk, maxval_container_disk, &
    2225              :                                       memory_parameter%actual_memory_usage_disk, .TRUE.)
    2226              :             DO i = 1, 64
    2227              :                CALL hfx_flush_last_cache(i, integral_caches_disk(i), integral_containers_disk(i), &
    2228              :                                          memory_parameter%actual_memory_usage_disk, .TRUE.)
    2229              :             END DO
    2230              :          END IF
    2231              :          !! reset all caches except we calculate all on the fly
    2232              :          CALL hfx_reset_cache_and_container(maxval_cache_disk, maxval_container_disk, memory_parameter%actual_memory_usage_disk, &
    2233              :                                             do_disk_storage)
    2234              :          DO i = 1, 64
    2235              :             CALL hfx_reset_cache_and_container(integral_caches_disk(i), integral_containers_disk(i), &
    2236              :                                                memory_parameter%actual_memory_usage_disk, do_disk_storage)
    2237              :          END DO
    2238              :       END IF
    2239              : !$OMP END CRITICAL(hfxenergy_out_critical)
    2240              : !$OMP BARRIER
    2241              :       !! Clean up
    2242              :       DEALLOCATE (last_sgf_global)
    2243              : !$OMP MASTER
    2244              :       DEALLOCATE (full_density_alpha)
    2245              :       IF (.NOT. treat_lsd_in_core) THEN
    2246              :          IF (my_nspins == 2) THEN
    2247              :             DEALLOCATE (full_density_beta)
    2248              :          END IF
    2249              :       END IF
    2250              :       IF (do_dynamic_load_balancing) THEN
    2251              :          DEALLOCATE (shm_master_x_data%task_list)
    2252              :       END IF
    2253              : !$OMP END MASTER
    2254              :       DEALLOCATE (pbd_buf, pbc_buf, pad_buf, pac_buf)
    2255              :       DEALLOCATE (kbd_buf, kbc_buf, kad_buf, kac_buf)
    2256              :       DEALLOCATE (set_list_ij, set_list_kl)
    2257              : 
    2258              :       DO i = 1, max_pgf**2
    2259              :          DEALLOCATE (pgf_list_ij(i)%image_list)
    2260              :          DEALLOCATE (pgf_list_kl(i)%image_list)
    2261              :       END DO
    2262              : 
    2263              :       DEALLOCATE (pgf_list_ij)
    2264              :       DEALLOCATE (pgf_list_kl)
    2265              : 
    2266              :       DEALLOCATE (max_contraction, kind_of)
    2267              : 
    2268              :       DEALLOCATE (ee_work2, ee_buffer1, ee_buffer2)
    2269              : 
    2270              :       DEALLOCATE (nimages)
    2271              : 
    2272              : !$OMP BARRIER
    2273              : !$OMP END PARALLEL
    2274              : 
    2275        43303 :       CALL timestop(handle)
    2276     90156846 :    END SUBROUTINE integrate_four_center
    2277              : 
    2278              : ! **************************************************************************************************
    2279              : !> \brief Given a 2d index pair, this function returns a 1d index pair for
    2280              : !>        a symmetric upper triangle NxN matrix
    2281              : !>        The compiler should inline this function, therefore it appears in
    2282              : !>        several modules
    2283              : !> \param i 2d index
    2284              : !> \param j 2d index
    2285              : !> \param N matrix size
    2286              : !> \return ...
    2287              : !> \par History
    2288              : !>      03.2009 created [Manuel Guidon]
    2289              : !> \author Manuel Guidon
    2290              : ! **************************************************************************************************
    2291        28224 :    PURE FUNCTION get_1D_idx(i, j, N)
    2292              :       INTEGER, INTENT(IN)                                :: i, j
    2293              :       INTEGER(int_8), INTENT(IN)                         :: N
    2294              :       INTEGER(int_8)                                     :: get_1D_idx
    2295              : 
    2296              :       INTEGER(int_8)                                     :: min_ij
    2297              : 
    2298        28224 :       min_ij = MIN(i, j)
    2299        28224 :       get_1D_idx = min_ij*N + MAX(i, j) - (min_ij - 1)*min_ij/2 - N
    2300              : 
    2301        28224 :    END FUNCTION get_1D_idx
    2302              : 
    2303              : ! **************************************************************************************************
    2304              : !> \brief This routine prefetches density/fock matrix elements and stores them
    2305              : !>        in cache friendly arrays. These buffers are then used to update the
    2306              : !>        fock matrix
    2307              : !> \param ma_max Size of matrix blocks
    2308              : !> \param mb_max Size of matrix blocks
    2309              : !> \param mc_max Size of matrix blocks
    2310              : !> \param md_max Size of matrix blocks
    2311              : !> \param fac multiplication factor (spin)
    2312              : !> \param symm_fac multiplication factor (symmetry)
    2313              : !> \param density upper triangular density matrix
    2314              : !> \param ks upper triangular fock matrix
    2315              : !> \param prim primitive integrals
    2316              : !> \param pbd buffer that will contain P(b,d)
    2317              : !> \param pbc buffer that will contain P(b,c)
    2318              : !> \param pad buffer that will contain P(a,d)
    2319              : !> \param pac buffer that will contain P(a,c)
    2320              : !> \param kbd buffer for KS(b,d)
    2321              : !> \param kbc buffer for KS(b,c)
    2322              : !> \param kad buffer for KS(a,d)
    2323              : !> \param kac buffer for KS(a,c)
    2324              : !> \param iatom ...
    2325              : !> \param jatom ...
    2326              : !> \param katom ...
    2327              : !> \param latom ...
    2328              : !> \param iset ...
    2329              : !> \param jset ...
    2330              : !> \param kset ...
    2331              : !> \param lset ...
    2332              : !> \param offset_bd_set ...
    2333              : !> \param offset_bc_set ...
    2334              : !> \param offset_ad_set ...
    2335              : !> \param offset_ac_set ...
    2336              : !> \param atomic_offset_bd ...
    2337              : !> \param atomic_offset_bc ...
    2338              : !> \param atomic_offset_ad ...
    2339              : !> \param atomic_offset_ac ...
    2340              : !> \par History
    2341              : !>      03.2009 created [Manuel Guidon]
    2342              : !> \author Manuel Guidon
    2343              : ! **************************************************************************************************
    2344              : 
    2345     80296970 :    SUBROUTINE update_fock_matrix(ma_max, mb_max, mc_max, md_max, &
    2346     80296970 :                                  fac, symm_fac, density, ks, prim, &
    2347              :                                  pbd, pbc, pad, pac, kbd, kbc, kad, kac, &
    2348              :                                  iatom, jatom, katom, latom, &
    2349              :                                  iset, jset, kset, lset, offset_bd_set, offset_bc_set, offset_ad_set, &
    2350              :                                  offset_ac_set, atomic_offset_bd, atomic_offset_bc, atomic_offset_ad, &
    2351              :                                  atomic_offset_ac)
    2352              : 
    2353              :       INTEGER, INTENT(IN)                                :: ma_max, mb_max, mc_max, md_max
    2354              :       REAL(dp), INTENT(IN)                               :: fac, symm_fac
    2355              :       REAL(dp), DIMENSION(:), INTENT(IN)                 :: density
    2356              :       REAL(dp), DIMENSION(:), INTENT(INOUT)              :: ks
    2357              :       REAL(dp), DIMENSION(ma_max*mb_max*mc_max*md_max), &
    2358              :          INTENT(IN)                                      :: prim
    2359              :       REAL(dp), DIMENSION(*), INTENT(INOUT)              :: pbd, pbc, pad, pac, kbd, kbc, kad, kac
    2360              :       INTEGER, INTENT(IN)                                :: iatom, jatom, katom, latom, iset, jset, &
    2361              :                                                             kset, lset
    2362              :       INTEGER, DIMENSION(:, :), POINTER, INTENT(IN)      :: offset_bd_set, offset_bc_set, &
    2363              :                                                             offset_ad_set, offset_ac_set
    2364              :       INTEGER, INTENT(IN)                                :: atomic_offset_bd, atomic_offset_bc, &
    2365              :                                                             atomic_offset_ad, atomic_offset_ac
    2366              : 
    2367              :       INTEGER                                            :: i, j, ma, mb, mc, md, offset_ac, &
    2368              :                                                             offset_ad, offset_bc, offset_bd
    2369              :       REAL(dp)                                           :: ki
    2370              : 
    2371     80296970 :       IF (jatom >= latom) THEN
    2372     79087433 :          i = 1
    2373     79087433 :          offset_bd = offset_bd_set(jset, lset) + atomic_offset_bd - 1
    2374     79087433 :          j = offset_bd
    2375    236075265 :          DO md = 1, md_max
    2376    520266551 :             DO mb = 1, mb_max
    2377    284191286 :                pbd(i) = density(j)
    2378    284191286 :                i = i + 1
    2379    441179118 :                j = j + 1
    2380              :             END DO
    2381              :          END DO
    2382              :       ELSE
    2383      1209537 :          i = 1
    2384      1209537 :          offset_bd = offset_bd_set(lset, jset) + atomic_offset_bd - 1
    2385      3553041 :          DO md = 1, md_max
    2386      2343504 :             j = offset_bd + md - 1
    2387      8698473 :             DO mb = 1, mb_max
    2388      5145432 :                pbd(i) = density(j)
    2389      5145432 :                i = i + 1
    2390      7488936 :                j = j + md_max
    2391              :             END DO
    2392              :          END DO
    2393              :       END IF
    2394     80296970 :       IF (jatom >= katom) THEN
    2395     80296970 :          i = 1
    2396     80296970 :          offset_bc = offset_bc_set(jset, kset) + atomic_offset_bc - 1
    2397     80296970 :          j = offset_bc
    2398    265040559 :          DO mc = 1, mc_max
    2399    590362510 :             DO mb = 1, mb_max
    2400    325321951 :                pbc(i) = density(j)
    2401    325321951 :                i = i + 1
    2402    510065540 :                j = j + 1
    2403              :             END DO
    2404              :          END DO
    2405              :       ELSE
    2406            0 :          i = 1
    2407            0 :          offset_bc = offset_bc_set(kset, jset) + atomic_offset_bc - 1
    2408            0 :          DO mc = 1, mc_max
    2409            0 :             j = offset_bc + mc - 1
    2410            0 :             DO mb = 1, mb_max
    2411            0 :                pbc(i) = density(j)
    2412            0 :                i = i + 1
    2413            0 :                j = j + mc_max
    2414              :             END DO
    2415              :          END DO
    2416              :       END IF
    2417     80296970 :       IF (iatom >= latom) THEN
    2418     57594052 :          i = 1
    2419     57594052 :          offset_ad = offset_ad_set(iset, lset) + atomic_offset_ad - 1
    2420     57594052 :          j = offset_ad
    2421    179643472 :          DO md = 1, md_max
    2422    438920848 :             DO ma = 1, ma_max
    2423    259277376 :                pad(i) = density(j)
    2424    259277376 :                i = i + 1
    2425    381326796 :                j = j + 1
    2426              :             END DO
    2427              :          END DO
    2428              :       ELSE
    2429     22702918 :          i = 1
    2430     22702918 :          offset_ad = offset_ad_set(lset, iset) + atomic_offset_ad - 1
    2431     59984834 :          DO md = 1, md_max
    2432     37281916 :             j = offset_ad + md - 1
    2433    149091418 :             DO ma = 1, ma_max
    2434     89106584 :                pad(i) = density(j)
    2435     89106584 :                i = i + 1
    2436    126388500 :                j = j + md_max
    2437              :             END DO
    2438              :          END DO
    2439              :       END IF
    2440     80296970 :       IF (iatom >= katom) THEN
    2441     76547842 :          i = 1
    2442     76547842 :          offset_ac = offset_ac_set(iset, kset) + atomic_offset_ac - 1
    2443     76547842 :          j = offset_ac
    2444    254495817 :          DO mc = 1, mc_max
    2445    639647951 :             DO ma = 1, ma_max
    2446    385152134 :                pac(i) = density(j)
    2447    385152134 :                i = i + 1
    2448    563100109 :                j = j + 1
    2449              :             END DO
    2450              :          END DO
    2451              :       ELSE
    2452      3749128 :          i = 1
    2453      3749128 :          offset_ac = offset_ac_set(kset, iset) + atomic_offset_ac - 1
    2454     10544742 :          DO mc = 1, mc_max
    2455      6795614 :             j = offset_ac + mc - 1
    2456     28476826 :             DO ma = 1, ma_max
    2457     17932084 :                pac(i) = density(j)
    2458     17932084 :                i = i + 1
    2459     24727698 :                j = j + mc_max
    2460              :             END DO
    2461              :          END DO
    2462              :       END IF
    2463              : 
    2464     80296970 :       CALL contract_block(ma_max, mb_max, mc_max, md_max, kbd, kbc, kad, kac, pbd, pbc, pad, pac, prim, fac*symm_fac)
    2465     80296970 :       IF (jatom >= latom) THEN
    2466              :          i = 1
    2467              :          j = offset_bd
    2468    236075265 :          DO md = 1, md_max
    2469    520266551 :             DO mb = 1, mb_max
    2470    284191286 :                ki = kbd(i)
    2471    284191286 : !$OMP           ATOMIC
    2472              :                ks(j) = ks(j) + ki
    2473    284191286 :                i = i + 1
    2474    441179118 :                j = j + 1
    2475              :             END DO
    2476              :          END DO
    2477              :       ELSE
    2478              :          i = 1
    2479      3553041 :          DO md = 1, md_max
    2480      2343504 :             j = offset_bd + md - 1
    2481      8698473 :             DO mb = 1, mb_max
    2482      5145432 :                ki = kbd(i)
    2483      5145432 : !$OMP           ATOMIC
    2484              :                ks(j) = ks(j) + ki
    2485      5145432 :                i = i + 1
    2486      7488936 :                j = j + md_max
    2487              :             END DO
    2488              :          END DO
    2489              :       END IF
    2490     80296970 :       IF (jatom >= katom) THEN
    2491              :          i = 1
    2492              :          j = offset_bc
    2493    265040559 :          DO mc = 1, mc_max
    2494    590362510 :             DO mb = 1, mb_max
    2495    325321951 :                ki = kbc(i)
    2496    325321951 : !$OMP           ATOMIC
    2497              :                ks(j) = ks(j) + ki
    2498    325321951 :                i = i + 1
    2499    510065540 :                j = j + 1
    2500              :             END DO
    2501              :          END DO
    2502              :       ELSE
    2503              :          i = 1
    2504            0 :          DO mc = 1, mc_max
    2505            0 :             j = offset_bc + mc - 1
    2506            0 :             DO mb = 1, mb_max
    2507            0 :                ki = kbc(i)
    2508            0 : !$OMP           ATOMIC
    2509              :                ks(j) = ks(j) + ki
    2510            0 :                i = i + 1
    2511            0 :                j = j + mc_max
    2512              :             END DO
    2513              :          END DO
    2514              :       END IF
    2515     80296970 :       IF (iatom >= latom) THEN
    2516              :          i = 1
    2517              :          j = offset_ad
    2518    179643472 :          DO md = 1, md_max
    2519    438920848 :             DO ma = 1, ma_max
    2520    259277376 :                ki = kad(i)
    2521    259277376 : !$OMP           ATOMIC
    2522              :                ks(j) = ks(j) + ki
    2523    259277376 :                i = i + 1
    2524    381326796 :                j = j + 1
    2525              :             END DO
    2526              :          END DO
    2527              :       ELSE
    2528              :          i = 1
    2529     59984834 :          DO md = 1, md_max
    2530     37281916 :             j = offset_ad + md - 1
    2531    149091418 :             DO ma = 1, ma_max
    2532     89106584 :                ki = kad(i)
    2533     89106584 : !$OMP           ATOMIC
    2534              :                ks(j) = ks(j) + ki
    2535     89106584 :                i = i + 1
    2536    126388500 :                j = j + md_max
    2537              :             END DO
    2538              :          END DO
    2539              :       END IF
    2540     80296970 :       IF (iatom >= katom) THEN
    2541              :          i = 1
    2542              :          j = offset_ac
    2543    254495817 :          DO mc = 1, mc_max
    2544    639647951 :             DO ma = 1, ma_max
    2545    385152134 :                ki = kac(i)
    2546    385152134 : !$OMP           ATOMIC
    2547              :                ks(j) = ks(j) + ki
    2548    385152134 :                i = i + 1
    2549    563100109 :                j = j + 1
    2550              :             END DO
    2551              :          END DO
    2552              :       ELSE
    2553              :          i = 1
    2554     10544742 :          DO mc = 1, mc_max
    2555      6795614 :             j = offset_ac + mc - 1
    2556     28476826 :             DO ma = 1, ma_max
    2557     17932084 :                ki = kac(i)
    2558     17932084 : !$OMP           ATOMIC
    2559              :                ks(j) = ks(j) + ki
    2560     17932084 :                i = i + 1
    2561     24727698 :                j = j + mc_max
    2562              :             END DO
    2563              :          END DO
    2564              :       END IF
    2565     80296970 :    END SUBROUTINE update_fock_matrix
    2566              : 
    2567              : ! **************************************************************************************************
    2568              : !> \brief ...
    2569              : !> \param ma_max ...
    2570              : !> \param mb_max ...
    2571              : !> \param mc_max ...
    2572              : !> \param md_max ...
    2573              : !> \param fac ...
    2574              : !> \param symm_fac ...
    2575              : !> \param density ...
    2576              : !> \param ks ...
    2577              : !> \param prim ...
    2578              : !> \param pbd ...
    2579              : !> \param pbc ...
    2580              : !> \param pad ...
    2581              : !> \param pac ...
    2582              : !> \param kbd ...
    2583              : !> \param kbc ...
    2584              : !> \param kad ...
    2585              : !> \param kac ...
    2586              : !> \param iatom ...
    2587              : !> \param jatom ...
    2588              : !> \param katom ...
    2589              : !> \param latom ...
    2590              : !> \param iset ...
    2591              : !> \param jset ...
    2592              : !> \param kset ...
    2593              : !> \param lset ...
    2594              : !> \param offset_bd_set ...
    2595              : !> \param offset_bc_set ...
    2596              : !> \param offset_ad_set ...
    2597              : !> \param offset_ac_set ...
    2598              : !> \param atomic_offset_bd ...
    2599              : !> \param atomic_offset_bc ...
    2600              : !> \param atomic_offset_ad ...
    2601              : !> \param atomic_offset_ac ...
    2602              : ! **************************************************************************************************
    2603      5564499 :    SUBROUTINE update_fock_matrix_as(ma_max, mb_max, mc_max, md_max, &
    2604      5564499 :                                     fac, symm_fac, density, ks, prim, &
    2605              :                                     pbd, pbc, pad, pac, kbd, kbc, kad, kac, &
    2606              :                                     iatom, jatom, katom, latom, &
    2607              :                                     iset, jset, kset, lset, offset_bd_set, offset_bc_set, offset_ad_set, &
    2608              :                                     offset_ac_set, atomic_offset_bd, atomic_offset_bc, atomic_offset_ad, &
    2609              :                                     atomic_offset_ac)
    2610              : 
    2611              :       INTEGER, INTENT(IN)                                :: ma_max, mb_max, mc_max, md_max
    2612              :       REAL(dp), INTENT(IN)                               :: fac, symm_fac
    2613              :       REAL(dp), DIMENSION(:), INTENT(IN)                 :: density
    2614              :       REAL(dp), DIMENSION(:), INTENT(INOUT)              :: ks
    2615              :       REAL(dp), DIMENSION(ma_max*mb_max*mc_max*md_max), &
    2616              :          INTENT(IN)                                      :: prim
    2617              :       REAL(dp), DIMENSION(*), INTENT(INOUT)              :: pbd, pbc, pad, pac, kbd, kbc, kad, kac
    2618              :       INTEGER, INTENT(IN)                                :: iatom, jatom, katom, latom, iset, jset, &
    2619              :                                                             kset, lset
    2620              :       INTEGER, DIMENSION(:, :), POINTER                  :: offset_bd_set, offset_bc_set, &
    2621              :                                                             offset_ad_set, offset_ac_set
    2622              :       INTEGER, INTENT(IN)                                :: atomic_offset_bd, atomic_offset_bc, &
    2623              :                                                             atomic_offset_ad, atomic_offset_ac
    2624              : 
    2625              :       INTEGER                                            :: i, j, ma, mb, mc, md, offset_ac, &
    2626              :                                                             offset_ad, offset_bc, offset_bd
    2627              : 
    2628      5564499 :       IF (jatom >= latom) THEN
    2629      5550987 :          i = 1
    2630      5550987 :          offset_bd = offset_bd_set(jset, lset) + atomic_offset_bd - 1
    2631      5550987 :          j = offset_bd
    2632     15219120 :          DO md = 1, md_max
    2633     29416357 :             DO mb = 1, mb_max
    2634     14197237 :                pbd(i) = +density(j)
    2635     14197237 :                i = i + 1
    2636     23865370 :                j = j + 1
    2637              :             END DO
    2638              :          END DO
    2639              :       ELSE
    2640        13512 :          i = 1
    2641        13512 :          offset_bd = offset_bd_set(lset, jset) + atomic_offset_bd - 1
    2642        28504 :          DO md = 1, md_max
    2643        14992 :             j = offset_bd + md - 1
    2644        47164 :             DO mb = 1, mb_max
    2645        18660 :                pbd(i) = -density(j)
    2646        18660 :                i = i + 1
    2647        33652 :                j = j + md_max
    2648              :             END DO
    2649              :          END DO
    2650              :       END IF
    2651      5564499 :       IF (jatom >= katom) THEN
    2652      5564499 :          i = 1
    2653      5564499 :          offset_bc = offset_bc_set(jset, kset) + atomic_offset_bc - 1
    2654      5564499 :          j = offset_bc
    2655     17101804 :          DO mc = 1, mc_max
    2656     33545825 :             DO mb = 1, mb_max
    2657     16444021 :                pbc(i) = -density(j)
    2658     16444021 :                i = i + 1
    2659     27981326 :                j = j + 1
    2660              :             END DO
    2661              :          END DO
    2662              :       ELSE
    2663            0 :          i = 1
    2664            0 :          offset_bc = offset_bc_set(kset, jset) + atomic_offset_bc - 1
    2665            0 :          DO mc = 1, mc_max
    2666            0 :             j = offset_bc + mc - 1
    2667            0 :             DO mb = 1, mb_max
    2668            0 :                pbc(i) = density(j)
    2669            0 :                i = i + 1
    2670            0 :                j = j + mc_max
    2671              :             END DO
    2672              :          END DO
    2673              :       END IF
    2674      5564499 :       IF (iatom >= latom) THEN
    2675      4163429 :          i = 1
    2676      4163429 :          offset_ad = offset_ad_set(iset, lset) + atomic_offset_ad - 1
    2677      4163429 :          j = offset_ad
    2678     12161472 :          DO md = 1, md_max
    2679     27376447 :             DO ma = 1, ma_max
    2680     15214975 :                pad(i) = -density(j)
    2681     15214975 :                i = i + 1
    2682     23213018 :                j = j + 1
    2683              :             END DO
    2684              :          END DO
    2685              :       ELSE
    2686      1401070 :          i = 1
    2687      1401070 :          offset_ad = offset_ad_set(lset, iset) + atomic_offset_ad - 1
    2688      3086152 :          DO md = 1, md_max
    2689      1685082 :             j = offset_ad + md - 1
    2690      6859450 :             DO ma = 1, ma_max
    2691      3773298 :                pad(i) = density(j)
    2692      3773298 :                i = i + 1
    2693      5458380 :                j = j + md_max
    2694              :             END DO
    2695              :          END DO
    2696              :       END IF
    2697      5564499 :       IF (iatom >= katom) THEN
    2698      5360331 :          i = 1
    2699      5360331 :          offset_ac = offset_ac_set(iset, kset) + atomic_offset_ac - 1
    2700      5360331 :          j = offset_ac
    2701     16604644 :          DO mc = 1, mc_max
    2702     38455863 :             DO ma = 1, ma_max
    2703     21851219 :                pac(i) = +density(j)
    2704     21851219 :                i = i + 1
    2705     33095532 :                j = j + 1
    2706              :             END DO
    2707              :          END DO
    2708              :       ELSE
    2709       204168 :          i = 1
    2710       204168 :          offset_ac = offset_ac_set(kset, iset) + atomic_offset_ac - 1
    2711       497160 :          DO mc = 1, mc_max
    2712       292992 :             j = offset_ac + mc - 1
    2713      1250254 :             DO ma = 1, ma_max
    2714       753094 :                pac(i) = -density(j)
    2715       753094 :                i = i + 1
    2716      1046086 :                j = j + mc_max
    2717              :             END DO
    2718              :          END DO
    2719              :       END IF
    2720              : 
    2721      5564499 :       CALL contract_block(ma_max, mb_max, mc_max, md_max, kbd, kbc, kad, kac, pbd, pbc, pad, pac, prim, fac*symm_fac)
    2722              : 
    2723      5564499 :       IF (jatom >= latom) THEN
    2724              :          i = 1
    2725              :          j = offset_bd
    2726     15219120 :          DO md = 1, md_max
    2727     29416357 :             DO mb = 1, mb_max
    2728     14197237 : !$OMP           ATOMIC
    2729              :                ks(j) = ks(j) + kbd(i)
    2730     14197237 :                i = i + 1
    2731     23865370 :                j = j + 1
    2732              :             END DO
    2733              :          END DO
    2734              :       ELSE
    2735              :          i = 1
    2736        28504 :          DO md = 1, md_max
    2737        14992 :             j = offset_bd + md - 1
    2738        47164 :             DO mb = 1, mb_max
    2739        18660 : !$OMP           ATOMIC
    2740              :                ks(j) = ks(j) - kbd(i)
    2741        18660 :                i = i + 1
    2742        33652 :                j = j + md_max
    2743              :             END DO
    2744              :          END DO
    2745              :       END IF
    2746      5564499 :       IF (jatom >= katom) THEN
    2747              :          i = 1
    2748              :          j = offset_bc
    2749     17101804 :          DO mc = 1, mc_max
    2750     33545825 :             DO mb = 1, mb_max
    2751     16444021 : !$OMP           ATOMIC
    2752              :                ks(j) = ks(j) - kbc(i)
    2753     16444021 :                i = i + 1
    2754     27981326 :                j = j + 1
    2755              :             END DO
    2756              :          END DO
    2757              :       ELSE
    2758              :          i = 1
    2759            0 :          DO mc = 1, mc_max
    2760            0 :             j = offset_bc + mc - 1
    2761            0 :             DO mb = 1, mb_max
    2762            0 : !$OMP           ATOMIC
    2763              :                ks(j) = ks(j) + kbc(i)
    2764            0 :                i = i + 1
    2765            0 :                j = j + mc_max
    2766              :             END DO
    2767              :          END DO
    2768              :       END IF
    2769      5564499 :       IF (iatom >= latom) THEN
    2770              :          i = 1
    2771              :          j = offset_ad
    2772     12161472 :          DO md = 1, md_max
    2773     27376447 :             DO ma = 1, ma_max
    2774     15214975 : !$OMP           ATOMIC
    2775              :                ks(j) = ks(j) - kad(i)
    2776     15214975 :                i = i + 1
    2777     23213018 :                j = j + 1
    2778              :             END DO
    2779              :          END DO
    2780              :       ELSE
    2781              :          i = 1
    2782      3086152 :          DO md = 1, md_max
    2783      1685082 :             j = offset_ad + md - 1
    2784      6859450 :             DO ma = 1, ma_max
    2785      3773298 : !$OMP           ATOMIC
    2786              :                ks(j) = ks(j) + kad(i)
    2787      3773298 :                i = i + 1
    2788      5458380 :                j = j + md_max
    2789              :             END DO
    2790              :          END DO
    2791              :       END IF
    2792              : ! XXXXXXXXXXXXXXXXXXXXXXXX
    2793      5564499 :       IF (iatom >= katom) THEN
    2794              :          i = 1
    2795              :          j = offset_ac
    2796     16604644 :          DO mc = 1, mc_max
    2797     38455863 :             DO ma = 1, ma_max
    2798     21851219 : !$OMP           ATOMIC
    2799              :                ks(j) = ks(j) + kac(i)
    2800     21851219 :                i = i + 1
    2801     33095532 :                j = j + 1
    2802              :             END DO
    2803              :          END DO
    2804              :       ELSE
    2805              :          i = 1
    2806       497160 :          DO mc = 1, mc_max
    2807       292992 :             j = offset_ac + mc - 1
    2808      1250254 :             DO ma = 1, ma_max
    2809       753094 : !$OMP           ATOMIC
    2810              :                ks(j) = ks(j) - kac(i)
    2811       753094 :                i = i + 1
    2812      1046086 :                j = j + mc_max
    2813              :             END DO
    2814              :          END DO
    2815              :       END IF
    2816              : 
    2817      5564499 :    END SUBROUTINE update_fock_matrix_as
    2818              : 
    2819              : ! **************************************************************************************************
    2820              : !> \brief ...
    2821              : !> \param i ...
    2822              : !> \param j ...
    2823              : !> \param k ...
    2824              : !> \param l ...
    2825              : !> \param set_offsets ...
    2826              : !> \param atom_offsets ...
    2827              : !> \param iset ...
    2828              : !> \param jset ...
    2829              : !> \param kset ...
    2830              : !> \param lset ...
    2831              : !> \param ma_max ...
    2832              : !> \param mb_max ...
    2833              : !> \param mc_max ...
    2834              : !> \param md_max ...
    2835              : !> \param prim ...
    2836              : !> \param output_unit ...
    2837              : ! **************************************************************************************************
    2838            0 :    SUBROUTINE print_integrals(i, j, k, l, set_offsets, atom_offsets, iset, jset, kset, lset, &
    2839            0 :                               ma_max, mb_max, mc_max, md_max, prim, output_unit)
    2840              :       INTEGER                                            :: i, j, k, l
    2841              :       INTEGER, DIMENSION(:, :, :, :), POINTER            :: set_offsets
    2842              :       INTEGER, DIMENSION(:, :), POINTER                  :: atom_offsets
    2843              :       INTEGER                                            :: iset, jset, kset, lset, ma_max, mb_max, &
    2844              :                                                             mc_max, md_max
    2845              :       REAL(dp), DIMENSION(ma_max*mb_max*mc_max*md_max), &
    2846              :          INTENT(IN)                                      :: prim
    2847              :       INTEGER, OPTIONAL                                  :: output_unit
    2848              : 
    2849              :       REAL(KIND=dp), PARAMETER                           :: eps_int = 1.0E-13_dp
    2850              : 
    2851              :       INTEGER                                            :: iint, ma, mb, mc, md, my_output_unit
    2852              : 
    2853            0 :       my_output_unit = 99
    2854            0 :       IF (PRESENT(output_unit)) my_output_unit = output_unit
    2855              : 
    2856            0 :       iint = 0
    2857            0 :       DO md = 1, md_max
    2858            0 :          DO mc = 1, mc_max
    2859            0 :             DO mb = 1, mb_max
    2860            0 :                DO ma = 1, ma_max
    2861            0 :                   iint = iint + 1
    2862            0 :                   IF (ABS(prim(iint)) > eps_int) THEN
    2863            0 :                      IF (my_output_unit > 0) THEN
    2864            0 :                         WRITE (my_output_unit, *) atom_offsets(i, 1) + ma + set_offsets(iset, 1, i, 1) - 1, &
    2865            0 :                            atom_offsets(j, 1) + ma + set_offsets(jset, 1, j, 1) - 1, &
    2866            0 :                            atom_offsets(k, 1) + ma + set_offsets(kset, 1, k, 1) - 1, &
    2867            0 :                            atom_offsets(l, 1) + ma + set_offsets(lset, 1, l, 1) - 1, &
    2868            0 :                            prim(iint)
    2869              :                      END IF
    2870              :                   END IF
    2871              :                END DO
    2872              :             END DO
    2873              :          END DO
    2874              :       END DO
    2875              : 
    2876            0 :    END SUBROUTINE print_integrals
    2877              : 
    2878              :    #:include "hfx_get_pmax_val.fypp"
    2879              : 
    2880              : END MODULE hfx_energy_potential
        

Generated by: LCOV version 2.0-1