LCOV - code coverage report
Current view: top level - src - gw_utils.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:51fc4cd) Lines: 93.0 % 1306 1214
Test Date: 2026-02-04 06:28:27 Functions: 95.7 % 47 45

            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
      10              : !> \author Jan Wilhelm
      11              : !> \date 07.2023
      12              : ! **************************************************************************************************
      13              : MODULE gw_utils
      14              :    USE atomic_kind_types,               ONLY: atomic_kind_type,&
      15              :                                               get_atomic_kind_set
      16              :    USE basis_set_types,                 ONLY: get_gto_basis_set,&
      17              :                                               gto_basis_set_type
      18              :    USE bibliography,                    ONLY: Graml2024,&
      19              :                                               cite_reference
      20              :    USE cell_types,                      ONLY: cell_type,&
      21              :                                               pbc,&
      22              :                                               scaled_to_real
      23              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      24              :                                               cp_blacs_env_release,&
      25              :                                               cp_blacs_env_type
      26              :    USE cp_cfm_types,                    ONLY: cp_cfm_create,&
      27              :                                               cp_cfm_release,&
      28              :                                               cp_cfm_to_cfm,&
      29              :                                               cp_cfm_to_fm,&
      30              :                                               cp_cfm_type
      31              :    USE cp_control_types,                ONLY: dft_control_type
      32              :    USE cp_dbcsr_api,                    ONLY: &
      33              :         dbcsr_create, dbcsr_distribution_release, dbcsr_distribution_type, dbcsr_p_type, &
      34              :         dbcsr_release, dbcsr_set, dbcsr_type, dbcsr_type_no_symmetry, dbcsr_type_symmetric
      35              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      36              :                                               copy_fm_to_dbcsr,&
      37              :                                               cp_dbcsr_dist2d_to_dist,&
      38              :                                               dbcsr_allocate_matrix_set,&
      39              :                                               dbcsr_deallocate_matrix_set
      40              :    USE cp_files,                        ONLY: close_file,&
      41              :                                               open_file
      42              :    USE cp_fm_basic_linalg,              ONLY: cp_fm_scale_and_add
      43              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      44              :                                               cp_fm_struct_release,&
      45              :                                               cp_fm_struct_type
      46              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      47              :                                               cp_fm_get_diag,&
      48              :                                               cp_fm_release,&
      49              :                                               cp_fm_set_all,&
      50              :                                               cp_fm_type
      51              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      52              :                                               cp_logger_type
      53              :    USE cp_output_handling,              ONLY: cp_print_key_generate_filename
      54              :    USE dbt_api,                         ONLY: &
      55              :         dbt_clear, dbt_create, dbt_destroy, dbt_filter, dbt_iterator_blocks_left, &
      56              :         dbt_iterator_next_block, dbt_iterator_start, dbt_iterator_stop, dbt_iterator_type, &
      57              :         dbt_mp_environ_pgrid, dbt_pgrid_create, dbt_pgrid_destroy, dbt_pgrid_type, dbt_type
      58              :    USE distribution_2d_types,           ONLY: distribution_2d_type
      59              :    USE gw_communication,                ONLY: fm_to_local_array
      60              :    USE gw_integrals,                    ONLY: build_3c_integral_block
      61              :    USE input_constants,                 ONLY: do_potential_truncated,&
      62              :                                               large_cell_Gamma,&
      63              :                                               ri_rpa_g0w0_crossing_newton,&
      64              :                                               rtp_method_bse,&
      65              :                                               small_cell_full_kp,&
      66              :                                               xc_none
      67              :    USE input_section_types,             ONLY: section_vals_get,&
      68              :                                               section_vals_get_subs_vals,&
      69              :                                               section_vals_type,&
      70              :                                               section_vals_val_get,&
      71              :                                               section_vals_val_set
      72              :    USE kinds,                           ONLY: default_path_length,&
      73              :                                               default_string_length,&
      74              :                                               dp,&
      75              :                                               int_8
      76              :    USE kpoint_k_r_trafo_simple,         ONLY: rs_to_kp
      77              :    USE kpoint_types,                    ONLY: get_kpoint_info,&
      78              :                                               kpoint_create,&
      79              :                                               kpoint_type
      80              :    USE libint_2c_3c,                    ONLY: libint_potential_type
      81              :    USE libint_wrapper,                  ONLY: cp_libint_static_cleanup,&
      82              :                                               cp_libint_static_init
      83              :    USE machine,                         ONLY: m_memory,&
      84              :                                               m_walltime
      85              :    USE mathconstants,                   ONLY: gaussi,&
      86              :                                               z_one,&
      87              :                                               z_zero
      88              :    USE mathlib,                         ONLY: diag_complex,&
      89              :                                               gcd
      90              :    USE message_passing,                 ONLY: mp_cart_type,&
      91              :                                               mp_para_env_type
      92              :    USE minimax_exp,                     ONLY: get_exp_minimax_coeff
      93              :    USE minimax_exp_gw,                  ONLY: get_exp_minimax_coeff_gw
      94              :    USE minimax_rpa,                     ONLY: get_rpa_minimax_coeff,&
      95              :                                               get_rpa_minimax_coeff_larger_grid
      96              :    USE mp2_gpw,                         ONLY: create_mat_munu
      97              :    USE mp2_grids,                       ONLY: get_l_sq_wghts_cos_tf_t_to_w,&
      98              :                                               get_l_sq_wghts_cos_tf_w_to_t,&
      99              :                                               get_l_sq_wghts_sin_tf_t_to_w
     100              :    USE mp2_ri_2c,                       ONLY: trunc_coulomb_for_exchange
     101              :    USE parallel_gemm_api,               ONLY: parallel_gemm
     102              :    USE particle_methods,                ONLY: get_particle_set
     103              :    USE particle_types,                  ONLY: particle_type
     104              :    USE physcon,                         ONLY: angstrom,&
     105              :                                               evolt
     106              :    USE post_scf_bandstructure_types,    ONLY: post_scf_bandstructure_type
     107              :    USE post_scf_bandstructure_utils,    ONLY: rsmat_to_kp
     108              :    USE qs_energy_types,                 ONLY: qs_energy_type
     109              :    USE qs_environment_types,            ONLY: get_qs_env,&
     110              :                                               qs_env_part_release,&
     111              :                                               qs_environment_type
     112              :    USE qs_integral_utils,               ONLY: basis_set_list_setup
     113              :    USE qs_interactions,                 ONLY: init_interaction_radii_orb_basis
     114              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
     115              :                                               qs_kind_type
     116              :    USE qs_ks_methods,                   ONLY: qs_ks_build_kohn_sham_matrix
     117              :    USE qs_neighbor_list_types,          ONLY: neighbor_list_set_p_type,&
     118              :                                               release_neighbor_list_sets
     119              :    USE qs_tensors,                      ONLY: build_2c_integrals,&
     120              :                                               build_2c_neighbor_lists,&
     121              :                                               build_3c_integrals,&
     122              :                                               build_3c_neighbor_lists,&
     123              :                                               get_tensor_occupancy,&
     124              :                                               neighbor_list_3c_destroy
     125              :    USE qs_tensors_types,                ONLY: create_2c_tensor,&
     126              :                                               create_3c_tensor,&
     127              :                                               distribution_3d_create,&
     128              :                                               distribution_3d_type,&
     129              :                                               neighbor_list_3c_type
     130              :    USE rpa_gw,                          ONLY: continuation_pade
     131              : #include "base/base_uses.f90"
     132              : 
     133              :    IMPLICIT NONE
     134              : 
     135              :    PRIVATE
     136              : 
     137              :    PUBLIC :: create_and_init_bs_env_for_gw, de_init_bs_env, get_i_j_atoms, &
     138              :              compute_xkp, time_to_freq, analyt_conti_and_print, &
     139              :              add_R, is_cell_in_index_to_cell, get_V_tr_R, power
     140              : 
     141              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'gw_utils'
     142              : 
     143              : CONTAINS
     144              : 
     145              : ! **************************************************************************************************
     146              : !> \brief ...
     147              : !> \param qs_env ...
     148              : !> \param bs_env ...
     149              : !> \param bs_sec ...
     150              : ! **************************************************************************************************
     151           28 :    SUBROUTINE create_and_init_bs_env_for_gw(qs_env, bs_env, bs_sec)
     152              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     153              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     154              :       TYPE(section_vals_type), POINTER                   :: bs_sec
     155              : 
     156              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'create_and_init_bs_env_for_gw'
     157              : 
     158              :       INTEGER                                            :: handle
     159              : 
     160           28 :       CALL timeset(routineN, handle)
     161              : 
     162           28 :       CALL cite_reference(Graml2024)
     163              : 
     164           28 :       CALL read_gw_input_parameters(bs_env, bs_sec)
     165              : 
     166           28 :       CALL print_header_and_input_parameters(bs_env)
     167              : 
     168           28 :       CALL setup_AO_and_RI_basis_set(qs_env, bs_env)
     169              : 
     170           28 :       CALL get_RI_basis_and_basis_function_indices(qs_env, bs_env)
     171              : 
     172           28 :       CALL set_heuristic_parameters(bs_env, qs_env)
     173              : 
     174           28 :       CALL cp_libint_static_init()
     175              : 
     176           28 :       CALL setup_kpoints_chi_eps_W(bs_env, bs_env%kpoints_chi_eps_W)
     177              : 
     178           28 :       IF (bs_env%small_cell_full_kp_or_large_cell_Gamma == small_cell_full_kp) THEN
     179            6 :          CALL setup_cells_3c(qs_env, bs_env)
     180              :       END IF
     181              : 
     182           28 :       CALL set_parallelization_parameters(qs_env, bs_env)
     183              : 
     184           28 :       CALL allocate_matrices(qs_env, bs_env)
     185              : 
     186           28 :       CALL compute_V_xc(qs_env, bs_env)
     187              : 
     188           28 :       CALL create_tensors(qs_env, bs_env)
     189              : 
     190           50 :       SELECT CASE (bs_env%small_cell_full_kp_or_large_cell_Gamma)
     191              :       CASE (large_cell_Gamma)
     192              : 
     193           22 :          CALL allocate_GW_eigenvalues(bs_env)
     194              : 
     195           22 :          CALL check_sparsity_3c(qs_env, bs_env)
     196              : 
     197           22 :          CALL set_sparsity_parallelization_parameters(bs_env)
     198              : 
     199           22 :          CALL check_for_restart_files(qs_env, bs_env)
     200              : 
     201              :       CASE (small_cell_full_kp)
     202              : 
     203            6 :          CALL compute_3c_integrals(qs_env, bs_env)
     204              : 
     205            6 :          CALL setup_cells_Delta_R(bs_env)
     206              : 
     207            6 :          CALL setup_parallelization_Delta_R(bs_env)
     208              : 
     209            6 :          CALL allocate_matrices_small_cell_full_kp(qs_env, bs_env)
     210              : 
     211            6 :          CALL trafo_V_xc_R_to_kp(qs_env, bs_env)
     212              : 
     213           34 :          CALL heuristic_RI_regularization(qs_env, bs_env)
     214              : 
     215              :       END SELECT
     216              : 
     217           28 :       CALL setup_time_and_frequency_minimax_grid(bs_env)
     218              : 
     219              :       ! free memory in qs_env; only if one is not calculating the LDOS because
     220              :       ! we need real-space grid operations in pw_env, task_list for the LDOS
     221              :       ! Recommendation in case of memory issues: first perform GW calculation without calculating
     222              :       !                                          LDOS (to safe memor). Then, use GW restart files
     223              :       !                                          in a subsequent calculation to calculate the LDOS
     224              :       ! Marek : TODO - boolean that does not interfere with RTP init but sets this to correct value
     225              :       IF (.NOT. bs_env%do_ldos .AND. .FALSE.) THEN
     226              :          CALL qs_env_part_release(qs_env)
     227              :       END IF
     228              : 
     229           28 :       CALL timestop(handle)
     230              : 
     231           28 :    END SUBROUTINE create_and_init_bs_env_for_gw
     232              : 
     233              : ! **************************************************************************************************
     234              : !> \brief ...
     235              : !> \param bs_env ...
     236              : ! **************************************************************************************************
     237           28 :    SUBROUTINE de_init_bs_env(bs_env)
     238              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     239              : 
     240              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'de_init_bs_env'
     241              : 
     242              :       INTEGER                                            :: handle
     243              : 
     244           28 :       CALL timeset(routineN, handle)
     245              :       ! deallocate quantities here which:
     246              :       ! 1. cannot be deallocated in bs_env_release due to circular dependencies
     247              :       ! 2. consume a lot of memory and should not be kept until the quantity is
     248              :       !    deallocated in bs_env_release
     249              : 
     250           28 :       IF (ASSOCIATED(bs_env%nl_3c%ij_list) .AND. (bs_env%rtp_method == rtp_method_bse)) THEN
     251           12 :          IF (bs_env%unit_nr > 0) WRITE (bs_env%unit_nr, *) "Retaining nl_3c for RTBSE"
     252              :       ELSE
     253           16 :          CALL neighbor_list_3c_destroy(bs_env%nl_3c)
     254              :       END IF
     255              : 
     256           28 :       CALL cp_libint_static_cleanup()
     257              : 
     258           28 :       CALL timestop(handle)
     259              : 
     260           28 :    END SUBROUTINE de_init_bs_env
     261              : 
     262              : ! **************************************************************************************************
     263              : !> \brief ...
     264              : !> \param bs_env ...
     265              : !> \param bs_sec ...
     266              : ! **************************************************************************************************
     267           28 :    SUBROUTINE read_gw_input_parameters(bs_env, bs_sec)
     268              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     269              :       TYPE(section_vals_type), POINTER                   :: bs_sec
     270              : 
     271              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'read_gw_input_parameters'
     272              : 
     273              :       INTEGER                                            :: handle
     274              :       TYPE(section_vals_type), POINTER                   :: gw_sec
     275              : 
     276           28 :       CALL timeset(routineN, handle)
     277              : 
     278           28 :       NULLIFY (gw_sec)
     279           28 :       gw_sec => section_vals_get_subs_vals(bs_sec, "GW")
     280              : 
     281           28 :       CALL section_vals_val_get(gw_sec, "NUM_TIME_FREQ_POINTS", i_val=bs_env%num_time_freq_points)
     282           28 :       CALL section_vals_val_get(gw_sec, "EPS_FILTER", r_val=bs_env%eps_filter)
     283           28 :       CALL section_vals_val_get(gw_sec, "REGULARIZATION_RI", r_val=bs_env%input_regularization_RI)
     284           28 :       CALL section_vals_val_get(gw_sec, "REGULARIZATION_MINIMAX", r_val=bs_env%input_regularization_minimax)
     285           28 :       CALL section_vals_val_get(gw_sec, "CUTOFF_RADIUS_RI", r_val=bs_env%ri_metric%cutoff_radius)
     286           28 :       CALL section_vals_val_get(gw_sec, "MEMORY_PER_PROC", r_val=bs_env%input_memory_per_proc_GB)
     287           28 :       CALL section_vals_val_get(gw_sec, "APPROX_KP_EXTRAPOL", l_val=bs_env%approx_kp_extrapol)
     288           28 :       CALL section_vals_val_get(gw_sec, "SIZE_LATTICE_SUM", i_val=bs_env%size_lattice_sum_V)
     289           28 :       CALL section_vals_val_get(gw_sec, "KPOINTS_W", i_vals=bs_env%nkp_grid_chi_eps_W_input)
     290           28 :       CALL section_vals_val_get(gw_sec, "HEDIN_SHIFT", l_val=bs_env%do_hedin_shift)
     291           28 :       CALL section_vals_val_get(gw_sec, "FREQ_MAX_FIT", r_val=bs_env%freq_max_fit)
     292           28 :       CALL section_vals_val_get(gw_sec, "PRINT%PRINT_DBT_CONTRACT", l_val=bs_env%print_contract)
     293           28 :       CALL section_vals_val_get(gw_sec, "PRINT%PRINT_DBT_CONTRACT_VERBOSE", l_val=bs_env%print_contract_verbose)
     294              : 
     295           28 :       IF (bs_env%print_contract) THEN
     296            0 :          bs_env%unit_nr_contract = bs_env%unit_nr
     297              :       ELSE
     298           28 :          bs_env%unit_nr_contract = 0
     299              :       END IF
     300           28 :       CALL timestop(handle)
     301              : 
     302           28 :    END SUBROUTINE read_gw_input_parameters
     303              : 
     304              : ! **************************************************************************************************
     305              : !> \brief ...
     306              : !> \param qs_env ...
     307              : !> \param bs_env ...
     308              : ! **************************************************************************************************
     309           28 :    SUBROUTINE setup_AO_and_RI_basis_set(qs_env, bs_env)
     310              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     311              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     312              : 
     313              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_AO_and_RI_basis_set'
     314              : 
     315              :       INTEGER                                            :: handle, natom, nkind
     316           28 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     317           28 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     318              : 
     319           28 :       CALL timeset(routineN, handle)
     320              : 
     321              :       CALL get_qs_env(qs_env, &
     322              :                       qs_kind_set=qs_kind_set, &
     323              :                       particle_set=particle_set, &
     324           28 :                       natom=natom, nkind=nkind)
     325              : 
     326              :       ! set up basis
     327          140 :       ALLOCATE (bs_env%sizes_RI(natom), bs_env%sizes_AO(natom))
     328          228 :       ALLOCATE (bs_env%basis_set_RI(nkind), bs_env%basis_set_AO(nkind))
     329              : 
     330           28 :       CALL basis_set_list_setup(bs_env%basis_set_RI, "RI_AUX", qs_kind_set)
     331           28 :       CALL basis_set_list_setup(bs_env%basis_set_AO, "ORB", qs_kind_set)
     332              : 
     333              :       CALL get_particle_set(particle_set, qs_kind_set, nsgf=bs_env%sizes_RI, &
     334           28 :                             basis=bs_env%basis_set_RI)
     335              :       CALL get_particle_set(particle_set, qs_kind_set, nsgf=bs_env%sizes_AO, &
     336           28 :                             basis=bs_env%basis_set_AO)
     337              : 
     338           28 :       CALL timestop(handle)
     339              : 
     340           28 :    END SUBROUTINE setup_AO_and_RI_basis_set
     341              : 
     342              : ! **************************************************************************************************
     343              : !> \brief ...
     344              : !> \param qs_env ...
     345              : !> \param bs_env ...
     346              : ! **************************************************************************************************
     347           28 :    SUBROUTINE get_RI_basis_and_basis_function_indices(qs_env, bs_env)
     348              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     349              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     350              : 
     351              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_RI_basis_and_basis_function_indices'
     352              : 
     353              :       INTEGER                                            :: handle, i_RI, iatom, ikind, iset, &
     354              :                                                             max_AO_bf_per_atom, n_ao_test, n_atom, &
     355              :                                                             n_kind, n_RI, nset, nsgf, u
     356           28 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: kind_of
     357           28 :       INTEGER, DIMENSION(:), POINTER                     :: l_max, l_min, nsgf_set
     358           28 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     359              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a
     360           28 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     361              : 
     362           28 :       CALL timeset(routineN, handle)
     363              : 
     364              :       ! determine RI basis set size
     365           28 :       CALL get_qs_env(qs_env, atomic_kind_set=atomic_kind_set, qs_kind_set=qs_kind_set)
     366              : 
     367           28 :       n_kind = SIZE(qs_kind_set)
     368           28 :       n_atom = bs_env%n_atom
     369              : 
     370           28 :       CALL get_atomic_kind_set(atomic_kind_set, kind_of=kind_of)
     371              : 
     372           72 :       DO ikind = 1, n_kind
     373              :          CALL get_qs_kind(qs_kind=qs_kind_set(ikind), basis_set=basis_set_a, &
     374           44 :                           basis_type="RI_AUX")
     375           72 :          IF (.NOT. ASSOCIATED(basis_set_a)) THEN
     376              :             CALL cp_abort(__LOCATION__, &
     377            0 :                           "At least one RI_AUX basis set was not explicitly invoked in &KIND-section.")
     378              :          END IF
     379              :       END DO
     380              : 
     381           84 :       ALLOCATE (bs_env%i_RI_start_from_atom(n_atom))
     382           56 :       ALLOCATE (bs_env%i_RI_end_from_atom(n_atom))
     383           56 :       ALLOCATE (bs_env%i_ao_start_from_atom(n_atom))
     384           56 :       ALLOCATE (bs_env%i_ao_end_from_atom(n_atom))
     385              : 
     386           28 :       n_RI = 0
     387           92 :       DO iatom = 1, n_atom
     388           64 :          bs_env%i_RI_start_from_atom(iatom) = n_RI + 1
     389           64 :          ikind = kind_of(iatom)
     390           64 :          CALL get_qs_kind(qs_kind=qs_kind_set(ikind), nsgf=nsgf, basis_type="RI_AUX")
     391           64 :          n_RI = n_RI + nsgf
     392           92 :          bs_env%i_RI_end_from_atom(iatom) = n_RI
     393              :       END DO
     394           28 :       bs_env%n_RI = n_RI
     395              : 
     396           28 :       max_AO_bf_per_atom = 0
     397           28 :       n_ao_test = 0
     398           92 :       DO iatom = 1, n_atom
     399           64 :          bs_env%i_ao_start_from_atom(iatom) = n_ao_test + 1
     400           64 :          ikind = kind_of(iatom)
     401           64 :          CALL get_qs_kind(qs_kind=qs_kind_set(ikind), nsgf=nsgf, basis_type="ORB")
     402           64 :          n_ao_test = n_ao_test + nsgf
     403           64 :          bs_env%i_ao_end_from_atom(iatom) = n_ao_test
     404           92 :          max_AO_bf_per_atom = MAX(max_AO_bf_per_atom, nsgf)
     405              :       END DO
     406           28 :       CPASSERT(n_ao_test == bs_env%n_ao)
     407           28 :       bs_env%max_AO_bf_per_atom = max_AO_bf_per_atom
     408              : 
     409           84 :       ALLOCATE (bs_env%l_RI(n_RI))
     410           28 :       i_RI = 0
     411           92 :       DO iatom = 1, n_atom
     412           64 :          ikind = kind_of(iatom)
     413              : 
     414           64 :          nset = bs_env%basis_set_RI(ikind)%gto_basis_set%nset
     415           64 :          l_max => bs_env%basis_set_RI(ikind)%gto_basis_set%lmax
     416           64 :          l_min => bs_env%basis_set_RI(ikind)%gto_basis_set%lmin
     417           64 :          nsgf_set => bs_env%basis_set_RI(ikind)%gto_basis_set%nsgf_set
     418              : 
     419          268 :          DO iset = 1, nset
     420          176 :             CPASSERT(l_max(iset) == l_min(iset))
     421          536 :             bs_env%l_RI(i_RI + 1:i_RI + nsgf_set(iset)) = l_max(iset)
     422          240 :             i_RI = i_RI + nsgf_set(iset)
     423              :          END DO
     424              : 
     425              :       END DO
     426           28 :       CPASSERT(i_RI == n_RI)
     427              : 
     428           28 :       u = bs_env%unit_nr
     429              : 
     430           28 :       IF (u > 0) THEN
     431           14 :          WRITE (u, FMT="(T2,A)") " "
     432           14 :          WRITE (u, FMT="(T2,2A,T75,I8)") "Number of auxiliary Gaussian basis functions ", &
     433           28 :             "for χ, ε, W", n_RI
     434              :       END IF
     435              : 
     436           28 :       CALL timestop(handle)
     437              : 
     438           56 :    END SUBROUTINE get_RI_basis_and_basis_function_indices
     439              : 
     440              : ! **************************************************************************************************
     441              : !> \brief ...
     442              : !> \param bs_env ...
     443              : !> \param kpoints ...
     444              : ! **************************************************************************************************
     445           28 :    SUBROUTINE setup_kpoints_chi_eps_W(bs_env, kpoints)
     446              : 
     447              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     448              :       TYPE(kpoint_type), POINTER                         :: kpoints
     449              : 
     450              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_kpoints_chi_eps_W'
     451              : 
     452              :       INTEGER                                            :: handle, i_dim, n_dim, nkp, nkp_extra, &
     453              :                                                             nkp_orig, u
     454              :       INTEGER, DIMENSION(3)                              :: nkp_grid, nkp_grid_extra, periodic
     455              :       REAL(KIND=dp)                                      :: exp_s_p, n_dim_inv
     456              : 
     457           28 :       CALL timeset(routineN, handle)
     458              : 
     459              :       ! routine adapted from mp2_integrals.F
     460           28 :       NULLIFY (kpoints)
     461           28 :       CALL kpoint_create(kpoints)
     462              : 
     463           28 :       kpoints%kp_scheme = "GENERAL"
     464              : 
     465          112 :       periodic(1:3) = bs_env%periodic(1:3)
     466              : 
     467           28 :       CPASSERT(SIZE(bs_env%nkp_grid_chi_eps_W_input) == 3)
     468              : 
     469              :       IF (bs_env%nkp_grid_chi_eps_W_input(1) > 0 .AND. &
     470           28 :           bs_env%nkp_grid_chi_eps_W_input(2) > 0 .AND. &
     471              :           bs_env%nkp_grid_chi_eps_W_input(3) > 0) THEN
     472              :          ! 1. k-point mesh for χ, ε, W from input
     473            0 :          DO i_dim = 1, 3
     474            0 :             SELECT CASE (periodic(i_dim))
     475              :             CASE (0)
     476            0 :                nkp_grid(i_dim) = 1
     477            0 :                nkp_grid_extra(i_dim) = 1
     478              :             CASE (1)
     479            0 :                nkp_grid(i_dim) = bs_env%nkp_grid_chi_eps_W_input(i_dim)
     480            0 :                nkp_grid_extra(i_dim) = nkp_grid(i_dim)*2
     481              :             CASE DEFAULT
     482            0 :                CPABORT("Error in periodicity.")
     483              :             END SELECT
     484              :          END DO
     485              : 
     486              :       ELSE IF (bs_env%nkp_grid_chi_eps_W_input(1) == -1 .AND. &
     487           28 :                bs_env%nkp_grid_chi_eps_W_input(2) == -1 .AND. &
     488              :                bs_env%nkp_grid_chi_eps_W_input(3) == -1) THEN
     489              :          ! 2. automatic k-point mesh for χ, ε, W
     490              : 
     491          112 :          DO i_dim = 1, 3
     492              : 
     493           84 :             CPASSERT(periodic(i_dim) == 0 .OR. periodic(i_dim) == 1)
     494              : 
     495           28 :             SELECT CASE (periodic(i_dim))
     496              :             CASE (0)
     497           52 :                nkp_grid(i_dim) = 1
     498           52 :                nkp_grid_extra(i_dim) = 1
     499              :             CASE (1)
     500           52 :                SELECT CASE (bs_env%small_cell_full_kp_or_large_cell_Gamma)
     501              :                CASE (large_cell_Gamma)
     502           20 :                   nkp_grid(i_dim) = 4
     503           20 :                   nkp_grid_extra(i_dim) = 6
     504              :                CASE (small_cell_full_kp)
     505           12 :                   nkp_grid(i_dim) = bs_env%kpoints_scf_desymm%nkp_grid(i_dim)*4
     506           32 :                   nkp_grid_extra(i_dim) = bs_env%kpoints_scf_desymm%nkp_grid(i_dim)*8
     507              :                END SELECT
     508              :             CASE DEFAULT
     509           84 :                CPABORT("Error in periodicity.")
     510              :             END SELECT
     511              : 
     512              :          END DO
     513              : 
     514              :       ELSE
     515              : 
     516            0 :          CPABORT("An error occured when setting up the k-mesh for W.")
     517              : 
     518              :       END IF
     519              : 
     520           28 :       nkp_orig = MAX(nkp_grid(1)*nkp_grid(2)*nkp_grid(3)/2, 1)
     521              : 
     522           28 :       nkp_extra = nkp_grid_extra(1)*nkp_grid_extra(2)*nkp_grid_extra(3)/2
     523              : 
     524           28 :       nkp = nkp_orig + nkp_extra
     525              : 
     526          112 :       kpoints%nkp_grid(1:3) = nkp_grid(1:3)
     527           28 :       kpoints%nkp = nkp
     528              : 
     529          112 :       bs_env%nkp_grid_chi_eps_W_orig(1:3) = nkp_grid(1:3)
     530          112 :       bs_env%nkp_grid_chi_eps_W_extra(1:3) = nkp_grid_extra(1:3)
     531           28 :       bs_env%nkp_chi_eps_W_orig = nkp_orig
     532           28 :       bs_env%nkp_chi_eps_W_extra = nkp_extra
     533           28 :       bs_env%nkp_chi_eps_W_orig_plus_extra = nkp
     534              : 
     535          140 :       ALLOCATE (kpoints%xkp(3, nkp), kpoints%wkp(nkp))
     536          140 :       ALLOCATE (bs_env%wkp_no_extra(nkp), bs_env%wkp_s_p(nkp))
     537              : 
     538           28 :       CALL compute_xkp(kpoints%xkp, 1, nkp_orig, nkp_grid)
     539           28 :       CALL compute_xkp(kpoints%xkp, nkp_orig + 1, nkp, nkp_grid_extra)
     540              : 
     541          112 :       n_dim = SUM(periodic)
     542           28 :       IF (n_dim == 0) THEN
     543              :          ! molecules
     544           12 :          kpoints%wkp(1) = 1.0_dp
     545           12 :          bs_env%wkp_s_p(1) = 1.0_dp
     546           12 :          bs_env%wkp_no_extra(1) = 1.0_dp
     547              :       ELSE
     548              : 
     549           16 :          n_dim_inv = 1.0_dp/REAL(n_dim, KIND=dp)
     550              : 
     551              :          ! k-point weights are chosen to automatically extrapolate the k-point mesh
     552           16 :          CALL compute_wkp(kpoints%wkp(1:nkp_orig), nkp_orig, nkp_extra, n_dim_inv)
     553           16 :          CALL compute_wkp(kpoints%wkp(nkp_orig + 1:nkp), nkp_extra, nkp_orig, n_dim_inv)
     554              : 
     555          864 :          bs_env%wkp_no_extra(1:nkp_orig) = 0.0_dp
     556         3268 :          bs_env%wkp_no_extra(nkp_orig + 1:nkp) = 1.0_dp/REAL(nkp_extra, KIND=dp)
     557              : 
     558           16 :          IF (n_dim == 3) THEN
     559              :             ! W_PQ(k) for an s-function P and a p-function Q diverges as 1/k at k=0
     560              :             ! (instead of 1/k^2 for P and Q both being s-functions).
     561            0 :             exp_s_p = 2.0_dp*n_dim_inv
     562            0 :             CALL compute_wkp(bs_env%wkp_s_p(1:nkp_orig), nkp_orig, nkp_extra, exp_s_p)
     563            0 :             CALL compute_wkp(bs_env%wkp_s_p(nkp_orig + 1:nkp), nkp_extra, nkp_orig, exp_s_p)
     564              :          ELSE
     565         4116 :             bs_env%wkp_s_p(1:nkp) = bs_env%wkp_no_extra(1:nkp)
     566              :          END IF
     567              : 
     568              :       END IF
     569              : 
     570           28 :       IF (bs_env%approx_kp_extrapol) THEN
     571            2 :          bs_env%wkp_orig = 1.0_dp/REAL(nkp_orig, KIND=dp)
     572              :       END IF
     573              : 
     574              :       ! heuristic parameter: how many k-points for χ, ε, and W are used simultaneously
     575              :       ! (less simultaneous k-points: less memory, but more computational effort because of
     576              :       !  recomputation of V(k))
     577           28 :       bs_env%nkp_chi_eps_W_batch = 4
     578              : 
     579              :       bs_env%num_chi_eps_W_batches = (bs_env%nkp_chi_eps_W_orig_plus_extra - 1)/ &
     580           28 :                                      bs_env%nkp_chi_eps_W_batch + 1
     581              : 
     582           28 :       u = bs_env%unit_nr
     583              : 
     584           28 :       IF (u > 0) THEN
     585           14 :          WRITE (u, FMT="(T2,A)") " "
     586           14 :          WRITE (u, FMT="(T2,1A,T71,3I4)") "K-point mesh 1 for χ, ε, W", nkp_grid(1:3)
     587           14 :          WRITE (u, FMT="(T2,2A,T71,3I4)") "K-point mesh 2 for χ, ε, W ", &
     588           28 :             "(for k-point extrapolation of W)", nkp_grid_extra(1:3)
     589           14 :          WRITE (u, FMT="(T2,A,T80,L)") "Approximate the k-point extrapolation", &
     590           28 :             bs_env%approx_kp_extrapol
     591              :       END IF
     592              : 
     593           28 :       CALL timestop(handle)
     594              : 
     595           28 :    END SUBROUTINE setup_kpoints_chi_eps_W
     596              : 
     597              : ! **************************************************************************************************
     598              : !> \brief ...
     599              : !> \param xkp ...
     600              : !> \param ikp_start ...
     601              : !> \param ikp_end ...
     602              : !> \param grid ...
     603              : ! **************************************************************************************************
     604           56 :    SUBROUTINE compute_xkp(xkp, ikp_start, ikp_end, grid)
     605              : 
     606              :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: xkp
     607              :       INTEGER                                            :: ikp_start, ikp_end
     608              :       INTEGER, DIMENSION(3)                              :: grid
     609              : 
     610              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_xkp'
     611              : 
     612              :       INTEGER                                            :: handle, i, ix, iy, iz
     613              : 
     614           56 :       CALL timeset(routineN, handle)
     615              : 
     616           56 :       i = ikp_start
     617          236 :       DO ix = 1, grid(1)
     618         3280 :          DO iy = 1, grid(2)
     619        11448 :             DO iz = 1, grid(3)
     620              : 
     621         8224 :                IF (i > ikp_end) CYCLE
     622              : 
     623         4112 :                xkp(1, i) = REAL(2*ix - grid(1) - 1, KIND=dp)/(2._dp*REAL(grid(1), KIND=dp))
     624         4112 :                xkp(2, i) = REAL(2*iy - grid(2) - 1, KIND=dp)/(2._dp*REAL(grid(2), KIND=dp))
     625         4112 :                xkp(3, i) = REAL(2*iz - grid(3) - 1, KIND=dp)/(2._dp*REAL(grid(3), KIND=dp))
     626        11268 :                i = i + 1
     627              : 
     628              :             END DO
     629              :          END DO
     630              :       END DO
     631              : 
     632           56 :       CALL timestop(handle)
     633              : 
     634           56 :    END SUBROUTINE compute_xkp
     635              : 
     636              : ! **************************************************************************************************
     637              : !> \brief ...
     638              : !> \param wkp ...
     639              : !> \param nkp_1 ...
     640              : !> \param nkp_2 ...
     641              : !> \param exponent ...
     642              : ! **************************************************************************************************
     643           32 :    SUBROUTINE compute_wkp(wkp, nkp_1, nkp_2, exponent)
     644              :       REAL(KIND=dp), DIMENSION(:)                        :: wkp
     645              :       INTEGER                                            :: nkp_1, nkp_2
     646              :       REAL(KIND=dp)                                      :: exponent
     647              : 
     648              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_wkp'
     649              : 
     650              :       INTEGER                                            :: handle
     651              :       REAL(KIND=dp)                                      :: nkp_ratio
     652              : 
     653           32 :       CALL timeset(routineN, handle)
     654              : 
     655           32 :       nkp_ratio = REAL(nkp_2, KIND=dp)/REAL(nkp_1, KIND=dp)
     656              : 
     657         4132 :       wkp(:) = 1.0_dp/REAL(nkp_1, KIND=dp)/(1.0_dp - nkp_ratio**exponent)
     658              : 
     659           32 :       CALL timestop(handle)
     660              : 
     661           32 :    END SUBROUTINE compute_wkp
     662              : 
     663              : ! **************************************************************************************************
     664              : !> \brief ...
     665              : !> \param qs_env ...
     666              : !> \param bs_env ...
     667              : ! **************************************************************************************************
     668           28 :    SUBROUTINE allocate_matrices(qs_env, bs_env)
     669              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     670              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     671              : 
     672              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'allocate_matrices'
     673              : 
     674              :       INTEGER                                            :: handle, i_t
     675              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env, blacs_env_tensor
     676              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct, fm_struct_RI_global
     677              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     678              : 
     679           28 :       CALL timeset(routineN, handle)
     680              : 
     681           28 :       CALL get_qs_env(qs_env, para_env=para_env, blacs_env=blacs_env)
     682              : 
     683           28 :       fm_struct => bs_env%fm_ks_Gamma(1)%matrix_struct
     684              : 
     685           28 :       CALL cp_fm_create(bs_env%fm_Gocc, fm_struct)
     686           28 :       CALL cp_fm_create(bs_env%fm_Gvir, fm_struct)
     687              : 
     688           28 :       NULLIFY (fm_struct_RI_global)
     689              :       CALL cp_fm_struct_create(fm_struct_RI_global, context=blacs_env, nrow_global=bs_env%n_RI, &
     690           28 :                                ncol_global=bs_env%n_RI, para_env=para_env)
     691           28 :       CALL cp_fm_create(bs_env%fm_RI_RI, fm_struct_RI_global)
     692           28 :       CALL cp_fm_create(bs_env%fm_chi_Gamma_freq, fm_struct_RI_global)
     693           28 :       CALL cp_fm_create(bs_env%fm_W_MIC_freq, fm_struct_RI_global)
     694           28 :       IF (bs_env%approx_kp_extrapol) THEN
     695            2 :          CALL cp_fm_create(bs_env%fm_W_MIC_freq_1_extra, fm_struct_RI_global)
     696            2 :          CALL cp_fm_create(bs_env%fm_W_MIC_freq_1_no_extra, fm_struct_RI_global)
     697            2 :          CALL cp_fm_set_all(bs_env%fm_W_MIC_freq_1_extra, 0.0_dp)
     698            2 :          CALL cp_fm_set_all(bs_env%fm_W_MIC_freq_1_no_extra, 0.0_dp)
     699              :       END IF
     700           28 :       CALL cp_fm_struct_release(fm_struct_RI_global)
     701              : 
     702              :       ! create blacs_env for subgroups of tensor operations
     703           28 :       NULLIFY (blacs_env_tensor)
     704           28 :       CALL cp_blacs_env_create(blacs_env=blacs_env_tensor, para_env=bs_env%para_env_tensor)
     705              : 
     706              :       ! allocate dbcsr matrices in the tensor subgroup; actually, one only needs a small
     707              :       ! subset of blocks in the tensor subgroup, however, all atomic blocks are allocated.
     708              :       ! One might think of creating a dbcsr matrix with only the blocks that are needed
     709              :       ! in the tensor subgroup
     710              :       CALL create_mat_munu(bs_env%mat_ao_ao_tensor, qs_env, bs_env%eps_atom_grid_2d_mat, &
     711           28 :                            blacs_env_tensor, do_ri_aux_basis=.FALSE.)
     712              : 
     713              :       CALL create_mat_munu(bs_env%mat_RI_RI_tensor, qs_env, bs_env%eps_atom_grid_2d_mat, &
     714           28 :                            blacs_env_tensor, do_ri_aux_basis=.TRUE.)
     715              : 
     716              :       CALL create_mat_munu(bs_env%mat_RI_RI, qs_env, bs_env%eps_atom_grid_2d_mat, &
     717           28 :                            blacs_env, do_ri_aux_basis=.TRUE.)
     718              : 
     719           28 :       CALL cp_blacs_env_release(blacs_env_tensor)
     720              : 
     721           28 :       NULLIFY (bs_env%mat_chi_Gamma_tau)
     722           28 :       CALL dbcsr_allocate_matrix_set(bs_env%mat_chi_Gamma_tau, bs_env%num_time_freq_points)
     723              : 
     724          396 :       DO i_t = 1, bs_env%num_time_freq_points
     725          368 :          ALLOCATE (bs_env%mat_chi_Gamma_tau(i_t)%matrix)
     726          396 :          CALL dbcsr_create(bs_env%mat_chi_Gamma_tau(i_t)%matrix, template=bs_env%mat_RI_RI%matrix)
     727              :       END DO
     728              : 
     729           28 :       CALL timestop(handle)
     730              : 
     731           28 :    END SUBROUTINE allocate_matrices
     732              : 
     733              : ! **************************************************************************************************
     734              : !> \brief ...
     735              : !> \param bs_env ...
     736              : ! **************************************************************************************************
     737           22 :    SUBROUTINE allocate_GW_eigenvalues(bs_env)
     738              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     739              : 
     740              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'allocate_GW_eigenvalues'
     741              : 
     742              :       INTEGER                                            :: handle
     743              : 
     744           22 :       CALL timeset(routineN, handle)
     745              : 
     746          110 :       ALLOCATE (bs_env%eigenval_G0W0(bs_env%n_ao, bs_env%nkp_bs_and_DOS, bs_env%n_spin))
     747          110 :       ALLOCATE (bs_env%eigenval_HF(bs_env%n_ao, bs_env%nkp_bs_and_DOS, bs_env%n_spin))
     748              : 
     749           22 :       CALL timestop(handle)
     750              : 
     751           22 :    END SUBROUTINE allocate_GW_eigenvalues
     752              : 
     753              : ! **************************************************************************************************
     754              : !> \brief ...
     755              : !> \param qs_env ...
     756              : !> \param bs_env ...
     757              : ! **************************************************************************************************
     758           28 :    SUBROUTINE create_tensors(qs_env, bs_env)
     759              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     760              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     761              : 
     762              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'create_tensors'
     763              : 
     764              :       INTEGER                                            :: handle
     765              : 
     766           28 :       CALL timeset(routineN, handle)
     767              : 
     768           28 :       CALL init_interaction_radii(bs_env)
     769              : 
     770              :       ! split blocks does not improve load balancing/efficienfy for tensor contraction, so we go
     771              :       ! with the standard atomic blocks
     772              :       CALL create_3c_t(bs_env%t_RI_AO__AO, bs_env%para_env_tensor, "(RI AO | AO)", [1, 2], [3], &
     773              :                        bs_env%sizes_RI, bs_env%sizes_AO, &
     774           28 :                        create_nl_3c=.TRUE., nl_3c=bs_env%nl_3c, qs_env=qs_env)
     775              :       CALL create_3c_t(bs_env%t_RI__AO_AO, bs_env%para_env_tensor, "(RI | AO AO)", [1], [2, 3], &
     776           28 :                        bs_env%sizes_RI, bs_env%sizes_AO)
     777              : 
     778           28 :       CALL create_2c_t(bs_env, bs_env%sizes_RI, bs_env%sizes_AO)
     779              : 
     780           28 :       CALL timestop(handle)
     781              : 
     782           28 :    END SUBROUTINE create_tensors
     783              : 
     784              : ! **************************************************************************************************
     785              : !> \brief ...
     786              : !> \param qs_env ...
     787              : !> \param bs_env ...
     788              : ! **************************************************************************************************
     789           22 :    SUBROUTINE check_sparsity_3c(qs_env, bs_env)
     790              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     791              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     792              : 
     793              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'check_sparsity_3c'
     794              : 
     795              :       INTEGER                                            :: handle, n_atom_step, RI_atom
     796              :       INTEGER(int_8)                                     :: non_zero_elements_sum, nze
     797              :       REAL(dp)                                           :: max_dist_AO_atoms, occ, occupation_sum
     798              :       REAL(KIND=dp)                                      :: t1, t2
     799           22 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:, :)       :: t_3c_global_array
     800              : 
     801              : !TYPE(dbt_type)                                     :: t_3c_global
     802              : 
     803              :       !TYPE(neighbor_list_3c_type)                        :: nl_3c_global
     804              : 
     805           22 :       CALL timeset(routineN, handle)
     806              : 
     807              :       ! check the sparsity of 3c integral tensor (µν|P); calculate maximum distance between
     808              :       ! AO atoms µ, ν where at least a single integral (µν|P) is larger than the filter threshold
     809              : 
     810          198 :       ALLOCATE (t_3c_global_array(1, 1))
     811           22 :       CALL dbt_create(bs_env%t_RI_AO__AO, t_3c_global_array(1, 1))
     812              : 
     813              :       ! Allocate arrays to store min/max indices for overlap with other AO/RI functions on each atom
     814              :       ! (Filled during loop)
     815           88 :       ALLOCATE (bs_env%min_RI_idx_from_AO_AO_atom(bs_env%n_atom, bs_env%n_atom))
     816           88 :       ALLOCATE (bs_env%max_RI_idx_from_AO_AO_atom(bs_env%n_atom, bs_env%n_atom))
     817           88 :       ALLOCATE (bs_env%min_AO_idx_from_RI_AO_atom(bs_env%n_atom, bs_env%n_atom))
     818           88 :       ALLOCATE (bs_env%max_AO_idx_from_RI_AO_atom(bs_env%n_atom, bs_env%n_atom))
     819          178 :       bs_env%min_RI_idx_from_AO_AO_atom(:, :) = bs_env%n_RI
     820          178 :       bs_env%max_RI_idx_from_AO_AO_atom(:, :) = 1
     821          178 :       bs_env%min_AO_idx_from_RI_AO_atom(:, :) = bs_env%n_AO
     822          178 :       bs_env%max_AO_idx_from_RI_AO_atom(:, :) = 1
     823              : 
     824           22 :       CALL bs_env%para_env%sync()
     825           22 :       t1 = m_walltime()
     826              : 
     827           22 :       occupation_sum = 0.0_dp
     828           22 :       non_zero_elements_sum = 0
     829           22 :       max_dist_AO_atoms = 0.0_dp
     830           22 :       n_atom_step = INT(SQRT(REAL(bs_env%n_atom, KIND=dp)))
     831              :       ! do not compute full 3c integrals at once because it may cause out of memory
     832           70 :       DO RI_atom = 1, bs_env%n_atom, n_atom_step
     833              : 
     834              :          CALL build_3c_integrals(t_3c_global_array, &
     835              :                                  bs_env%eps_filter, &
     836              :                                  qs_env, &
     837              :                                  bs_env%nl_3c, &
     838              :                                  int_eps=bs_env%eps_filter, &
     839              :                                  basis_i=bs_env%basis_set_RI, &
     840              :                                  basis_j=bs_env%basis_set_AO, &
     841              :                                  basis_k=bs_env%basis_set_AO, &
     842              :                                  bounds_i=[RI_atom, MIN(RI_atom + n_atom_step - 1, bs_env%n_atom)], &
     843              :                                  potential_parameter=bs_env%ri_metric, &
     844          144 :                                  desymmetrize=.FALSE.)
     845              : 
     846           48 :          CALL dbt_filter(t_3c_global_array(1, 1), bs_env%eps_filter)
     847              : 
     848           48 :          CALL bs_env%para_env%sync()
     849              : 
     850           48 :          CALL get_tensor_occupancy(t_3c_global_array(1, 1), nze, occ)
     851           48 :          non_zero_elements_sum = non_zero_elements_sum + nze
     852           48 :          occupation_sum = occupation_sum + occ
     853              : 
     854           48 :          CALL get_max_dist_AO_atoms(t_3c_global_array(1, 1), max_dist_AO_atoms, qs_env)
     855              : 
     856              :          ! Extract indices per block
     857           48 :          CALL get_i_j_atom_ranges(t_3c_global_array(1, 1), bs_env)
     858              : 
     859          118 :          CALL dbt_clear(t_3c_global_array(1, 1))
     860              : 
     861              :       END DO
     862              : 
     863           22 :       t2 = m_walltime()
     864              : 
     865           22 :       CALL bs_env%para_env%min(bs_env%min_RI_idx_from_AO_AO_atom)
     866           22 :       CALL bs_env%para_env%max(bs_env%max_RI_idx_from_AO_AO_atom)
     867           22 :       CALL bs_env%para_env%min(bs_env%min_AO_idx_from_RI_AO_atom)
     868           22 :       CALL bs_env%para_env%max(bs_env%max_AO_idx_from_RI_AO_atom)
     869              : 
     870           22 :       bs_env%occupation_3c_int = occupation_sum
     871           22 :       bs_env%max_dist_AO_atoms = max_dist_AO_atoms
     872              : 
     873           22 :       CALL dbt_destroy(t_3c_global_array(1, 1))
     874           44 :       DEALLOCATE (t_3c_global_array)
     875              : 
     876           22 :       IF (bs_env%unit_nr > 0) THEN
     877           11 :          WRITE (bs_env%unit_nr, '(T2,A)') ''
     878              :          WRITE (bs_env%unit_nr, '(T2,A,F27.1,A)') &
     879           11 :             'Computed 3-center integrals (µν|P), execution time', t2 - t1, ' s'
     880           11 :          WRITE (bs_env%unit_nr, '(T2,A,F48.3,A)') 'Percentage of non-zero (µν|P)', &
     881           22 :             occupation_sum*100, ' %'
     882           11 :          WRITE (bs_env%unit_nr, '(T2,A,F33.1,A)') 'Max. distance between µ,ν in non-zero (µν|P)', &
     883           22 :             max_dist_AO_atoms*angstrom, ' A'
     884           11 :          WRITE (bs_env%unit_nr, '(T2,2A,I20,A)') 'Required memory if storing all 3-center ', &
     885           22 :             'integrals (µν|P)', INT(REAL(non_zero_elements_sum, KIND=dp)*8.0E-9_dp), ' GB'
     886              :       END IF
     887              : 
     888           22 :       CALL timestop(handle)
     889              : 
     890           44 :    END SUBROUTINE check_sparsity_3c
     891              : 
     892              : ! **************************************************************************************************
     893              : !> \brief ...
     894              : !> \param t_3c ...
     895              : !> \param bs_env ...
     896              : ! **************************************************************************************************
     897           48 :    SUBROUTINE get_i_j_atom_ranges(t_3c, bs_env)
     898              :       TYPE(dbt_type)                                     :: t_3c
     899              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     900              : 
     901              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_i_j_atom_ranges'
     902              : 
     903              :       INTEGER                                            :: handle, idx_AO_end, idx_AO_start, &
     904              :                                                             idx_RI_end, idx_RI_start
     905              :       INTEGER, DIMENSION(3)                              :: atom_ind
     906              :       TYPE(dbt_iterator_type)                            :: iter
     907              : 
     908           48 :       CALL timeset(routineN, handle)
     909              : 
     910              :       ! Loop over blocks in 3c, for given min_atom: RI_min/max index from min_atom
     911              : !$OMP PARALLEL DEFAULT(NONE) &
     912              : !$OMP SHARED(t_3c, bs_env) &
     913              : !$OMP PRIVATE(iter, atom_ind, &
     914           48 : !$OMP         idx_RI_start, idx_RI_end, idx_AO_start, idx_AO_end)
     915              : 
     916              :       CALL dbt_iterator_start(iter, t_3c)
     917              :       DO WHILE (dbt_iterator_blocks_left(iter))
     918              :          CALL dbt_iterator_next_block(iter, atom_ind)
     919              : 
     920              :          ! Pre-fetch indices to avoid referencing 'bs_env' twice inside the ATOMIC blocks
     921              :          idx_RI_start = bs_env%i_RI_start_from_atom(atom_ind(1))
     922              :          idx_RI_end = bs_env%i_RI_end_from_atom(atom_ind(1))
     923              : 
     924              :          idx_AO_start = bs_env%i_ao_start_from_atom(atom_ind(2))
     925              :          idx_AO_end = bs_env%i_ao_end_from_atom(atom_ind(2))
     926              : 
     927              :          ! Update values safely inside ATOMIC blocks, otherwise race conditions occur
     928              : !$OMP ATOMIC UPDATE
     929              :          bs_env%min_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)) = &
     930              :             MIN(bs_env%min_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)), idx_RI_start)
     931              : !$OMP ATOMIC UPDATE
     932              :          bs_env%max_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)) = &
     933              :             MAX(bs_env%max_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)), idx_RI_end)
     934              : 
     935              : !$OMP ATOMIC UPDATE
     936              :          bs_env%min_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)) = &
     937              :             MIN(bs_env%min_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)), idx_AO_start)
     938              : !$OMP ATOMIC UPDATE
     939              :          bs_env%max_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)) = &
     940              :             MAX(bs_env%max_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)), idx_AO_end)
     941              : 
     942              :       END DO
     943              :       CALL dbt_iterator_stop(iter)
     944              : !$OMP END PARALLEL
     945              : 
     946           48 :       CALL timestop(handle)
     947              : 
     948           48 :    END SUBROUTINE get_i_j_atom_ranges
     949              : 
     950              : ! **************************************************************************************************
     951              : !> \brief ...
     952              : !> \param bs_env ...
     953              : !> \param sizes_RI ...
     954              : !> \param sizes_AO ...
     955              : ! **************************************************************************************************
     956           28 :    SUBROUTINE create_2c_t(bs_env, sizes_RI, sizes_AO)
     957              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     958              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: sizes_RI, sizes_AO
     959              : 
     960              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'create_2c_t'
     961              : 
     962              :       INTEGER                                            :: handle
     963           28 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist_1, dist_2
     964              :       INTEGER, DIMENSION(2)                              :: pdims_2d
     965           84 :       TYPE(dbt_pgrid_type)                               :: pgrid_2d
     966              : 
     967           28 :       CALL timeset(routineN, handle)
     968              : 
     969              :       ! inspired from rpa_im_time.F / hfx_types.F
     970              : 
     971           28 :       pdims_2d = 0
     972           28 :       CALL dbt_pgrid_create(bs_env%para_env_tensor, pdims_2d, pgrid_2d)
     973              : 
     974              :       CALL create_2c_tensor(bs_env%t_G, dist_1, dist_2, pgrid_2d, sizes_AO, sizes_AO, &
     975           28 :                             name="(AO | AO)")
     976           28 :       DEALLOCATE (dist_1, dist_2)
     977              :       CALL create_2c_tensor(bs_env%t_chi, dist_1, dist_2, pgrid_2d, sizes_RI, sizes_RI, &
     978           28 :                             name="(RI | RI)")
     979           28 :       DEALLOCATE (dist_1, dist_2)
     980              :       CALL create_2c_tensor(bs_env%t_W, dist_1, dist_2, pgrid_2d, sizes_RI, sizes_RI, &
     981           28 :                             name="(RI | RI)")
     982           28 :       DEALLOCATE (dist_1, dist_2)
     983           28 :       CALL dbt_pgrid_destroy(pgrid_2d)
     984              : 
     985           28 :       CALL timestop(handle)
     986              : 
     987           28 :    END SUBROUTINE create_2c_t
     988              : 
     989              : ! **************************************************************************************************
     990              : !> \brief ...
     991              : !> \param tensor ...
     992              : !> \param para_env ...
     993              : !> \param tensor_name ...
     994              : !> \param map1 ...
     995              : !> \param map2 ...
     996              : !> \param sizes_RI ...
     997              : !> \param sizes_AO ...
     998              : !> \param create_nl_3c ...
     999              : !> \param nl_3c ...
    1000              : !> \param qs_env ...
    1001              : ! **************************************************************************************************
    1002           56 :    SUBROUTINE create_3c_t(tensor, para_env, tensor_name, map1, map2, sizes_RI, sizes_AO, &
    1003              :                           create_nl_3c, nl_3c, qs_env)
    1004              :       TYPE(dbt_type)                                     :: tensor
    1005              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1006              :       CHARACTER(LEN=12)                                  :: tensor_name
    1007              :       INTEGER, DIMENSION(:)                              :: map1, map2
    1008              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: sizes_RI, sizes_AO
    1009              :       LOGICAL, OPTIONAL                                  :: create_nl_3c
    1010              :       TYPE(neighbor_list_3c_type), OPTIONAL              :: nl_3c
    1011              :       TYPE(qs_environment_type), OPTIONAL, POINTER       :: qs_env
    1012              : 
    1013              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'create_3c_t'
    1014              : 
    1015              :       INTEGER                                            :: handle, nkind
    1016           56 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist_AO_1, dist_AO_2, dist_RI
    1017              :       INTEGER, DIMENSION(3)                              :: pcoord, pdims, pdims_3d
    1018              :       LOGICAL                                            :: my_create_nl_3c
    1019          168 :       TYPE(dbt_pgrid_type)                               :: pgrid_3d
    1020              :       TYPE(distribution_3d_type)                         :: dist_3d
    1021           56 :       TYPE(mp_cart_type)                                 :: mp_comm_t3c_2
    1022           56 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1023              : 
    1024           56 :       CALL timeset(routineN, handle)
    1025              : 
    1026           56 :       pdims_3d = 0
    1027           56 :       CALL dbt_pgrid_create(para_env, pdims_3d, pgrid_3d)
    1028              :       CALL create_3c_tensor(tensor, dist_RI, dist_AO_1, dist_AO_2, &
    1029              :                             pgrid_3d, sizes_RI, sizes_AO, sizes_AO, &
    1030           56 :                             map1=map1, map2=map2, name=tensor_name)
    1031              : 
    1032           56 :       IF (PRESENT(create_nl_3c)) THEN
    1033           28 :          my_create_nl_3c = create_nl_3c
    1034              :       ELSE
    1035              :          my_create_nl_3c = .FALSE.
    1036              :       END IF
    1037              : 
    1038           28 :       IF (my_create_nl_3c) THEN
    1039           28 :          CALL get_qs_env(qs_env, nkind=nkind, particle_set=particle_set)
    1040           28 :          CALL dbt_mp_environ_pgrid(pgrid_3d, pdims, pcoord)
    1041           28 :          CALL mp_comm_t3c_2%create(pgrid_3d%mp_comm_2d, 3, pdims)
    1042              :          CALL distribution_3d_create(dist_3d, dist_RI, dist_AO_1, dist_AO_2, &
    1043           28 :                                      nkind, particle_set, mp_comm_t3c_2, own_comm=.TRUE.)
    1044              : 
    1045              :          CALL build_3c_neighbor_lists(nl_3c, &
    1046              :                                       qs_env%bs_env%basis_set_RI, &
    1047              :                                       qs_env%bs_env%basis_set_AO, &
    1048              :                                       qs_env%bs_env%basis_set_AO, &
    1049              :                                       dist_3d, qs_env%bs_env%ri_metric, &
    1050           28 :                                       "GW_3c_nl", qs_env, own_dist=.TRUE.)
    1051              :       END IF
    1052              : 
    1053           56 :       DEALLOCATE (dist_RI, dist_AO_1, dist_AO_2)
    1054           56 :       CALL dbt_pgrid_destroy(pgrid_3d)
    1055              : 
    1056           56 :       CALL timestop(handle)
    1057              : 
    1058          112 :    END SUBROUTINE create_3c_t
    1059              : 
    1060              : ! **************************************************************************************************
    1061              : !> \brief ...
    1062              : !> \param bs_env ...
    1063              : ! **************************************************************************************************
    1064           28 :    SUBROUTINE init_interaction_radii(bs_env)
    1065              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1066              : 
    1067              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'init_interaction_radii'
    1068              : 
    1069              :       INTEGER                                            :: handle, ibasis
    1070              :       TYPE(gto_basis_set_type), POINTER                  :: orb_basis, ri_basis
    1071              : 
    1072           28 :       CALL timeset(routineN, handle)
    1073              : 
    1074           72 :       DO ibasis = 1, SIZE(bs_env%basis_set_AO)
    1075              : 
    1076           44 :          orb_basis => bs_env%basis_set_AO(ibasis)%gto_basis_set
    1077           44 :          CALL init_interaction_radii_orb_basis(orb_basis, bs_env%eps_filter)
    1078              : 
    1079           44 :          ri_basis => bs_env%basis_set_RI(ibasis)%gto_basis_set
    1080           72 :          CALL init_interaction_radii_orb_basis(ri_basis, bs_env%eps_filter)
    1081              : 
    1082              :       END DO
    1083              : 
    1084           28 :       CALL timestop(handle)
    1085              : 
    1086           28 :    END SUBROUTINE init_interaction_radii
    1087              : 
    1088              : ! **************************************************************************************************
    1089              : !> \brief ...
    1090              : !> \param t_3c_int ...
    1091              : !> \param max_dist_AO_atoms ...
    1092              : !> \param qs_env ...
    1093              : ! **************************************************************************************************
    1094           48 :    SUBROUTINE get_max_dist_AO_atoms(t_3c_int, max_dist_AO_atoms, qs_env)
    1095              :       TYPE(dbt_type)                                     :: t_3c_int
    1096              :       REAL(KIND=dp)                                      :: max_dist_AO_atoms
    1097              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1098              : 
    1099              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_max_dist_AO_atoms'
    1100              : 
    1101              :       INTEGER                                            :: atom_1, atom_2, handle, num_cells
    1102              :       INTEGER, DIMENSION(3)                              :: atom_ind
    1103           48 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    1104              :       REAL(KIND=dp)                                      :: abs_rab
    1105              :       REAL(KIND=dp), DIMENSION(3)                        :: rab
    1106              :       TYPE(cell_type), POINTER                           :: cell
    1107              :       TYPE(dbt_iterator_type)                            :: iter
    1108              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1109           48 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1110              : 
    1111           48 :       CALL timeset(routineN, handle)
    1112              : 
    1113           48 :       NULLIFY (cell, particle_set, para_env)
    1114           48 :       CALL get_qs_env(qs_env, cell=cell, particle_set=particle_set, para_env=para_env)
    1115              : 
    1116              : ! IMPORTANT: Use thread-local copy for max_dist_AO_atoms via REDUCTION to avoid race conditions
    1117              : !$OMP PARALLEL DEFAULT(NONE) &
    1118              : !$OMP SHARED(t_3c_int, num_cells, index_to_cell, particle_set, cell) &
    1119              : !$OMP PRIVATE(iter, atom_ind, rab, abs_rab, atom_1, atom_2) &
    1120           48 : !$OMP REDUCTION(MAX:max_dist_AO_atoms)
    1121              : 
    1122              :       CALL dbt_iterator_start(iter, t_3c_int)
    1123              :       DO WHILE (dbt_iterator_blocks_left(iter))
    1124              :          CALL dbt_iterator_next_block(iter, atom_ind)
    1125              : 
    1126              :          atom_1 = atom_ind(2)
    1127              :          atom_2 = atom_ind(3)
    1128              :          rab = pbc(particle_set(atom_1)%r(1:3), particle_set(atom_2)%r(1:3), cell)
    1129              :          abs_rab = SQRT(rab(1)**2 + rab(2)**2 + rab(3)**2)
    1130              : 
    1131              :          ! Reduction takes care of using a thread-local copy
    1132              :          max_dist_AO_atoms = MAX(max_dist_AO_atoms, abs_rab)
    1133              : 
    1134              :       END DO
    1135              :       CALL dbt_iterator_stop(iter)
    1136              : !$OMP END PARALLEL
    1137              : 
    1138           48 :       CALL para_env%max(max_dist_AO_atoms)
    1139              : 
    1140           48 :       CALL timestop(handle)
    1141              : 
    1142           48 :    END SUBROUTINE get_max_dist_AO_atoms
    1143              : 
    1144              : ! **************************************************************************************************
    1145              : !> \brief ...
    1146              : !> \param bs_env ...
    1147              : ! **************************************************************************************************
    1148           22 :    SUBROUTINE set_sparsity_parallelization_parameters(bs_env)
    1149              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1150              : 
    1151              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_sparsity_parallelization_parameters'
    1152              : 
    1153              :       INTEGER :: handle, i_ivl, IL_ivl, j_ivl, n_atom_per_IL_ivl, n_atom_per_ivl, n_intervals_i, &
    1154              :          n_intervals_inner_loop_atoms, n_intervals_j, u
    1155              :       INTEGER(KIND=int_8)                                :: input_memory_per_proc
    1156              : 
    1157           22 :       CALL timeset(routineN, handle)
    1158              : 
    1159              :       ! heuristic parameter to prevent out of memory
    1160           22 :       bs_env%safety_factor_memory = 0.10_dp
    1161              : 
    1162           22 :       input_memory_per_proc = INT(bs_env%input_memory_per_proc_GB*1.0E9_dp, KIND=int_8)
    1163              : 
    1164              :       ! choose atomic range for λ ("i_atom"), ν ("j_atom") in
    1165              :       ! M_λνP(iτ) = sum_µ (µν|P) G^occ_µλ(i|τ|,k=0)
    1166              :       ! N_νλQ(iτ) = sum_σ (σλ|Q) G^vir_σν(i|τ|,k=0)
    1167              :       ! such that M and N fit into the memory
    1168              :       n_atom_per_ivl = INT(SQRT(bs_env%safety_factor_memory*input_memory_per_proc &
    1169              :                                 *bs_env%group_size_tensor/24/bs_env%n_RI &
    1170           22 :                                 /SQRT(bs_env%occupation_3c_int)))/bs_env%max_AO_bf_per_atom
    1171              : 
    1172           22 :       n_intervals_i = (bs_env%n_atom_i - 1)/n_atom_per_ivl + 1
    1173           22 :       n_intervals_j = (bs_env%n_atom_j - 1)/n_atom_per_ivl + 1
    1174              : 
    1175           22 :       bs_env%n_atom_per_interval_ij = n_atom_per_ivl
    1176           22 :       bs_env%n_intervals_i = n_intervals_i
    1177           22 :       bs_env%n_intervals_j = n_intervals_j
    1178              : 
    1179           66 :       ALLOCATE (bs_env%i_atom_intervals(2, n_intervals_i))
    1180           66 :       ALLOCATE (bs_env%j_atom_intervals(2, n_intervals_j))
    1181              : 
    1182           44 :       DO i_ivl = 1, n_intervals_i
    1183           22 :          bs_env%i_atom_intervals(1, i_ivl) = (i_ivl - 1)*n_atom_per_ivl + bs_env%atoms_i(1)
    1184              :          bs_env%i_atom_intervals(2, i_ivl) = MIN(i_ivl*n_atom_per_ivl + bs_env%atoms_i(1) - 1, &
    1185           44 :                                                  bs_env%atoms_i(2))
    1186              :       END DO
    1187              : 
    1188           44 :       DO j_ivl = 1, n_intervals_j
    1189           22 :          bs_env%j_atom_intervals(1, j_ivl) = (j_ivl - 1)*n_atom_per_ivl + bs_env%atoms_j(1)
    1190              :          bs_env%j_atom_intervals(2, j_ivl) = MIN(j_ivl*n_atom_per_ivl + bs_env%atoms_j(1) - 1, &
    1191           44 :                                                  bs_env%atoms_j(2))
    1192              :       END DO
    1193              : 
    1194           88 :       ALLOCATE (bs_env%skip_Sigma_occ(n_intervals_i, n_intervals_j))
    1195           66 :       ALLOCATE (bs_env%skip_Sigma_vir(n_intervals_i, n_intervals_j))
    1196           66 :       bs_env%skip_Sigma_occ(:, :) = .FALSE.
    1197           66 :       bs_env%skip_Sigma_vir(:, :) = .FALSE.
    1198           22 :       bs_env%n_skip_chi = 0
    1199              : 
    1200           66 :       ALLOCATE (bs_env%skip_chi(n_intervals_i, n_intervals_j))
    1201           66 :       bs_env%skip_chi(:, :) = .FALSE.
    1202           22 :       bs_env%n_skip_sigma = 0
    1203              : 
    1204              :       ! choose atomic range for µ and σ ("inner loop (IL) atom") in
    1205              :       ! M_λνP(iτ) = sum_µ (µν|P) G^occ_µλ(i|τ|,k=0)
    1206              :       ! N_νλQ(iτ) = sum_σ (σλ|Q) G^vir_σν(i|τ|,k=0)
    1207              :       n_atom_per_IL_ivl = MIN(INT(bs_env%safety_factor_memory*input_memory_per_proc &
    1208              :                                   *bs_env%group_size_tensor/n_atom_per_ivl &
    1209              :                                   /bs_env%max_AO_bf_per_atom &
    1210              :                                   /bs_env%n_RI/8/SQRT(bs_env%occupation_3c_int) &
    1211           22 :                                   /bs_env%max_AO_bf_per_atom), bs_env%n_atom)
    1212              : 
    1213           22 :       n_intervals_inner_loop_atoms = (bs_env%n_atom - 1)/n_atom_per_IL_ivl + 1
    1214              : 
    1215           22 :       bs_env%n_atom_per_IL_interval = n_atom_per_IL_ivl
    1216           22 :       bs_env%n_intervals_inner_loop_atoms = n_intervals_inner_loop_atoms
    1217              : 
    1218           66 :       ALLOCATE (bs_env%inner_loop_atom_intervals(2, n_intervals_inner_loop_atoms))
    1219           44 :       DO IL_ivl = 1, n_intervals_inner_loop_atoms
    1220           22 :          bs_env%inner_loop_atom_intervals(1, IL_ivl) = (IL_ivl - 1)*n_atom_per_IL_ivl + 1
    1221           44 :          bs_env%inner_loop_atom_intervals(2, IL_ivl) = MIN(IL_ivl*n_atom_per_IL_ivl, bs_env%n_atom)
    1222              :       END DO
    1223              : 
    1224           22 :       u = bs_env%unit_nr
    1225           22 :       IF (u > 0) THEN
    1226           11 :          WRITE (u, '(T2,A)') ''
    1227           11 :          WRITE (u, '(T2,A,I33)') 'Number of i and j atoms in M_λνP(τ), N_νλQ(τ):', n_atom_per_ivl
    1228           11 :          WRITE (u, '(T2,A,I18)') 'Number of inner loop atoms for µ in M_λνP = sum_µ (µν|P) G_µλ', &
    1229           22 :             n_atom_per_IL_ivl
    1230              :       END IF
    1231              : 
    1232           22 :       CALL timestop(handle)
    1233              : 
    1234           22 :    END SUBROUTINE set_sparsity_parallelization_parameters
    1235              : 
    1236              : ! **************************************************************************************************
    1237              : !> \brief ...
    1238              : !> \param qs_env ...
    1239              : !> \param bs_env ...
    1240              : ! **************************************************************************************************
    1241           22 :    SUBROUTINE check_for_restart_files(qs_env, bs_env)
    1242              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1243              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1244              : 
    1245              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'check_for_restart_files'
    1246              : 
    1247              :       CHARACTER(LEN=9)                                   :: frmt
    1248              :       CHARACTER(len=default_path_length)                 :: project_name
    1249              :       CHARACTER(len=default_string_length)               :: f_chi, f_s_n, f_s_p, f_s_x, f_w_t, prefix
    1250              :       INTEGER                                            :: handle, i_spin, i_t_or_w, ind, n_spin, &
    1251              :                                                             num_time_freq_points
    1252              :       LOGICAL                                            :: chi_exists, Sigma_neg_time_exists, &
    1253              :                                                             Sigma_pos_time_exists, &
    1254              :                                                             Sigma_x_spin_exists, W_time_exists
    1255              :       TYPE(cp_logger_type), POINTER                      :: logger
    1256              :       TYPE(section_vals_type), POINTER                   :: input, print_key
    1257              : 
    1258           22 :       CALL timeset(routineN, handle)
    1259              : 
    1260           22 :       num_time_freq_points = bs_env%num_time_freq_points
    1261           22 :       n_spin = bs_env%n_spin
    1262              : 
    1263           66 :       ALLOCATE (bs_env%read_chi(num_time_freq_points))
    1264           44 :       ALLOCATE (bs_env%calc_chi(num_time_freq_points))
    1265           88 :       ALLOCATE (bs_env%Sigma_c_exists(num_time_freq_points, n_spin))
    1266              : 
    1267           22 :       CALL get_qs_env(qs_env, input=input)
    1268              : 
    1269           22 :       logger => cp_get_default_logger()
    1270           22 :       print_key => section_vals_get_subs_vals(input, 'PROPERTIES%BANDSTRUCTURE%GW%PRINT%RESTART')
    1271              :       project_name = cp_print_key_generate_filename(logger, print_key, extension="", &
    1272           22 :                                                     my_local=.FALSE.)
    1273           22 :       WRITE (prefix, '(2A)') TRIM(project_name), "-RESTART_"
    1274           22 :       bs_env%prefix = prefix
    1275              : 
    1276           22 :       bs_env%all_W_exist = .TRUE.
    1277              : 
    1278          346 :       DO i_t_or_w = 1, num_time_freq_points
    1279              : 
    1280          324 :          IF (i_t_or_w < 10) THEN
    1281          186 :             WRITE (frmt, '(A)') '(3A,I1,A)'
    1282          186 :             WRITE (f_chi, frmt) TRIM(prefix), bs_env%chi_name, "_0", i_t_or_w, ".matrix"
    1283          186 :             WRITE (f_W_t, frmt) TRIM(prefix), bs_env%W_time_name, "_0", i_t_or_w, ".matrix"
    1284          138 :          ELSE IF (i_t_or_w < 100) THEN
    1285          138 :             WRITE (frmt, '(A)') '(3A,I2,A)'
    1286          138 :             WRITE (f_chi, frmt) TRIM(prefix), bs_env%chi_name, "_", i_t_or_w, ".matrix"
    1287          138 :             WRITE (f_W_t, frmt) TRIM(prefix), bs_env%W_time_name, "_", i_t_or_w, ".matrix"
    1288              :          ELSE
    1289            0 :             CPABORT('Please implement more than 99 time/frequency points.')
    1290              :          END IF
    1291              : 
    1292          324 :          INQUIRE (file=TRIM(f_chi), exist=chi_exists)
    1293          324 :          INQUIRE (file=TRIM(f_W_t), exist=W_time_exists)
    1294              : 
    1295          324 :          bs_env%read_chi(i_t_or_w) = chi_exists
    1296          324 :          bs_env%calc_chi(i_t_or_w) = .NOT. chi_exists
    1297              : 
    1298          324 :          bs_env%all_W_exist = bs_env%all_W_exist .AND. W_time_exists
    1299              : 
    1300              :          ! the self-energy is spin-dependent
    1301          710 :          DO i_spin = 1, n_spin
    1302              : 
    1303          364 :             ind = i_t_or_w + (i_spin - 1)*num_time_freq_points
    1304              : 
    1305          364 :             IF (ind < 10) THEN
    1306          186 :                WRITE (frmt, '(A)') '(3A,I1,A)'
    1307          186 :                WRITE (f_S_p, frmt) TRIM(prefix), bs_env%Sigma_p_name, "_0", ind, ".matrix"
    1308          186 :                WRITE (f_S_n, frmt) TRIM(prefix), bs_env%Sigma_n_name, "_0", ind, ".matrix"
    1309          178 :             ELSE IF (i_t_or_w < 100) THEN
    1310          178 :                WRITE (frmt, '(A)') '(3A,I2,A)'
    1311          178 :                WRITE (f_S_p, frmt) TRIM(prefix), bs_env%Sigma_p_name, "_", ind, ".matrix"
    1312          178 :                WRITE (f_S_n, frmt) TRIM(prefix), bs_env%Sigma_n_name, "_", ind, ".matrix"
    1313              :             END IF
    1314              : 
    1315          364 :             INQUIRE (file=TRIM(f_S_p), exist=Sigma_pos_time_exists)
    1316          364 :             INQUIRE (file=TRIM(f_S_n), exist=Sigma_neg_time_exists)
    1317              : 
    1318              :             bs_env%Sigma_c_exists(i_t_or_w, i_spin) = Sigma_pos_time_exists .AND. &
    1319          932 :                                                       Sigma_neg_time_exists
    1320              : 
    1321              :          END DO
    1322              : 
    1323              :       END DO
    1324              : 
    1325              :       ! Marek : In the RTBSE run, check also for zero frequency W
    1326           22 :       IF (bs_env%rtp_method == rtp_method_bse) THEN
    1327           12 :          WRITE (f_W_t, '(3A,I1,A)') TRIM(prefix), "W_freq_rtp", "_0", 0, ".matrix"
    1328           12 :          INQUIRE (file=TRIM(f_W_t), exist=W_time_exists)
    1329           20 :          bs_env%all_W_exist = bs_env%all_W_exist .AND. W_time_exists
    1330              :       END IF
    1331              : 
    1332           22 :       IF (bs_env%all_W_exist) THEN
    1333          106 :          bs_env%read_chi(:) = .FALSE.
    1334          106 :          bs_env%calc_chi(:) = .FALSE.
    1335              :       END IF
    1336              : 
    1337           22 :       bs_env%Sigma_x_exists = .TRUE.
    1338           48 :       DO i_spin = 1, n_spin
    1339           26 :          WRITE (f_S_x, '(3A,I1,A)') TRIM(prefix), bs_env%Sigma_x_name, "_0", i_spin, ".matrix"
    1340           26 :          INQUIRE (file=TRIM(f_S_x), exist=Sigma_x_spin_exists)
    1341           66 :          bs_env%Sigma_x_exists = bs_env%Sigma_x_exists .AND. Sigma_x_spin_exists
    1342              :       END DO
    1343              : 
    1344              :       ! If any restart files are read, check if the SCF converged in 1 step.
    1345              :       ! This is important because a re-iterated SCF can lead to spurious GW results
    1346              :       IF (ANY(bs_env%read_chi(:)) &
    1347              :           .OR. ANY(bs_env%Sigma_c_exists) &
    1348              :           .OR. bs_env%all_W_exist &
    1349          608 :           .OR. bs_env%Sigma_x_exists &
    1350              :           ) THEN
    1351              : 
    1352            6 :          IF (qs_env%scf_env%iter_count /= 1) THEN
    1353              :             CALL cp_warn(__LOCATION__, "SCF needed more than 1 step, "// &
    1354            6 :                          "which might lead to spurious GW results when using GW restart files. ")
    1355              :          END IF
    1356              :       END IF
    1357              : 
    1358           22 :       CALL timestop(handle)
    1359              : 
    1360           22 :    END SUBROUTINE check_for_restart_files
    1361              : 
    1362              : ! **************************************************************************************************
    1363              : !> \brief ...
    1364              : !> \param qs_env ...
    1365              : !> \param bs_env ...
    1366              : ! **************************************************************************************************
    1367           28 :    SUBROUTINE set_parallelization_parameters(qs_env, bs_env)
    1368              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1369              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1370              : 
    1371              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_parallelization_parameters'
    1372              : 
    1373              :       INTEGER                                            :: color_sub, dummy_1, dummy_2, handle, &
    1374              :                                                             num_pe, num_t_groups, u
    1375              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1376              : 
    1377           28 :       CALL timeset(routineN, handle)
    1378              : 
    1379           28 :       CALL get_qs_env(qs_env, para_env=para_env)
    1380              : 
    1381           28 :       num_pe = para_env%num_pe
    1382              :       ! if not already set, use all processors for the group (for large-cell GW, performance
    1383              :       ! seems to be best for a single group with all MPI processes per group)
    1384           28 :       IF (bs_env%group_size_tensor < 0 .OR. bs_env%group_size_tensor > num_pe) &
    1385           22 :          bs_env%group_size_tensor = num_pe
    1386              : 
    1387              :       ! group_size_tensor must divide num_pe without rest; otherwise everything will be complicated
    1388           28 :       IF (MODULO(num_pe, bs_env%group_size_tensor) /= 0) THEN
    1389            0 :          CALL find_good_group_size(num_pe, bs_env%group_size_tensor)
    1390              :       END IF
    1391              : 
    1392              :       ! para_env_tensor for tensor subgroups
    1393           28 :       color_sub = para_env%mepos/bs_env%group_size_tensor
    1394           28 :       bs_env%tensor_group_color = color_sub
    1395              : 
    1396           28 :       ALLOCATE (bs_env%para_env_tensor)
    1397           28 :       CALL bs_env%para_env_tensor%from_split(para_env, color_sub)
    1398              : 
    1399           28 :       num_t_groups = para_env%num_pe/bs_env%group_size_tensor
    1400           28 :       bs_env%num_tensor_groups = num_t_groups
    1401              : 
    1402              :       CALL get_i_j_atoms(bs_env%atoms_i, bs_env%atoms_j, bs_env%n_atom_i, bs_env%n_atom_j, &
    1403           28 :                          color_sub, bs_env)
    1404              : 
    1405           84 :       ALLOCATE (bs_env%atoms_i_t_group(2, num_t_groups))
    1406           84 :       ALLOCATE (bs_env%atoms_j_t_group(2, num_t_groups))
    1407           62 :       DO color_sub = 0, num_t_groups - 1
    1408              :          CALL get_i_j_atoms(bs_env%atoms_i_t_group(1:2, color_sub + 1), &
    1409              :                             bs_env%atoms_j_t_group(1:2, color_sub + 1), &
    1410           62 :                             dummy_1, dummy_2, color_sub, bs_env)
    1411              :       END DO
    1412              : 
    1413           28 :       u = bs_env%unit_nr
    1414           28 :       IF (u > 0) THEN
    1415           14 :          WRITE (u, '(T2,A,I47)') 'Group size for tensor operations', bs_env%group_size_tensor
    1416           14 :          IF (bs_env%group_size_tensor > 1 .AND. bs_env%n_atom < 5) THEN
    1417           11 :             WRITE (u, '(T2,A)') 'The requested group size is > 1 which can lead to bad performance.'
    1418           11 :             WRITE (u, '(T2,A)') 'Using more memory per MPI process might improve performance.'
    1419           11 :             WRITE (u, '(T2,A)') '(Also increase MEMORY_PER_PROC when using more memory per process.)'
    1420              :          END IF
    1421              :       END IF
    1422              : 
    1423           28 :       CALL timestop(handle)
    1424              : 
    1425           28 :    END SUBROUTINE set_parallelization_parameters
    1426              : 
    1427              : ! **************************************************************************************************
    1428              : !> \brief ...
    1429              : !> \param num_pe ...
    1430              : !> \param group_size ...
    1431              : ! **************************************************************************************************
    1432            0 :    SUBROUTINE find_good_group_size(num_pe, group_size)
    1433              : 
    1434              :       INTEGER                                            :: num_pe, group_size
    1435              : 
    1436              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'find_good_group_size'
    1437              : 
    1438              :       INTEGER                                            :: group_size_minus, group_size_orig, &
    1439              :                                                             group_size_plus, handle, i_diff
    1440              : 
    1441            0 :       CALL timeset(routineN, handle)
    1442              : 
    1443            0 :       group_size_orig = group_size
    1444              : 
    1445            0 :       DO i_diff = 1, num_pe
    1446              : 
    1447            0 :          group_size_minus = group_size - i_diff
    1448              : 
    1449            0 :          IF (MODULO(num_pe, group_size_minus) == 0 .AND. group_size_minus > 0) THEN
    1450            0 :             group_size = group_size_minus
    1451            0 :             EXIT
    1452              :          END IF
    1453              : 
    1454            0 :          group_size_plus = group_size + i_diff
    1455              : 
    1456            0 :          IF (MODULO(num_pe, group_size_plus) == 0 .AND. group_size_plus <= num_pe) THEN
    1457            0 :             group_size = group_size_plus
    1458            0 :             EXIT
    1459              :          END IF
    1460              : 
    1461              :       END DO
    1462              : 
    1463            0 :       IF (group_size_orig == group_size) CPABORT("Group size error")
    1464              : 
    1465            0 :       CALL timestop(handle)
    1466              : 
    1467            0 :    END SUBROUTINE find_good_group_size
    1468              : 
    1469              : ! **************************************************************************************************
    1470              : !> \brief ...
    1471              : !> \param atoms_i ...
    1472              : !> \param atoms_j ...
    1473              : !> \param n_atom_i ...
    1474              : !> \param n_atom_j ...
    1475              : !> \param color_sub ...
    1476              : !> \param bs_env ...
    1477              : ! **************************************************************************************************
    1478           62 :    SUBROUTINE get_i_j_atoms(atoms_i, atoms_j, n_atom_i, n_atom_j, color_sub, bs_env)
    1479              : 
    1480              :       INTEGER, DIMENSION(2)                              :: atoms_i, atoms_j
    1481              :       INTEGER                                            :: n_atom_i, n_atom_j, color_sub
    1482              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1483              : 
    1484              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_i_j_atoms'
    1485              : 
    1486              :       INTEGER                                            :: handle, i_atoms_per_group, i_group, &
    1487              :                                                             ipcol, ipcol_loop, iprow, iprow_loop, &
    1488              :                                                             j_atoms_per_group, npcol, nprow
    1489              : 
    1490           62 :       CALL timeset(routineN, handle)
    1491              : 
    1492              :       ! create a square mesh of tensor groups for iatom and jatom; code from blacs_env_create
    1493           62 :       CALL square_mesh(nprow, npcol, bs_env%num_tensor_groups)
    1494              : 
    1495           62 :       i_group = 0
    1496          124 :       DO ipcol_loop = 0, npcol - 1
    1497          204 :          DO iprow_loop = 0, nprow - 1
    1498           80 :             IF (i_group == color_sub) THEN
    1499           62 :                iprow = iprow_loop
    1500           62 :                ipcol = ipcol_loop
    1501              :             END IF
    1502          142 :             i_group = i_group + 1
    1503              :          END DO
    1504              :       END DO
    1505              : 
    1506           62 :       IF (MODULO(bs_env%n_atom, nprow) == 0) THEN
    1507           50 :          i_atoms_per_group = bs_env%n_atom/nprow
    1508              :       ELSE
    1509           12 :          i_atoms_per_group = bs_env%n_atom/nprow + 1
    1510              :       END IF
    1511              : 
    1512           62 :       IF (MODULO(bs_env%n_atom, npcol) == 0) THEN
    1513           62 :          j_atoms_per_group = bs_env%n_atom/npcol
    1514              :       ELSE
    1515            0 :          j_atoms_per_group = bs_env%n_atom/npcol + 1
    1516              :       END IF
    1517              : 
    1518           62 :       atoms_i(1) = iprow*i_atoms_per_group + 1
    1519           62 :       atoms_i(2) = MIN((iprow + 1)*i_atoms_per_group, bs_env%n_atom)
    1520           62 :       n_atom_i = atoms_i(2) - atoms_i(1) + 1
    1521              : 
    1522           62 :       atoms_j(1) = ipcol*j_atoms_per_group + 1
    1523           62 :       atoms_j(2) = MIN((ipcol + 1)*j_atoms_per_group, bs_env%n_atom)
    1524           62 :       n_atom_j = atoms_j(2) - atoms_j(1) + 1
    1525              : 
    1526           62 :       CALL timestop(handle)
    1527              : 
    1528           62 :    END SUBROUTINE get_i_j_atoms
    1529              : 
    1530              : ! **************************************************************************************************
    1531              : !> \brief ...
    1532              : !> \param nprow ...
    1533              : !> \param npcol ...
    1534              : !> \param nproc ...
    1535              : ! **************************************************************************************************
    1536           62 :    SUBROUTINE square_mesh(nprow, npcol, nproc)
    1537              :       INTEGER                                            :: nprow, npcol, nproc
    1538              : 
    1539              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'square_mesh'
    1540              : 
    1541              :       INTEGER                                            :: gcd_max, handle, ipe, jpe
    1542              : 
    1543           62 :       CALL timeset(routineN, handle)
    1544              : 
    1545           62 :       gcd_max = -1
    1546          142 :       DO ipe = 1, CEILING(SQRT(REAL(nproc, dp)))
    1547           80 :          jpe = nproc/ipe
    1548           80 :          IF (ipe*jpe /= nproc) CYCLE
    1549          142 :          IF (gcd(ipe, jpe) >= gcd_max) THEN
    1550           80 :             nprow = ipe
    1551           80 :             npcol = jpe
    1552           80 :             gcd_max = gcd(ipe, jpe)
    1553              :          END IF
    1554              :       END DO
    1555              : 
    1556           62 :       CALL timestop(handle)
    1557              : 
    1558           62 :    END SUBROUTINE square_mesh
    1559              : 
    1560              : ! **************************************************************************************************
    1561              : !> \brief ...
    1562              : !> \param bs_env ...
    1563              : !> \param qs_env ...
    1564              : ! **************************************************************************************************
    1565           28 :    SUBROUTINE set_heuristic_parameters(bs_env, qs_env)
    1566              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1567              :       TYPE(qs_environment_type), OPTIONAL, POINTER       :: qs_env
    1568              : 
    1569              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_heuristic_parameters'
    1570              : 
    1571              :       INTEGER                                            :: handle, u
    1572              :       LOGICAL                                            :: do_BvK_cell
    1573              : 
    1574           28 :       CALL timeset(routineN, handle)
    1575              : 
    1576              :       ! for generating numerically stable minimax Fourier integration weights
    1577           28 :       bs_env%num_points_per_magnitude = 200
    1578              : 
    1579           28 :       IF (bs_env%input_regularization_minimax > -1.0E-12_dp) THEN
    1580            0 :          bs_env%regularization_minimax = bs_env%input_regularization_minimax
    1581              :       ELSE
    1582              :          ! for periodic systems and for 20 minimax points, we use a regularized minimax mesh
    1583              :          ! (from experience: regularized minimax meshes converges faster for periodic systems
    1584              :          !  and for 20 pts)
    1585          112 :          IF (SUM(bs_env%periodic) /= 0 .OR. bs_env%num_time_freq_points >= 20) THEN
    1586           28 :             bs_env%regularization_minimax = 1.0E-6_dp
    1587              :          ELSE
    1588            0 :             bs_env%regularization_minimax = 0.0_dp
    1589              :          END IF
    1590              :       END IF
    1591              : 
    1592           28 :       bs_env%stabilize_exp = 70.0_dp
    1593           28 :       bs_env%eps_atom_grid_2d_mat = 1.0E-50_dp
    1594              : 
    1595              :       ! use a 16-parameter Padé fit
    1596           28 :       bs_env%nparam_pade = 16
    1597              : 
    1598              :       ! resolution of the identity with the truncated Coulomb metric, cutoff radius 3 Angström
    1599           28 :       bs_env%ri_metric%potential_type = do_potential_truncated
    1600           28 :       bs_env%ri_metric%omega = 0.0_dp
    1601              :       ! cutoff radius is specified in the input
    1602           28 :       bs_env%ri_metric%filename = "t_c_g.dat"
    1603              : 
    1604           28 :       bs_env%eps_eigval_mat_RI = 0.0_dp
    1605              : 
    1606           28 :       IF (bs_env%input_regularization_RI > -1.0E-12_dp) THEN
    1607            0 :          bs_env%regularization_RI = bs_env%input_regularization_RI
    1608              :       ELSE
    1609              :          ! default case:
    1610              : 
    1611              :          ! 1. for periodic systems, we use the regularized resolution of the identity per default
    1612           28 :          bs_env%regularization_RI = 1.0E-2_dp
    1613              : 
    1614              :          ! 2. for molecules, no regularization is necessary
    1615          112 :          IF (SUM(bs_env%periodic) == 0) bs_env%regularization_RI = 0.0_dp
    1616              : 
    1617              :       END IF
    1618              : 
    1619              :       ! truncated Coulomb operator for exchange self-energy
    1620              :       ! (see details in Guidon, VandeVondele, Hutter, JCTC 5, 3010 (2009) and references therein)
    1621           28 :       do_BvK_cell = bs_env%small_cell_full_kp_or_large_cell_Gamma == small_cell_full_kp
    1622              :       CALL trunc_coulomb_for_exchange(qs_env, bs_env%trunc_coulomb, &
    1623              :                                       rel_cutoff_trunc_coulomb_ri_x=0.5_dp, &
    1624              :                                       cell_grid=bs_env%cell_grid_scf_desymm, &
    1625           28 :                                       do_BvK_cell=do_BvK_cell)
    1626              : 
    1627              :       ! for small-cell GW, we need more cells than normally used by the filter bs_env%eps_filter
    1628              :       ! (in particular for computing the self-energy because of higher number of cells needed)
    1629           28 :       bs_env%heuristic_filter_factor = 1.0E-4
    1630              : 
    1631           28 :       u = bs_env%unit_nr
    1632           28 :       IF (u > 0) THEN
    1633           14 :          WRITE (u, FMT="(T2,2A,F21.1,A)") "Cutoff radius for the truncated Coulomb ", &
    1634           28 :             "operator in Σ^x:", bs_env%trunc_coulomb%cutoff_radius*angstrom, " Å"
    1635           14 :          WRITE (u, FMT="(T2,2A,F15.1,A)") "Cutoff radius for the truncated Coulomb ", &
    1636           28 :             "operator in RI metric:", bs_env%ri_metric%cutoff_radius*angstrom, " Å"
    1637           14 :          WRITE (u, FMT="(T2,A,ES48.1)") "Regularization parameter of RI ", bs_env%regularization_RI
    1638           14 :          WRITE (u, FMT="(T2,A,ES38.1)") "Regularization parameter of minimax grids", &
    1639           28 :             bs_env%regularization_minimax
    1640           14 :          WRITE (u, FMT="(T2,A,I53)") "Lattice sum size for V(k):", bs_env%size_lattice_sum_V
    1641              :       END IF
    1642              : 
    1643           28 :       CALL timestop(handle)
    1644              : 
    1645           28 :    END SUBROUTINE set_heuristic_parameters
    1646              : 
    1647              : ! **************************************************************************************************
    1648              : !> \brief ...
    1649              : !> \param bs_env ...
    1650              : ! **************************************************************************************************
    1651           28 :    SUBROUTINE print_header_and_input_parameters(bs_env)
    1652              : 
    1653              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1654              : 
    1655              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_header_and_input_parameters'
    1656              : 
    1657              :       INTEGER                                            :: handle, u
    1658              : 
    1659           28 :       CALL timeset(routineN, handle)
    1660              : 
    1661           28 :       u = bs_env%unit_nr
    1662              : 
    1663           28 :       IF (u > 0) THEN
    1664           14 :          WRITE (u, '(T2,A)') ' '
    1665           14 :          WRITE (u, '(T2,A)') REPEAT('-', 79)
    1666           14 :          WRITE (u, '(T2,A,A78)') '-', '-'
    1667           14 :          WRITE (u, '(T2,A,A46,A32)') '-', 'GW CALCULATION', '-'
    1668           14 :          WRITE (u, '(T2,A,A78)') '-', '-'
    1669           14 :          WRITE (u, '(T2,A)') REPEAT('-', 79)
    1670           14 :          WRITE (u, '(T2,A)') ' '
    1671           14 :          WRITE (u, '(T2,A,I45)') 'Input: Number of time/freq. points', bs_env%num_time_freq_points
    1672           14 :          WRITE (u, "(T2,A,F44.1,A)") 'Input: ω_max for fitting Σ(iω) (eV)', bs_env%freq_max_fit*evolt
    1673           14 :          WRITE (u, '(T2,A,ES27.1)') 'Input: Filter threshold for sparse tensor operations', &
    1674           28 :             bs_env%eps_filter
    1675           14 :          WRITE (u, "(T2,A,L55)") 'Input: Apply Hedin shift', bs_env%do_hedin_shift
    1676           14 :          WRITE (u, '(T2,A,F37.1,A)') 'Input: Available memory per MPI process', &
    1677           28 :             bs_env%input_memory_per_proc_GB, ' GB'
    1678              :       END IF
    1679              : 
    1680           28 :       CALL timestop(handle)
    1681              : 
    1682           28 :    END SUBROUTINE print_header_and_input_parameters
    1683              : 
    1684              : ! **************************************************************************************************
    1685              : !> \brief ...
    1686              : !> \param qs_env ...
    1687              : !> \param bs_env ...
    1688              : ! **************************************************************************************************
    1689           56 :    SUBROUTINE compute_V_xc(qs_env, bs_env)
    1690              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1691              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1692              : 
    1693              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_V_xc'
    1694              : 
    1695              :       INTEGER                                            :: handle, img, ispin, myfun, nimages
    1696              :       LOGICAL                                            :: hf_present
    1697              :       REAL(KIND=dp)                                      :: energy_ex, energy_exc, energy_total, &
    1698              :                                                             myfraction
    1699           28 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mat_ks_without_v_xc
    1700           28 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp
    1701              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1702              :       TYPE(qs_energy_type), POINTER                      :: energy
    1703              :       TYPE(section_vals_type), POINTER                   :: hf_section, input, xc_section
    1704              : 
    1705           28 :       CALL timeset(routineN, handle)
    1706              : 
    1707           28 :       CALL get_qs_env(qs_env, input=input, energy=energy, dft_control=dft_control)
    1708              : 
    1709              :       ! previously, dft_control%nimages set to # neighbor cells, revert for Γ-only KS matrix
    1710           28 :       nimages = dft_control%nimages
    1711           28 :       dft_control%nimages = bs_env%nimages_scf
    1712              : 
    1713              :       ! we need to reset XC functional, therefore, get XC input
    1714           28 :       xc_section => section_vals_get_subs_vals(input, "DFT%XC")
    1715           28 :       CALL section_vals_val_get(xc_section, "XC_FUNCTIONAL%_SECTION_PARAMETERS_", i_val=myfun)
    1716           28 :       CALL section_vals_val_set(xc_section, "XC_FUNCTIONAL%_SECTION_PARAMETERS_", i_val=xc_none)
    1717              :       ! IF (ASSOCIATED(section_vals_get_subs_vals(xc_section, "HF", can_return_null=.TRUE.))) THEN
    1718           28 :       hf_section => section_vals_get_subs_vals(input, "DFT%XC%HF", can_return_null=.TRUE.)
    1719           28 :       hf_present = .FALSE.
    1720           28 :       IF (ASSOCIATED(hf_section)) THEN
    1721           28 :          CALL section_vals_get(hf_section, explicit=hf_present)
    1722              :       END IF
    1723           28 :       IF (hf_present) THEN
    1724              :          ! Special case for handling hfx
    1725            0 :          CALL section_vals_val_get(xc_section, "HF%FRACTION", r_val=myfraction)
    1726            0 :          CALL section_vals_val_set(xc_section, "HF%FRACTION", r_val=0.0_dp)
    1727              :       END IF
    1728              : 
    1729              :       ! save the energy before the energy gets updated
    1730           28 :       energy_total = energy%total
    1731           28 :       energy_exc = energy%exc
    1732           28 :       energy_ex = energy%ex
    1733              : 
    1734           50 :       SELECT CASE (bs_env%small_cell_full_kp_or_large_cell_Gamma)
    1735              :       CASE (large_cell_Gamma)
    1736              : 
    1737           22 :          NULLIFY (mat_ks_without_v_xc)
    1738           22 :          CALL dbcsr_allocate_matrix_set(mat_ks_without_v_xc, bs_env%n_spin)
    1739              : 
    1740           48 :          DO ispin = 1, bs_env%n_spin
    1741           26 :             ALLOCATE (mat_ks_without_v_xc(ispin)%matrix)
    1742           48 :             IF (hf_present) THEN
    1743              :                CALL dbcsr_create(mat_ks_without_v_xc(ispin)%matrix, template=bs_env%mat_ao_ao%matrix, &
    1744            0 :                                  matrix_type=dbcsr_type_symmetric)
    1745              :             ELSE
    1746           26 :                CALL dbcsr_create(mat_ks_without_v_xc(ispin)%matrix, template=bs_env%mat_ao_ao%matrix)
    1747              :             END IF
    1748              :          END DO
    1749              : 
    1750              :          ! calculate KS-matrix without XC
    1751              :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., just_energy=.FALSE., &
    1752           22 :                                            ext_ks_matrix=mat_ks_without_v_xc)
    1753              : 
    1754           48 :          DO ispin = 1, bs_env%n_spin
    1755              :             ! transfer dbcsr matrix to fm
    1756           26 :             CALL cp_fm_create(bs_env%fm_V_xc_Gamma(ispin), bs_env%fm_s_Gamma%matrix_struct)
    1757           26 :             CALL copy_dbcsr_to_fm(mat_ks_without_v_xc(ispin)%matrix, bs_env%fm_V_xc_Gamma(ispin))
    1758              : 
    1759              :             ! v_xc = h_ks - h_ks(v_xc = 0)
    1760              :             CALL cp_fm_scale_and_add(alpha=-1.0_dp, matrix_a=bs_env%fm_V_xc_Gamma(ispin), &
    1761           48 :                                      beta=1.0_dp, matrix_b=bs_env%fm_ks_Gamma(ispin))
    1762              :          END DO
    1763              : 
    1764           22 :          CALL dbcsr_deallocate_matrix_set(mat_ks_without_v_xc)
    1765              : 
    1766              :       CASE (small_cell_full_kp)
    1767              : 
    1768              :          ! calculate KS-matrix without XC
    1769            6 :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., just_energy=.FALSE.)
    1770            6 :          CALL get_qs_env(qs_env=qs_env, matrix_ks_kp=matrix_ks_kp)
    1771              : 
    1772          208 :          ALLOCATE (bs_env%fm_V_xc_R(dft_control%nimages, bs_env%n_spin))
    1773           40 :          DO ispin = 1, bs_env%n_spin
    1774          190 :             DO img = 1, dft_control%nimages
    1775              :                ! safe fm_V_xc_R in fm_matrix because saving in dbcsr matrix caused trouble...
    1776          178 :                CALL copy_dbcsr_to_fm(matrix_ks_kp(ispin, img)%matrix, bs_env%fm_work_mo(1))
    1777              :                CALL cp_fm_create(bs_env%fm_V_xc_R(img, ispin), bs_env%fm_work_mo(1)%matrix_struct, &
    1778          178 :                                  set_zero=.TRUE.)
    1779              :                ! store h_ks(v_xc = 0) in fm_V_xc_R
    1780              :                CALL cp_fm_scale_and_add(alpha=1.0_dp, matrix_a=bs_env%fm_V_xc_R(img, ispin), &
    1781          184 :                                         beta=1.0_dp, matrix_b=bs_env%fm_work_mo(1))
    1782              :             END DO
    1783              :          END DO
    1784              : 
    1785              :       END SELECT
    1786              : 
    1787              :       ! set back the energy
    1788           28 :       energy%total = energy_total
    1789           28 :       energy%exc = energy_exc
    1790           28 :       energy%ex = energy_ex
    1791              : 
    1792              :       ! set back nimages
    1793           28 :       dft_control%nimages = nimages
    1794              : 
    1795              :       ! set the DFT functional and HF fraction back
    1796              :       CALL section_vals_val_set(xc_section, "XC_FUNCTIONAL%_SECTION_PARAMETERS_", &
    1797           28 :                                 i_val=myfun)
    1798           28 :       IF (hf_present) THEN
    1799              :          CALL section_vals_val_set(xc_section, "HF%FRACTION", &
    1800            0 :                                    r_val=myfraction)
    1801              :       END IF
    1802              : 
    1803           28 :       IF (bs_env%small_cell_full_kp_or_large_cell_Gamma == small_cell_full_kp) THEN
    1804              :          ! calculate KS-matrix again with XC
    1805            6 :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., just_energy=.FALSE.)
    1806           12 :          DO ispin = 1, bs_env%n_spin
    1807          190 :             DO img = 1, dft_control%nimages
    1808              :                ! store h_ks in fm_work_mo
    1809          178 :                CALL copy_dbcsr_to_fm(matrix_ks_kp(ispin, img)%matrix, bs_env%fm_work_mo(1))
    1810              :                ! v_xc = h_ks - h_ks(v_xc = 0)
    1811              :                CALL cp_fm_scale_and_add(alpha=-1.0_dp, matrix_a=bs_env%fm_V_xc_R(img, ispin), &
    1812          184 :                                         beta=1.0_dp, matrix_b=bs_env%fm_work_mo(1))
    1813              :             END DO
    1814              :          END DO
    1815              :       END IF
    1816              : 
    1817           28 :       CALL timestop(handle)
    1818              : 
    1819           28 :    END SUBROUTINE compute_V_xc
    1820              : 
    1821              : ! **************************************************************************************************
    1822              : !> \brief ...
    1823              : !> \param bs_env ...
    1824              : ! **************************************************************************************************
    1825           28 :    SUBROUTINE setup_time_and_frequency_minimax_grid(bs_env)
    1826              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1827              : 
    1828              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_time_and_frequency_minimax_grid'
    1829              : 
    1830              :       INTEGER                                            :: handle, homo, i_w, ierr, ispin, j_w, &
    1831              :                                                             n_mo, num_time_freq_points, u
    1832              :       REAL(KIND=dp)                                      :: E_max, E_max_ispin, E_min, E_min_ispin, &
    1833              :                                                             E_range, max_error_min
    1834           28 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: points_and_weights
    1835              : 
    1836           28 :       CALL timeset(routineN, handle)
    1837              : 
    1838           28 :       n_mo = bs_env%n_ao
    1839           28 :       num_time_freq_points = bs_env%num_time_freq_points
    1840              : 
    1841           84 :       ALLOCATE (bs_env%imag_freq_points(num_time_freq_points))
    1842           84 :       ALLOCATE (bs_env%imag_time_points(num_time_freq_points))
    1843           84 :       ALLOCATE (bs_env%imag_time_weights_freq_zero(num_time_freq_points))
    1844          112 :       ALLOCATE (bs_env%weights_cos_t_to_w(num_time_freq_points, num_time_freq_points))
    1845          112 :       ALLOCATE (bs_env%weights_cos_w_to_t(num_time_freq_points, num_time_freq_points))
    1846          112 :       ALLOCATE (bs_env%weights_sin_t_to_w(num_time_freq_points, num_time_freq_points))
    1847              : 
    1848              :       ! minimum and maximum difference between eigenvalues of unoccupied and an occupied MOs
    1849           28 :       E_min = 1000.0_dp
    1850           28 :       E_max = -1000.0_dp
    1851           60 :       DO ispin = 1, bs_env%n_spin
    1852           32 :          homo = bs_env%n_occ(ispin)
    1853           58 :          SELECT CASE (bs_env%small_cell_full_kp_or_large_cell_Gamma)
    1854              :          CASE (large_cell_Gamma)
    1855              :             E_min_ispin = bs_env%eigenval_scf_Gamma(homo + 1, ispin) - &
    1856           26 :                           bs_env%eigenval_scf_Gamma(homo, ispin)
    1857              :             E_max_ispin = bs_env%eigenval_scf_Gamma(n_mo, ispin) - &
    1858           26 :                           bs_env%eigenval_scf_Gamma(1, ispin)
    1859              :          CASE (small_cell_full_kp)
    1860              :             E_min_ispin = MINVAL(bs_env%eigenval_scf(homo + 1, :, ispin)) - &
    1861          334 :                           MAXVAL(bs_env%eigenval_scf(homo, :, ispin))
    1862              :             E_max_ispin = MAXVAL(bs_env%eigenval_scf(n_mo, :, ispin)) - &
    1863          366 :                           MINVAL(bs_env%eigenval_scf(1, :, ispin))
    1864              :          END SELECT
    1865           32 :          E_min = MIN(E_min, E_min_ispin)
    1866           60 :          E_max = MAX(E_max, E_max_ispin)
    1867              :       END DO
    1868              : 
    1869           28 :       E_range = E_max/E_min
    1870              : 
    1871           84 :       ALLOCATE (points_and_weights(2*num_time_freq_points))
    1872              : 
    1873              :       ! frequency points
    1874           28 :       IF (num_time_freq_points <= 20) THEN
    1875           28 :          CALL get_rpa_minimax_coeff(num_time_freq_points, E_range, points_and_weights, ierr, .FALSE.)
    1876              :       ELSE
    1877            0 :          CALL get_rpa_minimax_coeff_larger_grid(num_time_freq_points, E_range, points_and_weights)
    1878              :       END IF
    1879              : 
    1880              :       ! one needs to scale the minimax grids, see Azizi, Wilhelm, Golze, Panades-Barrueta,
    1881              :       ! Giantomassi, Rinke, Draxl, Gonze et al., 2 publications
    1882          396 :       bs_env%imag_freq_points(:) = points_and_weights(1:num_time_freq_points)*E_min
    1883              : 
    1884              :       ! determine number of fit points in the interval [0,ω_max] for virt, or [-ω_max,0] for occ
    1885           28 :       bs_env%num_freq_points_fit = 0
    1886          396 :       DO i_w = 1, num_time_freq_points
    1887          396 :          IF (bs_env%imag_freq_points(i_w) < bs_env%freq_max_fit) THEN
    1888          126 :             bs_env%num_freq_points_fit = bs_env%num_freq_points_fit + 1
    1889              :          END IF
    1890              :       END DO
    1891              : 
    1892              :       ! iω values for the analytic continuation Σ^c_n(iω,k) -> Σ^c_n(ϵ,k)
    1893           84 :       ALLOCATE (bs_env%imag_freq_points_fit(bs_env%num_freq_points_fit))
    1894           28 :       j_w = 0
    1895          396 :       DO i_w = 1, num_time_freq_points
    1896          396 :          IF (bs_env%imag_freq_points(i_w) < bs_env%freq_max_fit) THEN
    1897          126 :             j_w = j_w + 1
    1898          126 :             bs_env%imag_freq_points_fit(j_w) = bs_env%imag_freq_points(i_w)
    1899              :          END IF
    1900              :       END DO
    1901              : 
    1902              :       ! reset the number of Padé parameters if smaller than the number of
    1903              :       ! imaginary-frequency points for the fit
    1904           28 :       IF (bs_env%num_freq_points_fit < bs_env%nparam_pade) THEN
    1905           28 :          bs_env%nparam_pade = bs_env%num_freq_points_fit
    1906              :       END IF
    1907              : 
    1908              :       ! time points
    1909           28 :       IF (num_time_freq_points <= 20) THEN
    1910           28 :          CALL get_exp_minimax_coeff(num_time_freq_points, E_range, points_and_weights)
    1911              :       ELSE
    1912            0 :          CALL get_exp_minimax_coeff_gw(num_time_freq_points, E_range, points_and_weights)
    1913              :       END IF
    1914              : 
    1915          396 :       bs_env%imag_time_points(:) = points_and_weights(1:num_time_freq_points)/(2.0_dp*E_min)
    1916          396 :       bs_env%imag_time_weights_freq_zero(:) = points_and_weights(num_time_freq_points + 1:)/(E_min)
    1917              : 
    1918           28 :       DEALLOCATE (points_and_weights)
    1919              : 
    1920           28 :       u = bs_env%unit_nr
    1921           28 :       IF (u > 0) THEN
    1922           14 :          WRITE (u, '(T2,A)') ''
    1923           14 :          WRITE (u, '(T2,A,F55.2)') 'SCF direct band gap (eV)', E_min*evolt
    1924           14 :          WRITE (u, '(T2,A,F53.2)') 'Max. SCF eigval diff. (eV)', E_max*evolt
    1925           14 :          WRITE (u, '(T2,A,F55.2)') 'E-Range for minimax grid', E_range
    1926           14 :          WRITE (u, '(T2,A,I27)') 'Number of Padé parameters for analytic continuation:', &
    1927           28 :             bs_env%nparam_pade
    1928           14 :          WRITE (u, '(T2,A)') ''
    1929              :       END IF
    1930              : 
    1931              :       ! in minimax grids, Fourier transforms t -> w and w -> t are split using
    1932              :       ! e^(iwt) = cos(wt) + i sin(wt); we thus calculate weights for trafos with a cos and
    1933              :       ! sine prefactor; details in Azizi, Wilhelm, Golze, Giantomassi, Panades-Barrueta,
    1934              :       ! Rinke, Draxl, Gonze et al., 2 publications
    1935              : 
    1936              :       ! cosine transform weights imaginary time to imaginary frequency
    1937              :       CALL get_l_sq_wghts_cos_tf_t_to_w(num_time_freq_points, &
    1938              :                                         bs_env%imag_time_points, &
    1939              :                                         bs_env%weights_cos_t_to_w, &
    1940              :                                         bs_env%imag_freq_points, &
    1941              :                                         E_min, E_max, max_error_min, &
    1942              :                                         bs_env%num_points_per_magnitude, &
    1943           28 :                                         bs_env%regularization_minimax)
    1944              : 
    1945              :       ! cosine transform weights imaginary frequency to imaginary time
    1946              :       CALL get_l_sq_wghts_cos_tf_w_to_t(num_time_freq_points, &
    1947              :                                         bs_env%imag_time_points, &
    1948              :                                         bs_env%weights_cos_w_to_t, &
    1949              :                                         bs_env%imag_freq_points, &
    1950              :                                         E_min, E_max, max_error_min, &
    1951              :                                         bs_env%num_points_per_magnitude, &
    1952           28 :                                         bs_env%regularization_minimax)
    1953              : 
    1954              :       ! sine transform weights imaginary time to imaginary frequency
    1955              :       CALL get_l_sq_wghts_sin_tf_t_to_w(num_time_freq_points, &
    1956              :                                         bs_env%imag_time_points, &
    1957              :                                         bs_env%weights_sin_t_to_w, &
    1958              :                                         bs_env%imag_freq_points, &
    1959              :                                         E_min, E_max, max_error_min, &
    1960              :                                         bs_env%num_points_per_magnitude, &
    1961           28 :                                         bs_env%regularization_minimax)
    1962              : 
    1963           28 :       CALL timestop(handle)
    1964              : 
    1965           56 :    END SUBROUTINE setup_time_and_frequency_minimax_grid
    1966              : 
    1967              : ! **************************************************************************************************
    1968              : !> \brief ...
    1969              : !> \param qs_env ...
    1970              : !> \param bs_env ...
    1971              : ! **************************************************************************************************
    1972            6 :    SUBROUTINE setup_cells_3c(qs_env, bs_env)
    1973              : 
    1974              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1975              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1976              : 
    1977              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'setup_cells_3c'
    1978              : 
    1979              :       INTEGER :: atom_i, atom_j, atom_k, block_count, handle, i, i_cell_x, i_cell_x_max, &
    1980              :          i_cell_x_min, i_size, ikind, img, j, j_cell, j_cell_max, j_cell_y, j_cell_y_max, &
    1981              :          j_cell_y_min, j_size, k_cell, k_cell_max, k_cell_z, k_cell_z_max, k_cell_z_min, k_size, &
    1982              :          nimage_pairs_3c, nimages_3c, nimages_3c_max, nkind, u
    1983              :       INTEGER(KIND=int_8)                                :: mem_occ_per_proc
    1984            6 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: kind_of, n_other_3c_images_max
    1985            6 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: index_to_cell_3c_max, nblocks_3c_max
    1986              :       INTEGER, DIMENSION(3)                              :: cell_index, n_max
    1987              :       REAL(KIND=dp) :: avail_mem_per_proc_GB, cell_dist, cell_radius_3c, dij, dik, djk, eps, &
    1988              :          exp_min_ao, exp_min_RI, frobenius_norm, mem_3c_GB, mem_occ_per_proc_GB, radius_ao, &
    1989              :          radius_ao_product, radius_RI
    1990            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: exp_ao_kind, exp_RI_kind, &
    1991            6 :                                                             radius_ao_kind, &
    1992            6 :                                                             radius_ao_product_kind, radius_RI_kind
    1993            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: int_3c
    1994              :       REAL(KIND=dp), DIMENSION(3)                        :: rij, rik, rjk, vec_cell_j, vec_cell_k
    1995            6 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: exp_ao, exp_RI
    1996            6 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1997              :       TYPE(cell_type), POINTER                           :: cell
    1998            6 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1999              : 
    2000            6 :       CALL timeset(routineN, handle)
    2001              : 
    2002            6 :       CALL get_qs_env(qs_env, nkind=nkind, atomic_kind_set=atomic_kind_set, particle_set=particle_set, cell=cell)
    2003              : 
    2004              :       ALLOCATE (exp_ao_kind(nkind), exp_RI_kind(nkind), radius_ao_kind(nkind), &
    2005           42 :                 radius_ao_product_kind(nkind), radius_RI_kind(nkind))
    2006              : 
    2007           18 :       exp_min_RI = 10.0_dp
    2008           18 :       exp_min_ao = 10.0_dp
    2009           18 :       exp_RI_kind = 10.0_dp
    2010           18 :       exp_AO_kind = 10.0_dp
    2011              : 
    2012            6 :       eps = bs_env%eps_filter*bs_env%heuristic_filter_factor
    2013              : 
    2014           18 :       DO ikind = 1, nkind
    2015              : 
    2016           12 :          CALL get_gto_basis_set(bs_env%basis_set_RI(ikind)%gto_basis_set, zet=exp_RI)
    2017           12 :          CALL get_gto_basis_set(bs_env%basis_set_ao(ikind)%gto_basis_set, zet=exp_ao)
    2018              : 
    2019              :          ! we need to remove all exponents lower than a lower bound, e.g. 1E-3, because
    2020              :          ! for contracted basis sets, there might be exponents = 0 in zet
    2021           24 :          DO i = 1, SIZE(exp_RI, 1)
    2022           42 :             DO j = 1, SIZE(exp_RI, 2)
    2023           18 :                IF (exp_RI(i, j) < exp_min_RI .AND. exp_RI(i, j) > 1E-3_dp) exp_min_RI = exp_RI(i, j)
    2024           18 :                IF (exp_RI(i, j) < exp_RI_kind(ikind) .AND. exp_RI(i, j) > 1E-3_dp) &
    2025           24 :                   exp_RI_kind(ikind) = exp_RI(i, j)
    2026              :             END DO
    2027              :          END DO
    2028           60 :          DO i = 1, SIZE(exp_ao, 1)
    2029          144 :             DO j = 1, SIZE(exp_ao, 2)
    2030           84 :                IF (exp_ao(i, j) < exp_min_ao .AND. exp_ao(i, j) > 1E-3_dp) exp_min_ao = exp_ao(i, j)
    2031           84 :                IF (exp_ao(i, j) < exp_ao_kind(ikind) .AND. exp_ao(i, j) > 1E-3_dp) &
    2032           84 :                   exp_ao_kind(ikind) = exp_ao(i, j)
    2033              :             END DO
    2034              :          END DO
    2035           12 :          radius_ao_kind(ikind) = SQRT(-LOG(eps)/exp_ao_kind(ikind))
    2036           12 :          radius_ao_product_kind(ikind) = SQRT(-LOG(eps)/(2.0_dp*exp_ao_kind(ikind)))
    2037           18 :          radius_RI_kind(ikind) = SQRT(-LOG(eps)/exp_RI_kind(ikind))
    2038              :       END DO
    2039              : 
    2040            6 :       radius_ao = SQRT(-LOG(eps)/exp_min_ao)
    2041            6 :       radius_ao_product = SQRT(-LOG(eps)/(2.0_dp*exp_min_ao))
    2042            6 :       radius_RI = SQRT(-LOG(eps)/exp_min_RI)
    2043              : 
    2044            6 :       CALL get_atomic_kind_set(atomic_kind_set=atomic_kind_set, kind_of=kind_of)
    2045              : 
    2046              :       ! For a 3c integral (μR υS | P0) we have that cell R and cell S need to be within radius_3c
    2047            6 :       cell_radius_3c = radius_ao_product + radius_RI + bs_env%ri_metric%cutoff_radius
    2048              : 
    2049           24 :       n_max(1:3) = bs_env%periodic(1:3)*30
    2050              : 
    2051            6 :       nimages_3c_max = 0
    2052              : 
    2053            6 :       i_cell_x_min = 0
    2054            6 :       i_cell_x_max = 0
    2055            6 :       j_cell_y_min = 0
    2056            6 :       j_cell_y_max = 0
    2057            6 :       k_cell_z_min = 0
    2058            6 :       k_cell_z_max = 0
    2059              : 
    2060          132 :       DO i_cell_x = -n_max(1), n_max(1)
    2061         7818 :          DO j_cell_y = -n_max(2), n_max(2)
    2062        30138 :             DO k_cell_z = -n_max(3), n_max(3)
    2063              : 
    2064        89304 :                cell_index(1:3) = [i_cell_x, j_cell_y, k_cell_z]
    2065              : 
    2066        22326 :                CALL get_cell_dist(cell_index, bs_env%hmat, cell_dist)
    2067              : 
    2068        30012 :                IF (cell_dist < cell_radius_3c) THEN
    2069          142 :                   nimages_3c_max = nimages_3c_max + 1
    2070          142 :                   i_cell_x_min = MIN(i_cell_x_min, i_cell_x)
    2071          142 :                   i_cell_x_max = MAX(i_cell_x_max, i_cell_x)
    2072          142 :                   j_cell_y_min = MIN(j_cell_y_min, j_cell_y)
    2073          142 :                   j_cell_y_max = MAX(j_cell_y_max, j_cell_y)
    2074          142 :                   k_cell_z_min = MIN(k_cell_z_min, k_cell_z)
    2075          142 :                   k_cell_z_max = MAX(k_cell_z_max, k_cell_z)
    2076              :                END IF
    2077              : 
    2078              :             END DO
    2079              :          END DO
    2080              :       END DO
    2081              : 
    2082              :       ! get index_to_cell_3c_max for the maximum possible cell range;
    2083              :       ! compute 3c integrals later in this routine and check really which cell is needed
    2084           18 :       ALLOCATE (index_to_cell_3c_max(3, nimages_3c_max))
    2085              : 
    2086            6 :       img = 0
    2087          132 :       DO i_cell_x = -n_max(1), n_max(1)
    2088         7818 :          DO j_cell_y = -n_max(2), n_max(2)
    2089        30138 :             DO k_cell_z = -n_max(3), n_max(3)
    2090              : 
    2091        89304 :                cell_index(1:3) = [i_cell_x, j_cell_y, k_cell_z]
    2092              : 
    2093        22326 :                CALL get_cell_dist(cell_index, bs_env%hmat, cell_dist)
    2094              : 
    2095        30012 :                IF (cell_dist < cell_radius_3c) THEN
    2096          142 :                   img = img + 1
    2097          568 :                   index_to_cell_3c_max(1:3, img) = cell_index(1:3)
    2098              :                END IF
    2099              : 
    2100              :             END DO
    2101              :          END DO
    2102              :       END DO
    2103              : 
    2104              :       ! get pairs of R and S which have non-zero 3c integral (μR υS | P0)
    2105           24 :       ALLOCATE (nblocks_3c_max(nimages_3c_max, nimages_3c_max))
    2106         3530 :       nblocks_3c_max(:, :) = 0
    2107              : 
    2108              :       block_count = 0
    2109          148 :       DO j_cell = 1, nimages_3c_max
    2110         3530 :          DO k_cell = 1, nimages_3c_max
    2111              : 
    2112        12788 :             DO atom_j = 1, bs_env%n_atom
    2113        38674 :             DO atom_k = 1, bs_env%n_atom
    2114       109848 :             DO atom_i = 1, bs_env%n_atom
    2115              : 
    2116        74556 :                block_count = block_count + 1
    2117        74556 :                IF (MODULO(block_count, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    2118              : 
    2119       149112 :                CALL scaled_to_real(vec_cell_j, REAL(index_to_cell_3c_max(1:3, j_cell), kind=dp), cell)
    2120       149112 :                CALL scaled_to_real(vec_cell_k, REAL(index_to_cell_3c_max(1:3, k_cell), kind=dp), cell)
    2121              : 
    2122       149112 :                rij = pbc(particle_set(atom_j)%r(:), cell) - pbc(particle_set(atom_i)%r(:), cell) + vec_cell_j(:)
    2123              :                rjk = pbc(particle_set(atom_k)%r(:), cell) - pbc(particle_set(atom_j)%r(:), cell) &
    2124       149112 :                      + vec_cell_k(:) - vec_cell_j(:)
    2125       149112 :                rik(:) = rij(:) + rjk(:)
    2126       149112 :                dij = NORM2(rij)
    2127       149112 :                dik = NORM2(rik)
    2128       149112 :                djk = NORM2(rjk)
    2129        37278 :                IF (djk > radius_ao_kind(kind_of(atom_j)) + radius_ao_kind(kind_of(atom_k))) CYCLE
    2130        11682 :                IF (dij > radius_ao_kind(kind_of(atom_j)) + radius_RI_kind(kind_of(atom_i)) &
    2131              :                    + bs_env%ri_metric%cutoff_radius) CYCLE
    2132         5932 :                IF (dik > radius_RI_kind(kind_of(atom_i)) + radius_ao_kind(kind_of(atom_k)) &
    2133              :                    + bs_env%ri_metric%cutoff_radius) CYCLE
    2134              : 
    2135         3867 :                j_size = bs_env%i_ao_end_from_atom(atom_j) - bs_env%i_ao_start_from_atom(atom_j) + 1
    2136         3867 :                k_size = bs_env%i_ao_end_from_atom(atom_k) - bs_env%i_ao_start_from_atom(atom_k) + 1
    2137         3867 :                i_size = bs_env%i_RI_end_from_atom(atom_i) - bs_env%i_RI_start_from_atom(atom_i) + 1
    2138              : 
    2139        19335 :                ALLOCATE (int_3c(j_size, k_size, i_size))
    2140              : 
    2141              :                ! compute 3-c int. ( μ(atom j) R , ν (atom k) S | P (atom i) 0 )
    2142              :                ! ("|": truncated Coulomb operator), inside build_3c_integrals: (j k | i)
    2143              :                CALL build_3c_integral_block(int_3c, qs_env, bs_env%ri_metric, &
    2144              :                                             basis_j=bs_env%basis_set_AO, &
    2145              :                                             basis_k=bs_env%basis_set_AO, &
    2146              :                                             basis_i=bs_env%basis_set_RI, &
    2147              :                                             cell_j=index_to_cell_3c_max(1:3, j_cell), &
    2148              :                                             cell_k=index_to_cell_3c_max(1:3, k_cell), &
    2149         3867 :                                             atom_k=atom_k, atom_j=atom_j, atom_i=atom_i)
    2150              : 
    2151       206126 :                frobenius_norm = SQRT(SUM(int_3c(:, :, :)**2))
    2152              : 
    2153         3867 :                DEALLOCATE (int_3c)
    2154              : 
    2155              :                ! we use a higher threshold here to safe memory when storing the 3c integrals
    2156              :                ! in every tensor group
    2157        29895 :                IF (frobenius_norm > eps) THEN
    2158          825 :                   nblocks_3c_max(j_cell, k_cell) = nblocks_3c_max(j_cell, k_cell) + 1
    2159              :                END IF
    2160              : 
    2161              :             END DO
    2162              :             END DO
    2163              :             END DO
    2164              : 
    2165              :          END DO
    2166              :       END DO
    2167              : 
    2168            6 :       CALL bs_env%para_env%sum(nblocks_3c_max)
    2169              : 
    2170           18 :       ALLOCATE (n_other_3c_images_max(nimages_3c_max))
    2171          148 :       n_other_3c_images_max(:) = 0
    2172              : 
    2173            6 :       nimages_3c = 0
    2174            6 :       nimage_pairs_3c = 0
    2175              : 
    2176          148 :       DO j_cell = 1, nimages_3c_max
    2177         3524 :          DO k_cell = 1, nimages_3c_max
    2178         3524 :             IF (nblocks_3c_max(j_cell, k_cell) > 0) THEN
    2179          290 :                n_other_3c_images_max(j_cell) = n_other_3c_images_max(j_cell) + 1
    2180          290 :                nimage_pairs_3c = nimage_pairs_3c + 1
    2181              :             END IF
    2182              :          END DO
    2183              : 
    2184          148 :          IF (n_other_3c_images_max(j_cell) > 0) nimages_3c = nimages_3c + 1
    2185              : 
    2186              :       END DO
    2187              : 
    2188            6 :       bs_env%nimages_3c = nimages_3c
    2189           18 :       ALLOCATE (bs_env%index_to_cell_3c(3, nimages_3c))
    2190              :       ALLOCATE (bs_env%cell_to_index_3c(i_cell_x_min:i_cell_x_max, &
    2191              :                                         j_cell_y_min:j_cell_y_max, &
    2192           30 :                                         k_cell_z_min:k_cell_z_max))
    2193          288 :       bs_env%cell_to_index_3c(:, :, :) = -1
    2194              : 
    2195           24 :       ALLOCATE (bs_env%nblocks_3c(nimages_3c, nimages_3c))
    2196            6 :       bs_env%nblocks_3c(nimages_3c, nimages_3c) = 0
    2197              : 
    2198            6 :       j_cell = 0
    2199          148 :       DO j_cell_max = 1, nimages_3c_max
    2200          142 :          IF (n_other_3c_images_max(j_cell_max) == 0) CYCLE
    2201           58 :          j_cell = j_cell + 1
    2202          232 :          cell_index(1:3) = index_to_cell_3c_max(1:3, j_cell_max)
    2203          232 :          bs_env%index_to_cell_3c(1:3, j_cell) = cell_index(1:3)
    2204           58 :          bs_env%cell_to_index_3c(cell_index(1), cell_index(2), cell_index(3)) = j_cell
    2205              : 
    2206           58 :          k_cell = 0
    2207         1474 :          DO k_cell_max = 1, nimages_3c_max
    2208         1410 :             IF (n_other_3c_images_max(k_cell_max) == 0) CYCLE
    2209          626 :             k_cell = k_cell + 1
    2210              : 
    2211         1552 :             bs_env%nblocks_3c(j_cell, k_cell) = nblocks_3c_max(j_cell_max, k_cell_max)
    2212              :          END DO
    2213              : 
    2214              :       END DO
    2215              : 
    2216              :       ! we use: 8*10^-9 GB / double precision number
    2217              :       mem_3c_GB = REAL(bs_env%n_RI, KIND=dp)*REAL(bs_env%n_ao, KIND=dp)**2 &
    2218            6 :                   *REAL(nimage_pairs_3c, KIND=dp)*8E-9_dp
    2219              : 
    2220            6 :       CALL m_memory(mem_occ_per_proc)
    2221            6 :       CALL bs_env%para_env%max(mem_occ_per_proc)
    2222              : 
    2223            6 :       mem_occ_per_proc_GB = REAL(mem_occ_per_proc, KIND=dp)/1.0E9_dp
    2224              : 
    2225              :       ! number of processors per group that entirely stores the 3c integrals and does tensor ops
    2226            6 :       avail_mem_per_proc_GB = bs_env%input_memory_per_proc_GB - mem_occ_per_proc_GB
    2227              : 
    2228              :       ! careful: downconvering real to integer, 1.9 -> 1; thus add 1.0 for upconversion, 1.9 -> 2
    2229            6 :       bs_env%group_size_tensor = MAX(INT(mem_3c_GB/avail_mem_per_proc_GB + 1.0_dp), 1)
    2230              : 
    2231            6 :       u = bs_env%unit_nr
    2232              : 
    2233            6 :       IF (u > 0) THEN
    2234            3 :          WRITE (u, FMT="(T2,A,F52.1,A)") "Radius of atomic orbitals", radius_ao*angstrom, " Å"
    2235            3 :          WRITE (u, FMT="(T2,A,F55.1,A)") "Radius of RI functions", radius_RI*angstrom, " Å"
    2236            3 :          WRITE (u, FMT="(T2,A,I47)") "Number of cells for 3c integrals", nimages_3c
    2237            3 :          WRITE (u, FMT="(T2,A,I42)") "Number of cell pairs for 3c integrals", nimage_pairs_3c
    2238            3 :          WRITE (u, '(T2,A)') ''
    2239            3 :          WRITE (u, '(T2,A,F37.1,A)') 'Input: Available memory per MPI process', &
    2240            6 :             bs_env%input_memory_per_proc_GB, ' GB'
    2241            3 :          WRITE (u, '(T2,A,F35.1,A)') 'Used memory per MPI process before GW run', &
    2242            6 :             mem_occ_per_proc_GB, ' GB'
    2243            3 :          WRITE (u, '(T2,A,F44.1,A)') 'Memory of three-center integrals', mem_3c_GB, ' GB'
    2244              :       END IF
    2245              : 
    2246            6 :       CALL timestop(handle)
    2247              : 
    2248           18 :    END SUBROUTINE setup_cells_3c
    2249              : 
    2250              : ! **************************************************************************************************
    2251              : !> \brief ...
    2252              : !> \param index_to_cell_1 ...
    2253              : !> \param index_to_cell_2 ...
    2254              : !> \param nimages_1 ...
    2255              : !> \param nimages_2 ...
    2256              : !> \param index_to_cell ...
    2257              : !> \param cell_to_index ...
    2258              : !> \param nimages ...
    2259              : ! **************************************************************************************************
    2260            6 :    SUBROUTINE sum_two_R_grids(index_to_cell_1, index_to_cell_2, nimages_1, nimages_2, &
    2261              :                               index_to_cell, cell_to_index, nimages)
    2262              : 
    2263              :       INTEGER, DIMENSION(:, :)                           :: index_to_cell_1, index_to_cell_2
    2264              :       INTEGER                                            :: nimages_1, nimages_2
    2265              :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: index_to_cell
    2266              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    2267              :       INTEGER                                            :: nimages
    2268              : 
    2269              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'sum_two_R_grids'
    2270              : 
    2271              :       INTEGER                                            :: handle, i_dim, img_1, img_2, nimages_max
    2272            6 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: index_to_cell_tmp
    2273              :       INTEGER, DIMENSION(3)                              :: cell_1, cell_2, R, R_max, R_min
    2274              : 
    2275            6 :       CALL timeset(routineN, handle)
    2276              : 
    2277           24 :       DO i_dim = 1, 3
    2278          366 :          R_min(i_dim) = MINVAL(index_to_cell_1(i_dim, :)) + MINVAL(index_to_cell_2(i_dim, :))
    2279          390 :          R_max(i_dim) = MAXVAL(index_to_cell_1(i_dim, :)) + MAXVAL(index_to_cell_2(i_dim, :))
    2280              :       END DO
    2281              : 
    2282            6 :       nimages_max = (R_max(1) - R_min(1) + 1)*(R_max(2) - R_min(2) + 1)*(R_max(3) - R_min(3) + 1)
    2283              : 
    2284           18 :       ALLOCATE (index_to_cell_tmp(3, nimages_max))
    2285          766 :       index_to_cell_tmp(:, :) = -1
    2286              : 
    2287           30 :       ALLOCATE (cell_to_index(R_min(1):R_max(1), R_min(2):R_max(2), R_min(3):R_max(3)))
    2288          376 :       cell_to_index(:, :, :) = -1
    2289              : 
    2290            6 :       nimages = 0
    2291              : 
    2292           64 :       DO img_1 = 1, nimages_1
    2293              : 
    2294          690 :          DO img_2 = 1, nimages_2
    2295              : 
    2296         2504 :             cell_1(1:3) = index_to_cell_1(1:3, img_1)
    2297         2504 :             cell_2(1:3) = index_to_cell_2(1:3, img_2)
    2298              : 
    2299         2504 :             R(1:3) = cell_1(1:3) + cell_2(1:3)
    2300              : 
    2301              :             ! check whether we have found a new cell
    2302          684 :             IF (cell_to_index(R(1), R(2), R(3)) == -1) THEN
    2303              : 
    2304          166 :                nimages = nimages + 1
    2305          166 :                cell_to_index(R(1), R(2), R(3)) = nimages
    2306          664 :                index_to_cell_tmp(1:3, nimages) = R(1:3)
    2307              : 
    2308              :             END IF
    2309              : 
    2310              :          END DO
    2311              : 
    2312              :       END DO
    2313              : 
    2314           18 :       ALLOCATE (index_to_cell(3, nimages))
    2315          670 :       index_to_cell(:, :) = index_to_cell_tmp(1:3, 1:nimages)
    2316              : 
    2317            6 :       CALL timestop(handle)
    2318              : 
    2319           12 :    END SUBROUTINE sum_two_R_grids
    2320              : 
    2321              : ! **************************************************************************************************
    2322              : !> \brief ...
    2323              : !> \param qs_env ...
    2324              : !> \param bs_env ...
    2325              : ! **************************************************************************************************
    2326            6 :    SUBROUTINE compute_3c_integrals(qs_env, bs_env)
    2327              : 
    2328              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2329              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2330              : 
    2331              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_3c_integrals'
    2332              : 
    2333              :       INTEGER                                            :: handle, j_cell, k_cell, nimages_3c
    2334              : 
    2335            6 :       CALL timeset(routineN, handle)
    2336              : 
    2337            6 :       nimages_3c = bs_env%nimages_3c
    2338          756 :       ALLOCATE (bs_env%t_3c_int(nimages_3c, nimages_3c))
    2339           64 :       DO j_cell = 1, nimages_3c
    2340          690 :          DO k_cell = 1, nimages_3c
    2341          684 :             CALL dbt_create(bs_env%t_RI_AO__AO, bs_env%t_3c_int(j_cell, k_cell))
    2342              :          END DO
    2343              :       END DO
    2344              : 
    2345              :       CALL build_3c_integrals(bs_env%t_3c_int, &
    2346              :                               bs_env%eps_filter, &
    2347              :                               qs_env, &
    2348              :                               bs_env%nl_3c, &
    2349              :                               int_eps=bs_env%eps_filter*0.05_dp, &
    2350              :                               basis_i=bs_env%basis_set_RI, &
    2351              :                               basis_j=bs_env%basis_set_AO, &
    2352              :                               basis_k=bs_env%basis_set_AO, &
    2353              :                               potential_parameter=bs_env%ri_metric, &
    2354              :                               desymmetrize=.FALSE., do_kpoints=.TRUE., cell_sym=.TRUE., &
    2355            6 :                               cell_to_index_ext=bs_env%cell_to_index_3c)
    2356              : 
    2357            6 :       CALL bs_env%para_env%sync()
    2358              : 
    2359            6 :       CALL timestop(handle)
    2360              : 
    2361            6 :    END SUBROUTINE compute_3c_integrals
    2362              : 
    2363              : ! **************************************************************************************************
    2364              : !> \brief ...
    2365              : !> \param cell_index ...
    2366              : !> \param hmat ...
    2367              : !> \param cell_dist ...
    2368              : ! **************************************************************************************************
    2369        44652 :    SUBROUTINE get_cell_dist(cell_index, hmat, cell_dist)
    2370              : 
    2371              :       INTEGER, DIMENSION(3)                              :: cell_index
    2372              :       REAL(KIND=dp)                                      :: hmat(3, 3), cell_dist
    2373              : 
    2374              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_cell_dist'
    2375              : 
    2376              :       INTEGER                                            :: handle, i_dim
    2377              :       INTEGER, DIMENSION(3)                              :: cell_index_adj
    2378              :       REAL(KIND=dp)                                      :: cell_dist_3(3)
    2379              : 
    2380        44652 :       CALL timeset(routineN, handle)
    2381              : 
    2382              :       ! the distance of cells needs to be taken to adjacent neighbors, not
    2383              :       ! between the center of the cells. We thus need to rescale the cell index
    2384       178608 :       DO i_dim = 1, 3
    2385       133956 :          IF (cell_index(i_dim) > 0) cell_index_adj(i_dim) = cell_index(i_dim) - 1
    2386       133956 :          IF (cell_index(i_dim) < 0) cell_index_adj(i_dim) = cell_index(i_dim) + 1
    2387       178608 :          IF (cell_index(i_dim) == 0) cell_index_adj(i_dim) = cell_index(i_dim)
    2388              :       END DO
    2389              : 
    2390       714432 :       cell_dist_3(1:3) = MATMUL(hmat, REAL(cell_index_adj, KIND=dp))
    2391              : 
    2392       178608 :       cell_dist = SQRT(ABS(SUM(cell_dist_3(1:3)**2)))
    2393              : 
    2394        44652 :       CALL timestop(handle)
    2395              : 
    2396        44652 :    END SUBROUTINE get_cell_dist
    2397              : 
    2398              : ! **************************************************************************************************
    2399              : !> \brief ...
    2400              : !> \param qs_env ...
    2401              : !> \param bs_env ...
    2402              : !> \param kpoints ...
    2403              : !> \param do_print ...
    2404              : ! **************************************************************************************************
    2405            0 :    SUBROUTINE setup_kpoints_scf_desymm(qs_env, bs_env, kpoints, do_print)
    2406              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2407              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2408              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2409              : 
    2410              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_kpoints_scf_desymm'
    2411              : 
    2412              :       INTEGER                                            :: handle, i_cell_x, i_dim, img, j_cell_y, &
    2413              :                                                             k_cell_z, nimages, nkp, u
    2414              :       INTEGER, DIMENSION(3)                              :: cell_grid, cixd, nkp_grid
    2415              :       TYPE(kpoint_type), POINTER                         :: kpoints_scf
    2416              : 
    2417              :       LOGICAL:: do_print
    2418              : 
    2419            0 :       CALL timeset(routineN, handle)
    2420              : 
    2421            0 :       NULLIFY (kpoints)
    2422            0 :       CALL kpoint_create(kpoints)
    2423              : 
    2424            0 :       CALL get_qs_env(qs_env=qs_env, kpoints=kpoints_scf)
    2425              : 
    2426            0 :       nkp_grid(1:3) = kpoints_scf%nkp_grid(1:3)
    2427            0 :       nkp = nkp_grid(1)*nkp_grid(2)*nkp_grid(3)
    2428              : 
    2429              :       ! we need in periodic directions at least 2 k-points in the SCF
    2430            0 :       DO i_dim = 1, 3
    2431            0 :          IF (bs_env%periodic(i_dim) == 1) THEN
    2432            0 :             CPASSERT(nkp_grid(i_dim) > 1)
    2433              :          END IF
    2434              :       END DO
    2435              : 
    2436            0 :       kpoints%kp_scheme = "GENERAL"
    2437            0 :       kpoints%nkp_grid(1:3) = nkp_grid(1:3)
    2438            0 :       kpoints%nkp = nkp
    2439            0 :       bs_env%nkp_scf_desymm = nkp
    2440              : 
    2441            0 :       ALLOCATE (kpoints%xkp(1:3, nkp))
    2442            0 :       CALL compute_xkp(kpoints%xkp, 1, nkp, nkp_grid)
    2443              : 
    2444            0 :       ALLOCATE (kpoints%wkp(nkp))
    2445            0 :       kpoints%wkp(:) = 1.0_dp/REAL(nkp, KIND=dp)
    2446              : 
    2447              :       ! for example 4x3x6 kpoint grid -> 3x3x5 cell grid because we need the same number of
    2448              :       ! neighbor cells on both sides of the unit cell
    2449            0 :       cell_grid(1:3) = nkp_grid(1:3) - MODULO(nkp_grid(1:3) + 1, 2)
    2450              :       ! cell index: for example for x: from -n_x/2 to +n_x/2, n_x: number of cells in x direction
    2451            0 :       cixd(1:3) = cell_grid(1:3)/2
    2452              : 
    2453            0 :       nimages = cell_grid(1)*cell_grid(2)*cell_grid(3)
    2454              : 
    2455            0 :       bs_env%nimages_scf_desymm = nimages
    2456              : 
    2457            0 :       ALLOCATE (kpoints%cell_to_index(-cixd(1):cixd(1), -cixd(2):cixd(2), -cixd(3):cixd(3)))
    2458            0 :       ALLOCATE (kpoints%index_to_cell(3, nimages))
    2459              : 
    2460            0 :       img = 0
    2461            0 :       DO i_cell_x = -cixd(1), cixd(1)
    2462            0 :          DO j_cell_y = -cixd(2), cixd(2)
    2463            0 :             DO k_cell_z = -cixd(3), cixd(3)
    2464            0 :                img = img + 1
    2465            0 :                kpoints%cell_to_index(i_cell_x, j_cell_y, k_cell_z) = img
    2466            0 :                kpoints%index_to_cell(1:3, img) = [i_cell_x, j_cell_y, k_cell_z]
    2467              :             END DO
    2468              :          END DO
    2469              :       END DO
    2470              : 
    2471            0 :       u = bs_env%unit_nr
    2472            0 :       IF (u > 0 .AND. do_print) THEN
    2473            0 :          WRITE (u, FMT="(T2,A,I49)") "Number of cells for G, χ, W, Σ", nimages
    2474              :       END IF
    2475              : 
    2476            0 :       CALL timestop(handle)
    2477              : 
    2478            0 :    END SUBROUTINE setup_kpoints_scf_desymm
    2479              : 
    2480              : ! **************************************************************************************************
    2481              : !> \brief ...
    2482              : !> \param bs_env ...
    2483              : ! **************************************************************************************************
    2484            6 :    SUBROUTINE setup_cells_Delta_R(bs_env)
    2485              : 
    2486              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2487              : 
    2488              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_cells_Delta_R'
    2489              : 
    2490              :       INTEGER                                            :: handle
    2491              : 
    2492            6 :       CALL timeset(routineN, handle)
    2493              : 
    2494              :       ! cell sums batch wise for fixed ΔR = S_1 - R_1; for example:
    2495              :       ! Σ_λσ^R = sum_PR1νS1 M^G_λ0,νS1,PR1 M^W_σR,νS1,PR1
    2496              : 
    2497              :       CALL sum_two_R_grids(bs_env%index_to_cell_3c, &
    2498              :                            bs_env%index_to_cell_3c, &
    2499              :                            bs_env%nimages_3c, bs_env%nimages_3c, &
    2500              :                            bs_env%index_to_cell_Delta_R, &
    2501              :                            bs_env%cell_to_index_Delta_R, &
    2502            6 :                            bs_env%nimages_Delta_R)
    2503              : 
    2504            6 :       IF (bs_env%unit_nr > 0) THEN
    2505            3 :          WRITE (bs_env%unit_nr, FMT="(T2,A,I61)") "Number of cells ΔR", bs_env%nimages_Delta_R
    2506              :       END IF
    2507              : 
    2508            6 :       CALL timestop(handle)
    2509              : 
    2510            6 :    END SUBROUTINE setup_cells_Delta_R
    2511              : 
    2512              : ! **************************************************************************************************
    2513              : !> \brief ...
    2514              : !> \param bs_env ...
    2515              : ! **************************************************************************************************
    2516            6 :    SUBROUTINE setup_parallelization_Delta_R(bs_env)
    2517              : 
    2518              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2519              : 
    2520              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_parallelization_Delta_R'
    2521              : 
    2522              :       INTEGER                                            :: handle, i_cell_Delta_R, i_task_local, &
    2523              :                                                             n_tasks_local
    2524            6 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: i_cell_Delta_R_group, &
    2525            6 :                                                             n_tensor_ops_Delta_R
    2526              : 
    2527            6 :       CALL timeset(routineN, handle)
    2528              : 
    2529            6 :       CALL compute_n_tensor_ops_Delta_R(bs_env, n_tensor_ops_Delta_R)
    2530              : 
    2531            6 :       CALL compute_Delta_R_dist(bs_env, n_tensor_ops_Delta_R, i_cell_Delta_R_group, n_tasks_local)
    2532              : 
    2533            6 :       bs_env%n_tasks_Delta_R_local = n_tasks_local
    2534              : 
    2535           18 :       ALLOCATE (bs_env%task_Delta_R(n_tasks_local))
    2536              : 
    2537            6 :       i_task_local = 0
    2538          172 :       DO i_cell_Delta_R = 1, bs_env%nimages_Delta_R
    2539              : 
    2540          166 :          IF (i_cell_Delta_R_group(i_cell_Delta_R) /= bs_env%tensor_group_color) CYCLE
    2541              : 
    2542           73 :          i_task_local = i_task_local + 1
    2543              : 
    2544          172 :          bs_env%task_Delta_R(i_task_local) = i_cell_Delta_R
    2545              : 
    2546              :       END DO
    2547              : 
    2548           18 :       ALLOCATE (bs_env%skip_DR_chi(n_tasks_local))
    2549           79 :       bs_env%skip_DR_chi(:) = .FALSE.
    2550           18 :       ALLOCATE (bs_env%skip_DR_Sigma(n_tasks_local))
    2551           79 :       bs_env%skip_DR_Sigma(:) = .FALSE.
    2552              : 
    2553            6 :       CALL allocate_skip_3xR(bs_env%skip_DR_R12_S_Goccx3c_chi, bs_env)
    2554            6 :       CALL allocate_skip_3xR(bs_env%skip_DR_R12_S_Gvirx3c_chi, bs_env)
    2555            6 :       CALL allocate_skip_3xR(bs_env%skip_DR_R_R2_MxM_chi, bs_env)
    2556              : 
    2557            6 :       CALL allocate_skip_3xR(bs_env%skip_DR_R1_S2_Gx3c_Sigma, bs_env)
    2558            6 :       CALL allocate_skip_3xR(bs_env%skip_DR_R1_R_MxM_Sigma, bs_env)
    2559              : 
    2560            6 :       CALL timestop(handle)
    2561              : 
    2562           12 :    END SUBROUTINE setup_parallelization_Delta_R
    2563              : 
    2564              : ! **************************************************************************************************
    2565              : !> \brief ...
    2566              : !> \param skip ...
    2567              : !> \param bs_env ...
    2568              : ! **************************************************************************************************
    2569           30 :    SUBROUTINE allocate_skip_3xR(skip, bs_env)
    2570              :       LOGICAL, ALLOCATABLE, DIMENSION(:, :, :)           :: skip
    2571              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2572              : 
    2573              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'allocate_skip_3xR'
    2574              : 
    2575              :       INTEGER                                            :: handle
    2576              : 
    2577           30 :       CALL timeset(routineN, handle)
    2578              : 
    2579          150 :       ALLOCATE (skip(bs_env%n_tasks_Delta_R_local, bs_env%nimages_3c, bs_env%nimages_scf_desymm))
    2580        38235 :       skip(:, :, :) = .FALSE.
    2581              : 
    2582           30 :       CALL timestop(handle)
    2583              : 
    2584           30 :    END SUBROUTINE allocate_skip_3xR
    2585              : 
    2586              : ! **************************************************************************************************
    2587              : !> \brief ...
    2588              : !> \param bs_env ...
    2589              : !> \param n_tensor_ops_Delta_R ...
    2590              : !> \param i_cell_Delta_R_group ...
    2591              : !> \param n_tasks_local ...
    2592              : ! **************************************************************************************************
    2593            6 :    SUBROUTINE compute_Delta_R_dist(bs_env, n_tensor_ops_Delta_R, i_cell_Delta_R_group, n_tasks_local)
    2594              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2595              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: n_tensor_ops_Delta_R, &
    2596              :                                                             i_cell_Delta_R_group
    2597              :       INTEGER                                            :: n_tasks_local
    2598              : 
    2599              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_Delta_R_dist'
    2600              : 
    2601              :       INTEGER                                            :: handle, i_Delta_R_max_op, i_group_min, &
    2602              :                                                             nimages_Delta_R, u
    2603            6 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: n_tensor_ops_Delta_R_in_group
    2604              : 
    2605            6 :       CALL timeset(routineN, handle)
    2606              : 
    2607            6 :       nimages_Delta_R = bs_env%nimages_Delta_R
    2608              : 
    2609            6 :       u = bs_env%unit_nr
    2610              : 
    2611            6 :       IF (u > 0 .AND. nimages_Delta_R < bs_env%num_tensor_groups) THEN
    2612            0 :          WRITE (u, FMT="(T2,A,I5,A,I5,A)") "There are only ", nimages_Delta_R, &
    2613            0 :             " tasks to work on but there are ", bs_env%num_tensor_groups, " groups."
    2614            0 :          WRITE (u, FMT="(T2,A)") "Please reduce the number of MPI processes."
    2615            0 :          WRITE (u, '(T2,A)') ''
    2616              :       END IF
    2617              : 
    2618           18 :       ALLOCATE (n_tensor_ops_Delta_R_in_group(bs_env%num_tensor_groups))
    2619           18 :       n_tensor_ops_Delta_R_in_group(:) = 0
    2620           18 :       ALLOCATE (i_cell_Delta_R_group(nimages_Delta_R))
    2621          172 :       i_cell_Delta_R_group(:) = -1
    2622              : 
    2623            6 :       n_tasks_local = 0
    2624              : 
    2625          624 :       DO WHILE (ANY(n_tensor_ops_Delta_R(:) /= 0))
    2626              : 
    2627              :          ! get largest element of n_tensor_ops_Delta_R
    2628         4684 :          i_Delta_R_max_op = MAXLOC(n_tensor_ops_Delta_R, 1)
    2629              : 
    2630              :          ! distribute i_Delta_R_max_op to tensor group which has currently the smallest load
    2631          584 :          i_group_min = MINLOC(n_tensor_ops_Delta_R_in_group, 1)
    2632              : 
    2633              :          ! the tensor groups are 0-index based; but i_group_min is 1-index based
    2634          146 :          i_cell_Delta_R_group(i_Delta_R_max_op) = i_group_min - 1
    2635              :          n_tensor_ops_Delta_R_in_group(i_group_min) = n_tensor_ops_Delta_R_in_group(i_group_min) + &
    2636          146 :                                                       n_tensor_ops_Delta_R(i_Delta_R_max_op)
    2637              : 
    2638              :          ! remove i_Delta_R_max_op from n_tensor_ops_Delta_R
    2639          146 :          n_tensor_ops_Delta_R(i_Delta_R_max_op) = 0
    2640              : 
    2641          152 :          IF (bs_env%tensor_group_color == i_group_min - 1) n_tasks_local = n_tasks_local + 1
    2642              : 
    2643              :       END DO
    2644              : 
    2645            6 :       CALL timestop(handle)
    2646              : 
    2647           12 :    END SUBROUTINE compute_Delta_R_dist
    2648              : 
    2649              : ! **************************************************************************************************
    2650              : !> \brief ...
    2651              : !> \param bs_env ...
    2652              : !> \param n_tensor_ops_Delta_R ...
    2653              : ! **************************************************************************************************
    2654            6 :    SUBROUTINE compute_n_tensor_ops_Delta_R(bs_env, n_tensor_ops_Delta_R)
    2655              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2656              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: n_tensor_ops_Delta_R
    2657              : 
    2658              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_n_tensor_ops_Delta_R'
    2659              : 
    2660              :       INTEGER :: handle, i_cell_Delta_R, i_cell_R, i_cell_R1, i_cell_R1_minus_R, i_cell_R2, &
    2661              :          i_cell_R2_m_R1, i_cell_S1, i_cell_S1_m_R1_p_R2, i_cell_S1_minus_R, i_cell_S2, &
    2662              :          nimages_Delta_R
    2663              :       INTEGER, DIMENSION(3) :: cell_DR, cell_m_R1, cell_R, cell_R1, cell_R1_minus_R, cell_R2, &
    2664              :          cell_R2_m_R1, cell_S1, cell_S1_m_R2_p_R1, cell_S1_minus_R, cell_S1_p_S2_m_R1, cell_S2
    2665              :       LOGICAL                                            :: cell_found
    2666              : 
    2667            6 :       CALL timeset(routineN, handle)
    2668              : 
    2669            6 :       nimages_Delta_R = bs_env%nimages_Delta_R
    2670              : 
    2671           18 :       ALLOCATE (n_tensor_ops_Delta_R(nimages_Delta_R))
    2672          172 :       n_tensor_ops_Delta_R(:) = 0
    2673              : 
    2674              :       ! compute number of tensor operations for specific Delta_R
    2675          172 :       DO i_cell_Delta_R = 1, nimages_Delta_R
    2676              : 
    2677          166 :          IF (MODULO(i_cell_Delta_R, bs_env%num_tensor_groups) /= bs_env%tensor_group_color) CYCLE
    2678              : 
    2679          994 :          DO i_cell_R1 = 1, bs_env%nimages_3c
    2680              : 
    2681         3620 :             cell_R1(1:3) = bs_env%index_to_cell_3c(1:3, i_cell_R1)
    2682         3620 :             cell_DR(1:3) = bs_env%index_to_cell_Delta_R(1:3, i_cell_Delta_R)
    2683              : 
    2684              :             ! S_1 = R_1 + ΔR (from ΔR = S_1 - R_1)
    2685              :             CALL add_R(cell_R1, cell_DR, bs_env%index_to_cell_3c, cell_S1, &
    2686          905 :                        cell_found, bs_env%cell_to_index_3c, i_cell_S1)
    2687          905 :             IF (.NOT. cell_found) CYCLE
    2688              : 
    2689         2950 :             DO i_cell_R2 = 1, bs_env%nimages_scf_desymm
    2690              : 
    2691        10620 :                cell_R2(1:3) = bs_env%kpoints_scf_desymm%index_to_cell(1:3, i_cell_R2)
    2692              : 
    2693              :                ! R_2 - R_1
    2694              :                CALL add_R(cell_R2, -cell_R1, bs_env%index_to_cell_3c, cell_R2_m_R1, &
    2695        10620 :                           cell_found, bs_env%cell_to_index_3c, i_cell_R2_m_R1)
    2696         2655 :                IF (.NOT. cell_found) CYCLE
    2697              : 
    2698              :                ! S_1 - R_1 + R_2
    2699              :                CALL add_R(cell_S1, cell_R2_m_R1, bs_env%index_to_cell_3c, cell_S1_m_R2_p_R1, &
    2700         1575 :                           cell_found, bs_env%cell_to_index_3c, i_cell_S1_m_R1_p_R2)
    2701         1575 :                IF (.NOT. cell_found) CYCLE
    2702              : 
    2703         3993 :                n_tensor_ops_Delta_R(i_cell_Delta_R) = n_tensor_ops_Delta_R(i_cell_Delta_R) + 1
    2704              : 
    2705              :             END DO ! i_cell_R2
    2706              : 
    2707         2950 :             DO i_cell_S2 = 1, bs_env%nimages_scf_desymm
    2708              : 
    2709        10620 :                cell_S2(1:3) = bs_env%kpoints_scf_desymm%index_to_cell(1:3, i_cell_S2)
    2710        10620 :                cell_m_R1(1:3) = -cell_R1(1:3)
    2711        10620 :                cell_S1_p_S2_m_R1(1:3) = cell_S1(1:3) + cell_S2(1:3) - cell_R1(1:3)
    2712              : 
    2713         2655 :                CALL is_cell_in_index_to_cell(cell_m_R1, bs_env%index_to_cell_3c, cell_found)
    2714         2655 :                IF (.NOT. cell_found) CYCLE
    2715              : 
    2716         2169 :                CALL is_cell_in_index_to_cell(cell_S1_p_S2_m_R1, bs_env%index_to_cell_3c, cell_found)
    2717          295 :                IF (.NOT. cell_found) CYCLE
    2718              : 
    2719              :             END DO ! i_cell_S2
    2720              : 
    2721         4021 :             DO i_cell_R = 1, bs_env%nimages_scf_desymm
    2722              : 
    2723        10620 :                cell_R = bs_env%kpoints_scf_desymm%index_to_cell(1:3, i_cell_R)
    2724              : 
    2725              :                ! R_1 - R
    2726              :                CALL add_R(cell_R1, -cell_R, bs_env%index_to_cell_3c, cell_R1_minus_R, &
    2727        10620 :                           cell_found, bs_env%cell_to_index_3c, i_cell_R1_minus_R)
    2728         2655 :                IF (.NOT. cell_found) CYCLE
    2729              : 
    2730              :                ! S_1 - R
    2731              :                CALL add_R(cell_S1, -cell_R, bs_env%index_to_cell_3c, cell_S1_minus_R, &
    2732         6804 :                           cell_found, bs_env%cell_to_index_3c, i_cell_S1_minus_R)
    2733          905 :                IF (.NOT. cell_found) CYCLE
    2734              : 
    2735              :             END DO ! i_cell_R
    2736              : 
    2737              :          END DO ! i_cell_R1
    2738              : 
    2739              :       END DO ! i_cell_Delta_R
    2740              : 
    2741            6 :       CALL bs_env%para_env%sum(n_tensor_ops_Delta_R)
    2742              : 
    2743            6 :       CALL timestop(handle)
    2744              : 
    2745            6 :    END SUBROUTINE compute_n_tensor_ops_Delta_R
    2746              : 
    2747              : ! **************************************************************************************************
    2748              : !> \brief ...
    2749              : !> \param cell_1 ...
    2750              : !> \param cell_2 ...
    2751              : !> \param index_to_cell ...
    2752              : !> \param cell_1_plus_2 ...
    2753              : !> \param cell_found ...
    2754              : !> \param cell_to_index ...
    2755              : !> \param i_cell_1_plus_2 ...
    2756              : ! **************************************************************************************************
    2757        85114 :    SUBROUTINE add_R(cell_1, cell_2, index_to_cell, cell_1_plus_2, cell_found, &
    2758              :                     cell_to_index, i_cell_1_plus_2)
    2759              : 
    2760              :       INTEGER, DIMENSION(3)                              :: cell_1, cell_2
    2761              :       INTEGER, DIMENSION(:, :)                           :: index_to_cell
    2762              :       INTEGER, DIMENSION(3)                              :: cell_1_plus_2
    2763              :       LOGICAL                                            :: cell_found
    2764              :       INTEGER, DIMENSION(:, :, :), INTENT(IN), &
    2765              :          OPTIONAL, POINTER                               :: cell_to_index
    2766              :       INTEGER, INTENT(OUT), OPTIONAL                     :: i_cell_1_plus_2
    2767              : 
    2768              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'add_R'
    2769              : 
    2770              :       INTEGER                                            :: handle
    2771              : 
    2772        85114 :       CALL timeset(routineN, handle)
    2773              : 
    2774       340456 :       cell_1_plus_2(1:3) = cell_1(1:3) + cell_2(1:3)
    2775              : 
    2776        85114 :       CALL is_cell_in_index_to_cell(cell_1_plus_2, index_to_cell, cell_found)
    2777              : 
    2778        85114 :       IF (PRESENT(i_cell_1_plus_2)) THEN
    2779        85114 :          IF (cell_found) THEN
    2780        48214 :             CPASSERT(PRESENT(cell_to_index))
    2781        48214 :             i_cell_1_plus_2 = cell_to_index(cell_1_plus_2(1), cell_1_plus_2(2), cell_1_plus_2(3))
    2782              :          ELSE
    2783        36900 :             i_cell_1_plus_2 = -1000
    2784              :          END IF
    2785              :       END IF
    2786              : 
    2787        85114 :       CALL timestop(handle)
    2788              : 
    2789        85114 :    END SUBROUTINE add_R
    2790              : 
    2791              : ! **************************************************************************************************
    2792              : !> \brief ...
    2793              : !> \param cell ...
    2794              : !> \param index_to_cell ...
    2795              : !> \param cell_found ...
    2796              : ! **************************************************************************************************
    2797       133779 :    SUBROUTINE is_cell_in_index_to_cell(cell, index_to_cell, cell_found)
    2798              :       INTEGER, DIMENSION(3)                              :: cell
    2799              :       INTEGER, DIMENSION(:, :)                           :: index_to_cell
    2800              :       LOGICAL                                            :: cell_found
    2801              : 
    2802              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'is_cell_in_index_to_cell'
    2803              : 
    2804              :       INTEGER                                            :: handle, i_cell, nimg
    2805              :       INTEGER, DIMENSION(3)                              :: cell_i
    2806              : 
    2807       133779 :       CALL timeset(routineN, handle)
    2808              : 
    2809       133779 :       nimg = SIZE(index_to_cell, 2)
    2810              : 
    2811       133779 :       cell_found = .FALSE.
    2812              : 
    2813      1653594 :       DO i_cell = 1, nimg
    2814              : 
    2815      6079260 :          cell_i(1:3) = index_to_cell(1:3, i_cell)
    2816              : 
    2817      1653594 :          IF (cell_i(1) == cell(1) .AND. cell_i(2) == cell(2) .AND. cell_i(3) == cell(3)) THEN
    2818        79661 :             cell_found = .TRUE.
    2819              :          END IF
    2820              : 
    2821              :       END DO
    2822              : 
    2823       133779 :       CALL timestop(handle)
    2824              : 
    2825       133779 :    END SUBROUTINE is_cell_in_index_to_cell
    2826              : 
    2827              : ! **************************************************************************************************
    2828              : !> \brief ...
    2829              : !> \param qs_env ...
    2830              : !> \param bs_env ...
    2831              : ! **************************************************************************************************
    2832            6 :    SUBROUTINE allocate_matrices_small_cell_full_kp(qs_env, bs_env)
    2833              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2834              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2835              : 
    2836              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'allocate_matrices_small_cell_full_kp'
    2837              : 
    2838              :       INTEGER                                            :: handle, i_spin, i_t, img, n_spin, &
    2839              :                                                             nimages_scf, num_time_freq_points
    2840              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    2841              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2842              : 
    2843            6 :       CALL timeset(routineN, handle)
    2844              : 
    2845            6 :       nimages_scf = bs_env%nimages_scf_desymm
    2846            6 :       num_time_freq_points = bs_env%num_time_freq_points
    2847            6 :       n_spin = bs_env%n_spin
    2848              : 
    2849            6 :       CALL get_qs_env(qs_env, para_env=para_env, blacs_env=blacs_env)
    2850              : 
    2851           72 :       ALLOCATE (bs_env%fm_G_S(nimages_scf))
    2852           72 :       ALLOCATE (bs_env%fm_Sigma_x_R(nimages_scf))
    2853          464 :       ALLOCATE (bs_env%fm_chi_R_t(nimages_scf, num_time_freq_points))
    2854          464 :       ALLOCATE (bs_env%fm_MWM_R_t(nimages_scf, num_time_freq_points))
    2855          476 :       ALLOCATE (bs_env%fm_Sigma_c_R_neg_tau(nimages_scf, num_time_freq_points, n_spin))
    2856          476 :       ALLOCATE (bs_env%fm_Sigma_c_R_pos_tau(nimages_scf, num_time_freq_points, n_spin))
    2857           60 :       DO img = 1, nimages_scf
    2858           54 :          CALL cp_fm_create(bs_env%fm_G_S(img), bs_env%fm_work_mo(1)%matrix_struct)
    2859           54 :          CALL cp_fm_create(bs_env%fm_Sigma_x_R(img), bs_env%fm_work_mo(1)%matrix_struct)
    2860          456 :          DO i_t = 1, num_time_freq_points
    2861          396 :             CALL cp_fm_create(bs_env%fm_chi_R_t(img, i_t), bs_env%fm_RI_RI%matrix_struct)
    2862          396 :             CALL cp_fm_create(bs_env%fm_MWM_R_t(img, i_t), bs_env%fm_RI_RI%matrix_struct)
    2863          396 :             CALL cp_fm_set_all(bs_env%fm_MWM_R_t(img, i_t), 0.0_dp)
    2864          846 :             DO i_spin = 1, n_spin
    2865              :                CALL cp_fm_create(bs_env%fm_Sigma_c_R_neg_tau(img, i_t, i_spin), &
    2866          396 :                                  bs_env%fm_work_mo(1)%matrix_struct)
    2867              :                CALL cp_fm_create(bs_env%fm_Sigma_c_R_pos_tau(img, i_t, i_spin), &
    2868          396 :                                  bs_env%fm_work_mo(1)%matrix_struct)
    2869          396 :                CALL cp_fm_set_all(bs_env%fm_Sigma_c_R_neg_tau(img, i_t, i_spin), 0.0_dp)
    2870          792 :                CALL cp_fm_set_all(bs_env%fm_Sigma_c_R_pos_tau(img, i_t, i_spin), 0.0_dp)
    2871              :             END DO
    2872              :          END DO
    2873              :       END DO
    2874              : 
    2875            6 :       CALL timestop(handle)
    2876              : 
    2877            6 :    END SUBROUTINE allocate_matrices_small_cell_full_kp
    2878              : 
    2879              : ! **************************************************************************************************
    2880              : !> \brief ...
    2881              : !> \param qs_env ...
    2882              : !> \param bs_env ...
    2883              : ! **************************************************************************************************
    2884            6 :    SUBROUTINE trafo_V_xc_R_to_kp(qs_env, bs_env)
    2885              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2886              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2887              : 
    2888              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'trafo_V_xc_R_to_kp'
    2889              : 
    2890              :       INTEGER                                            :: handle, ikp, img, ispin, n_ao
    2891            6 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index_scf
    2892              :       TYPE(cp_cfm_type)                                  :: cfm_mo_coeff, cfm_tmp, cfm_V_xc
    2893              :       TYPE(cp_fm_type)                                   :: fm_V_xc_re
    2894            6 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks
    2895              :       TYPE(kpoint_type), POINTER                         :: kpoints_scf
    2896              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2897            6 :          POINTER                                         :: sab_nl
    2898              : 
    2899            6 :       CALL timeset(routineN, handle)
    2900              : 
    2901            6 :       n_ao = bs_env%n_ao
    2902              : 
    2903            6 :       CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks, kpoints=kpoints_scf)
    2904              : 
    2905            6 :       NULLIFY (sab_nl)
    2906            6 :       CALL get_kpoint_info(kpoints_scf, sab_nl=sab_nl, cell_to_index=cell_to_index_scf)
    2907              : 
    2908            6 :       CALL cp_cfm_create(cfm_V_xc, bs_env%cfm_work_mo%matrix_struct)
    2909            6 :       CALL cp_cfm_create(cfm_mo_coeff, bs_env%cfm_work_mo%matrix_struct)
    2910            6 :       CALL cp_cfm_create(cfm_tmp, bs_env%cfm_work_mo%matrix_struct)
    2911            6 :       CALL cp_fm_create(fm_V_xc_re, bs_env%cfm_work_mo%matrix_struct)
    2912              : 
    2913          184 :       DO img = 1, bs_env%nimages_scf
    2914          362 :          DO ispin = 1, bs_env%n_spin
    2915              :             ! JW kind of hack because the format of matrix_ks remains dubious...
    2916          178 :             CALL dbcsr_set(matrix_ks(ispin, img)%matrix, 0.0_dp)
    2917          356 :             CALL copy_fm_to_dbcsr(bs_env%fm_V_xc_R(img, ispin), matrix_ks(ispin, img)%matrix)
    2918              :          END DO
    2919              :       END DO
    2920              : 
    2921           30 :       ALLOCATE (bs_env%v_xc_n(n_ao, bs_env%nkp_bs_and_DOS, bs_env%n_spin))
    2922              : 
    2923           12 :       DO ispin = 1, bs_env%n_spin
    2924          170 :          DO ikp = 1, bs_env%nkp_bs_and_DOS
    2925              : 
    2926              :             ! v^xc^R -> v^xc(k)  (matrix_ks stores v^xc^R, see SUBROUTINE compute_V_xc)
    2927              :             CALL rsmat_to_kp(matrix_ks, ispin, bs_env%kpoints_DOS%xkp(1:3, ikp), &
    2928          158 :                              cell_to_index_scf, sab_nl, bs_env, cfm_V_xc)
    2929              : 
    2930              :             ! get C_µn(k)
    2931          158 :             CALL cp_cfm_to_cfm(bs_env%cfm_mo_coeff_kp(ikp, ispin), cfm_mo_coeff)
    2932              : 
    2933              :             ! v^xc_nm(k_i) = sum_µν C^*_µn(k_i) v^xc_µν(k_i) C_νn(k_i)
    2934              :             CALL parallel_gemm('N', 'N', n_ao, n_ao, n_ao, z_one, cfm_V_xc, cfm_mo_coeff, &
    2935          158 :                                z_zero, cfm_tmp)
    2936              :             CALL parallel_gemm('C', 'N', n_ao, n_ao, n_ao, z_one, cfm_mo_coeff, cfm_tmp, &
    2937          158 :                                z_zero, cfm_V_xc)
    2938              : 
    2939              :             ! get v^xc_nn(k_i) which is a real quantity as v^xc is Hermitian
    2940          158 :             CALL cp_cfm_to_fm(cfm_V_xc, fm_V_xc_re)
    2941          164 :             CALL cp_fm_get_diag(fm_V_xc_re, bs_env%v_xc_n(:, ikp, ispin))
    2942              : 
    2943              :          END DO
    2944              : 
    2945              :       END DO
    2946              : 
    2947              :       ! just rebuild the overwritten KS matrix again
    2948            6 :       CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., just_energy=.FALSE.)
    2949              : 
    2950            6 :       CALL cp_cfm_release(cfm_V_xc)
    2951            6 :       CALL cp_cfm_release(cfm_mo_coeff)
    2952            6 :       CALL cp_cfm_release(cfm_tmp)
    2953            6 :       CALL cp_fm_release(fm_V_xc_re)
    2954              : 
    2955            6 :       CALL timestop(handle)
    2956              : 
    2957           12 :    END SUBROUTINE trafo_V_xc_R_to_kp
    2958              : 
    2959              : ! **************************************************************************************************
    2960              : !> \brief ...
    2961              : !> \param qs_env ...
    2962              : !> \param bs_env ...
    2963              : ! **************************************************************************************************
    2964            6 :    SUBROUTINE heuristic_RI_regularization(qs_env, bs_env)
    2965              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2966              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2967              : 
    2968              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'heuristic_RI_regularization'
    2969              : 
    2970            6 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)  :: M
    2971              :       INTEGER                                            :: handle, ikp, ikp_local, n_RI, nkp, &
    2972              :                                                             nkp_local, u
    2973              :       REAL(KIND=dp)                                      :: cond_nr, cond_nr_max, max_ev, &
    2974              :                                                             max_ev_ikp, min_ev, min_ev_ikp
    2975            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: M_R
    2976              : 
    2977            6 :       CALL timeset(routineN, handle)
    2978              : 
    2979              :       ! compute M^R_PQ = <phi_P,0|V^tr(rc)|phi_Q,R> for RI metric
    2980            6 :       CALL get_V_tr_R(M_R, bs_env%ri_metric, 0.0_dp, bs_env, qs_env)
    2981              : 
    2982            6 :       nkp = bs_env%nkp_chi_eps_W_orig_plus_extra
    2983            6 :       n_RI = bs_env%n_RI
    2984              : 
    2985            6 :       nkp_local = 0
    2986         3846 :       DO ikp = 1, nkp
    2987              :          ! trivial parallelization over k-points
    2988         3840 :          IF (MODULO(ikp, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    2989         3846 :          nkp_local = nkp_local + 1
    2990              :       END DO
    2991              : 
    2992           30 :       ALLOCATE (M(n_RI, n_RI, nkp_local))
    2993              : 
    2994            6 :       ikp_local = 0
    2995            6 :       cond_nr_max = 0.0_dp
    2996            6 :       min_ev = 1000.0_dp
    2997            6 :       max_ev = -1000.0_dp
    2998              : 
    2999         3846 :       DO ikp = 1, nkp
    3000              : 
    3001              :          ! trivial parallelization
    3002         3840 :          IF (MODULO(ikp, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    3003              : 
    3004         1920 :          ikp_local = ikp_local + 1
    3005              : 
    3006              :          ! M(k) = sum_R e^ikR M^R
    3007              :          CALL rs_to_kp(M_R, M(:, :, ikp_local), &
    3008              :                        bs_env%kpoints_scf_desymm%index_to_cell, &
    3009         1920 :                        bs_env%kpoints_chi_eps_W%xkp(1:3, ikp))
    3010              : 
    3011              :          ! compute condition number of M_PQ(k)
    3012         1920 :          CALL power(M(:, :, ikp_local), 1.0_dp, 0.0_dp, cond_nr, min_ev_ikp, max_ev_ikp)
    3013              : 
    3014         1920 :          IF (cond_nr > cond_nr_max) cond_nr_max = cond_nr
    3015         1920 :          IF (max_ev_ikp > max_ev) max_ev = max_ev_ikp
    3016         1926 :          IF (min_ev_ikp < min_ev) min_ev = min_ev_ikp
    3017              : 
    3018              :       END DO ! ikp
    3019              : 
    3020            6 :       CALL bs_env%para_env%max(cond_nr_max)
    3021              : 
    3022            6 :       u = bs_env%unit_nr
    3023            6 :       IF (u > 0) THEN
    3024            3 :          WRITE (u, FMT="(T2,A,ES34.1)") "Min. abs. eigenvalue of RI metric matrix M(k)", min_ev
    3025            3 :          WRITE (u, FMT="(T2,A,ES34.1)") "Max. abs. eigenvalue of RI metric matrix M(k)", max_ev
    3026            3 :          WRITE (u, FMT="(T2,A,ES50.1)") "Max. condition number of M(k)", cond_nr_max
    3027              :       END IF
    3028              : 
    3029            6 :       CALL timestop(handle)
    3030              : 
    3031           12 :    END SUBROUTINE heuristic_RI_regularization
    3032              : 
    3033              : ! **************************************************************************************************
    3034              : !> \brief ...
    3035              : !> \param V_tr_R ...
    3036              : !> \param pot_type ...
    3037              : !> \param regularization_RI ...
    3038              : !> \param bs_env ...
    3039              : !> \param qs_env ...
    3040              : ! **************************************************************************************************
    3041           68 :    SUBROUTINE get_V_tr_R(V_tr_R, pot_type, regularization_RI, bs_env, qs_env)
    3042              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: V_tr_R
    3043              :       TYPE(libint_potential_type)                        :: pot_type
    3044              :       REAL(KIND=dp)                                      :: regularization_RI
    3045              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3046              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3047              : 
    3048              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_V_tr_R'
    3049              : 
    3050              :       INTEGER                                            :: handle, img, nimages_scf_desymm
    3051              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: sizes_RI
    3052           68 :       INTEGER, DIMENSION(:), POINTER                     :: col_bsize, row_bsize
    3053              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    3054           68 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: fm_V_tr_R
    3055              :       TYPE(dbcsr_distribution_type)                      :: dbcsr_dist
    3056           68 :       TYPE(dbcsr_type), ALLOCATABLE, DIMENSION(:)        :: mat_V_tr_R
    3057              :       TYPE(distribution_2d_type), POINTER                :: dist_2d
    3058              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3059           68 :          POINTER                                         :: sab_RI
    3060           68 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    3061           68 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    3062              : 
    3063           68 :       CALL timeset(routineN, handle)
    3064              : 
    3065           68 :       NULLIFY (sab_RI, dist_2d)
    3066              : 
    3067              :       CALL get_qs_env(qs_env=qs_env, &
    3068              :                       blacs_env=blacs_env, &
    3069              :                       distribution_2d=dist_2d, &
    3070              :                       qs_kind_set=qs_kind_set, &
    3071           68 :                       particle_set=particle_set)
    3072              : 
    3073          204 :       ALLOCATE (sizes_RI(bs_env%n_atom))
    3074           68 :       CALL get_particle_set(particle_set, qs_kind_set, nsgf=sizes_RI, basis=bs_env%basis_set_RI)
    3075              :       CALL build_2c_neighbor_lists(sab_RI, bs_env%basis_set_RI, bs_env%basis_set_RI, &
    3076              :                                    pot_type, "2c_nl_RI", qs_env, sym_ij=.FALSE., &
    3077           68 :                                    dist_2d=dist_2d)
    3078           68 :       CALL cp_dbcsr_dist2d_to_dist(dist_2d, dbcsr_dist)
    3079          204 :       ALLOCATE (row_bsize(SIZE(sizes_RI)))
    3080          204 :       ALLOCATE (col_bsize(SIZE(sizes_RI)))
    3081          244 :       row_bsize(:) = sizes_RI
    3082          244 :       col_bsize(:) = sizes_RI
    3083              : 
    3084           68 :       nimages_scf_desymm = bs_env%nimages_scf_desymm
    3085          816 :       ALLOCATE (mat_V_tr_R(nimages_scf_desymm))
    3086              :       CALL dbcsr_create(mat_V_tr_R(1), "(RI|RI)", dbcsr_dist, dbcsr_type_no_symmetry, &
    3087           68 :                         row_bsize, col_bsize)
    3088           68 :       DEALLOCATE (row_bsize, col_bsize)
    3089              : 
    3090          612 :       DO img = 2, nimages_scf_desymm
    3091          612 :          CALL dbcsr_create(mat_V_tr_R(img), template=mat_V_tr_R(1))
    3092              :       END DO
    3093              : 
    3094              :       CALL build_2c_integrals(mat_V_tr_R, 0.0_dp, qs_env, sab_RI, bs_env%basis_set_RI, &
    3095              :                               bs_env%basis_set_RI, pot_type, do_kpoints=.TRUE., &
    3096              :                               ext_kpoints=bs_env%kpoints_scf_desymm, &
    3097           68 :                               regularization_RI=regularization_RI)
    3098              : 
    3099          816 :       ALLOCATE (fm_V_tr_R(nimages_scf_desymm))
    3100          680 :       DO img = 1, nimages_scf_desymm
    3101          612 :          CALL cp_fm_create(fm_V_tr_R(img), bs_env%fm_RI_RI%matrix_struct)
    3102          612 :          CALL copy_dbcsr_to_fm(mat_V_tr_R(img), fm_V_tr_R(img))
    3103          680 :          CALL dbcsr_release(mat_V_tr_R(img))
    3104              :       END DO
    3105              : 
    3106           68 :       IF (.NOT. ALLOCATED(V_tr_R)) THEN
    3107          340 :          ALLOCATE (V_tr_R(bs_env%n_RI, bs_env%n_RI, nimages_scf_desymm))
    3108              :       END IF
    3109              : 
    3110           68 :       CALL fm_to_local_array(fm_V_tr_R, V_tr_R)
    3111              : 
    3112           68 :       CALL cp_fm_release(fm_V_tr_R)
    3113           68 :       CALL dbcsr_distribution_release(dbcsr_dist)
    3114           68 :       CALL release_neighbor_list_sets(sab_RI)
    3115              : 
    3116           68 :       CALL timestop(handle)
    3117              : 
    3118          204 :    END SUBROUTINE get_V_tr_R
    3119              : 
    3120              : ! **************************************************************************************************
    3121              : !> \brief ...
    3122              : !> \param matrix ...
    3123              : !> \param exponent ...
    3124              : !> \param eps ...
    3125              : !> \param cond_nr ...
    3126              : !> \param min_ev ...
    3127              : !> \param max_ev ...
    3128              : ! **************************************************************************************************
    3129        34320 :    SUBROUTINE power(matrix, exponent, eps, cond_nr, min_ev, max_ev)
    3130              :       COMPLEX(KIND=dp), DIMENSION(:, :)                  :: matrix
    3131              :       REAL(KIND=dp)                                      :: exponent, eps
    3132              :       REAL(KIND=dp), OPTIONAL                            :: cond_nr, min_ev, max_ev
    3133              : 
    3134              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'power'
    3135              : 
    3136        34320 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: eigenvectors
    3137              :       INTEGER                                            :: handle, i, n
    3138              :       REAL(KIND=dp)                                      :: pos_eval
    3139        34320 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenvalues
    3140              : 
    3141        34320 :       CALL timeset(routineN, handle)
    3142              : 
    3143              :       ! make matrix perfectly Hermitian
    3144      2559696 :       matrix(:, :) = 0.5_dp*(matrix(:, :) + CONJG(TRANSPOSE(matrix(:, :))))
    3145              : 
    3146        34320 :       n = SIZE(matrix, 1)
    3147       205920 :       ALLOCATE (eigenvalues(n), eigenvectors(n, n))
    3148        34320 :       CALL diag_complex(matrix, eigenvectors, eigenvalues)
    3149              : 
    3150        59920 :       IF (PRESENT(cond_nr)) cond_nr = MAXVAL(ABS(eigenvalues))/MINVAL(ABS(eigenvalues))
    3151        47120 :       IF (PRESENT(min_ev)) min_ev = MINVAL(ABS(eigenvalues))
    3152        47120 :       IF (PRESENT(max_ev)) max_ev = MAXVAL(ABS(eigenvalues))
    3153              : 
    3154       225344 :       DO i = 1, n
    3155       191024 :          IF (eps < eigenvalues(i)) THEN
    3156       191024 :             pos_eval = (eigenvalues(i))**(0.5_dp*exponent)
    3157              :          ELSE
    3158              :             pos_eval = 0.0_dp
    3159              :          END IF
    3160      1297008 :          eigenvectors(:, i) = eigenvectors(:, i)*pos_eval
    3161              :       END DO
    3162              : 
    3163        34320 :       CALL ZGEMM("N", "C", n, n, n, z_one, eigenvectors, n, eigenvectors, n, z_zero, matrix, n)
    3164              : 
    3165        34320 :       DEALLOCATE (eigenvalues, eigenvectors)
    3166              : 
    3167        34320 :       CALL timestop(handle)
    3168              : 
    3169        34320 :    END SUBROUTINE power
    3170              : 
    3171              : ! **************************************************************************************************
    3172              : !> \brief ...
    3173              : !> \param bs_env ...
    3174              : !> \param Sigma_c_n_time ...
    3175              : !> \param Sigma_c_n_freq ...
    3176              : !> \param ispin ...
    3177              : ! **************************************************************************************************
    3178          196 :    SUBROUTINE time_to_freq(bs_env, Sigma_c_n_time, Sigma_c_n_freq, ispin)
    3179              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3180              :       REAL(KIND=dp), DIMENSION(:, :, :)                  :: Sigma_c_n_time, Sigma_c_n_freq
    3181              :       INTEGER                                            :: ispin
    3182              : 
    3183              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'time_to_freq'
    3184              : 
    3185              :       INTEGER                                            :: handle, i_t, j_w, n_occ
    3186              :       REAL(KIND=dp)                                      :: freq_j, time_i, w_cos_ij, w_sin_ij
    3187          196 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: Sigma_c_n_cos_time, Sigma_c_n_sin_time
    3188              : 
    3189          196 :       CALL timeset(routineN, handle)
    3190              : 
    3191          784 :       ALLOCATE (Sigma_c_n_cos_time(bs_env%n_ao, bs_env%num_time_freq_points))
    3192          588 :       ALLOCATE (Sigma_c_n_sin_time(bs_env%n_ao, bs_env%num_time_freq_points))
    3193              : 
    3194        19028 :       Sigma_c_n_cos_time(:, :) = 0.5_dp*(Sigma_c_n_time(:, :, 1) + Sigma_c_n_time(:, :, 2))
    3195        19028 :       Sigma_c_n_sin_time(:, :) = 0.5_dp*(Sigma_c_n_time(:, :, 1) - Sigma_c_n_time(:, :, 2))
    3196              : 
    3197        38252 :       Sigma_c_n_freq(:, :, :) = 0.0_dp
    3198              : 
    3199         1988 :       DO i_t = 1, bs_env%num_time_freq_points
    3200              : 
    3201        20580 :          DO j_w = 1, bs_env%num_time_freq_points
    3202              : 
    3203        18592 :             freq_j = bs_env%imag_freq_points(j_w)
    3204        18592 :             time_i = bs_env%imag_time_points(i_t)
    3205              :             ! integration weights for cosine and sine transform
    3206        18592 :             w_cos_ij = bs_env%weights_cos_t_to_w(j_w, i_t)*COS(freq_j*time_i)
    3207        18592 :             w_sin_ij = bs_env%weights_sin_t_to_w(j_w, i_t)*SIN(freq_j*time_i)
    3208              : 
    3209              :             ! 1. Re(Σ^c_nn(k_i,iω)) from cosine transform
    3210              :             Sigma_c_n_freq(:, j_w, 1) = Sigma_c_n_freq(:, j_w, 1) + &
    3211       167872 :                                         w_cos_ij*Sigma_c_n_cos_time(:, i_t)
    3212              : 
    3213              :             ! 2. Im(Σ^c_nn(k_i,iω)) from sine transform
    3214              :             Sigma_c_n_freq(:, j_w, 2) = Sigma_c_n_freq(:, j_w, 2) + &
    3215       169664 :                                         w_sin_ij*Sigma_c_n_sin_time(:, i_t)
    3216              : 
    3217              :          END DO
    3218              : 
    3219              :       END DO
    3220              : 
    3221              :       ! for occupied levels, we need the correlation self-energy for negative omega.
    3222              :       ! Therefore, weight_sin should be computed with -omega, which results in an
    3223              :       ! additional minus for the imaginary part:
    3224          196 :       n_occ = bs_env%n_occ(ispin)
    3225         8356 :       Sigma_c_n_freq(1:n_occ, :, 2) = -Sigma_c_n_freq(1:n_occ, :, 2)
    3226              : 
    3227          196 :       CALL timestop(handle)
    3228              : 
    3229          392 :    END SUBROUTINE time_to_freq
    3230              : 
    3231              : ! **************************************************************************************************
    3232              : !> \brief ...
    3233              : !> \param bs_env ...
    3234              : !> \param Sigma_c_ikp_n_freq ...
    3235              : !> \param Sigma_x_ikp_n ...
    3236              : !> \param V_xc_ikp_n ...
    3237              : !> \param eigenval_scf ...
    3238              : !> \param ikp ...
    3239              : !> \param ispin ...
    3240              : ! **************************************************************************************************
    3241          196 :    SUBROUTINE analyt_conti_and_print(bs_env, Sigma_c_ikp_n_freq, Sigma_x_ikp_n, V_xc_ikp_n, &
    3242          196 :                                      eigenval_scf, ikp, ispin)
    3243              : 
    3244              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3245              :       REAL(KIND=dp), DIMENSION(:, :, :)                  :: Sigma_c_ikp_n_freq
    3246              :       REAL(KIND=dp), DIMENSION(:)                        :: Sigma_x_ikp_n, V_xc_ikp_n, eigenval_scf
    3247              :       INTEGER                                            :: ikp, ispin
    3248              : 
    3249              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'analyt_conti_and_print'
    3250              : 
    3251              :       CHARACTER(len=3)                                   :: occ_vir
    3252              :       CHARACTER(len=default_string_length)               :: fname
    3253              :       INTEGER                                            :: handle, i_mo, ikp_for_print, iunit, &
    3254              :                                                             n_mo, nkp
    3255              :       LOGICAL                                            :: is_bandstruc_kpoint, print_DOS_kpoints, &
    3256              :                                                             print_ikp
    3257              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: dummy, Sigma_c_ikp_n_qp
    3258              : 
    3259          196 :       CALL timeset(routineN, handle)
    3260              : 
    3261          196 :       n_mo = bs_env%n_ao
    3262          784 :       ALLOCATE (dummy(n_mo), Sigma_c_ikp_n_qp(n_mo))
    3263         2308 :       Sigma_c_ikp_n_qp(:) = 0.0_dp
    3264              : 
    3265         2308 :       DO i_mo = 1, n_mo
    3266              : 
    3267              :          ! parallelization
    3268         2112 :          IF (MODULO(i_mo, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    3269              : 
    3270              :          CALL continuation_pade(Sigma_c_ikp_n_qp, &
    3271              :                                 bs_env%imag_freq_points_fit, dummy, dummy, &
    3272              :                                 Sigma_c_ikp_n_freq(:, 1:bs_env%num_freq_points_fit, 1)*z_one + &
    3273              :                                 Sigma_c_ikp_n_freq(:, 1:bs_env%num_freq_points_fit, 2)*gaussi, &
    3274              :                                 Sigma_x_ikp_n(:) - V_xc_ikp_n(:), &
    3275              :                                 eigenval_scf(:), eigenval_scf(:), &
    3276              :                                 bs_env%do_hedin_shift, &
    3277              :                                 i_mo, bs_env%n_occ(ispin), bs_env%n_vir(ispin), &
    3278              :                                 bs_env%nparam_pade, bs_env%num_freq_points_fit, &
    3279              :                                 ri_rpa_g0w0_crossing_newton, bs_env%n_occ(ispin), &
    3280        68230 :                                 0.0_dp, .TRUE., .FALSE., 1, e_fermi_ext=bs_env%e_fermi(ispin))
    3281              :       END DO
    3282              : 
    3283          196 :       CALL bs_env%para_env%sum(Sigma_c_ikp_n_qp)
    3284              : 
    3285          196 :       CALL correct_obvious_fitting_fails(Sigma_c_ikp_n_qp, ispin, bs_env)
    3286              : 
    3287              :       bs_env%eigenval_G0W0(:, ikp, ispin) = eigenval_scf(:) + &
    3288              :                                             Sigma_c_ikp_n_qp(:) + &
    3289              :                                             Sigma_x_ikp_n(:) - &
    3290         2308 :                                             V_xc_ikp_n(:)
    3291              : 
    3292         2308 :       bs_env%eigenval_HF(:, ikp, ispin) = eigenval_scf(:) + Sigma_x_ikp_n(:) - V_xc_ikp_n(:)
    3293              : 
    3294              :       ! only print eigenvalues of DOS k-points in case no bandstructure path has been given
    3295          196 :       print_DOS_kpoints = (bs_env%nkp_only_bs <= 0)
    3296              :       ! in kpoints_DOS, the last nkp_only_bs are bandstructure k-points
    3297          196 :       is_bandstruc_kpoint = (ikp > bs_env%nkp_only_DOS)
    3298          196 :       print_ikp = print_DOS_kpoints .OR. is_bandstruc_kpoint
    3299              : 
    3300          196 :       IF (bs_env%para_env%is_source() .AND. print_ikp) THEN
    3301              : 
    3302           82 :          IF (print_DOS_kpoints) THEN
    3303           51 :             nkp = bs_env%nkp_only_DOS
    3304           51 :             ikp_for_print = ikp
    3305              :          ELSE
    3306           31 :             nkp = bs_env%nkp_only_bs
    3307           31 :             ikp_for_print = ikp - bs_env%nkp_only_DOS
    3308              :          END IF
    3309              : 
    3310           82 :          fname = "bandstructure_SCF_and_G0W0"
    3311              : 
    3312           82 :          IF (ikp_for_print == 1) THEN
    3313              :             CALL open_file(TRIM(fname), unit_number=iunit, file_status="REPLACE", &
    3314           16 :                            file_action="WRITE")
    3315              :          ELSE
    3316              :             CALL open_file(TRIM(fname), unit_number=iunit, file_status="OLD", &
    3317           66 :                            file_action="WRITE", file_position="APPEND")
    3318              :          END IF
    3319              : 
    3320           82 :          WRITE (iunit, "(A)") " "
    3321           82 :          WRITE (iunit, "(A10,I7,A25,3F10.4)") "kpoint: ", ikp_for_print, "coordinate: ", &
    3322          164 :             bs_env%kpoints_DOS%xkp(:, ikp)
    3323           82 :          WRITE (iunit, "(A)") " "
    3324           82 :          WRITE (iunit, "(A5,A12,3A17,A16,A18)") "n", "k", "ϵ_nk^DFT (eV)", "Σ^c_nk (eV)", &
    3325          164 :             "Σ^x_nk (eV)", "v_nk^xc (eV)", "ϵ_nk^G0W0 (eV)"
    3326           82 :          WRITE (iunit, "(A)") " "
    3327              : 
    3328          994 :          DO i_mo = 1, n_mo
    3329          912 :             IF (i_mo <= bs_env%n_occ(ispin)) occ_vir = 'occ'
    3330          912 :             IF (i_mo > bs_env%n_occ(ispin)) occ_vir = 'vir'
    3331          912 :             WRITE (iunit, "(I5,3A,I5,4F16.3,F17.3)") i_mo, ' (', occ_vir, ') ', ikp_for_print, &
    3332          912 :                eigenval_scf(i_mo)*evolt, &
    3333          912 :                Sigma_c_ikp_n_qp(i_mo)*evolt, &
    3334          912 :                Sigma_x_ikp_n(i_mo)*evolt, &
    3335          912 :                V_xc_ikp_n(i_mo)*evolt, &
    3336         1906 :                bs_env%eigenval_G0W0(i_mo, ikp, ispin)*evolt
    3337              :          END DO
    3338              : 
    3339           82 :          WRITE (iunit, "(A)") " "
    3340              : 
    3341           82 :          CALL close_file(iunit)
    3342              : 
    3343              :       END IF
    3344              : 
    3345          196 :       CALL timestop(handle)
    3346              : 
    3347          392 :    END SUBROUTINE analyt_conti_and_print
    3348              : 
    3349              : ! **************************************************************************************************
    3350              : !> \brief ...
    3351              : !> \param Sigma_c_ikp_n_qp ...
    3352              : !> \param ispin ...
    3353              : !> \param bs_env ...
    3354              : ! **************************************************************************************************
    3355          196 :    SUBROUTINE correct_obvious_fitting_fails(Sigma_c_ikp_n_qp, ispin, bs_env)
    3356              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: Sigma_c_ikp_n_qp
    3357              :       INTEGER                                            :: ispin
    3358              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3359              : 
    3360              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'correct_obvious_fitting_fails'
    3361              : 
    3362              :       INTEGER                                            :: handle, homo, i_mo, j_mo, &
    3363              :                                                             n_levels_scissor, n_mo
    3364              :       LOGICAL                                            :: is_occ, is_vir
    3365              :       REAL(KIND=dp)                                      :: sum_Sigma_c
    3366              : 
    3367          196 :       CALL timeset(routineN, handle)
    3368              : 
    3369          196 :       n_mo = bs_env%n_ao
    3370          196 :       homo = bs_env%n_occ(ispin)
    3371              : 
    3372         2308 :       DO i_mo = 1, n_mo
    3373              : 
    3374              :          ! if |𝚺^c| > 13 eV, we use a scissors shift
    3375         2308 :          IF (ABS(Sigma_c_ikp_n_qp(i_mo)) > 13.0_dp/evolt) THEN
    3376              : 
    3377            0 :             is_occ = (i_mo <= homo)
    3378            0 :             is_vir = (i_mo > homo)
    3379              : 
    3380            0 :             n_levels_scissor = 0
    3381            0 :             sum_Sigma_c = 0.0_dp
    3382              : 
    3383              :             ! compute scissor
    3384            0 :             DO j_mo = 1, n_mo
    3385              : 
    3386              :                ! only compute scissor from other GW levels close in energy
    3387            0 :                IF (is_occ .AND. j_mo > homo) CYCLE
    3388            0 :                IF (is_vir .AND. j_mo <= homo) CYCLE
    3389            0 :                IF (ABS(i_mo - j_mo) > 10) CYCLE
    3390            0 :                IF (i_mo == j_mo) CYCLE
    3391              : 
    3392            0 :                n_levels_scissor = n_levels_scissor + 1
    3393            0 :                sum_Sigma_c = sum_Sigma_c + Sigma_c_ikp_n_qp(j_mo)
    3394              : 
    3395              :             END DO
    3396              : 
    3397              :             ! overwrite the self-energy with scissor shift
    3398            0 :             Sigma_c_ikp_n_qp(i_mo) = sum_Sigma_c/REAL(n_levels_scissor, KIND=dp)
    3399              : 
    3400              :          END IF
    3401              : 
    3402              :       END DO ! i_mo
    3403              : 
    3404          196 :       CALL timestop(handle)
    3405              : 
    3406          196 :    END SUBROUTINE correct_obvious_fitting_fails
    3407              : 
    3408              : END MODULE gw_utils
        

Generated by: LCOV version 2.0-1