LCOV - code coverage report
Current view: top level - src - gw_utils.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:8ebf9ad) Lines: 92.9 % 1285 1194
Test Date: 2026-01-22 06:43:13 Functions: 95.7 % 46 44

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

Generated by: LCOV version 2.0-1