LCOV - code coverage report
Current view: top level - src - gw_utils.F (source / functions) Hit Total Coverage
Test: CP2K Regtests (git:3130539) Lines: 1191 1290 92.3 %
Date: 2025-05-14 06:57:18 Functions: 44 47 93.6 %

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

Generated by: LCOV version 1.15