LCOV - code coverage report
Current view: top level - src - gw_utils.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 96.3 % 1695 1632
Test Date: 2026-11-24 01:22:08 Functions: 96.8 % 62 60

            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              : !> \par History
      11              : !>      01.2026 Maximilian Graml: add more bounds to exploit sparsity in 3c integrals, fixes
      12              : !> \author Jan Wilhelm
      13              : !> \date 07.2023
      14              : ! **************************************************************************************************
      15              : MODULE gw_utils
      16              :    USE admm_types,                      ONLY: admm_type
      17              :    USE atomic_kind_types,               ONLY: atomic_kind_type,&
      18              :                                               get_atomic_kind_set
      19              :    USE auto_basis,                      ONLY: create_ri_aux_basis_set
      20              :    USE basis_set_container_types,       ONLY: add_basis_set_to_container
      21              :    USE basis_set_types,                 ONLY: get_gto_basis_set,&
      22              :                                               gto_basis_set_type,&
      23              :                                               init_orb_basis_set
      24              :    USE bibliography,                    ONLY: Fei2021,&
      25              :                                               Graml2024,&
      26              :                                               cite_reference
      27              :    USE cell_types,                      ONLY: cell_type,&
      28              :                                               pbc,&
      29              :                                               scaled_to_real
      30              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      31              :                                               cp_blacs_env_release,&
      32              :                                               cp_blacs_env_type
      33              :    USE cp_cfm_types,                    ONLY: cp_cfm_copy_general,&
      34              :                                               cp_cfm_create,&
      35              :                                               cp_cfm_release,&
      36              :                                               cp_cfm_to_cfm,&
      37              :                                               cp_cfm_to_fm,&
      38              :                                               cp_cfm_type
      39              :    USE cp_control_types,                ONLY: dft_control_type
      40              :    USE cp_dbcsr_api,                    ONLY: dbcsr_create,&
      41              :                                               dbcsr_p_type,&
      42              :                                               dbcsr_set,&
      43              :                                               dbcsr_type_symmetric
      44              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      45              :                                               copy_fm_to_dbcsr,&
      46              :                                               dbcsr_allocate_matrix_set,&
      47              :                                               dbcsr_deallocate_matrix_set
      48              :    USE cp_files,                        ONLY: close_file,&
      49              :                                               open_file
      50              :    USE cp_fm_basic_linalg,              ONLY: cp_fm_scale_and_add
      51              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      52              :                                               cp_fm_struct_release,&
      53              :                                               cp_fm_struct_type
      54              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      55              :                                               cp_fm_get_diag,&
      56              :                                               cp_fm_release,&
      57              :                                               cp_fm_set_all,&
      58              :                                               cp_fm_to_fm,&
      59              :                                               cp_fm_type
      60              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      61              :                                               cp_logger_type
      62              :    USE cp_output_handling,              ONLY: cp_print_key_generate_filename
      63              :    USE dbt_api,                         ONLY: &
      64              :         dbt_clear, dbt_create, dbt_destroy, dbt_filter, dbt_iterator_blocks_left, &
      65              :         dbt_iterator_next_block, dbt_iterator_start, dbt_iterator_stop, dbt_iterator_type, &
      66              :         dbt_mp_environ_pgrid, dbt_pgrid_create, dbt_pgrid_destroy, dbt_pgrid_type, dbt_type
      67              :    USE gw_auto_ri_generate_RI_basis,    ONLY: generate_auto_ri_basis
      68              :    USE gw_auto_ri_types,                ONLY: auto_ri_type
      69              :    USE gw_compute_V_and_W,              ONLY: get_V_tr_R
      70              :    USE gw_nevanlinna,                   ONLY: nevanlinna_create_windows,&
      71              :                                               nevanlinna_prepare_window_grid,&
      72              :                                               nevanlinna_type,&
      73              :                                               nevanlinna_window_grid_type
      74              :    USE gw_ri_rs_small_cell_full_kp_q0_corr,ONLY: prepare_ri_rs_gamma_correction
      75              :    USE gw_utils_compute_integrals,      ONLY: build_3c_integral_block
      76              :    USE gw_utils_fm,                     ONLY: cfm_contract_ABA,&
      77              :                                               fm_invert,&
      78              :                                               local_complex_power
      79              :    USE hfx_types,                       ONLY: hfx_type
      80              :    USE input_constants,                 ONLY: &
      81              :         G0W0, cohsex_qp_update, do_potential_coulomb, do_potential_short, do_potential_truncated, &
      82              :         evGW0, gw_ac_nevanlinna, ri_rpa_g0w0_crossing_newton, ri_rs_large_cell_Gamma, &
      83              :         ri_rs_non_periodic, ri_rs_small_cell_full_kp, rtp_bse_kernel_ri_ao, rtp_bse_kernel_ri_rs, &
      84              :         rtp_method_bse, rtp_method_bse_linearized, tensor_large_cell_Gamma, &
      85              :         tensor_small_cell_full_kp, tensor_static_cohsex, xc_none
      86              :    USE input_section_types,             ONLY: section_vals_get,&
      87              :                                               section_vals_get_subs_vals,&
      88              :                                               section_vals_type,&
      89              :                                               section_vals_val_get,&
      90              :                                               section_vals_val_set
      91              :    USE kinds,                           ONLY: default_path_length,&
      92              :                                               default_string_length,&
      93              :                                               dp,&
      94              :                                               int_8
      95              :    USE kpoint_k_r_trafo_simple,         ONLY: rs_to_kp
      96              :    USE kpoint_types,                    ONLY: kpoint_create,&
      97              :                                               kpoint_release,&
      98              :                                               kpoint_type
      99              :    USE machine,                         ONLY: m_flush,&
     100              :                                               m_walltime
     101              :    USE mathlib,                         ONLY: erfc_cutoff,&
     102              :                                               gcd
     103              :    USE message_passing,                 ONLY: mp_cart_type,&
     104              :                                               mp_mem_avail_per_rank_GB,&
     105              :                                               mp_mem_used_per_rank_GB,&
     106              :                                               mp_para_env_type
     107              :    USE mp2_gpw,                         ONLY: create_mat_munu
     108              :    USE mp2_ri_2c,                       ONLY: RI_2c_integral_mat,&
     109              :                                               trunc_coulomb_for_exchange
     110              :    USE particle_methods,                ONLY: get_particle_set
     111              :    USE particle_types,                  ONLY: particle_type
     112              :    USE physcon,                         ONLY: angstrom,&
     113              :                                               evolt
     114              :    USE post_scf_bandstructure_types,    ONLY: post_scf_bandstructure_type
     115              :    USE post_scf_bandstructure_utils,    ONLY: create_operator_kpoints,&
     116              :                                               gw_flavour_label
     117              :    USE qs_energy_types,                 ONLY: qs_energy_type
     118              :    USE qs_environment_types,            ONLY: get_qs_env,&
     119              :                                               qs_env_part_release,&
     120              :                                               qs_environment_type
     121              :    USE qs_integral_utils,               ONLY: basis_set_list_setup
     122              :    USE qs_interactions,                 ONLY: init_interaction_radii_orb_basis
     123              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
     124              :                                               qs_kind_type
     125              :    USE qs_kpoint_operators,             ONLY: kpoint_operator_context_create,&
     126              :                                               kpoint_operator_context_release,&
     127              :                                               kpoint_operator_context_type,&
     128              :                                               kpoint_operator_get,&
     129              :                                               kpoint_operator_prepare,&
     130              :                                               kpoint_slot_ks
     131              :    USE qs_ks_methods,                   ONLY: qs_ks_build_kohn_sham_matrix
     132              :    USE qs_rho_methods,                  ONLY: qs_rho_update_rho
     133              :    USE qs_rho_types,                    ONLY: qs_rho_type
     134              :    USE qs_tensors,                      ONLY: build_3c_integrals,&
     135              :                                               build_3c_neighbor_lists,&
     136              :                                               get_tensor_occupancy,&
     137              :                                               neighbor_list_3c_destroy
     138              :    USE qs_tensors_types,                ONLY: create_2c_tensor,&
     139              :                                               create_3c_tensor,&
     140              :                                               distribution_3d_create,&
     141              :                                               distribution_3d_type,&
     142              :                                               neighbor_list_3c_type
     143              :    USE ri_rs_types,                     ONLY: ri_rs_env,&
     144              :                                               ri_rs_grid_opt_type
     145              :    USE rpa_gw,                          ONLY: continuation_pade
     146              :    USE rpa_gw_im_time_util,             ONLY: build_ao_propagator
     147              :    USE time_frequency_grids,            ONLY: build_minimax_time_frequency_grid
     148              :    USE util,                            ONLY: sort
     149              : #include "base/base_uses.f90"
     150              : 
     151              :    IMPLICIT NONE
     152              : 
     153              :    PRIVATE
     154              : 
     155              :    PUBLIC :: create_and_init_bs_env_for_gw, &
     156              :              de_init_bs_env, &
     157              :              compute_xkp, &
     158              :              analyt_conti_and_print, &
     159              :              add_R, &
     160              :              is_cell_in_index_to_cell, &
     161              :              rtbse_resolve_rirs_flag, &
     162              :              G_occ_vir, &
     163              :              gw_qp_summary_type
     164              : 
     165              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'gw_utils'
     166              : 
     167              : !> \brief Nevanlinna diagnostics for one GW cycle. n_kpoints is the number of target k-points per spin.
     168              :    TYPE gw_qp_summary_type
     169              :       PRIVATE
     170              :       INTEGER, PUBLIC                                    :: n_kpoints = 1
     171              :       INTEGER(KIND=int_8)                               :: n_reliable = 0_int_8, n_unstable = 0_int_8, &
     172              :                                                            n_multi = 0_int_8, n_pade = 0_int_8
     173              :       REAL(KIND=dp)                                      :: start_time = 0.0_dp
     174              :    END TYPE gw_qp_summary_type
     175              : 
     176              : CONTAINS
     177              : 
     178              : ! **************************************************************************************************
     179              : !> \brief Initializes the GW environment from the input and electronic-structure data.
     180              : !> \param qs_env ...
     181              : !> \param bs_env Band-structure environment containing GW parameters.
     182              : !> \param bs_sec BAND_STRUCTURE input section
     183              : ! **************************************************************************************************
     184          156 :    SUBROUTINE create_and_init_bs_env_for_gw(qs_env, bs_env, bs_sec)
     185              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     186              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     187              :       TYPE(section_vals_type), POINTER                   :: bs_sec
     188              : 
     189              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'create_and_init_bs_env_for_gw'
     190              : 
     191              :       INTEGER                                            :: handle
     192              : 
     193          156 :       CALL timeset(routineN, handle)
     194              : 
     195          156 :       CALL cite_reference(Graml2024)
     196              : 
     197          156 :       CALL get_parameters_from_qs_env(qs_env, bs_env)
     198              : 
     199          156 :       CALL read_gw_input_parameters(bs_env, bs_sec)
     200              : 
     201          156 :       CALL print_header_and_input_parameters(bs_env)
     202              : 
     203          156 :       CALL setup_AO_and_RI_basis_set(qs_env, bs_env)
     204              : 
     205          156 :       CALL set_heuristic_parameters(bs_env, qs_env)
     206              : 
     207          156 :       IF (bs_env%auto_ri%enabled) CALL generate_auto_ri_basis(qs_env, bs_env)
     208              : 
     209          156 :       CALL get_RI_basis(qs_env, bs_env)
     210              : 
     211          156 :       CALL compute_V_xc(qs_env, bs_env)
     212              : 
     213          156 :       CALL init_interaction_radii(bs_env)
     214              : 
     215              :       ! The RI-RS drivers build their (µν|P) blocks on the fly through gw_3c_ctx
     216              :       ! RT-BSE with the AO-RI kernel need nl_3c it after GW, so
     217              :       ! keep everything when an RT-BSE run follows.
     218              :       IF (.NOT. bs_env%do_gw_ri_rs .OR. &
     219          156 :           bs_env%rtp_method == rtp_method_bse .OR. &
     220              :           bs_env%rtp_method == rtp_method_bse_linearized) THEN
     221          114 :          CALL create_tensors(qs_env, bs_env)
     222              :       END IF
     223              : 
     224          156 :       CALL allocate_GW_eigenvalues(bs_env)
     225              : 
     226          240 :       SELECT CASE (bs_env%gw_implementation)
     227              :       CASE (tensor_large_cell_Gamma, tensor_static_cohsex)
     228              : 
     229           84 :          CALL check_sparsity_3c(qs_env, bs_env)
     230              : 
     231           84 :          CALL set_sparsity_parallelization_parameters(bs_env)
     232              : 
     233           84 :          CALL check_for_restart_files(qs_env, bs_env)
     234              : 
     235              :       CASE (ri_rs_large_cell_Gamma, ri_rs_non_periodic)
     236              : 
     237           42 :          CALL check_for_restart_files(qs_env, bs_env)
     238              : 
     239              :       CASE (tensor_small_cell_full_kp)
     240              : 
     241           16 :          CALL compute_3c_integrals(qs_env, bs_env)
     242              : 
     243           16 :          CALL setup_cells_Delta_R(bs_env)
     244              : 
     245           16 :          CALL setup_parallelization_Delta_R(bs_env)
     246              : 
     247           16 :          CALL allocate_matrices_small_cell_full_kp_tensor(qs_env, bs_env)
     248              : 
     249           16 :          CALL trafo_V_xc_R_to_kp(qs_env, bs_env)
     250              : 
     251           16 :          CALL heuristic_RI_regularization(qs_env, bs_env)
     252              : 
     253              :       CASE (ri_rs_small_cell_full_kp)
     254              : 
     255           14 :          CALL trafo_V_xc_R_to_kp(qs_env, bs_env)
     256              : 
     257          170 :          CALL prepare_ri_rs_gamma_correction(qs_env, bs_env)
     258              : 
     259              :       END SELECT
     260              : 
     261          156 :       CALL setup_time_and_frequency_minimax_grid(bs_env)
     262              : 
     263              :       ! Free memory in qs_env. SCF real-space grids, task  lists, neighbor
     264              :       ! lists and work arrays on large systems hold GBs per rank for the whole run.
     265              :       ! Not required by GW. LDOS and RT-BSE still needs these information.
     266              :       !
     267              :       ! Recommendation in case of memory issues: first perform GW calculation without calculating
     268              :       !                                          LDOS (to save memory). Then, use GW restart files
     269              :       !                                          in a subsequent calculation to calculate the LDOS
     270              :       IF (.NOT. bs_env%do_ldos .AND. &
     271          156 :           bs_env%rtp_method /= rtp_method_bse .AND. &
     272              :           bs_env%rtp_method /= rtp_method_bse_linearized) THEN
     273           82 :          CALL qs_env_part_release(qs_env)
     274              :       END IF
     275              : 
     276          156 :       CALL timestop(handle)
     277              : 
     278          156 :    END SUBROUTINE create_and_init_bs_env_for_gw
     279              : 
     280              : ! **************************************************************************************************
     281              : !> \brief Store the QS environment parameters needed by GW.
     282              : !> \param qs_env ...
     283              : !> \param bs_env ...
     284              : ! **************************************************************************************************
     285          156 :    SUBROUTINE get_parameters_from_qs_env(qs_env, bs_env)
     286              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     287              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     288              : 
     289              :       TYPE(section_vals_type), POINTER                   :: input, rtbse_sec
     290              : 
     291          156 :       NULLIFY (input, rtbse_sec)
     292              :       CALL get_qs_env(qs_env, atomic_kind_set=bs_env%ri_rs%atomic_kind_set, &
     293          156 :                       cell=bs_env%ri_rs%cell, particle_set=bs_env%ri_rs%particle_set, input=input)
     294          156 :       rtbse_sec => section_vals_get_subs_vals(input, "DFT%REAL_TIME_PROPAGATION%RTBSE")
     295          156 :       CALL section_vals_val_get(rtbse_sec, "CUTOFF_RADIUS_W0", r_val=bs_env%ri_rs%cutoff_radius_w0)
     296              : 
     297          156 :    END SUBROUTINE get_parameters_from_qs_env
     298              : 
     299              : ! **************************************************************************************************
     300              : !> \brief Reads the GW input parameters.
     301              : !> \param bs_env ...
     302              : !> \param bs_sec BAND_STRUCTURE input section
     303              : ! **************************************************************************************************
     304          312 :    SUBROUTINE read_gw_input_parameters(bs_env, bs_sec)
     305              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     306              :       TYPE(section_vals_type), POINTER                   :: bs_sec
     307              : 
     308              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'read_gw_input_parameters'
     309              : 
     310              :       INTEGER                                            :: handle
     311              :       LOGICAL                                            :: do_evgw0
     312              :       TYPE(section_vals_type), POINTER                   :: auto_ri_sec, cohsex_sec, evgw0_sec, &
     313              :                                                             grid_opt_sec, gw_sec, ri_rs_sec
     314              : 
     315          156 :       CALL timeset(routineN, handle)
     316              : 
     317          156 :       NULLIFY (auto_ri_sec, cohsex_sec, evgw0_sec, grid_opt_sec, gw_sec, ri_rs_sec)
     318          156 :       gw_sec => section_vals_get_subs_vals(bs_sec, "GW")
     319          156 :       auto_ri_sec => section_vals_get_subs_vals(gw_sec, "AUTO_RI")
     320          156 :       cohsex_sec => section_vals_get_subs_vals(gw_sec, "COHSEX")
     321          156 :       evgw0_sec => section_vals_get_subs_vals(gw_sec, "EVGW0")
     322          156 :       ri_rs_sec => section_vals_get_subs_vals(gw_sec, "RI_RS")
     323          156 :       grid_opt_sec => section_vals_get_subs_vals(ri_rs_sec, "GRID_OPTIMIZATION")
     324              : 
     325          156 :       CALL section_vals_val_get(gw_sec, "NUM_TIME_FREQ_POINTS", i_val=bs_env%num_time_freq_points)
     326          156 :       CALL section_vals_val_get(gw_sec, "EPS_FILTER", r_val=bs_env%eps_filter)
     327          156 :       CALL section_vals_val_get(gw_sec, "REGULARIZATION_RI", r_val=bs_env%input_regularization_RI)
     328          156 :       CALL section_vals_val_get(gw_sec, "REGULARIZATION_MINIMAX", r_val=bs_env%input_regularization_minimax)
     329          156 :       CALL section_vals_val_get(gw_sec, "CUTOFF_RADIUS_RI", r_val=bs_env%ri_metric%cutoff_radius)
     330          156 :       CALL section_vals_val_get(gw_sec, "RI_CUTOFF_ATTENUATION", r_val=bs_env%ri_metric%omega)
     331          156 :       CALL section_vals_val_get(gw_sec, "MEMORY_PER_PROC", r_val=bs_env%input_memory_per_proc_GB)
     332          156 :       CALL section_vals_val_get(gw_sec, "APPROX_KP_EXTRAPOL", l_val=bs_env%approx_kp_extrapol)
     333          156 :       CALL section_vals_val_get(gw_sec, "SIZE_LATTICE_SUM", i_val=bs_env%size_lattice_sum_V)
     334          156 :       CALL section_vals_val_get(gw_sec, "KPOINTS_W", i_vals=bs_env%nkp_grid_chi_eps_W_input)
     335          156 :       CALL section_vals_val_get(gw_sec, "HEDIN_SHIFT", l_val=bs_env%do_hedin_shift)
     336          156 :       CALL section_vals_val_get(gw_sec, "FREQ_MAX_FIT", r_val=bs_env%freq_max_fit)
     337          156 :       CALL section_vals_val_get(gw_sec, "ANALYTIC_CONTINUATION", i_val=bs_env%ac_method)
     338          156 :       CALL section_vals_val_get(cohsex_sec, "SCALE_OCC", r_val=bs_env%cohsex_scale_occ)
     339          156 :       CALL section_vals_val_get(cohsex_sec, "SCALE_VIRT", r_val=bs_env%cohsex_scale_virt)
     340          156 :       CALL read_rirs_input(bs_env%ri_rs, ri_rs_sec)
     341          156 :       IF (bs_env%ri_rs%tikhonov < 0.0_dp) THEN
     342          136 :          IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     343            0 :             bs_env%ri_rs%tikhonov = 1.0E-4_dp
     344              :          ELSE
     345          136 :             bs_env%ri_rs%tikhonov = 1.0E-8_dp
     346              :          END IF
     347              :       END IF
     348          156 :       CALL read_rirs_grid_opt(bs_env%ri_rs, grid_opt_sec)
     349          156 :       CALL read_evgw0_input(bs_env, evgw0_sec, do_evgw0)
     350          156 :       CALL read_auto_ri_input(bs_env%auto_ri, auto_ri_sec)
     351          156 :       CALL check_gw_input(bs_env, do_evgw0)
     352              : 
     353          156 :       CALL timestop(handle)
     354              : 
     355          156 :    END SUBROUTINE read_gw_input_parameters
     356              : 
     357              : ! **************************************************************************************************
     358              : !> \brief Reads the RI-RS input.
     359              : !> \param ri_rs RI-RS calculation parameters
     360              : !> \param ri_rs_sec RI_RS input section
     361              : ! **************************************************************************************************
     362          156 :    SUBROUTINE read_rirs_input(ri_rs, ri_rs_sec)
     363              :       TYPE(ri_rs_env), INTENT(INOUT)                     :: ri_rs
     364              :       TYPE(section_vals_type), POINTER                   :: ri_rs_sec
     365              : 
     366              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'read_rirs_input'
     367              : 
     368              :       INTEGER                                            :: handle
     369              : 
     370          156 :       CALL timeset(routineN, handle)
     371              : 
     372          156 :       CALL section_vals_val_get(ri_rs_sec, "TIKHONOV", r_val=ri_rs%tikhonov)
     373          156 :       CALL section_vals_val_get(ri_rs_sec, "GRID_SELECT", i_val=ri_rs%grid_select)
     374          156 :       CALL section_vals_val_get(ri_rs_sec, "CUTOFF_RADIUS_RL_AO", r_val=ri_rs%cutoff_radius_ri_ao)
     375          156 :       CALL section_vals_val_get(ri_rs_sec, "CUTOFF_RADIUS_RL_W", r_val=ri_rs%cutoff_radius_v_w)
     376              : 
     377          156 :       CALL timestop(handle)
     378              : 
     379          156 :    END SUBROUTINE read_rirs_input
     380              : 
     381              : ! **************************************************************************************************
     382              : !> \brief Read the RI-RS grid optimization input.
     383              : !> \param ri_rs RI-RS parameters receiving the optimized-grid settings
     384              : !> \param grid_opt_sec GRID_OPTIMIZATION input section
     385              : ! **************************************************************************************************
     386          156 :    SUBROUTINE read_rirs_grid_opt(ri_rs, grid_opt_sec)
     387              :       TYPE(ri_rs_env), INTENT(INOUT), TARGET             :: ri_rs
     388              :       TYPE(section_vals_type), POINTER                   :: grid_opt_sec
     389              : 
     390              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'read_rirs_grid_opt'
     391              : 
     392              :       INTEGER                                            :: handle
     393              :       TYPE(ri_rs_grid_opt_type), POINTER                 :: grid_opt
     394              : 
     395          156 :       CALL timeset(routineN, handle)
     396              : 
     397          156 :       CALL section_vals_get(grid_opt_sec, explicit=ri_rs%grid_opt%enabled)
     398          156 :       IF (.NOT. ri_rs%grid_opt%enabled) THEN
     399          132 :          CALL timestop(handle)
     400          132 :          RETURN
     401              :       END IF
     402              : 
     403              :       NULLIFY (grid_opt)
     404           24 :       grid_opt => ri_rs%grid_opt
     405              : 
     406           24 :       CALL section_vals_val_get(grid_opt_sec, "CUTOFF_ATOMIC_CLUSTER", r_val=grid_opt%cutoff_atomic_cluster)
     407           24 :       CALL section_vals_val_get(grid_opt_sec, "MAX_ITER", i_val=grid_opt%max_iter)
     408           24 :       CALL section_vals_val_get(grid_opt_sec, "RS_AO_RATIO", r_val=grid_opt%rs_ao_ratio)
     409              : 
     410           24 :       CALL timestop(handle)
     411              : 
     412              :    END SUBROUTINE read_rirs_grid_opt
     413              : 
     414              : ! **************************************************************************************************
     415              : !> \brief Reads the eigenvalue-self-consistent GW input.
     416              : !> \param bs_env GW environment receiving the evGW0 convergence settings
     417              : !> \param evgw0_sec EVGW0 input section
     418              : !> \param do_evgw0 whether the EVGW0 section is activated
     419              : ! **************************************************************************************************
     420          312 :    SUBROUTINE read_evgw0_input(bs_env, evgw0_sec, do_evgw0)
     421              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     422              :       TYPE(section_vals_type), POINTER                   :: evgw0_sec
     423              :       LOGICAL, INTENT(OUT)                               :: do_evgw0
     424              : 
     425              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'read_evgw0_input'
     426              : 
     427              :       INTEGER                                            :: handle
     428              : 
     429          156 :       CALL timeset(routineN, handle)
     430              : 
     431          156 :       CALL section_vals_val_get(evgw0_sec, "_SECTION_PARAMETERS_", l_val=do_evgw0)
     432          156 :       CALL section_vals_val_get(evgw0_sec, "MAX_ITER", i_val=bs_env%evgw0_n_iter)
     433          156 :       CALL section_vals_val_get(evgw0_sec, "EPS_ITER", r_val=bs_env%evgw0_eps_iter)
     434              : 
     435          156 :       CALL timestop(handle)
     436              : 
     437          156 :    END SUBROUTINE read_evgw0_input
     438              : 
     439              : ! **************************************************************************************************
     440              : !> \brief Reads the automatic RI input.
     441              : !> \param auto_ri automatic RI basis optimization parameters
     442              : !> \param auto_ri_sec AUTO_RI input section
     443              : ! **************************************************************************************************
     444          156 :    SUBROUTINE read_auto_ri_input(auto_ri, auto_ri_sec)
     445              :       TYPE(auto_ri_type), INTENT(INOUT)                  :: auto_ri
     446              :       TYPE(section_vals_type), POINTER                   :: auto_ri_sec
     447              : 
     448              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'read_auto_ri_input'
     449              : 
     450              :       INTEGER                                            :: handle
     451              : 
     452          156 :       CALL timeset(routineN, handle)
     453              : 
     454          156 :       CALL section_vals_get(auto_ri_sec, explicit=auto_ri%enabled)
     455          156 :       IF (.NOT. auto_ri%enabled) THEN
     456          144 :          CALL timestop(handle)
     457          144 :          RETURN
     458              :       END IF
     459              : 
     460           12 :       CALL section_vals_val_get(auto_ri_sec, "RI_AO_RATIO", r_val=auto_ri%ri_ao_ratio)
     461           12 :       CALL section_vals_val_get(auto_ri_sec, "OCC_EMPTY_FRONTIER_ORBITAL_WINDOW", r_val=auto_ri%occ_energy_window)
     462              : 
     463           12 :       CALL timestop(handle)
     464              : 
     465              :    END SUBROUTINE read_auto_ri_input
     466              : 
     467              : ! **************************************************************************************************
     468              : !> \brief Checks compatibility among the GW input sections and assigns the GW flavour.
     469              : !> \param bs_env ...
     470              : !> \param do_evgw0 whether eigenvalue self-consistency is requested
     471              : ! **************************************************************************************************
     472          156 :    SUBROUTINE check_gw_input(bs_env, do_evgw0)
     473              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     474              :       LOGICAL, INTENT(IN)                                :: do_evgw0
     475              : 
     476              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'check_gw_input'
     477              : 
     478              :       INTEGER                                            :: handle
     479              : 
     480          156 :       CALL timeset(routineN, handle)
     481              : 
     482              :       ! GRID_OPTIMIZATION is available only with RI-RS.
     483          156 :       CPASSERT(.NOT. bs_env%ri_rs%grid_opt%enabled .OR. bs_env%do_gw_ri_rs)
     484          156 :       IF (bs_env%ri_rs%grid_opt%enabled) THEN
     485           24 :          IF (bs_env%ri_rs%grid_opt%rs_ao_ratio == 0.0_dp) CPABORT("RS_AO_RATIO must be nonzero")
     486           24 :          IF (bs_env%ri_rs%grid_opt%max_iter < 1) THEN
     487            0 :             CPABORT("GRID_OPTIMIZATION%MAX_ITER must be positive")
     488              :          END IF
     489           24 :          IF (bs_env%ri_rs%grid_opt%cutoff_atomic_cluster == 0.0_dp) THEN
     490            0 :             CPABORT("CUTOFF_ATOMIC_CLUSTER must be nonzero")
     491              :          END IF
     492              :       END IF
     493          156 :       IF (bs_env%do_gw_ri_rs) THEN
     494           56 :          IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     495           14 :             IF (.NOT. bs_env%ri_rs%grid_opt%enabled) THEN
     496            0 :                CPABORT("Full-k RI-RS GW requires RI_RS%GRID_OPTIMIZATION")
     497              :             END IF
     498           14 :             IF (bs_env%size_lattice_sum_V < 1) THEN
     499            0 :                CPABORT("GW%SIZE_LATTICE_SUM must be positive")
     500              :             END IF
     501              :          END IF
     502              :       END IF
     503          156 :       IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     504           14 :          IF (.NOT. (bs_env%ri_metric%omega > 0.0_dp)) THEN
     505            0 :             CPABORT("RI_CUTOFF_ATTENUATION must be positive for periodic RI-RS GW")
     506              :          END IF
     507           98 :          IF (.NOT. (ALL(bs_env%periodic == [1, 1, 0]) .OR. ALL(bs_env%periodic == 1))) THEN
     508            0 :             CPABORT("Periodic RI-RS GW requires PERIODIC XY or XYZ")
     509              :          END IF
     510           14 :          IF (bs_env%approx_kp_extrapol) THEN
     511            0 :             CPABORT("APPROX_KP_EXTRAPOL cannot be combined with RI-RS GW")
     512              :          END IF
     513              :       END IF
     514          156 :       IF (.NOT. do_evgw0) bs_env%evgw0_n_iter = 1
     515          156 :       IF (do_evgw0 .AND. bs_env%evgw0_eps_iter <= 0.0_dp) THEN
     516            0 :          CPABORT("EVGW0%EPS_ITER must be positive")
     517              :       END IF
     518              : 
     519              :       ! evGW0 implemented so far only with RI-RS.
     520          156 :       CPASSERT(.NOT. do_evgw0 .OR. bs_env%do_gw_ri_rs)
     521          156 :       IF (bs_env%auto_ri%enabled) THEN
     522              :          ! AUTO_RI is available only with RI-RS.
     523           12 :          CPASSERT(bs_env%do_gw_ri_rs)
     524           12 :          IF (bs_env%do_periodic .AND. &
     525              :              bs_env%gw_implementation /= ri_rs_small_cell_full_kp) THEN
     526            0 :             CPABORT('Periodic AUTO_RI requires RI_RS_SMALL_CELL_FULL_KP')
     527              :          END IF
     528           12 :          IF (.NOT. (bs_env%auto_ri%ri_ao_ratio > 0.0_dp)) CPABORT("AUTO_RI%RI_AO_RATIO must be positive")
     529           12 :          IF (.NOT. (bs_env%auto_ri%occ_energy_window >= 0.0_dp)) THEN
     530            0 :             CPABORT("AUTO_RI%OCC_EMPTY_FRONTIER_ORBITAL_WINDOW must be nonnegative")
     531              :          END IF
     532              :       END IF
     533              : 
     534          156 :       bs_env%gw_flavour = G0W0
     535          156 :       IF (do_evgw0) THEN
     536            4 :          bs_env%gw_flavour = evGW0
     537              :          CALL cp_warn(__LOCATION__, &
     538              :                       "evGW0 in the RI-RS GW code is experimental. The quasiparticle energies "// &
     539              :                       "of the previous cycle are fed back into the Green's function, so the "// &
     540              :                       "error of the analytic continuation propagates and accumulates over the "// &
     541              :                       "cycles instead of affecting one state only, as it does in G0W0. In "// &
     542              :                       "tests on small molecules the resulting deviation stayed below 100 meV, "// &
     543              :                       "but this has not been established in general. Use at your own risk and "// &
     544            4 :                       "check the convergence of the reported states.")
     545              :       END IF
     546              : 
     547          156 :       CALL resolve_memory_per_proc(bs_env)
     548              : 
     549          156 :       CALL timestop(handle)
     550              : 
     551          156 :    END SUBROUTINE check_gw_input
     552              : 
     553              : ! **************************************************************************************************
     554              : !> \brief Determine memory per processor available for low-sclaing tensor GW routines.
     555              : !>
     556              : !>        MEMORY_PER_PROC = -1 (the default) : Automatically detect available memory from the system.
     557              : !>        MEMORY_PER_PROC > 0.0 : Override with user-defined value (in GB).
     558              : !>
     559              : !> \param bs_env ...
     560              : ! **************************************************************************************************
     561          156 :    SUBROUTINE resolve_memory_per_proc(bs_env)
     562              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     563              : 
     564              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'resolve_memory_per_proc'
     565              :       REAL(KIND=dp), PARAMETER :: detected_memory_fraction = 0.8_dp, &
     566              :          fallback_memory_per_proc_GB = 2.0_dp
     567              : 
     568              :       INTEGER                                            :: handle
     569              :       REAL(KIND=dp)                                      :: mem_free_per_proc_GB, mem_occ_per_proc_GB
     570              : 
     571          156 :       CALL timeset(routineN, handle)
     572              : 
     573          156 :       bs_env%auto_memory_per_proc = bs_env%input_memory_per_proc_GB <= 0.0_dp
     574              : 
     575          156 :       IF (bs_env%auto_memory_per_proc) THEN
     576              : 
     577          150 :          CALL mp_mem_avail_per_rank_GB(bs_env%para_env, mem_free_per_proc_GB)
     578          150 :          CALL mp_mem_used_per_rank_GB(bs_env%para_env, mem_occ_per_proc_GB)
     579              : 
     580              :          ! detected_memory_fraction is a safety net on the detected free memory
     581              :          bs_env%input_memory_per_proc_GB = detected_memory_fraction*mem_free_per_proc_GB &
     582          150 :                                            + mem_occ_per_proc_GB
     583              : 
     584              :          ! mp_mem_avail_per_rank_GB returns zero if the free memory cannot be detected
     585          150 :          IF (mem_free_per_proc_GB <= 0.0_dp) THEN
     586            0 :             bs_env%auto_memory_per_proc = .FALSE.
     587            0 :             bs_env%input_memory_per_proc_GB = fallback_memory_per_proc_GB
     588              :             CALL cp_warn(__LOCATION__, &
     589              :                          "Could not detect the available memory per MPI process. Falling back "// &
     590              :                          "to MEMORY_PER_PROC = 2 GB. Set MEMORY_PER_PROC in the GW section "// &
     591            0 :                          "explicitly for good performance.")
     592              :          END IF
     593              : 
     594            6 :       ELSE IF (bs_env%do_gw_ri_rs) THEN
     595              : 
     596              :          CALL cp_warn(__LOCATION__, &
     597              :                       "MEMORY_PER_PROC is set, but it is not used by this RI-RS GW code path, "// &
     598              :                       "which detects the available memory per MPI process automatically. The "// &
     599            0 :                       "keyword is ignored.")
     600              : 
     601              :       END IF
     602              : 
     603          156 :       CALL timestop(handle)
     604              : 
     605          156 :    END SUBROUTINE resolve_memory_per_proc
     606              : 
     607              : ! **************************************************************************************************
     608              : !> \brief Prints the common GW input parameters and the RI-RS block when active.
     609              : !> \param bs_env ...
     610              : ! **************************************************************************************************
     611          156 :    SUBROUTINE print_header_and_input_parameters(bs_env)
     612              : 
     613              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     614              : 
     615              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_header_and_input_parameters'
     616              : 
     617              :       INTEGER                                            :: handle, u
     618              : 
     619          156 :       CALL timeset(routineN, handle)
     620              : 
     621          156 :       u = bs_env%unit_nr
     622              : 
     623          156 :       IF (u > 0) THEN
     624           78 :          WRITE (u, '(T2,A)') ' '
     625           78 :          WRITE (u, '(T2,A)') REPEAT('-', 79)
     626           78 :          WRITE (u, '(T2,A,A78)') '-', '-'
     627           78 :          WRITE (u, '(T2,A,A46,A32)') '-', 'GW CALCULATION', '-'
     628           78 :          WRITE (u, '(T2,A,A78)') '-', '-'
     629           78 :          WRITE (u, '(T2,A)') REPEAT('-', 79)
     630           78 :          WRITE (u, '(T2,A)') ' '
     631           78 :          WRITE (u, '(T2,A,I45)') 'Input: Number of time/freq. points', bs_env%num_time_freq_points
     632           78 :          WRITE (u, "(T2,A,F44.1,A)") 'Input: ω_max for fitting Σ(iω) (eV)', bs_env%freq_max_fit*evolt
     633           78 :          IF (bs_env%ac_method == gw_ac_nevanlinna) THEN
     634           77 :             WRITE (u, "(T2,A,A51)") 'Input: Analytic continuation', 'NEVANLINNA'
     635              :          ELSE
     636            1 :             WRITE (u, "(T2,A,A51)") 'Input: Analytic continuation', 'PADE'
     637              :          END IF
     638           78 :          WRITE (u, '(T2,A,ES27.1)') 'Input: Filter threshold for sparse tensor operations', &
     639          156 :             bs_env%eps_filter
     640           78 :          WRITE (u, "(T2,A,L55)") 'Input: Apply Hedin shift', bs_env%do_hedin_shift
     641           78 :          IF (bs_env%auto_memory_per_proc) THEN
     642           75 :             WRITE (u, '(T2,A,F34.1,A)') 'Detected: Available memory per MPI process', &
     643          150 :                bs_env%input_memory_per_proc_GB, ' GB'
     644              :          ELSE
     645            3 :             WRITE (u, '(T2,A,F37.1,A)') 'Input: Available memory per MPI process', &
     646            6 :                bs_env%input_memory_per_proc_GB, ' GB'
     647              :          END IF
     648           78 :          IF (bs_env%do_gw_ri_rs) CALL print_gw_rirs_input(bs_env)
     649           78 :          IF (bs_env%do_static_cohsex) THEN
     650            4 :             IF (bs_env%cohsex_flavor == cohsex_qp_update) THEN
     651            3 :                WRITE (u, FMT="(T2,A,T71,A10)") "static COHSEX approximation (COHSEX)", "QP_UPDATE"
     652              :             ELSE
     653            1 :                WRITE (u, FMT="(T2,A,T71,A10)") "static COHSEX approximation (COHSEX)", "DIAGONAL"
     654              :             END IF
     655            4 :             WRITE (u, FMT="(T2,A,T74,F8.6)") "static COHSEX scaling of Σ^c, occ-occ (COHSEX%SCALE_OCC):", &
     656            8 :                bs_env%cohsex_scale_occ
     657            4 :             WRITE (u, FMT="(T2,A,T74,F8.6)") "static COHSEX scaling of Σ^c, virt-virt (COHSEX%SCALE_VIRT):", &
     658            8 :                bs_env%cohsex_scale_virt
     659              :          END IF
     660           78 :          WRITE (u, '(A)') ' '
     661              :       END IF
     662              : 
     663          156 :       CALL timestop(handle)
     664              : 
     665          156 :    END SUBROUTINE print_header_and_input_parameters
     666              : 
     667              : ! **************************************************************************************************
     668              : !> \brief Prints the input parameters specific to an RI-RS GW calculation.
     669              : !> \param bs_env ...
     670              : ! **************************************************************************************************
     671           28 :    SUBROUTINE print_gw_rirs_input(bs_env)
     672              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     673              : 
     674              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_gw_rirs_input'
     675              : 
     676              :       INTEGER                                            :: handle, unit_nr
     677              : 
     678           28 :       CALL timeset(routineN, handle)
     679              : 
     680           28 :       unit_nr = bs_env%unit_nr
     681              : 
     682           28 :       WRITE (unit_nr, '(A)') ' '
     683           28 :       WRITE (unit_nr, '(T2,A,ES43.2)') 'Input: RI-RS Tikhonov regularization', &
     684           56 :          bs_env%ri_rs%tikhonov
     685              :       CALL print_cutoff_radius_input(unit_nr, 'AO grid hard cutoff radius', &
     686           28 :                                      bs_env%ri_rs%cutoff_radius_ri_ao)
     687              :       CALL print_cutoff_radius_input(unit_nr, 'G/W panel truncation radius', &
     688           28 :                                      bs_env%ri_rs%cutoff_radius_v_w)
     689           28 :       WRITE (unit_nr, '(T2,A,A62)') 'Input: GW flavour', TRIM(gw_flavour_label(bs_env))
     690              : 
     691           28 :       IF (bs_env%ri_rs%grid_opt%enabled) THEN
     692           12 :          WRITE (unit_nr, '(A)') ' '
     693              :          WRITE (unit_nr, '(T2,A,T80,L1)') &
     694           12 :             'Input: RI-RS grid optimization activated', .TRUE.
     695           12 :          IF (bs_env%ri_rs%grid_opt%cutoff_atomic_cluster < 0.0_dp) THEN
     696              :             WRITE (unit_nr, '(T2,A,T52,A29)') &
     697            2 :                'Input: Atomic cluster radius', 'Automatic: 1.4 x nearest atom'
     698              :          ELSE
     699              :             WRITE (unit_nr, '(T2,A,T73,F6.1,A)') &
     700           10 :                'Input: Cutoff radius for atomic clusters', &
     701           20 :                bs_env%ri_rs%grid_opt%cutoff_atomic_cluster*angstrom, ' Å'
     702              :          END IF
     703              :          WRITE (unit_nr, '(T2,A,T75,I6)') &
     704           12 :             'Input: Maximum grid optimization iterations', &
     705           24 :             bs_env%ri_rs%grid_opt%max_iter
     706              :       END IF
     707              : 
     708           28 :       IF (bs_env%auto_ri%enabled) THEN
     709            6 :          WRITE (unit_nr, '(A)') ' '
     710              :          WRITE (unit_nr, '(T2,A,T80,L1)') &
     711            6 :             'Input: AUTO_RI basis optimization activated:', .TRUE.
     712              :          WRITE (unit_nr, '(T2,A,T69,F12.1)') &
     713            6 :             'Input: AUTO_RI number of RI functions per AO function:', bs_env%auto_ri%ri_ao_ratio
     714              :          WRITE (unit_nr, '(T2,A,T74,F4.1,A)') &
     715            6 :             'Input: AUTO_RI frontier orbital window:', bs_env%auto_ri%occ_energy_window*evolt, ' eV'
     716              :       END IF
     717              : 
     718           28 :       IF (bs_env%gw_flavour == evGW0) THEN
     719            2 :          WRITE (unit_nr, '(T2,A,I42)') 'Input: Maximum number of evGW0 cycles', &
     720            4 :             bs_env%evgw0_n_iter
     721            2 :          WRITE (unit_nr, '(T2,A,F42.5,A)') 'Input: evGW0 convergence threshold', &
     722            4 :             bs_env%evgw0_eps_iter*evolt, ' eV'
     723              :       END IF
     724           28 :       WRITE (unit_nr, '(A)') ' '
     725              : 
     726           28 :       CALL timestop(handle)
     727              : 
     728           28 :    END SUBROUTINE print_gw_rirs_input
     729              : 
     730              : ! **************************************************************************************************
     731              : !> \brief Prints a positive RI-RS cutoff radius.
     732              : !> \param unit_nr output unit
     733              : !> \param label description of the cutoff radius
     734              : !> \param cutoff_radius cutoff radius in atomic units
     735              : ! **************************************************************************************************
     736           56 :    SUBROUTINE print_cutoff_radius_input(unit_nr, label, cutoff_radius)
     737              :       INTEGER, INTENT(IN)                                :: unit_nr
     738              :       CHARACTER(LEN=*), INTENT(IN)                       :: label
     739              :       REAL(KIND=dp), INTENT(IN)                          :: cutoff_radius
     740              : 
     741              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_cutoff_radius_input'
     742              : 
     743              :       INTEGER                                            :: handle
     744              : 
     745           56 :       CALL timeset(routineN, handle)
     746              : 
     747           56 :       IF (cutoff_radius > 0.0_dp) THEN
     748              :          WRITE (unit_nr, '(T2,2A,T73,F6.2,A)') &
     749            2 :             'Input: ', TRIM(label), cutoff_radius*angstrom, ' Å'
     750              :       END IF
     751              : 
     752           56 :       CALL timestop(handle)
     753              : 
     754           56 :    END SUBROUTINE print_cutoff_radius_input
     755              : 
     756              : ! **************************************************************************************************
     757              : !> \brief Creates the AO and reference RI basis sets for every atomic kind.
     758              : !> \param qs_env ...
     759              : !> \param bs_env ...
     760              : ! **************************************************************************************************
     761          156 :    SUBROUTINE setup_AO_and_RI_basis_set(qs_env, bs_env)
     762              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     763              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     764              : 
     765              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_AO_and_RI_basis_set'
     766              : 
     767              :       INTEGER                                            :: handle, ikind, natom, nkind, sort_basis
     768              :       TYPE(dft_control_type), POINTER                    :: dft_control
     769              :       TYPE(gto_basis_set_type), POINTER                  :: reference_basis
     770          156 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     771          156 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     772              : 
     773          156 :       CALL timeset(routineN, handle)
     774              : 
     775              :       CALL get_qs_env(qs_env, &
     776              :                       qs_kind_set=qs_kind_set, &
     777              :                       particle_set=particle_set, &
     778          156 :                       natom=natom, nkind=nkind, dft_control=dft_control)
     779              : 
     780              :       ! AUTO_RI needs a reference pool before its atom-local contraction.
     781          156 :       IF (bs_env%auto_ri%enabled) THEN
     782           12 :          CALL section_vals_val_get(qs_env%input, "DFT%SORT_BASIS", i_val=sort_basis)
     783           28 :          DO ikind = 1, nkind
     784           16 :             NULLIFY (reference_basis)
     785           16 :             CALL get_qs_kind(qs_kind_set(ikind), basis_set=reference_basis, basis_type="RI_AUX")
     786           28 :             IF (.NOT. ASSOCIATED(reference_basis)) THEN
     787              :                CALL create_ri_aux_basis_set(reference_basis, qs_kind_set(ikind), &
     788            6 :                                             dft_control%auto_basis_ri_aux, basis_sort=sort_basis)
     789            6 :                IF (reference_basis%norm_type < 0) reference_basis%norm_type = 2
     790            6 :                CALL init_orb_basis_set(reference_basis)
     791            6 :                CALL add_basis_set_to_container(qs_kind_set(ikind)%basis_sets, reference_basis, "RI_AUX")
     792              :             END IF
     793              :          END DO
     794              :       END IF
     795              : 
     796              :       ! set up basis
     797          624 :       ALLOCATE (bs_env%sizes_RI(natom), bs_env%sizes_AO(natom))
     798         1068 :       ALLOCATE (bs_env%basis_set_RI(nkind), bs_env%basis_set_AO(nkind))
     799              : 
     800          156 :       CALL basis_set_list_setup(bs_env%basis_set_RI, "RI_AUX", qs_kind_set)
     801          156 :       CALL basis_set_list_setup(bs_env%basis_set_AO, "ORB", qs_kind_set)
     802              : 
     803              :       CALL get_particle_set(particle_set, qs_kind_set, nsgf=bs_env%sizes_RI, &
     804          156 :                             basis=bs_env%basis_set_RI)
     805              :       CALL get_particle_set(particle_set, qs_kind_set, nsgf=bs_env%sizes_AO, &
     806          156 :                             basis=bs_env%basis_set_AO)
     807              : 
     808          156 :       CALL timestop(handle)
     809              : 
     810          156 :    END SUBROUTINE setup_AO_and_RI_basis_set
     811              : 
     812              : ! **************************************************************************************************
     813              : !> \brief Sets internal GW heuristics that are not exposed as user input.
     814              : !> \param bs_env ...
     815              : !> \param qs_env ...
     816              : ! **************************************************************************************************
     817          156 :    SUBROUTINE set_heuristic_parameters(bs_env, qs_env)
     818              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     819              :       TYPE(qs_environment_type), OPTIONAL, POINTER       :: qs_env
     820              : 
     821              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_heuristic_parameters'
     822              : 
     823              :       INTEGER                                            :: exchange_grid(3), handle, u
     824              :       LOGICAL                                            :: do_BvK_cell
     825              : 
     826          156 :       CALL timeset(routineN, handle)
     827              : 
     828              :       ! Use a 16-parameter Padé fit; cap it at the available fit frequencies below.
     829          156 :       bs_env%nparam_pade = 16
     830              : 
     831              :       ! for generating numerically stable minimax Fourier integration weights
     832          156 :       bs_env%num_points_per_magnitude = 200
     833              : 
     834          156 :       IF (bs_env%input_regularization_minimax > -1.0E-12_dp) THEN
     835            0 :          bs_env%regularization_minimax = bs_env%input_regularization_minimax
     836              :       ELSE
     837              :          ! for periodic systems and for 20 minimax points, we use a regularized minimax mesh
     838              :          ! (from experience: regularized minimax meshes converge faster for periodic systems
     839              :          !  and for 20 pts)
     840          156 :          IF (bs_env%do_periodic .OR. bs_env%num_time_freq_points >= 20) THEN
     841          126 :             bs_env%regularization_minimax = 1.0E-6_dp
     842              :          ELSE
     843           30 :             bs_env%regularization_minimax = 0.0_dp
     844              :          END IF
     845              :       END IF
     846              : 
     847          156 :       bs_env%stabilize_exp = 70.0_dp
     848          156 :       bs_env%eps_atom_grid_2d_mat = 1.0E-50_dp
     849              : 
     850              :       ! Nevanlinna continuation: weights of Σ^c(iτ) -> Σ^c(iω) by a truncated SVD, and the
     851              :       ! quasiparticle solution as median over fit windows with the Newton search and the
     852              :       ! solution of largest weight Z
     853          156 :       IF (bs_env%ac_method == gw_ac_nevanlinna) THEN
     854          154 :          bs_env%nevanlinna%rcond_weights = 1.0E-10_dp
     855          154 :          bs_env%nevanlinna%window_min_points = 6
     856          154 :          bs_env%nevanlinna%window_freq_min = 10.0_dp/evolt
     857          154 :          bs_env%nevanlinna%window_freq_max = 100.0_dp/evolt
     858          154 :          bs_env%nevanlinna%window_spread = 0.05_dp/evolt
     859          154 :          bs_env%nevanlinna%qp_newton_max_step = 1.0_dp/evolt
     860          154 :          bs_env%nevanlinna%qp_maxz_radius = 1.5_dp/evolt
     861              :       END IF
     862              : 
     863              :       ! Resolution of the identity with the truncated Coulomb metric.
     864          156 :       bs_env%ri_metric%potential_type = do_potential_truncated
     865          156 :       bs_env%ri_metric%filename = "t_c_g.dat"
     866          156 :       IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     867           14 :          bs_env%ri_metric%potential_type = do_potential_short
     868           14 :          CALL erfc_cutoff(1.0E-10_dp, bs_env%ri_metric%omega, bs_env%ri_metric%cutoff_radius)
     869           14 :          bs_env%ri_metric%filename = ""
     870              :       ELSE
     871          142 :          bs_env%ri_metric%omega = 0.0_dp
     872              :       END IF
     873              : 
     874          156 :       bs_env%eps_eigval_mat_RI = 0.0_dp
     875              : 
     876          156 :       IF (bs_env%input_regularization_RI >= 0.0_dp) THEN
     877            0 :          bs_env%regularization_RI = bs_env%input_regularization_RI
     878          156 :       ELSE IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     879              :          ! periodic RI-RS: relative eigenvalue cutoff when inverting the RI metric M(q)
     880           14 :          bs_env%regularization_RI = 1.0E-4_dp
     881              :       ELSE
     882              :          ! default case:
     883              : 
     884              :          ! 1. for periodic systems, we use the regularized resolution of the identity per default
     885          142 :          bs_env%regularization_RI = 1.0E-2_dp
     886              : 
     887              :          ! 2. for molecules, no regularization is necessary
     888          142 :          IF (.NOT. bs_env%do_periodic) bs_env%regularization_RI = 0.0_dp
     889              : 
     890              :       END IF
     891              : 
     892              :       ! Coulomb operator for the exchange self-energy. Periodic systems use the truncated
     893              :       ! operator described by Guidon, VandeVondele, and Hutter, JCTC 5, 3010 (2009).
     894          156 :       IF (bs_env%do_periodic) THEN
     895              :          do_BvK_cell = bs_env%gw_implementation == tensor_small_cell_full_kp .OR. &
     896           48 :                        bs_env%gw_implementation == ri_rs_small_cell_full_kp
     897           14 :          SELECT CASE (bs_env%gw_implementation)
     898              :          CASE (ri_rs_small_cell_full_kp)
     899              :             ! The Born-von Karman cell follows the SCF k mesh, not the AO image-list extent.
     900           56 :             exchange_grid = bs_env%kpoints_scf_desymm%nkp_grid
     901              :          CASE DEFAULT
     902          184 :             exchange_grid = bs_env%cell_grid_scf_desymm
     903              :          END SELECT
     904              :          CALL trunc_coulomb_for_exchange(qs_env, bs_env%trunc_coulomb, &
     905              :                                          rel_cutoff_trunc_coulomb_ri_x=0.5_dp, &
     906              :                                          cell_grid=exchange_grid, &
     907           48 :                                          do_BvK_cell=do_BvK_cell)
     908              :       ELSE
     909          108 :          bs_env%trunc_coulomb%potential_type = do_potential_coulomb
     910          108 :          bs_env%trunc_coulomb%cutoff_radius = -1.0_dp
     911          108 :          bs_env%trunc_coulomb%omega = 0.0_dp
     912          108 :          bs_env%trunc_coulomb%filename = ""
     913              :       END IF
     914              : 
     915              :       ! for small-cell GW, we need more cells than normally used by the filter bs_env%eps_filter
     916              :       ! (in particular for computing the self-energy because of higher number of cells needed)
     917          156 :       bs_env%heuristic_filter_factor = 1.0E-4_dp
     918              : 
     919          156 :       u = bs_env%unit_nr
     920          156 :       IF (u > 0) THEN
     921           78 :          IF (bs_env%do_periodic) THEN
     922           24 :             WRITE (u, FMT="(T2,2A,F21.1,A)") "Cutoff radius for the truncated Coulomb ", &
     923           48 :                "operator in Σ^x:", bs_env%trunc_coulomb%cutoff_radius*angstrom, " Å"
     924              :          END IF
     925           85 :          SELECT CASE (bs_env%ri_metric%potential_type)
     926              :          CASE (do_potential_short)
     927              :             ! ⁻¹ takes three bytes more than two columns: column 83 in bytes is column 80 on screen.
     928            7 :             WRITE (u, FMT="(T2,A,T73,F11.2)") "Attenuation of the RI metric (bohr⁻¹)", &
     929           14 :                bs_env%ri_metric%omega
     930              :          CASE (do_potential_truncated)
     931           71 :             WRITE (u, FMT="(T2,2A,F15.1,A)") "Cutoff radius for the truncated Coulomb ", &
     932          149 :                "operator in RI metric:", bs_env%ri_metric%cutoff_radius*angstrom, " Å"
     933              :          END SELECT
     934           78 :          IF (bs_env%num_time_freq_points < 35) THEN
     935           78 :             WRITE (u, FMT="(T2,A,ES38.1)") "Regularization parameter of minimax grids", &
     936          156 :                bs_env%regularization_minimax
     937              :          END IF
     938           78 :          IF (bs_env%ac_method == gw_ac_nevanlinna) THEN
     939           77 :             WRITE (u, FMT="(T2,A,ES31.1)") "SVD cutoff of minimax weights for Σ(iτ) -> Σ(iω)", &
     940          154 :                bs_env%nevanlinna%rcond_weights
     941              :          END IF
     942           78 :          IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     943            7 :             WRITE (u, FMT="(T2,A,T72,A9)") "Coulomb matrix V(q) from", "Ewald sum"
     944           24 :             IF (ALL(bs_env%periodic == [1, 1, 0])) THEN
     945            3 :                WRITE (u, FMT="(T2,A,I43)") "Lattice sum size for 2D V(q=0) body:", bs_env%size_lattice_sum_V
     946              :             END IF
     947           71 :          ELSE IF (bs_env%do_periodic) THEN
     948           17 :             WRITE (u, FMT="(T2,A,I53)") "Lattice sum size for V(k):", bs_env%size_lattice_sum_V
     949              :          END IF
     950              :       END IF
     951              : 
     952          156 :       CALL timestop(handle)
     953              : 
     954          156 :    END SUBROUTINE set_heuristic_parameters
     955              : 
     956              : ! **************************************************************************************************
     957              : !> \brief Sets up the RI basis, its matrix distributions, and M^-1(k=0).
     958              : !> \param qs_env ...
     959              : !> \param bs_env ...
     960              : ! **************************************************************************************************
     961          156 :    SUBROUTINE get_RI_basis(qs_env, bs_env)
     962              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     963              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     964              : 
     965              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_RI_basis'
     966              : 
     967              :       INTEGER                                            :: handle
     968              : 
     969          156 :       CALL timeset(routineN, handle)
     970              : 
     971          156 :       CALL set_AO_RI_basis_function_indices(qs_env, bs_env)
     972          156 :       CALL setup_kpoints_chi_eps_W(bs_env, bs_env%kpoints_chi_eps_W)
     973          156 :       IF (bs_env%gw_implementation == tensor_small_cell_full_kp .OR. &
     974              :           bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
     975           30 :          CALL setup_cells_3c(qs_env, bs_env)
     976              :       END IF
     977          156 :       CALL set_parallelization_parameters(qs_env, bs_env)
     978          156 :       CALL allocate_matrices(qs_env, bs_env)
     979          156 :       IF (bs_env%gw_implementation /= tensor_small_cell_full_kp .AND. &
     980              :           bs_env%gw_implementation /= ri_rs_small_cell_full_kp) THEN
     981          126 :          CALL compute_Minv_Gamma(qs_env, bs_env)
     982              :       END IF
     983              : 
     984          156 :       CALL timestop(handle)
     985              : 
     986          156 :    END SUBROUTINE get_RI_basis
     987              : 
     988              : ! **************************************************************************************************
     989              : !> \brief Determines the AO and RI basis-function indices for every atom.
     990              : !> \param qs_env ...
     991              : !> \param bs_env ...
     992              : ! **************************************************************************************************
     993          156 :    SUBROUTINE set_AO_RI_basis_function_indices(qs_env, bs_env)
     994              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     995              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     996              : 
     997              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_AO_RI_basis_function_indices'
     998              : 
     999              :       INTEGER                                            :: handle, i_RI, iatom, ikind, iset, &
    1000              :                                                             max_AO_bf_per_atom, n_ao_test, n_atom, &
    1001              :                                                             n_kind, n_RI, nset, u
    1002          156 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: kind_of
    1003          156 :       INTEGER, DIMENSION(:), POINTER                     :: l_max, l_min, nsgf_set
    1004          156 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1005              :       TYPE(gto_basis_set_type), POINTER                  :: basis
    1006          156 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1007              : 
    1008          156 :       CALL timeset(routineN, handle)
    1009              : 
    1010              :       ! determine RI basis set size
    1011          156 :       CALL get_qs_env(qs_env, atomic_kind_set=atomic_kind_set, qs_kind_set=qs_kind_set)
    1012              : 
    1013          156 :       n_kind = SIZE(qs_kind_set)
    1014          156 :       n_atom = bs_env%n_atom
    1015              : 
    1016          156 :       CALL get_atomic_kind_set(atomic_kind_set, kind_of=kind_of)
    1017              : 
    1018          378 :       DO ikind = 1, n_kind
    1019          222 :          CALL get_qs_kind(qs_kind_set(ikind), basis_set=basis, basis_type="RI_AUX")
    1020          378 :          CPASSERT(ASSOCIATED(basis))
    1021              :       END DO
    1022              : 
    1023          468 :       ALLOCATE (bs_env%i_RI_start_from_atom(n_atom))
    1024          312 :       ALLOCATE (bs_env%i_RI_end_from_atom(n_atom))
    1025          312 :       ALLOCATE (bs_env%i_ao_start_from_atom(n_atom))
    1026          312 :       ALLOCATE (bs_env%i_ao_end_from_atom(n_atom))
    1027              : 
    1028          156 :       n_RI = 0
    1029          524 :       DO iatom = 1, n_atom
    1030          368 :          bs_env%i_RI_start_from_atom(iatom) = n_RI + 1
    1031          368 :          n_RI = n_RI + bs_env%sizes_RI(iatom)
    1032          524 :          bs_env%i_RI_end_from_atom(iatom) = n_RI
    1033              :       END DO
    1034          156 :       bs_env%n_RI = n_RI
    1035              : 
    1036          156 :       max_AO_bf_per_atom = 0
    1037          156 :       n_ao_test = 0
    1038          524 :       DO iatom = 1, n_atom
    1039          368 :          bs_env%i_ao_start_from_atom(iatom) = n_ao_test + 1
    1040          368 :          n_ao_test = n_ao_test + bs_env%sizes_AO(iatom)
    1041          368 :          bs_env%i_ao_end_from_atom(iatom) = n_ao_test
    1042          524 :          max_AO_bf_per_atom = MAX(max_AO_bf_per_atom, bs_env%sizes_AO(iatom))
    1043              :       END DO
    1044          156 :       CPASSERT(n_ao_test == bs_env%n_ao)
    1045          156 :       bs_env%max_AO_bf_per_atom = max_AO_bf_per_atom
    1046              : 
    1047          156 :       u = bs_env%unit_nr
    1048         4866 :       ALLOCATE (bs_env%l_RI(n_RI), source=-1)
    1049          156 :       IF (bs_env%auto_ri%enabled) THEN
    1050           12 :          CPASSERT(bs_env%auto_ri%ready)
    1051              :       ELSE
    1052              :          i_RI = 0
    1053          484 :          DO iatom = 1, n_atom
    1054          340 :             ikind = kind_of(iatom)
    1055          340 :             nset = bs_env%basis_set_RI(ikind)%gto_basis_set%nset
    1056          340 :             l_max => bs_env%basis_set_RI(ikind)%gto_basis_set%lmax
    1057          340 :             l_min => bs_env%basis_set_RI(ikind)%gto_basis_set%lmin
    1058          340 :             nsgf_set => bs_env%basis_set_RI(ikind)%gto_basis_set%nsgf_set
    1059         2264 :             DO iset = 1, nset
    1060         1780 :                CPASSERT(l_max(iset) == l_min(iset))
    1061         6096 :                bs_env%l_RI(i_RI + 1:i_RI + nsgf_set(iset)) = l_max(iset)
    1062         2120 :                i_RI = i_RI + nsgf_set(iset)
    1063              :             END DO
    1064              :          END DO
    1065          144 :          CPASSERT(i_RI == n_RI)
    1066          144 :          IF (u > 0) THEN
    1067           72 :             WRITE (u, FMT="(T2,A)") " "
    1068           72 :             WRITE (u, FMT="(T2,2A,T75,I8)") "Number of auxiliary Gaussian basis functions ", &
    1069          144 :                "for χ, ε, W", n_RI
    1070              :          END IF
    1071              :       END IF
    1072              : 
    1073          156 :       CALL timestop(handle)
    1074              : 
    1075          312 :    END SUBROUTINE set_AO_RI_basis_function_indices
    1076              : 
    1077              : ! **************************************************************************************************
    1078              : !> \brief Sets the reciprocal mesh used for χ, ε, and W.
    1079              : !> \param bs_env ...
    1080              : !> \param kpoints_chi_eps_W reciprocal mesh used for χ, ε, and W
    1081              : ! **************************************************************************************************
    1082          156 :    SUBROUTINE setup_kpoints_chi_eps_W(bs_env, kpoints_chi_eps_W)
    1083              : 
    1084              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1085              :       TYPE(kpoint_type), POINTER                         :: kpoints_chi_eps_W
    1086              : 
    1087              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_kpoints_chi_eps_W'
    1088              : 
    1089              :       INTEGER                                            :: handle, i_dim, n_dim, nkp, nkp_extra, &
    1090              :                                                             nkp_orig, u
    1091              :       INTEGER, DIMENSION(3)                              :: nkp_grid, nkp_grid_extra, periodic
    1092              :       REAL(KIND=dp)                                      :: exp_s_p, n_dim_inv
    1093              : 
    1094          156 :       CALL timeset(routineN, handle)
    1095              : 
    1096              :       ! routine adapted from mp2_integrals.F
    1097          156 :       NULLIFY (kpoints_chi_eps_W)
    1098          156 :       CALL kpoint_create(kpoints_chi_eps_W)
    1099              : 
    1100          156 :       kpoints_chi_eps_W%kp_scheme = "GENERAL"
    1101          156 :       IF (ASSOCIATED(bs_env%kpoints_scf_desymm)) THEN
    1102           30 :          kpoints_chi_eps_W%rskp_transform = bs_env%kpoints_scf_desymm%rskp_transform
    1103              :       END IF
    1104              : 
    1105          624 :       periodic(1:3) = bs_env%periodic(1:3)
    1106              : 
    1107          156 :       CPASSERT(SIZE(bs_env%nkp_grid_chi_eps_W_input) == 3)
    1108              : 
    1109              :       IF (bs_env%nkp_grid_chi_eps_W_input(1) > 0 .AND. &
    1110          156 :           bs_env%nkp_grid_chi_eps_W_input(2) > 0 .AND. &
    1111              :           bs_env%nkp_grid_chi_eps_W_input(3) > 0) THEN
    1112              : 
    1113              :          ! 1. k-point mesh for χ, ε, W from input
    1114              : 
    1115           16 :          DO i_dim = 1, 3
    1116            4 :             SELECT CASE (periodic(i_dim))
    1117              :             CASE (0)
    1118            2 :                nkp_grid(i_dim) = 1
    1119            2 :                nkp_grid_extra(i_dim) = 1
    1120              :             CASE (1)
    1121           10 :                nkp_grid(i_dim) = bs_env%nkp_grid_chi_eps_W_input(i_dim)
    1122           10 :                nkp_grid_extra(i_dim) = nkp_grid(i_dim)*2
    1123              :             CASE DEFAULT
    1124           12 :                CPABORT("Error in periodicity.")
    1125              :             END SELECT
    1126              :          END DO
    1127              : 
    1128              :       ELSE IF (bs_env%nkp_grid_chi_eps_W_input(1) == -1 .AND. &
    1129          152 :                bs_env%nkp_grid_chi_eps_W_input(2) == -1 .AND. &
    1130              :                bs_env%nkp_grid_chi_eps_W_input(3) == -1) THEN
    1131              : 
    1132              :          ! 2. automatic k-point mesh for χ, ε, W
    1133              : 
    1134          608 :          DO i_dim = 1, 3
    1135              : 
    1136          456 :             CPASSERT(periodic(i_dim) == 0 .OR. periodic(i_dim) == 1)
    1137              : 
    1138          152 :             SELECT CASE (periodic(i_dim))
    1139              :             CASE (0)
    1140          360 :                nkp_grid(i_dim) = 1
    1141          360 :                nkp_grid_extra(i_dim) = 1
    1142              :             CASE (1)
    1143          124 :                SELECT CASE (bs_env%gw_implementation)
    1144              :                CASE (tensor_large_cell_Gamma, ri_rs_large_cell_Gamma, ri_rs_non_periodic, tensor_static_cohsex)
    1145           28 :                   nkp_grid(i_dim) = 4
    1146           28 :                   nkp_grid_extra(i_dim) = 6
    1147              :                CASE (ri_rs_small_cell_full_kp)
    1148           36 :                   nkp_grid(i_dim) = bs_env%kpoints_scf_desymm%nkp_grid(i_dim)
    1149           36 :                   nkp_grid_extra(i_dim) = 1
    1150              :                CASE (tensor_small_cell_full_kp)
    1151           32 :                   nkp_grid(i_dim) = bs_env%kpoints_scf_desymm%nkp_grid(i_dim)*4
    1152           96 :                   nkp_grid_extra(i_dim) = bs_env%kpoints_scf_desymm%nkp_grid(i_dim)*8
    1153              :                END SELECT
    1154              :             CASE DEFAULT
    1155          456 :                CPABORT("Error in periodicity.")
    1156              :             END SELECT
    1157              : 
    1158              :          END DO
    1159              : 
    1160              :       ELSE
    1161              : 
    1162            0 :          CPABORT("An error occured when setting up the k-mesh for W.")
    1163              : 
    1164              :       END IF
    1165              : 
    1166          624 :       nkp_orig = MAX(PRODUCT(nkp_grid)/2, 1)
    1167          624 :       nkp_extra = PRODUCT(nkp_grid_extra)/2
    1168          156 :       IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
    1169           56 :          CPASSERT(ALL(nkp_grid == bs_env%kpoints_scf_desymm%nkp_grid))
    1170           56 :          nkp_orig = PRODUCT(nkp_grid)
    1171           14 :          nkp_extra = 0
    1172           14 :          CPASSERT(nkp_orig == bs_env%nkp_scf_desymm)
    1173              :       END IF
    1174              : 
    1175          156 :       nkp = nkp_orig + nkp_extra
    1176              : 
    1177          624 :       kpoints_chi_eps_W%nkp_grid(1:3) = nkp_grid(1:3)
    1178          156 :       kpoints_chi_eps_W%nkp = nkp
    1179              : 
    1180          624 :       bs_env%nkp_grid_chi_eps_W_orig(1:3) = nkp_grid(1:3)
    1181          624 :       bs_env%nkp_grid_chi_eps_W_extra(1:3) = nkp_grid_extra(1:3)
    1182          156 :       bs_env%nkp_chi_eps_W_orig = nkp_orig
    1183          156 :       bs_env%nkp_chi_eps_W_orig_plus_extra = nkp
    1184              : 
    1185          780 :       ALLOCATE (kpoints_chi_eps_W%xkp(3, nkp), kpoints_chi_eps_W%wkp(nkp))
    1186          468 :       ALLOCATE (bs_env%wkp_no_extra(nkp), bs_env%wkp_s_p(nkp))
    1187              : 
    1188          156 :       IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
    1189         2012 :          kpoints_chi_eps_W%xkp = bs_env%kpoints_scf_desymm%xkp(1:3, :)
    1190              :       ELSE
    1191          142 :          CALL compute_xkp(kpoints_chi_eps_W%xkp, 1, nkp_orig, nkp_grid)
    1192          142 :          CALL compute_xkp(kpoints_chi_eps_W%xkp, nkp_orig + 1, nkp, nkp_grid_extra)
    1193              :       END IF
    1194              : 
    1195          624 :       n_dim = SUM(periodic)
    1196          156 :       IF (n_dim == 0) THEN
    1197              :          ! molecules
    1198          108 :          kpoints_chi_eps_W%wkp(1) = 1.0_dp
    1199          108 :          bs_env%wkp_s_p(1) = 1.0_dp
    1200          108 :          bs_env%wkp_no_extra(1) = 1.0_dp
    1201           48 :       ELSE IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
    1202          262 :          kpoints_chi_eps_W%wkp = 1.0_dp/REAL(nkp, dp)
    1203          524 :          bs_env%wkp_s_p(:) = kpoints_chi_eps_W%wkp
    1204          524 :          bs_env%wkp_no_extra(:) = kpoints_chi_eps_W%wkp
    1205              :       ELSE
    1206              : 
    1207           34 :          n_dim_inv = 1.0_dp/REAL(n_dim, KIND=dp)
    1208              : 
    1209              :          ! k-point weights are chosen to automatically extrapolate the k-point mesh
    1210           34 :          CALL compute_wkp(kpoints_chi_eps_W%wkp(1:nkp_orig), nkp_orig, nkp_extra, n_dim_inv)
    1211              :          CALL compute_wkp(kpoints_chi_eps_W%wkp(nkp_orig + 1:nkp), &
    1212           34 :                           nkp_extra, nkp_orig, n_dim_inv)
    1213              : 
    1214         2218 :          bs_env%wkp_no_extra(1:nkp_orig) = 0.0_dp
    1215         8606 :          bs_env%wkp_no_extra(nkp_orig + 1:nkp) = 1.0_dp/REAL(nkp_extra, KIND=dp)
    1216              : 
    1217           34 :          IF (n_dim == 3) THEN
    1218              :             ! W_PQ(k) for an s-function P and a p-function Q diverges as 1/k at k=0
    1219              :             ! (instead of 1/k^2 for P and Q both being s-functions).
    1220            2 :             exp_s_p = 2.0_dp*n_dim_inv
    1221            2 :             CALL compute_wkp(bs_env%wkp_s_p(1:nkp_orig), nkp_orig, nkp_extra, exp_s_p)
    1222            2 :             CALL compute_wkp(bs_env%wkp_s_p(nkp_orig + 1:nkp), nkp_extra, nkp_orig, exp_s_p)
    1223              :          ELSE
    1224        10716 :             bs_env%wkp_s_p(1:nkp) = bs_env%wkp_no_extra(1:nkp)
    1225              :          END IF
    1226              : 
    1227              :       END IF
    1228              : 
    1229          156 :       IF (bs_env%approx_kp_extrapol) THEN
    1230            2 :          bs_env%wkp_orig = 1.0_dp/REAL(nkp_orig, KIND=dp)
    1231              :       END IF
    1232              : 
    1233              :       ! heuristic parameter: how many k-points for χ, ε, and W are used simultaneously
    1234              :       ! (less simultaneous k-points: less memory, but more computational effort because of
    1235              :       !  recomputation of V(k))
    1236          156 :       bs_env%nkp_chi_eps_W_batch = 4
    1237              : 
    1238              :       bs_env%num_chi_eps_W_batches = (bs_env%nkp_chi_eps_W_orig_plus_extra - 1)/ &
    1239          156 :                                      bs_env%nkp_chi_eps_W_batch + 1
    1240              : 
    1241          156 :       u = bs_env%unit_nr
    1242              : 
    1243          156 :       IF (u > 0 .AND. bs_env%do_periodic) THEN
    1244           24 :          WRITE (u, FMT="(T2,A)") " "
    1245           31 :          SELECT CASE (bs_env%gw_implementation)
    1246              :          CASE (ri_rs_small_cell_full_kp)
    1247            7 :             WRITE (u, '(T2,A,T71,3I4)') "K-point mesh for χ, ε, W", nkp_grid
    1248              :          CASE DEFAULT
    1249           17 :             WRITE (u, FMT="(T2,1A,T71,3I4)") "K-point mesh 1 for χ, ε, W", nkp_grid(1:3)
    1250           17 :             WRITE (u, FMT="(T2,2A,T71,3I4)") "K-point mesh 2 for χ, ε, W ", &
    1251           34 :                "(for k-point extrapolation of W)", nkp_grid_extra(1:3)
    1252           17 :             WRITE (u, FMT="(T2,A,T80,L)") "Approximate the k-point extrapolation", &
    1253           58 :                bs_env%approx_kp_extrapol
    1254              :          END SELECT
    1255              :       END IF
    1256              : 
    1257          156 :       CALL timestop(handle)
    1258              : 
    1259          156 :    END SUBROUTINE setup_kpoints_chi_eps_W
    1260              : 
    1261              : ! **************************************************************************************************
    1262              : !> \brief ...
    1263              : !> \param xkp ...
    1264              : !> \param ikp_start ...
    1265              : !> \param ikp_end ...
    1266              : !> \param grid ...
    1267              : ! **************************************************************************************************
    1268          284 :    SUBROUTINE compute_xkp(xkp, ikp_start, ikp_end, grid)
    1269              : 
    1270              :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: xkp
    1271              :       INTEGER                                            :: ikp_start, ikp_end
    1272              :       INTEGER, DIMENSION(3)                              :: grid
    1273              : 
    1274              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_xkp'
    1275              : 
    1276              :       INTEGER                                            :: handle, i, ix, iy, iz
    1277              : 
    1278          284 :       CALL timeset(routineN, handle)
    1279              : 
    1280          284 :       i = ikp_start
    1281          720 :       DO ix = 1, grid(1)
    1282         4676 :          DO iy = 1, grid(2)
    1283        26120 :             DO iz = 1, grid(3)
    1284              : 
    1285        21728 :                IF (i > ikp_end) CYCLE
    1286              : 
    1287        10864 :                xkp(1, i) = REAL(2*ix - grid(1) - 1, KIND=dp)/(2._dp*REAL(grid(1), KIND=dp))
    1288        10864 :                xkp(2, i) = REAL(2*iy - grid(2) - 1, KIND=dp)/(2._dp*REAL(grid(2), KIND=dp))
    1289        10864 :                xkp(3, i) = REAL(2*iz - grid(3) - 1, KIND=dp)/(2._dp*REAL(grid(3), KIND=dp))
    1290        25684 :                i = i + 1
    1291              : 
    1292              :             END DO
    1293              :          END DO
    1294              :       END DO
    1295              : 
    1296          284 :       CALL timestop(handle)
    1297              : 
    1298          284 :    END SUBROUTINE compute_xkp
    1299              : 
    1300              : ! **************************************************************************************************
    1301              : !> \brief ...
    1302              : !> \param wkp ...
    1303              : !> \param nkp_1 ...
    1304              : !> \param nkp_2 ...
    1305              : !> \param exponent ...
    1306              : ! **************************************************************************************************
    1307           72 :    SUBROUTINE compute_wkp(wkp, nkp_1, nkp_2, exponent)
    1308              :       REAL(KIND=dp), DIMENSION(:)                        :: wkp
    1309              :       INTEGER                                            :: nkp_1, nkp_2
    1310              :       REAL(KIND=dp)                                      :: exponent
    1311              : 
    1312              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_wkp'
    1313              : 
    1314              :       INTEGER                                            :: handle
    1315              :       REAL(KIND=dp)                                      :: nkp_ratio
    1316              : 
    1317           72 :       CALL timeset(routineN, handle)
    1318              : 
    1319           72 :       nkp_ratio = REAL(nkp_2, KIND=dp)/REAL(nkp_1, KIND=dp)
    1320              : 
    1321        10900 :       wkp(:) = 1.0_dp/REAL(nkp_1, KIND=dp)/(1.0_dp - nkp_ratio**exponent)
    1322              : 
    1323           72 :       CALL timestop(handle)
    1324              : 
    1325           72 :    END SUBROUTINE compute_wkp
    1326              : 
    1327              : ! **************************************************************************************************
    1328              : !> \brief ...
    1329              : !> \param qs_env ...
    1330              : !> \param bs_env ...
    1331              : ! **************************************************************************************************
    1332           30 :    SUBROUTINE setup_cells_3c(qs_env, bs_env)
    1333              : 
    1334              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1335              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1336              : 
    1337              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'setup_cells_3c'
    1338              : 
    1339              :       INTEGER :: atom_i, atom_j, atom_k, block_count, handle, i, i_cell_x, i_cell_x_max, &
    1340              :          i_cell_x_min, i_size, ikind, img, j, j_cell, j_cell_max, j_cell_y, j_cell_y_max, &
    1341              :          j_cell_y_min, j_size, k_cell, k_cell_max, k_cell_z, k_cell_z_max, k_cell_z_min, k_size, &
    1342              :          nimage_pairs_3c, nimages_3c, nimages_3c_max, nkind, u
    1343           30 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: kind_of, n_other_3c_images_max
    1344           30 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: index_to_cell_3c_max, nblocks_3c_max
    1345              :       INTEGER, DIMENSION(3)                              :: cell_index, n_max
    1346              :       REAL(KIND=dp) :: avail_mem_per_proc_GB, cell_dist, cell_radius_3c, dij, dik, djk, eps, &
    1347              :          exp_min_ao, exp_min_RI, frobenius_norm, mem_3c_GB, mem_occ_per_proc_GB, radius_ao, &
    1348              :          radius_ao_product, radius_RI
    1349           30 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: exp_ao_kind, exp_RI_kind, &
    1350           30 :                                                             radius_ao_kind, &
    1351           30 :                                                             radius_ao_product_kind, radius_RI_kind
    1352           30 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: int_3c
    1353              :       REAL(KIND=dp), DIMENSION(3)                        :: rij, rik, rjk, vec_cell_j, vec_cell_k
    1354           30 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: exp_ao, exp_RI
    1355           30 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1356              :       TYPE(cell_type), POINTER                           :: cell
    1357           30 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1358              : 
    1359           30 :       CALL timeset(routineN, handle)
    1360              : 
    1361           30 :       CALL get_qs_env(qs_env, nkind=nkind, atomic_kind_set=atomic_kind_set, particle_set=particle_set, cell=cell)
    1362              : 
    1363              :       ALLOCATE (exp_ao_kind(nkind), exp_RI_kind(nkind), radius_ao_kind(nkind), &
    1364          210 :                 radius_ao_product_kind(nkind), radius_RI_kind(nkind))
    1365              : 
    1366           76 :       exp_min_RI = 10.0_dp
    1367           76 :       exp_min_ao = 10.0_dp
    1368           76 :       exp_RI_kind = 10.0_dp
    1369           76 :       exp_AO_kind = 10.0_dp
    1370              : 
    1371           30 :       eps = bs_env%eps_filter*bs_env%heuristic_filter_factor
    1372              : 
    1373           76 :       DO ikind = 1, nkind
    1374              : 
    1375           46 :          CALL get_gto_basis_set(bs_env%basis_set_RI(ikind)%gto_basis_set, zet=exp_RI)
    1376           46 :          CALL get_gto_basis_set(bs_env%basis_set_ao(ikind)%gto_basis_set, zet=exp_ao)
    1377              : 
    1378              :          ! we need to remove all exponents lower than a lower bound, e.g. 1E-3, because
    1379              :          ! for contracted basis sets, there might be exponents = 0 in zet
    1380          168 :          DO i = 1, SIZE(exp_RI, 1)
    1381          348 :             DO j = 1, SIZE(exp_RI, 2)
    1382          180 :                IF (exp_RI(i, j) < exp_min_RI .AND. exp_RI(i, j) > 1E-3_dp) exp_min_RI = exp_RI(i, j)
    1383          302 :                IF (exp_RI(i, j) < exp_RI_kind(ikind) .AND. exp_RI(i, j) > 1E-3_dp) THEN
    1384           58 :                   exp_RI_kind(ikind) = exp_RI(i, j)
    1385              :                END IF
    1386              :             END DO
    1387              :          END DO
    1388          222 :          DO i = 1, SIZE(exp_ao, 1)
    1389          494 :             DO j = 1, SIZE(exp_ao, 2)
    1390          272 :                IF (exp_ao(i, j) < exp_min_ao .AND. exp_ao(i, j) > 1E-3_dp) exp_min_ao = exp_ao(i, j)
    1391          448 :                IF (exp_ao(i, j) < exp_ao_kind(ikind) .AND. exp_ao(i, j) > 1E-3_dp) THEN
    1392          128 :                   exp_ao_kind(ikind) = exp_ao(i, j)
    1393              :                END IF
    1394              :             END DO
    1395              :          END DO
    1396           46 :          radius_ao_kind(ikind) = SQRT(-LOG(eps)/exp_ao_kind(ikind))
    1397           46 :          radius_ao_product_kind(ikind) = SQRT(-LOG(eps)/(2.0_dp*exp_ao_kind(ikind)))
    1398           76 :          radius_RI_kind(ikind) = SQRT(-LOG(eps)/exp_RI_kind(ikind))
    1399              :       END DO
    1400              : 
    1401           30 :       radius_ao = SQRT(-LOG(eps)/exp_min_ao)
    1402           30 :       radius_ao_product = SQRT(-LOG(eps)/(2.0_dp*exp_min_ao))
    1403           30 :       radius_RI = SQRT(-LOG(eps)/exp_min_RI)
    1404              : 
    1405           30 :       CALL get_atomic_kind_set(atomic_kind_set=atomic_kind_set, kind_of=kind_of)
    1406              : 
    1407              :       ! For a 3c integral (μR υS | P0) we have that cell R and cell S need to be within radius_3c
    1408           30 :       cell_radius_3c = radius_ao_product + radius_RI + bs_env%ri_metric%cutoff_radius
    1409              : 
    1410          120 :       n_max(1:3) = bs_env%periodic(1:3)*30
    1411              : 
    1412           30 :       nimages_3c_max = 0
    1413              : 
    1414           30 :       i_cell_x_min = 0
    1415           30 :       i_cell_x_max = 0
    1416           30 :       j_cell_y_min = 0
    1417           30 :       j_cell_y_max = 0
    1418           30 :       k_cell_z_min = 0
    1419           30 :       k_cell_z_max = 0
    1420              : 
    1421         1020 :       DO i_cell_x = -n_max(1), n_max(1)
    1422        61410 :          DO j_cell_y = -n_max(2), n_max(2)
    1423      1959090 :             DO k_cell_z = -n_max(3), n_max(3)
    1424              : 
    1425      7590840 :                cell_index(1:3) = [i_cell_x, j_cell_y, k_cell_z]
    1426              : 
    1427      1897710 :                CALL get_cell_dist(cell_index, bs_env%hmat, cell_dist)
    1428              : 
    1429      1958100 :                IF (cell_dist < cell_radius_3c) THEN
    1430         7330 :                   nimages_3c_max = nimages_3c_max + 1
    1431         7330 :                   i_cell_x_min = MIN(i_cell_x_min, i_cell_x)
    1432         7330 :                   i_cell_x_max = MAX(i_cell_x_max, i_cell_x)
    1433         7330 :                   j_cell_y_min = MIN(j_cell_y_min, j_cell_y)
    1434         7330 :                   j_cell_y_max = MAX(j_cell_y_max, j_cell_y)
    1435         7330 :                   k_cell_z_min = MIN(k_cell_z_min, k_cell_z)
    1436         7330 :                   k_cell_z_max = MAX(k_cell_z_max, k_cell_z)
    1437              :                END IF
    1438              : 
    1439              :             END DO
    1440              :          END DO
    1441              :       END DO
    1442              : 
    1443              :       ! get index_to_cell_3c_max for the maximum possible cell range;
    1444              :       ! compute 3c integrals later in this routine and check really which cell is needed
    1445           90 :       ALLOCATE (index_to_cell_3c_max(3, nimages_3c_max))
    1446              : 
    1447           30 :       img = 0
    1448         1020 :       DO i_cell_x = -n_max(1), n_max(1)
    1449        61410 :          DO j_cell_y = -n_max(2), n_max(2)
    1450      1959090 :             DO k_cell_z = -n_max(3), n_max(3)
    1451              : 
    1452      7590840 :                cell_index(1:3) = [i_cell_x, j_cell_y, k_cell_z]
    1453              : 
    1454      1897710 :                CALL get_cell_dist(cell_index, bs_env%hmat, cell_dist)
    1455              : 
    1456      1958100 :                IF (cell_dist < cell_radius_3c) THEN
    1457         7330 :                   img = img + 1
    1458        29320 :                   index_to_cell_3c_max(1:3, img) = cell_index(1:3)
    1459              :                END IF
    1460              : 
    1461              :             END DO
    1462              :          END DO
    1463              :       END DO
    1464              : 
    1465              :       ! get pairs of R and S which have non-zero 3c integral (μR υS | P0)
    1466          120 :       ALLOCATE (nblocks_3c_max(nimages_3c_max, nimages_3c_max))
    1467           30 :       nblocks_3c_max(:, :) = 0
    1468              : 
    1469           30 :       block_count = 0
    1470         7360 :       DO j_cell = 1, nimages_3c_max
    1471      4790270 :          DO k_cell = 1, nimages_3c_max
    1472              : 
    1473     14364810 :             DO atom_j = 1, bs_env%n_atom
    1474     33532870 :             DO atom_k = 1, bs_env%n_atom
    1475     67179490 :             DO atom_i = 1, bs_env%n_atom
    1476              : 
    1477     38429530 :                block_count = block_count + 1
    1478     38429530 :                IF (MODULO(block_count, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    1479              : 
    1480     76859060 :                CALL scaled_to_real(vec_cell_j, REAL(index_to_cell_3c_max(1:3, j_cell), kind=dp), cell)
    1481     76859060 :                CALL scaled_to_real(vec_cell_k, REAL(index_to_cell_3c_max(1:3, k_cell), kind=dp), cell)
    1482              : 
    1483     76859060 :                rij = pbc(particle_set(atom_j)%r(:), cell) - pbc(particle_set(atom_i)%r(:), cell) + vec_cell_j(:)
    1484              :                rjk = pbc(particle_set(atom_k)%r(:), cell) - pbc(particle_set(atom_j)%r(:), cell) &
    1485     76859060 :                      + vec_cell_k(:) - vec_cell_j(:)
    1486     76859060 :                rik(:) = rij(:) + rjk(:)
    1487     76859060 :                dij = NORM2(rij)
    1488     76859060 :                dik = NORM2(rik)
    1489     76859060 :                djk = NORM2(rjk)
    1490     19214765 :                IF (djk > radius_ao_kind(kind_of(atom_j)) + radius_ao_kind(kind_of(atom_k))) CYCLE
    1491      1296471 :                IF (dij > radius_ao_kind(kind_of(atom_j)) + radius_RI_kind(kind_of(atom_i)) &
    1492              :                    + bs_env%ri_metric%cutoff_radius) CYCLE
    1493       862533 :                IF (dik > radius_RI_kind(kind_of(atom_i)) + radius_ao_kind(kind_of(atom_k)) &
    1494              :                    + bs_env%ri_metric%cutoff_radius) CYCLE
    1495              : 
    1496       672634 :                IF (bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
    1497              :                   ! RI-RS forms its integrals later; only geometric cell support is needed here.
    1498       659812 :                   nblocks_3c_max(j_cell, k_cell) = nblocks_3c_max(j_cell, k_cell) + 1
    1499       659812 :                   CYCLE
    1500              :                END IF
    1501              : 
    1502        12822 :                j_size = bs_env%i_ao_end_from_atom(atom_j) - bs_env%i_ao_start_from_atom(atom_j) + 1
    1503        12822 :                k_size = bs_env%i_ao_end_from_atom(atom_k) - bs_env%i_ao_start_from_atom(atom_k) + 1
    1504        12822 :                i_size = bs_env%i_RI_end_from_atom(atom_i) - bs_env%i_RI_start_from_atom(atom_i) + 1
    1505              : 
    1506        64110 :                ALLOCATE (int_3c(j_size, k_size, i_size))
    1507              : 
    1508              :                ! compute 3-c int. ( μ(atom j) R , ν (atom k) S | P (atom i) 0 )
    1509              :                ! ("|": truncated Coulomb operator), inside build_3c_integrals: (j k | i)
    1510              :                CALL build_3c_integral_block(int_3c, qs_env, bs_env%ri_metric, &
    1511              :                                             basis_j=bs_env%basis_set_AO, &
    1512              :                                             basis_k=bs_env%basis_set_AO, &
    1513              :                                             basis_i=bs_env%basis_set_RI, &
    1514              :                                             cell_j=index_to_cell_3c_max(1:3, j_cell), &
    1515              :                                             cell_k=index_to_cell_3c_max(1:3, k_cell), &
    1516        12822 :                                             atom_k=atom_k, atom_j=atom_j, atom_i=atom_i)
    1517              : 
    1518       678851 :                frobenius_norm = NORM2(int_3c)
    1519              : 
    1520        12822 :                DEALLOCATE (int_3c)
    1521              : 
    1522              :                ! we use a higher threshold here to safe memory when storing the 3c integrals
    1523              :                ! in every tensor group
    1524     19188212 :                IF (frobenius_norm > eps) THEN
    1525         2720 :                   nblocks_3c_max(j_cell, k_cell) = nblocks_3c_max(j_cell, k_cell) + 1
    1526              :                END IF
    1527              : 
    1528              :             END DO
    1529              :             END DO
    1530              :             END DO
    1531              : 
    1532              :          END DO
    1533              :       END DO
    1534              : 
    1535           30 :       CALL bs_env%para_env%sum(nblocks_3c_max)
    1536              : 
    1537           90 :       ALLOCATE (n_other_3c_images_max(nimages_3c_max))
    1538           30 :       n_other_3c_images_max(:) = 0
    1539              : 
    1540           30 :       nimages_3c = 0
    1541           30 :       nimage_pairs_3c = 0
    1542              : 
    1543         7360 :       DO j_cell = 1, nimages_3c_max
    1544      4790240 :          DO k_cell = 1, nimages_3c_max
    1545      4790240 :             IF (nblocks_3c_max(j_cell, k_cell) > 0) THEN
    1546       230838 :                n_other_3c_images_max(j_cell) = n_other_3c_images_max(j_cell) + 1
    1547       230838 :                nimage_pairs_3c = nimage_pairs_3c + 1
    1548              :             END IF
    1549              :          END DO
    1550              : 
    1551         7360 :          IF (n_other_3c_images_max(j_cell) > 0) nimages_3c = nimages_3c + 1
    1552              : 
    1553              :       END DO
    1554              : 
    1555           30 :       bs_env%nimages_3c = nimages_3c
    1556           90 :       ALLOCATE (bs_env%index_to_cell_3c(3, nimages_3c))
    1557              :       ALLOCATE (bs_env%cell_to_index_3c(i_cell_x_min:i_cell_x_max, &
    1558              :                                         j_cell_y_min:j_cell_y_max, &
    1559          150 :                                         k_cell_z_min:k_cell_z_max))
    1560        13664 :       bs_env%cell_to_index_3c(:, :, :) = -1
    1561              : 
    1562          120 :       ALLOCATE (bs_env%nblocks_3c(nimages_3c, nimages_3c))
    1563           30 :       bs_env%nblocks_3c(nimages_3c, nimages_3c) = 0
    1564              : 
    1565           30 :       j_cell = 0
    1566         7360 :       DO j_cell_max = 1, nimages_3c_max
    1567         7330 :          IF (n_other_3c_images_max(j_cell_max) == 0) CYCLE
    1568         4528 :          j_cell = j_cell + 1
    1569        18112 :          cell_index(1:3) = index_to_cell_3c_max(1:3, j_cell_max)
    1570        18112 :          bs_env%index_to_cell_3c(1:3, j_cell) = cell_index(1:3)
    1571         4528 :          bs_env%cell_to_index_3c(cell_index(1), cell_index(2), cell_index(3)) = j_cell
    1572              : 
    1573         4528 :          k_cell = 0
    1574      2874994 :          DO k_cell_max = 1, nimages_3c_max
    1575      2870436 :             IF (n_other_3c_images_max(k_cell_max) == 0) CYCLE
    1576      1731584 :             k_cell = k_cell + 1
    1577              : 
    1578      2877766 :             bs_env%nblocks_3c(j_cell, k_cell) = nblocks_3c_max(j_cell_max, k_cell_max)
    1579              :          END DO
    1580              : 
    1581              :       END DO
    1582              : 
    1583              :       ! we use: 8*10^-9 GB / double precision number
    1584              :       mem_3c_GB = REAL(bs_env%n_RI, KIND=dp)*REAL(bs_env%n_ao, KIND=dp)**2 &
    1585           30 :                   *REAL(nimage_pairs_3c, KIND=dp)*8E-9_dp
    1586              : 
    1587           30 :       CALL mp_mem_used_per_rank_GB(bs_env%para_env, mem_occ_per_proc_GB)
    1588              : 
    1589              :       ! number of processors per group that entirely stores the 3c integrals and does tensor ops
    1590           30 :       avail_mem_per_proc_GB = bs_env%input_memory_per_proc_GB - mem_occ_per_proc_GB
    1591              : 
    1592              :       ! careful: downconvering real to integer, 1.9 -> 1; thus add 1.0 for upconversion, 1.9 -> 2
    1593           30 :       bs_env%group_size_tensor = MAX(INT(mem_3c_GB/avail_mem_per_proc_GB + 1.0_dp), 1)
    1594              : 
    1595           30 :       u = bs_env%unit_nr
    1596              : 
    1597           30 :       IF (u > 0) THEN
    1598           15 :          WRITE (u, FMT="(T2,A,F52.1,A)") "Radius of atomic orbitals", radius_ao*angstrom, " Å"
    1599           15 :          WRITE (u, FMT="(T2,A,F55.1,A)") "Radius of RI functions", radius_RI*angstrom, " Å"
    1600           15 :          WRITE (u, FMT="(T2,A,I47)") "Number of cells for 3c integrals", nimages_3c
    1601           15 :          WRITE (u, FMT="(T2,A,I42)") "Number of cell pairs for 3c integrals", nimage_pairs_3c
    1602           15 :          WRITE (u, '(T2,A)') ''
    1603           15 :          IF (bs_env%auto_memory_per_proc) THEN
    1604           15 :             WRITE (u, '(T2,A,F34.1,A)') 'Detected: Available memory per MPI process', &
    1605           30 :                bs_env%input_memory_per_proc_GB, ' GB'
    1606              :          ELSE
    1607            0 :             WRITE (u, '(T2,A,F37.1,A)') 'Input: Available memory per MPI process', &
    1608            0 :                bs_env%input_memory_per_proc_GB, ' GB'
    1609              :          END IF
    1610           15 :          WRITE (u, '(T2,A,F35.1,A)') 'Used memory per MPI process before GW run', &
    1611           30 :             mem_occ_per_proc_GB, ' GB'
    1612           15 :          WRITE (u, '(T2,A,F44.1,A)') 'Memory of three-center integrals', mem_3c_GB, ' GB'
    1613              :       END IF
    1614              : 
    1615           30 :       CALL timestop(handle)
    1616              : 
    1617           60 :    END SUBROUTINE setup_cells_3c
    1618              : 
    1619              : ! **************************************************************************************************
    1620              : !> \brief ...
    1621              : !> \param cell_index ...
    1622              : !> \param hmat ...
    1623              : !> \param cell_dist ...
    1624              : ! **************************************************************************************************
    1625      3795420 :    SUBROUTINE get_cell_dist(cell_index, hmat, cell_dist)
    1626              : 
    1627              :       INTEGER, DIMENSION(3)                              :: cell_index
    1628              :       REAL(KIND=dp)                                      :: hmat(3, 3), cell_dist
    1629              : 
    1630              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_cell_dist'
    1631              : 
    1632              :       INTEGER                                            :: handle, i_dim
    1633              :       INTEGER, DIMENSION(3)                              :: cell_index_adj
    1634              :       REAL(KIND=dp)                                      :: cell_dist_3(3)
    1635              : 
    1636      3795420 :       CALL timeset(routineN, handle)
    1637              : 
    1638              :       ! the distance of cells needs to be taken to adjacent neighbors, not
    1639              :       ! between the center of the cells. We thus need to rescale the cell index
    1640     15181680 :       DO i_dim = 1, 3
    1641     11386260 :          IF (cell_index(i_dim) > 0) cell_index_adj(i_dim) = cell_index(i_dim) - 1
    1642     11386260 :          IF (cell_index(i_dim) < 0) cell_index_adj(i_dim) = cell_index(i_dim) + 1
    1643     15181680 :          IF (cell_index(i_dim) == 0) cell_index_adj(i_dim) = cell_index(i_dim)
    1644              :       END DO
    1645              : 
    1646     60726720 :       cell_dist_3(1:3) = MATMUL(hmat, REAL(cell_index_adj, KIND=dp))
    1647              : 
    1648     15181680 :       cell_dist = NORM2(cell_dist_3)
    1649              : 
    1650      3795420 :       CALL timestop(handle)
    1651              : 
    1652      3795420 :    END SUBROUTINE get_cell_dist
    1653              : 
    1654              : ! **************************************************************************************************
    1655              : !> \brief ...
    1656              : !> \param qs_env ...
    1657              : !> \param bs_env ...
    1658              : ! **************************************************************************************************
    1659          156 :    SUBROUTINE set_parallelization_parameters(qs_env, bs_env)
    1660              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1661              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1662              : 
    1663              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_parallelization_parameters'
    1664              : 
    1665              :       INTEGER                                            :: color_sub, dummy_1, dummy_2, handle, &
    1666              :                                                             num_pe, num_t_groups, u
    1667              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1668              : 
    1669          156 :       CALL timeset(routineN, handle)
    1670              : 
    1671          156 :       CALL get_qs_env(qs_env, para_env=para_env)
    1672              : 
    1673          156 :       num_pe = para_env%num_pe
    1674              :       ! if not already set, use all processors for the group (for large-cell GW, performance
    1675              :       ! seems to be best for a single group with all MPI processes per group)
    1676          156 :       IF (bs_env%group_size_tensor < 0 .OR. bs_env%group_size_tensor > num_pe) THEN
    1677          126 :          bs_env%group_size_tensor = num_pe
    1678              :       END IF
    1679              : 
    1680              :       ! group_size_tensor must divide num_pe without rest; otherwise everything will be complicated
    1681          156 :       IF (MODULO(num_pe, bs_env%group_size_tensor) /= 0) THEN
    1682            0 :          CALL find_good_group_size(num_pe, bs_env%group_size_tensor)
    1683              :       END IF
    1684              : 
    1685              :       ! para_env_tensor for tensor subgroups
    1686          156 :       color_sub = para_env%mepos/bs_env%group_size_tensor
    1687          156 :       bs_env%tensor_group_color = color_sub
    1688              : 
    1689          156 :       ALLOCATE (bs_env%para_env_tensor)
    1690          156 :       CALL bs_env%para_env_tensor%from_split(para_env, color_sub)
    1691              : 
    1692          156 :       num_t_groups = para_env%num_pe/bs_env%group_size_tensor
    1693          156 :       bs_env%num_tensor_groups = num_t_groups
    1694              : 
    1695              :       CALL get_i_j_atoms(bs_env%atoms_i, bs_env%atoms_j, bs_env%n_atom_i, bs_env%n_atom_j, &
    1696          156 :                          color_sub, bs_env)
    1697              : 
    1698          468 :       ALLOCATE (bs_env%atoms_i_t_group(2, num_t_groups))
    1699          312 :       ALLOCATE (bs_env%atoms_j_t_group(2, num_t_groups))
    1700          342 :       DO color_sub = 0, num_t_groups - 1
    1701              :          CALL get_i_j_atoms(bs_env%atoms_i_t_group(1:2, color_sub + 1), &
    1702              :                             bs_env%atoms_j_t_group(1:2, color_sub + 1), &
    1703          342 :                             dummy_1, dummy_2, color_sub, bs_env)
    1704              :       END DO
    1705              : 
    1706          156 :       u = bs_env%unit_nr
    1707          156 :       IF (u > 0 .AND. .NOT. bs_env%do_gw_ri_rs) THEN
    1708           50 :          WRITE (u, '(T2,A,I47)') 'Group size for tensor operations', bs_env%group_size_tensor
    1709           50 :          IF (bs_env%group_size_tensor > 1 .AND. bs_env%n_atom < 5) THEN
    1710           42 :             WRITE (u, '(T2,A)') 'The requested group size is > 1 which can lead to bad performance.'
    1711           42 :             WRITE (u, '(T2,A)') 'Using more memory per MPI process might improve performance.'
    1712           42 :             WRITE (u, '(T2,A)') '(Also increase MEMORY_PER_PROC when using more memory per process.)'
    1713              :          END IF
    1714              :       END IF
    1715              : 
    1716          156 :       CALL timestop(handle)
    1717              : 
    1718          156 :    END SUBROUTINE set_parallelization_parameters
    1719              : 
    1720              : ! **************************************************************************************************
    1721              : !> \brief ...
    1722              : !> \param num_pe ...
    1723              : !> \param group_size ...
    1724              : ! **************************************************************************************************
    1725            0 :    SUBROUTINE find_good_group_size(num_pe, group_size)
    1726              : 
    1727              :       INTEGER                                            :: num_pe, group_size
    1728              : 
    1729              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'find_good_group_size'
    1730              : 
    1731              :       INTEGER                                            :: group_size_minus, group_size_orig, &
    1732              :                                                             group_size_plus, handle, i_diff
    1733              : 
    1734            0 :       CALL timeset(routineN, handle)
    1735              : 
    1736            0 :       group_size_orig = group_size
    1737              : 
    1738            0 :       DO i_diff = 1, num_pe
    1739              : 
    1740            0 :          group_size_minus = group_size - i_diff
    1741              : 
    1742            0 :          IF (MODULO(num_pe, group_size_minus) == 0 .AND. group_size_minus > 0) THEN
    1743            0 :             group_size = group_size_minus
    1744            0 :             EXIT
    1745              :          END IF
    1746              : 
    1747            0 :          group_size_plus = group_size + i_diff
    1748              : 
    1749            0 :          IF (MODULO(num_pe, group_size_plus) == 0 .AND. group_size_plus <= num_pe) THEN
    1750            0 :             group_size = group_size_plus
    1751            0 :             EXIT
    1752              :          END IF
    1753              : 
    1754              :       END DO
    1755              : 
    1756            0 :       IF (group_size_orig == group_size) CPABORT("Group size error")
    1757              : 
    1758            0 :       CALL timestop(handle)
    1759              : 
    1760            0 :    END SUBROUTINE find_good_group_size
    1761              : 
    1762              : ! **************************************************************************************************
    1763              : !> \brief ...
    1764              : !> \param atoms_i ...
    1765              : !> \param atoms_j ...
    1766              : !> \param n_atom_i ...
    1767              : !> \param n_atom_j ...
    1768              : !> \param color_sub ...
    1769              : !> \param bs_env ...
    1770              : ! **************************************************************************************************
    1771          342 :    SUBROUTINE get_i_j_atoms(atoms_i, atoms_j, n_atom_i, n_atom_j, color_sub, bs_env)
    1772              : 
    1773              :       INTEGER, DIMENSION(2)                              :: atoms_i, atoms_j
    1774              :       INTEGER                                            :: n_atom_i, n_atom_j, color_sub
    1775              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1776              : 
    1777              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_i_j_atoms'
    1778              : 
    1779              :       INTEGER                                            :: handle, i_atoms_per_group, i_group, &
    1780              :                                                             ipcol, ipcol_loop, iprow, iprow_loop, &
    1781              :                                                             j_atoms_per_group, npcol, nprow
    1782              : 
    1783          342 :       CALL timeset(routineN, handle)
    1784              : 
    1785              :       ! create a square mesh of tensor groups for iatom and jatom; code from blacs_env_create
    1786          342 :       CALL square_mesh(nprow, npcol, bs_env%num_tensor_groups)
    1787              : 
    1788          342 :       i_group = 0
    1789          684 :       DO ipcol_loop = 0, npcol - 1
    1790         1116 :          DO iprow_loop = 0, nprow - 1
    1791          432 :             IF (i_group == color_sub) THEN
    1792          342 :                iprow = iprow_loop
    1793          342 :                ipcol = ipcol_loop
    1794              :             END IF
    1795          774 :             i_group = i_group + 1
    1796              :          END DO
    1797              :       END DO
    1798              : 
    1799          342 :       IF (MODULO(bs_env%n_atom, nprow) == 0) THEN
    1800          300 :          i_atoms_per_group = bs_env%n_atom/nprow
    1801              :       ELSE
    1802           42 :          i_atoms_per_group = bs_env%n_atom/nprow + 1
    1803              :       END IF
    1804              : 
    1805          342 :       IF (MODULO(bs_env%n_atom, npcol) == 0) THEN
    1806          342 :          j_atoms_per_group = bs_env%n_atom/npcol
    1807              :       ELSE
    1808            0 :          j_atoms_per_group = bs_env%n_atom/npcol + 1
    1809              :       END IF
    1810              : 
    1811          342 :       atoms_i(1) = iprow*i_atoms_per_group + 1
    1812          342 :       atoms_i(2) = MIN((iprow + 1)*i_atoms_per_group, bs_env%n_atom)
    1813          342 :       n_atom_i = atoms_i(2) - atoms_i(1) + 1
    1814              : 
    1815          342 :       atoms_j(1) = ipcol*j_atoms_per_group + 1
    1816          342 :       atoms_j(2) = MIN((ipcol + 1)*j_atoms_per_group, bs_env%n_atom)
    1817          342 :       n_atom_j = atoms_j(2) - atoms_j(1) + 1
    1818              : 
    1819          342 :       CALL timestop(handle)
    1820              : 
    1821          342 :    END SUBROUTINE get_i_j_atoms
    1822              : 
    1823              : ! **************************************************************************************************
    1824              : !> \brief ...
    1825              : !> \param nprow ...
    1826              : !> \param npcol ...
    1827              : !> \param nproc ...
    1828              : ! **************************************************************************************************
    1829          342 :    SUBROUTINE square_mesh(nprow, npcol, nproc)
    1830              :       INTEGER                                            :: nprow, npcol, nproc
    1831              : 
    1832              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'square_mesh'
    1833              : 
    1834              :       INTEGER                                            :: gcd_max, handle, ipe, jpe
    1835              : 
    1836          342 :       CALL timeset(routineN, handle)
    1837              : 
    1838          342 :       gcd_max = -1
    1839          774 :       DO ipe = 1, CEILING(SQRT(REAL(nproc, dp)))
    1840          432 :          jpe = nproc/ipe
    1841          432 :          IF (ipe*jpe /= nproc) CYCLE
    1842          774 :          IF (gcd(ipe, jpe) >= gcd_max) THEN
    1843          432 :             nprow = ipe
    1844          432 :             npcol = jpe
    1845          432 :             gcd_max = gcd(ipe, jpe)
    1846              :          END IF
    1847              :       END DO
    1848              : 
    1849          342 :       CALL timestop(handle)
    1850              : 
    1851          342 :    END SUBROUTINE square_mesh
    1852              : 
    1853              : ! **************************************************************************************************
    1854              : !> \brief ...
    1855              : !> \param qs_env ...
    1856              : !> \param bs_env ...
    1857              : ! **************************************************************************************************
    1858          156 :    SUBROUTINE allocate_matrices(qs_env, bs_env)
    1859              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1860              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1861              : 
    1862              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'allocate_matrices'
    1863              : 
    1864              :       INTEGER                                            :: handle, i_t
    1865              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env, blacs_env_tensor
    1866              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct, fm_struct_RI_global
    1867              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1868              : 
    1869          156 :       CALL timeset(routineN, handle)
    1870              : 
    1871          156 :       CALL get_qs_env(qs_env, para_env=para_env, blacs_env=blacs_env)
    1872              : 
    1873          156 :       fm_struct => bs_env%fm_ks_Gamma(1)%matrix_struct
    1874              : 
    1875          156 :       CALL cp_fm_create(bs_env%fm_Gocc, fm_struct)
    1876          156 :       CALL cp_fm_create(bs_env%fm_Gvir, fm_struct)
    1877              : 
    1878          156 :       NULLIFY (fm_struct_RI_global)
    1879              :       CALL cp_fm_struct_create(fm_struct_RI_global, context=blacs_env, nrow_global=bs_env%n_RI, &
    1880          156 :                                ncol_global=bs_env%n_RI, para_env=para_env)
    1881          156 :       CALL cp_fm_create(bs_env%fm_RI_RI, fm_struct_RI_global)
    1882          156 :       CALL cp_fm_create(bs_env%fm_chi_Gamma_freq, fm_struct_RI_global)
    1883          156 :       CALL cp_fm_create(bs_env%fm_W_MIC_freq, fm_struct_RI_global)
    1884          156 :       IF (bs_env%approx_kp_extrapol) THEN
    1885            2 :          CALL cp_fm_create(bs_env%fm_W_MIC_freq_1_extra, fm_struct_RI_global)
    1886            2 :          CALL cp_fm_create(bs_env%fm_W_MIC_freq_1_no_extra, fm_struct_RI_global)
    1887            2 :          CALL cp_fm_set_all(bs_env%fm_W_MIC_freq_1_extra, 0.0_dp)
    1888            2 :          CALL cp_fm_set_all(bs_env%fm_W_MIC_freq_1_no_extra, 0.0_dp)
    1889              :       END IF
    1890          156 :       CALL cp_fm_struct_release(fm_struct_RI_global)
    1891              : 
    1892          156 :       IF (.NOT. bs_env%do_gw_ri_rs) THEN
    1893              :          ! create blacs_env for subgroups of tensor operations
    1894          100 :          NULLIFY (blacs_env_tensor)
    1895          100 :          CALL cp_blacs_env_create(blacs_env=blacs_env_tensor, para_env=bs_env%para_env_tensor)
    1896              : 
    1897              :          ! allocate dbcsr matrices in the tensor subgroup; actually, one only needs a small
    1898              :          ! subset of blocks in the tensor subgroup, however, all atomic blocks are allocated.
    1899              :          ! One might think of creating a dbcsr matrix with only the blocks that are needed
    1900              :          ! in the tensor subgroup
    1901              :          CALL create_mat_munu(bs_env%mat_ao_ao_tensor, qs_env, bs_env%eps_atom_grid_2d_mat, &
    1902          100 :                               blacs_env_tensor, do_ri_aux_basis=.FALSE.)
    1903              : 
    1904              :          CALL create_mat_munu(bs_env%mat_RI_RI_tensor, qs_env, bs_env%eps_atom_grid_2d_mat, &
    1905          100 :                               blacs_env_tensor, do_ri_aux_basis=.TRUE.)
    1906              : 
    1907          100 :          CALL cp_blacs_env_release(blacs_env_tensor)
    1908              :       END IF
    1909              : 
    1910              :       CALL create_mat_munu(bs_env%mat_RI_RI, qs_env, bs_env%eps_atom_grid_2d_mat, &
    1911              :                            blacs_env, do_ri_aux_basis=.TRUE., &
    1912          156 :                            custom_row_blk_sizes=bs_env%sizes_RI)
    1913              : 
    1914          156 :       NULLIFY (bs_env%mat_chi_Gamma_tau)
    1915          156 :       CALL dbcsr_allocate_matrix_set(bs_env%mat_chi_Gamma_tau, bs_env%num_time_freq_points)
    1916              : 
    1917         2580 :       DO i_t = 1, bs_env%num_time_freq_points
    1918         2424 :          ALLOCATE (bs_env%mat_chi_Gamma_tau(i_t)%matrix)
    1919         2580 :          CALL dbcsr_create(bs_env%mat_chi_Gamma_tau(i_t)%matrix, template=bs_env%mat_RI_RI%matrix)
    1920              :       END DO
    1921              : 
    1922          156 :       CALL timestop(handle)
    1923              : 
    1924          156 :    END SUBROUTINE allocate_matrices
    1925              : 
    1926              : ! **************************************************************************************************
    1927              : !> \brief Computes and stores the inverse RI metric at the Γ point.
    1928              : !> \param qs_env ...
    1929              : !> \param bs_env ...
    1930              : ! **************************************************************************************************
    1931          126 :    SUBROUTINE compute_Minv_Gamma(qs_env, bs_env)
    1932              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1933              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1934              : 
    1935              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_Minv_Gamma'
    1936              : 
    1937              :       INTEGER                                            :: handle
    1938              :       REAL(KIND=dp)                                      :: eigenvalue_threshold, &
    1939              :                                                             metric_regularization
    1940          126 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :)     :: fm_M
    1941              : 
    1942          126 :       CALL timeset(routineN, handle)
    1943              : 
    1944          126 :       CALL cp_fm_create(bs_env%fm_Minv_Gamma, bs_env%fm_RI_RI%matrix_struct)
    1945          126 :       IF (bs_env%auto_ri%enabled) THEN
    1946            4 :          CPASSERT(bs_env%auto_ri%ready)
    1947            4 :          CALL cp_fm_to_fm(bs_env%auto_ri%M_pq_inv, bs_env%fm_Minv_Gamma)
    1948              :       ELSE
    1949          122 :          metric_regularization = 0.0_dp
    1950          122 :          eigenvalue_threshold = 0.0_dp
    1951          122 :          IF (bs_env%do_gw_ri_rs) THEN
    1952           38 :             metric_regularization = bs_env%regularization_RI
    1953           38 :             eigenvalue_threshold = bs_env%eps_eigval_mat_RI
    1954              :          END IF
    1955              :          CALL RI_2c_integral_mat(qs_env, fm_M, bs_env%fm_RI_RI%matrix_struct, bs_env%n_RI, &
    1956              :                                  bs_env%ri_metric, &
    1957          122 :                                  regularization_RI=metric_regularization)
    1958          122 :          CALL fm_invert(fm_M(1, 1), eigenvalue_threshold, bs_env%unit_nr)
    1959          122 :          CALL cp_fm_to_fm(fm_M(1, 1), bs_env%fm_Minv_Gamma)
    1960          122 :          CALL cp_fm_release(fm_M)
    1961              :       END IF
    1962              : 
    1963          126 :       CALL timestop(handle)
    1964              : 
    1965          126 :    END SUBROUTINE compute_Minv_Gamma
    1966              : 
    1967              : ! **************************************************************************************************
    1968              : !> \brief ...
    1969              : !> \param qs_env ...
    1970              : !> \param bs_env ...
    1971              : ! **************************************************************************************************
    1972          156 :    SUBROUTINE compute_V_xc(qs_env, bs_env)
    1973              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1974              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1975              : 
    1976              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_V_xc'
    1977              : 
    1978              :       INTEGER                                            :: handle, img, ispin, myfun, &
    1979              :                                                             myfun_admm_aux, myfun_admm_primary, &
    1980              :                                                             nimages
    1981              :       LOGICAL                                            :: admm_charge_constrain, hf_present
    1982              :       REAL(KIND=dp)                                      :: energy_ex, energy_exc, energy_total
    1983          156 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: hf_fraction
    1984              :       TYPE(admm_type), POINTER                           :: admm_env
    1985          156 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mat_ks_without_v_xc
    1986          156 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp
    1987              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1988          156 :       TYPE(hfx_type), DIMENSION(:, :), POINTER           :: x_data
    1989              :       TYPE(qs_energy_type), POINTER                      :: energy
    1990              :       TYPE(section_vals_type), POINTER                   :: hf_section, input, xc_fun_admm_aux, &
    1991              :                                                             xc_fun_admm_primary, xc_section
    1992              : 
    1993          156 :       CALL timeset(routineN, handle)
    1994              : 
    1995              :       CALL get_qs_env(qs_env, input=input, energy=energy, dft_control=dft_control, x_data=x_data, &
    1996          156 :                       admm_env=admm_env)
    1997              : 
    1998              :       ! previously, dft_control%nimages set to # neighbor cells, revert for Γ-only KS matrix
    1999          156 :       nimages = dft_control%nimages
    2000          156 :       dft_control%nimages = bs_env%nimages_scf
    2001              : 
    2002              :       ! we need to reset XC functional, therefore, get XC input
    2003          156 :       xc_section => section_vals_get_subs_vals(input, "DFT%XC")
    2004          156 :       CALL section_vals_val_get(xc_section, "XC_FUNCTIONAL%_SECTION_PARAMETERS_", i_val=myfun)
    2005          156 :       CALL section_vals_val_set(xc_section, "XC_FUNCTIONAL%_SECTION_PARAMETERS_", i_val=xc_none)
    2006          156 :       hf_section => section_vals_get_subs_vals(input, "DFT%XC%HF", can_return_null=.TRUE.)
    2007          156 :       hf_present = .FALSE.
    2008          156 :       IF (ASSOCIATED(hf_section)) THEN
    2009          156 :          CALL section_vals_get(hf_section, explicit=hf_present)
    2010              :       END IF
    2011              :       ! the KS build takes the HF fraction from x_data, not from the input section
    2012          156 :       IF (hf_present) THEN
    2013          272 :          ALLOCATE (hf_fraction(SIZE(x_data, 1), SIZE(x_data, 2)))
    2014          204 :          hf_fraction(:, :) = x_data(:, :)%general_parameter%fraction
    2015          204 :          x_data(:, :)%general_parameter%fraction = 0.0_dp
    2016              :       END IF
    2017              :       ! ADMM evaluates the XC functional with its own copies of the XC section
    2018          156 :       IF (dft_control%do_admm) THEN
    2019            4 :          xc_fun_admm_aux => section_vals_get_subs_vals(admm_env%xc_section_aux, "XC_FUNCTIONAL")
    2020            4 :          CALL section_vals_val_get(xc_fun_admm_aux, "_SECTION_PARAMETERS_", i_val=myfun_admm_aux)
    2021            4 :          CALL section_vals_val_set(xc_fun_admm_aux, "_SECTION_PARAMETERS_", i_val=xc_none)
    2022            4 :          xc_fun_admm_primary => section_vals_get_subs_vals(admm_env%xc_section_primary, "XC_FUNCTIONAL")
    2023            4 :          CALL section_vals_val_get(xc_fun_admm_primary, "_SECTION_PARAMETERS_", i_val=myfun_admm_primary)
    2024            4 :          CALL section_vals_val_set(xc_fun_admm_primary, "_SECTION_PARAMETERS_", i_val=xc_none)
    2025              :          ! ADMMQ/ADMMS charge constraint must not act on the KS matrix without XC
    2026            4 :          admm_charge_constrain = admm_env%charge_constrain
    2027            4 :          admm_env%charge_constrain = .FALSE.
    2028              :       END IF
    2029              : 
    2030              :       ! save the energy before the energy gets updated
    2031          156 :       energy_total = energy%total
    2032          156 :       energy_exc = energy%exc
    2033          156 :       energy_ex = energy%ex
    2034              : 
    2035          282 :       SELECT CASE (bs_env%gw_implementation)
    2036              :       CASE (tensor_large_cell_Gamma, ri_rs_large_cell_Gamma, ri_rs_non_periodic, tensor_static_cohsex)
    2037              : 
    2038          126 :          NULLIFY (mat_ks_without_v_xc)
    2039          126 :          CALL dbcsr_allocate_matrix_set(mat_ks_without_v_xc, bs_env%n_spin)
    2040              : 
    2041          270 :          DO ispin = 1, bs_env%n_spin
    2042          144 :             ALLOCATE (mat_ks_without_v_xc(ispin)%matrix)
    2043          270 :             IF (hf_present) THEN
    2044              :                CALL dbcsr_create(mat_ks_without_v_xc(ispin)%matrix, template=bs_env%mat_ao_ao%matrix, &
    2045           78 :                                  matrix_type=dbcsr_type_symmetric)
    2046              :             ELSE
    2047           66 :                CALL dbcsr_create(mat_ks_without_v_xc(ispin)%matrix, template=bs_env%mat_ao_ao%matrix)
    2048              :             END IF
    2049              :          END DO
    2050              : 
    2051              :          ! calculate KS-matrix without XC
    2052              :          CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., just_energy=.FALSE., &
    2053          126 :                                            ext_ks_matrix=mat_ks_without_v_xc)
    2054              : 
    2055          270 :          DO ispin = 1, bs_env%n_spin
    2056              :             ! transfer dbcsr matrix to fm
    2057          144 :             CALL cp_fm_create(bs_env%fm_V_xc_Gamma(ispin), bs_env%fm_s_Gamma%matrix_struct)
    2058          144 :             CALL copy_dbcsr_to_fm(mat_ks_without_v_xc(ispin)%matrix, bs_env%fm_V_xc_Gamma(ispin))
    2059              : 
    2060              :             ! v_xc = h_ks - h_ks(v_xc = 0)
    2061              :             CALL cp_fm_scale_and_add(alpha=-1.0_dp, matrix_a=bs_env%fm_V_xc_Gamma(ispin), &
    2062          270 :                                      beta=1.0_dp, matrix_b=bs_env%fm_ks_Gamma(ispin))
    2063              :          END DO
    2064              : 
    2065          126 :          CALL dbcsr_deallocate_matrix_set(mat_ks_without_v_xc)
    2066              : 
    2067              :       CASE (tensor_small_cell_full_kp, ri_rs_small_cell_full_kp)
    2068              : 
    2069              :          ! calculate KS-matrix without XC
    2070           30 :          IF (hf_present) CALL restart_kp_hfx_from_full_density(x_data)
    2071           30 :          CALL build_periodic_ks_with_gapw_density(qs_env)
    2072           30 :          CALL get_qs_env(qs_env=qs_env, matrix_ks_kp=matrix_ks_kp)
    2073              : 
    2074         1544 :          ALLOCATE (bs_env%fm_V_xc_R(dft_control%nimages, bs_env%n_spin))
    2075          216 :          DO ispin = 1, bs_env%n_spin
    2076         1454 :             DO img = 1, dft_control%nimages
    2077              :                ! safe fm_V_xc_R in fm_matrix because saving in dbcsr matrix caused trouble...
    2078         1394 :                CALL copy_dbcsr_to_fm(matrix_ks_kp(ispin, img)%matrix, bs_env%fm_work_mo(1))
    2079              :                CALL cp_fm_create(bs_env%fm_V_xc_R(img, ispin), bs_env%fm_work_mo(1)%matrix_struct, &
    2080         1394 :                                  set_zero=.TRUE.)
    2081              :                ! store h_ks(v_xc = 0) in fm_V_xc_R
    2082              :                CALL cp_fm_scale_and_add(alpha=1.0_dp, matrix_a=bs_env%fm_V_xc_R(img, ispin), &
    2083         1424 :                                         beta=1.0_dp, matrix_b=bs_env%fm_work_mo(1))
    2084              :             END DO
    2085              :          END DO
    2086              : 
    2087              :       END SELECT
    2088              : 
    2089              :       ! set back the energy
    2090          156 :       energy%total = energy_total
    2091          156 :       energy%exc = energy_exc
    2092          156 :       energy%ex = energy_ex
    2093              : 
    2094              :       ! set back nimages
    2095          156 :       dft_control%nimages = nimages
    2096              : 
    2097              :       ! set the DFT functional and HF fraction back
    2098              :       CALL section_vals_val_set(xc_section, "XC_FUNCTIONAL%_SECTION_PARAMETERS_", &
    2099          156 :                                 i_val=myfun)
    2100          156 :       IF (hf_present) THEN
    2101          204 :          x_data(:, :)%general_parameter%fraction = hf_fraction(:, :)
    2102           68 :          DEALLOCATE (hf_fraction)
    2103              :       END IF
    2104          156 :       IF (dft_control%do_admm) THEN
    2105            4 :          CALL section_vals_val_set(xc_fun_admm_aux, "_SECTION_PARAMETERS_", i_val=myfun_admm_aux)
    2106            4 :          CALL section_vals_val_set(xc_fun_admm_primary, "_SECTION_PARAMETERS_", i_val=myfun_admm_primary)
    2107            4 :          admm_env%charge_constrain = admm_charge_constrain
    2108              :       END IF
    2109              : 
    2110          156 :       IF (bs_env%gw_implementation == tensor_small_cell_full_kp .OR. &
    2111              :           bs_env%gw_implementation == ri_rs_small_cell_full_kp) THEN
    2112              :          ! calculate KS-matrix again with XC
    2113           30 :          IF (hf_present) CALL restart_kp_hfx_from_full_density(x_data)
    2114           30 :          CALL build_periodic_ks_with_gapw_density(qs_env)
    2115           60 :          DO ispin = 1, bs_env%n_spin
    2116         1454 :             DO img = 1, dft_control%nimages
    2117              :                ! store h_ks in fm_work_mo
    2118         1394 :                CALL copy_dbcsr_to_fm(matrix_ks_kp(ispin, img)%matrix, bs_env%fm_work_mo(1))
    2119              :                ! v_xc = h_ks - h_ks(v_xc = 0)
    2120              :                CALL cp_fm_scale_and_add(alpha=-1.0_dp, matrix_a=bs_env%fm_V_xc_R(img, ispin), &
    2121         1424 :                                         beta=1.0_dp, matrix_b=bs_env%fm_work_mo(1))
    2122              :             END DO
    2123              :          END DO
    2124              :       END IF
    2125              : 
    2126          156 :       CALL timestop(handle)
    2127              : 
    2128          312 :    END SUBROUTINE compute_V_xc
    2129              : 
    2130              : ! **************************************************************************************************
    2131              : !> \brief k-point RI-HFX adds fraction*K(P - P_previous) to its stored exchange matrix. Clearing the
    2132              : !>        stored exchange matrix and density makes the next KS build evaluate fraction*K(P).
    2133              : !> \param x_data ...
    2134              : ! **************************************************************************************************
    2135            4 :    SUBROUTINE restart_kp_hfx_from_full_density(x_data)
    2136              :       TYPE(hfx_type), DIMENSION(:, :), POINTER           :: x_data
    2137              : 
    2138              :       INTEGER                                            :: i_img, i_spin, irep
    2139              : 
    2140            8 :       DO irep = 1, SIZE(x_data, 1)
    2141          188 :          DO i_img = 1, SIZE(x_data(irep, 1)%ri_data%ks_t, 2)
    2142          364 :             DO i_spin = 1, SIZE(x_data(irep, 1)%ri_data%ks_t, 1)
    2143          180 :                CALL dbt_clear(x_data(irep, 1)%ri_data%ks_t(i_spin, i_img))
    2144          360 :                CALL dbt_clear(x_data(irep, 1)%ri_data%rho_ao_t(i_spin, i_img))
    2145              :             END DO
    2146              :          END DO
    2147              :       END DO
    2148              : 
    2149            4 :    END SUBROUTINE restart_kp_hfx_from_full_density
    2150              : 
    2151              : ! **************************************************************************************************
    2152              : !> \brief Rebuild a periodic KS matrix with the GAPW density derived from the converged AO density.
    2153              : !> \param qs_env ...
    2154              : ! **************************************************************************************************
    2155           90 :    SUBROUTINE build_periodic_ks_with_gapw_density(qs_env)
    2156              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2157              : 
    2158              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2159              :       TYPE(qs_rho_type), POINTER                         :: rho
    2160              : 
    2161           90 :       CALL get_qs_env(qs_env, dft_control=dft_control)
    2162           90 :       IF (dft_control%qs_control%gapw .OR. dft_control%qs_control%gapw_xc) THEN
    2163            6 :          CALL get_qs_env(qs_env, rho=rho)
    2164            6 :          CALL qs_rho_update_rho(rho, qs_env)
    2165              :       END IF
    2166           90 :       CALL qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces=.FALSE., just_energy=.FALSE.)
    2167              : 
    2168           90 :    END SUBROUTINE build_periodic_ks_with_gapw_density
    2169              : 
    2170              : ! **************************************************************************************************
    2171              : !> \brief Sets the interaction radii used by the GW calculation.
    2172              : !> \param bs_env ...
    2173              : ! **************************************************************************************************
    2174          156 :    SUBROUTINE init_interaction_radii(bs_env)
    2175              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2176              : 
    2177              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'init_interaction_radii'
    2178              : 
    2179              :       INTEGER                                            :: handle, ibasis
    2180              :       TYPE(gto_basis_set_type), POINTER                  :: orb_basis, ri_basis
    2181              : 
    2182          156 :       CALL timeset(routineN, handle)
    2183              : 
    2184          378 :       DO ibasis = 1, SIZE(bs_env%basis_set_AO)
    2185              : 
    2186          222 :          orb_basis => bs_env%basis_set_AO(ibasis)%gto_basis_set
    2187          222 :          CALL init_interaction_radii_orb_basis(orb_basis, bs_env%eps_filter)
    2188              : 
    2189          222 :          ri_basis => bs_env%basis_set_RI(ibasis)%gto_basis_set
    2190          378 :          CALL init_interaction_radii_orb_basis(ri_basis, bs_env%eps_filter)
    2191              : 
    2192              :       END DO
    2193              : 
    2194          156 :       CALL timestop(handle)
    2195              : 
    2196          156 :    END SUBROUTINE init_interaction_radii
    2197              : 
    2198              : ! **************************************************************************************************
    2199              : !> \brief ...
    2200              : !> \param qs_env ...
    2201              : !> \param bs_env ...
    2202              : ! **************************************************************************************************
    2203          114 :    SUBROUTINE create_tensors(qs_env, bs_env)
    2204              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2205              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2206              : 
    2207              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'create_tensors'
    2208              : 
    2209              :       INTEGER                                            :: handle
    2210              : 
    2211          114 :       CALL timeset(routineN, handle)
    2212              : 
    2213              :       ! split blocks does not improve load balancing/efficienfy for tensor contraction, so we go
    2214              :       ! with the standard atomic blocks
    2215              :       CALL create_3c_t(bs_env%t_RI_AO__AO, bs_env%para_env_tensor, "(RI AO | AO)", [1, 2], [3], &
    2216              :                        bs_env%sizes_RI, bs_env%sizes_AO, &
    2217          114 :                        create_nl_3c=.TRUE., nl_3c=bs_env%nl_3c, qs_env=qs_env)
    2218              :       CALL create_3c_t(bs_env%t_RI__AO_AO, bs_env%para_env_tensor, "(RI | AO AO)", [1], [2, 3], &
    2219          114 :                        bs_env%sizes_RI, bs_env%sizes_AO)
    2220              : 
    2221          114 :       CALL create_2c_t(bs_env)
    2222              : 
    2223          114 :       CALL timestop(handle)
    2224              : 
    2225          114 :    END SUBROUTINE create_tensors
    2226              : 
    2227              : ! **************************************************************************************************
    2228              : !> \brief ...
    2229              : !> \param tensor ...
    2230              : !> \param para_env ...
    2231              : !> \param tensor_name ...
    2232              : !> \param map1 ...
    2233              : !> \param map2 ...
    2234              : !> \param sizes_RI ...
    2235              : !> \param sizes_AO ...
    2236              : !> \param create_nl_3c ...
    2237              : !> \param nl_3c ...
    2238              : !> \param qs_env ...
    2239              : ! **************************************************************************************************
    2240          228 :    SUBROUTINE create_3c_t(tensor, para_env, tensor_name, map1, map2, sizes_RI, sizes_AO, &
    2241              :                           create_nl_3c, nl_3c, qs_env)
    2242              :       TYPE(dbt_type)                                     :: tensor
    2243              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2244              :       CHARACTER(LEN=12)                                  :: tensor_name
    2245              :       INTEGER, DIMENSION(:)                              :: map1, map2
    2246              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: sizes_RI, sizes_AO
    2247              :       LOGICAL, OPTIONAL                                  :: create_nl_3c
    2248              :       TYPE(neighbor_list_3c_type), OPTIONAL              :: nl_3c
    2249              :       TYPE(qs_environment_type), OPTIONAL, POINTER       :: qs_env
    2250              : 
    2251              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'create_3c_t'
    2252              : 
    2253              :       INTEGER                                            :: handle, nkind
    2254          228 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist_AO_1, dist_AO_2, dist_RI
    2255              :       INTEGER, DIMENSION(3)                              :: pcoord, pdims, pdims_3d
    2256              :       LOGICAL                                            :: my_create_nl_3c
    2257          684 :       TYPE(dbt_pgrid_type)                               :: pgrid_3d
    2258              :       TYPE(distribution_3d_type)                         :: dist_3d
    2259          228 :       TYPE(mp_cart_type)                                 :: mp_comm_t3c_2
    2260          228 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2261              : 
    2262          228 :       CALL timeset(routineN, handle)
    2263              : 
    2264          228 :       pdims_3d = 0
    2265          228 :       CALL dbt_pgrid_create(para_env, pdims_3d, pgrid_3d)
    2266              :       CALL create_3c_tensor(tensor, dist_RI, dist_AO_1, dist_AO_2, &
    2267              :                             pgrid_3d, sizes_RI, sizes_AO, sizes_AO, &
    2268          228 :                             map1=map1, map2=map2, name=tensor_name)
    2269              : 
    2270          228 :       IF (PRESENT(create_nl_3c)) THEN
    2271          114 :          my_create_nl_3c = create_nl_3c
    2272              :       ELSE
    2273              :          my_create_nl_3c = .FALSE.
    2274              :       END IF
    2275              : 
    2276          114 :       IF (my_create_nl_3c) THEN
    2277          114 :          CALL get_qs_env(qs_env, nkind=nkind, particle_set=particle_set)
    2278          114 :          CALL dbt_mp_environ_pgrid(pgrid_3d, pdims, pcoord)
    2279          114 :          CALL mp_comm_t3c_2%create(pgrid_3d%mp_comm_2d, 3, pdims)
    2280              :          CALL distribution_3d_create(dist_3d, dist_RI, dist_AO_1, dist_AO_2, &
    2281          114 :                                      nkind, particle_set, mp_comm_t3c_2, own_comm=.TRUE.)
    2282              : 
    2283              :          CALL build_3c_neighbor_lists(nl_3c, &
    2284              :                                       qs_env%bs_env%basis_set_RI, &
    2285              :                                       qs_env%bs_env%basis_set_AO, &
    2286              :                                       qs_env%bs_env%basis_set_AO, &
    2287              :                                       dist_3d, qs_env%bs_env%ri_metric, &
    2288          114 :                                       "GW_3c_nl", qs_env, own_dist=.TRUE.)
    2289              :       END IF
    2290              : 
    2291          228 :       DEALLOCATE (dist_RI, dist_AO_1, dist_AO_2)
    2292          228 :       CALL dbt_pgrid_destroy(pgrid_3d)
    2293              : 
    2294          228 :       CALL timestop(handle)
    2295              : 
    2296          456 :    END SUBROUTINE create_3c_t
    2297              : 
    2298              : ! **************************************************************************************************
    2299              : !> \brief Creates the AO-AO and RI-RI two-center tensors.
    2300              : !> \param bs_env ...
    2301              : ! **************************************************************************************************
    2302          114 :    SUBROUTINE create_2c_t(bs_env)
    2303              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2304              : 
    2305              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'create_2c_t'
    2306              : 
    2307              :       INTEGER                                            :: handle
    2308          114 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: dist_1, dist_2
    2309              :       INTEGER, DIMENSION(2)                              :: pdims_2d
    2310          342 :       TYPE(dbt_pgrid_type)                               :: pgrid_2d
    2311              : 
    2312          114 :       CALL timeset(routineN, handle)
    2313              : 
    2314              :       ! inspired from rpa_im_time.F / hfx_types.F
    2315              : 
    2316          114 :       pdims_2d = 0
    2317          114 :       CALL dbt_pgrid_create(bs_env%para_env_tensor, pdims_2d, pgrid_2d)
    2318              : 
    2319              :       CALL create_2c_tensor(bs_env%t_G, dist_1, dist_2, pgrid_2d, &
    2320              :                             bs_env%sizes_AO, bs_env%sizes_AO, &
    2321          114 :                             name="(AO | AO)")
    2322          114 :       DEALLOCATE (dist_1, dist_2)
    2323              :       CALL create_2c_tensor(bs_env%t_chi, dist_1, dist_2, pgrid_2d, &
    2324              :                             bs_env%sizes_RI, bs_env%sizes_RI, &
    2325          114 :                             name="(RI | RI)")
    2326          114 :       DEALLOCATE (dist_1, dist_2)
    2327              :       CALL create_2c_tensor(bs_env%t_W, dist_1, dist_2, pgrid_2d, &
    2328              :                             bs_env%sizes_RI, bs_env%sizes_RI, &
    2329          114 :                             name="(RI | RI)")
    2330          114 :       DEALLOCATE (dist_1, dist_2)
    2331          114 :       CALL dbt_pgrid_destroy(pgrid_2d)
    2332              : 
    2333          114 :       CALL timestop(handle)
    2334              : 
    2335          114 :    END SUBROUTINE create_2c_t
    2336              : 
    2337              : ! **************************************************************************************************
    2338              : !> \brief Allocate the arrays holding the GW quasiparticle energies
    2339              : !> \param bs_env ...
    2340              : ! **************************************************************************************************
    2341          156 :    SUBROUTINE allocate_GW_eigenvalues(bs_env)
    2342              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2343              : 
    2344              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'allocate_GW_eigenvalues'
    2345              : 
    2346              :       INTEGER                                            :: handle, n_ao, n_spin, nkp
    2347              : 
    2348          156 :       CALL timeset(routineN, handle)
    2349              : 
    2350          156 :       n_ao = bs_env%n_ao
    2351          156 :       nkp = bs_env%nkp_bs_and_DOS
    2352          156 :       n_spin = bs_env%n_spin
    2353              : 
    2354          156 :       IF (.NOT. ALLOCATED(bs_env%eigenval_GW)) THEN
    2355          780 :          ALLOCATE (bs_env%eigenval_GW(n_ao, nkp, n_spin))
    2356              :       END IF
    2357          156 :       IF (.NOT. ALLOCATED(bs_env%eigenval_HF)) THEN
    2358          780 :          ALLOCATE (bs_env%eigenval_HF(n_ao, nkp, n_spin))
    2359              :       END IF
    2360              : 
    2361          312 :       SELECT CASE (bs_env%gw_flavour)
    2362              :       CASE (G0W0, evGW0)
    2363          156 :          IF (.NOT. ALLOCATED(bs_env%eigenval_G0W0)) THEN
    2364          780 :             ALLOCATE (bs_env%eigenval_G0W0(n_ao, nkp, n_spin))
    2365              :          END IF
    2366              :       END SELECT
    2367              : 
    2368          156 :       IF (bs_env%gw_flavour == evGW0 .AND. .NOT. ALLOCATED(bs_env%eigenval_evGW0)) THEN
    2369           20 :          ALLOCATE (bs_env%eigenval_evGW0(n_ao, nkp, n_spin))
    2370              :       END IF
    2371              : 
    2372          156 :       CALL timestop(handle)
    2373              : 
    2374          156 :    END SUBROUTINE allocate_GW_eigenvalues
    2375              : 
    2376              : ! **************************************************************************************************
    2377              : !> \brief ...
    2378              : !> \param qs_env ...
    2379              : !> \param bs_env ...
    2380              : ! **************************************************************************************************
    2381           84 :    SUBROUTINE check_sparsity_3c(qs_env, bs_env)
    2382              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2383              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2384              : 
    2385              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'check_sparsity_3c'
    2386              : 
    2387              :       INTEGER                                            :: handle, n_atom_step, RI_atom
    2388              :       INTEGER(int_8)                                     :: non_zero_elements_sum, nze
    2389              :       REAL(dp)                                           :: max_dist_AO_atoms, occ, occupation_sum
    2390              :       REAL(KIND=dp)                                      :: t1, t2
    2391           84 :       TYPE(dbt_type), ALLOCATABLE, DIMENSION(:, :)       :: t_3c_global_array
    2392              : 
    2393           84 :       CALL timeset(routineN, handle)
    2394              : 
    2395              :       ! check the sparsity of 3c integral tensor (µν|P); calculate maximum distance between
    2396              :       ! AO atoms µ, ν where at least a single integral (µν|P) is larger than the filter threshold
    2397              : 
    2398          756 :       ALLOCATE (t_3c_global_array(1, 1))
    2399           84 :       CALL dbt_create(bs_env%t_RI_AO__AO, t_3c_global_array(1, 1))
    2400              : 
    2401              :       ! Allocate arrays to store min/max indices for overlap with other AO/RI functions on each atom
    2402              :       ! (Filled during loop via get_i_j_atom_ranges)
    2403          336 :       ALLOCATE (bs_env%min_RI_idx_from_AO_AO_atom(bs_env%n_atom, bs_env%n_atom))
    2404          336 :       ALLOCATE (bs_env%max_RI_idx_from_AO_AO_atom(bs_env%n_atom, bs_env%n_atom))
    2405          336 :       ALLOCATE (bs_env%min_AO_idx_from_RI_AO_atom(bs_env%n_atom, bs_env%n_atom))
    2406          336 :       ALLOCATE (bs_env%max_AO_idx_from_RI_AO_atom(bs_env%n_atom, bs_env%n_atom))
    2407          696 :       bs_env%min_RI_idx_from_AO_AO_atom(:, :) = bs_env%n_RI
    2408          696 :       bs_env%max_RI_idx_from_AO_AO_atom(:, :) = 1
    2409          696 :       bs_env%min_AO_idx_from_RI_AO_atom(:, :) = bs_env%n_AO
    2410          696 :       bs_env%max_AO_idx_from_RI_AO_atom(:, :) = 1
    2411              : 
    2412           84 :       CALL bs_env%para_env%sync()
    2413           84 :       t1 = m_walltime()
    2414              : 
    2415           84 :       occupation_sum = 0.0_dp
    2416           84 :       non_zero_elements_sum = 0
    2417           84 :       max_dist_AO_atoms = 0.0_dp
    2418           84 :       n_atom_step = INT(SQRT(REAL(bs_env%n_atom, KIND=dp)))
    2419              :       ! do not compute full 3c integrals at once because it may cause out of memory
    2420          270 :       DO RI_atom = 1, bs_env%n_atom, n_atom_step
    2421              : 
    2422              :          CALL build_3c_integrals(t_3c_global_array, &
    2423              :                                  bs_env%eps_filter, &
    2424              :                                  qs_env, &
    2425              :                                  bs_env%nl_3c, &
    2426              :                                  int_eps=bs_env%eps_filter, &
    2427              :                                  basis_i=bs_env%basis_set_RI, &
    2428              :                                  basis_j=bs_env%basis_set_AO, &
    2429              :                                  basis_k=bs_env%basis_set_AO, &
    2430              :                                  bounds_i=[RI_atom, MIN(RI_atom + n_atom_step - 1, bs_env%n_atom)], &
    2431              :                                  potential_parameter=bs_env%ri_metric, &
    2432          558 :                                  desymmetrize=.FALSE.)
    2433              : 
    2434          186 :          CALL dbt_filter(t_3c_global_array(1, 1), bs_env%eps_filter)
    2435              : 
    2436          186 :          CALL bs_env%para_env%sync()
    2437              : 
    2438          186 :          CALL get_tensor_occupancy(t_3c_global_array(1, 1), nze, occ)
    2439          186 :          non_zero_elements_sum = non_zero_elements_sum + nze
    2440          186 :          occupation_sum = occupation_sum + occ
    2441              : 
    2442          186 :          CALL get_max_dist_AO_atoms(t_3c_global_array(1, 1), max_dist_AO_atoms, qs_env)
    2443              : 
    2444              :          ! Extract indices per block
    2445          186 :          CALL get_i_j_atom_ranges(t_3c_global_array(1, 1), bs_env)
    2446              : 
    2447          456 :          CALL dbt_clear(t_3c_global_array(1, 1))
    2448              : 
    2449              :       END DO
    2450              : 
    2451           84 :       t2 = m_walltime()
    2452              : 
    2453              :       ! Sync/max for max_dist_AO_atoms is done inside each get_max_dist_AO_atoms
    2454           84 :       bs_env%max_dist_AO_atoms = max_dist_AO_atoms
    2455              :       ! occupation_sum is a global quantity, also needs no sync here
    2456           84 :       bs_env%occupation_3c_int = occupation_sum
    2457              : 
    2458           84 :       CALL bs_env%para_env%min(bs_env%min_RI_idx_from_AO_AO_atom)
    2459           84 :       CALL bs_env%para_env%max(bs_env%max_RI_idx_from_AO_AO_atom)
    2460           84 :       CALL bs_env%para_env%min(bs_env%min_AO_idx_from_RI_AO_atom)
    2461           84 :       CALL bs_env%para_env%max(bs_env%max_AO_idx_from_RI_AO_atom)
    2462              : 
    2463           84 :       CALL dbt_destroy(t_3c_global_array(1, 1))
    2464          168 :       DEALLOCATE (t_3c_global_array)
    2465              : 
    2466           84 :       IF (bs_env%unit_nr > 0) THEN
    2467           42 :          WRITE (bs_env%unit_nr, '(T2,A)') ''
    2468              :          WRITE (bs_env%unit_nr, '(T2,A,F27.1,A)') &
    2469           42 :             'Computed 3-center integrals (µν|P), Exec. time', t2 - t1, ' s'
    2470           42 :          WRITE (bs_env%unit_nr, '(T2,A,F48.3,A)') 'Percentage of non-zero (µν|P)', &
    2471           84 :             bs_env%occupation_3c_int*100, ' %'
    2472           42 :          WRITE (bs_env%unit_nr, '(T2,A,F33.1,A)') 'Max. distance between µ,ν in non-zero (µν|P)', &
    2473           84 :             bs_env%max_dist_AO_atoms*angstrom, ' A'
    2474           42 :          WRITE (bs_env%unit_nr, '(T2,2A,I20,A)') 'Required memory if storing all 3-center ', &
    2475           84 :             'integrals (µν|P)', INT(REAL(non_zero_elements_sum, KIND=dp)*8.0E-9_dp), ' GB'
    2476              :       END IF
    2477              : 
    2478           84 :       CALL timestop(handle)
    2479              : 
    2480          168 :    END SUBROUTINE check_sparsity_3c
    2481              : 
    2482              : ! **************************************************************************************************
    2483              : !> \brief ...
    2484              : !> \param t_3c_int ...
    2485              : !> \param max_dist_AO_atoms ...
    2486              : !> \param qs_env ...
    2487              : ! **************************************************************************************************
    2488          186 :    SUBROUTINE get_max_dist_AO_atoms(t_3c_int, max_dist_AO_atoms, qs_env)
    2489              :       TYPE(dbt_type)                                     :: t_3c_int
    2490              :       REAL(KIND=dp), INTENT(INOUT)                       :: max_dist_AO_atoms
    2491              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2492              : 
    2493              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_max_dist_AO_atoms'
    2494              : 
    2495              :       INTEGER                                            :: atom_1, atom_2, handle, num_cells
    2496              :       INTEGER, DIMENSION(3)                              :: atom_ind
    2497          186 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    2498              :       REAL(KIND=dp)                                      :: abs_rab
    2499              :       REAL(KIND=dp), DIMENSION(3)                        :: rab
    2500              :       TYPE(cell_type), POINTER                           :: cell
    2501              :       TYPE(dbt_iterator_type)                            :: iter
    2502              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2503          186 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2504              : 
    2505          186 :       CALL timeset(routineN, handle)
    2506              : 
    2507          186 :       NULLIFY (cell, particle_set, para_env)
    2508          186 :       CALL get_qs_env(qs_env, cell=cell, particle_set=particle_set, para_env=para_env)
    2509              : 
    2510              :       ! max_dist_AO_atoms is compared to earlier steps in the loop with step n_atom_step
    2511              :       ! do not initialize/overwrite here
    2512              : 
    2513              : ! IMPORTANT: Use thread-local copy for max_dist_AO_atoms via REDUCTION to avoid race conditions
    2514              : !$OMP PARALLEL DEFAULT(NONE) &
    2515              : !$OMP SHARED(t_3c_int, num_cells, index_to_cell, particle_set, cell) &
    2516              : !$OMP PRIVATE(iter, atom_ind, rab, abs_rab, atom_1, atom_2) &
    2517          186 : !$OMP REDUCTION(MAX:max_dist_AO_atoms)
    2518              : 
    2519              :       CALL dbt_iterator_start(iter, t_3c_int)
    2520              :       DO WHILE (dbt_iterator_blocks_left(iter))
    2521              :          CALL dbt_iterator_next_block(iter, atom_ind)
    2522              : 
    2523              :          atom_1 = atom_ind(2)
    2524              :          atom_2 = atom_ind(3)
    2525              :          rab = pbc(particle_set(atom_1)%r(1:3), particle_set(atom_2)%r(1:3), cell)
    2526              :          abs_rab = SQRT(rab(1)**2 + rab(2)**2 + rab(3)**2)
    2527              : 
    2528              :          ! Reduction takes care of using a thread-local copy
    2529              :          max_dist_AO_atoms = MAX(max_dist_AO_atoms, abs_rab)
    2530              : 
    2531              :       END DO
    2532              :       CALL dbt_iterator_stop(iter)
    2533              : !$OMP END PARALLEL
    2534              : 
    2535          186 :       CALL para_env%max(max_dist_AO_atoms)
    2536              : 
    2537          186 :       CALL timestop(handle)
    2538              : 
    2539          186 :    END SUBROUTINE get_max_dist_AO_atoms
    2540              : 
    2541              : ! **************************************************************************************************
    2542              : !> \brief ...
    2543              : !> \param t_3c ...
    2544              : !> \param bs_env ...
    2545              : ! **************************************************************************************************
    2546          186 :    SUBROUTINE get_i_j_atom_ranges(t_3c, bs_env)
    2547              :       TYPE(dbt_type)                                     :: t_3c
    2548              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2549              : 
    2550              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_i_j_atom_ranges'
    2551              : 
    2552              :       INTEGER                                            :: handle, idx_AO_end, idx_AO_start, &
    2553              :                                                             idx_RI_end, idx_RI_start
    2554              :       INTEGER, DIMENSION(3)                              :: atom_ind
    2555              :       TYPE(dbt_iterator_type)                            :: iter
    2556              : 
    2557          186 :       CALL timeset(routineN, handle)
    2558              : 
    2559              :       ! Loop over blocks in 3c, for given min_atom: RI_min/max index from min_atom
    2560              : !$OMP PARALLEL DEFAULT(NONE) &
    2561              : !$OMP SHARED(t_3c, bs_env) &
    2562              : !$OMP PRIVATE(iter, atom_ind, &
    2563          186 : !$OMP         idx_RI_start, idx_RI_end, idx_AO_start, idx_AO_end)
    2564              : 
    2565              :       CALL dbt_iterator_start(iter, t_3c)
    2566              :       DO WHILE (dbt_iterator_blocks_left(iter))
    2567              :          CALL dbt_iterator_next_block(iter, atom_ind)
    2568              : 
    2569              :          ! Pre-fetch indices to avoid referencing 'bs_env' twice inside the ATOMIC blocks
    2570              :          idx_RI_start = bs_env%i_RI_start_from_atom(atom_ind(1))
    2571              :          idx_RI_end = bs_env%i_RI_end_from_atom(atom_ind(1))
    2572              : 
    2573              :          idx_AO_start = bs_env%i_ao_start_from_atom(atom_ind(2))
    2574              :          idx_AO_end = bs_env%i_ao_end_from_atom(atom_ind(2))
    2575              : 
    2576              :          ! Update values safely inside ATOMIC blocks, otherwise race conditions occur
    2577              : !$OMP ATOMIC UPDATE
    2578              :          bs_env%min_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)) = &
    2579              :             MIN(bs_env%min_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)), idx_RI_start)
    2580              : !$OMP ATOMIC UPDATE
    2581              :          bs_env%max_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)) = &
    2582              :             MAX(bs_env%max_RI_idx_from_AO_AO_atom(atom_ind(2), atom_ind(3)), idx_RI_end)
    2583              : 
    2584              : !$OMP ATOMIC UPDATE
    2585              :          bs_env%min_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)) = &
    2586              :             MIN(bs_env%min_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)), idx_AO_start)
    2587              : !$OMP ATOMIC UPDATE
    2588              :          bs_env%max_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)) = &
    2589              :             MAX(bs_env%max_AO_idx_from_RI_AO_atom(atom_ind(1), atom_ind(3)), idx_AO_end)
    2590              : 
    2591              :       END DO
    2592              :       CALL dbt_iterator_stop(iter)
    2593              : !$OMP END PARALLEL
    2594              : 
    2595          186 :       CALL timestop(handle)
    2596              : 
    2597          186 :    END SUBROUTINE get_i_j_atom_ranges
    2598              : 
    2599              : ! **************************************************************************************************
    2600              : !> \brief ...
    2601              : !> \param bs_env ...
    2602              : ! **************************************************************************************************
    2603           84 :    SUBROUTINE set_sparsity_parallelization_parameters(bs_env)
    2604              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2605              : 
    2606              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_sparsity_parallelization_parameters'
    2607              : 
    2608              :       INTEGER :: handle, i_ivl, IL_ivl, j_ivl, n_atom_per_IL_ivl, n_atom_per_ivl, n_intervals_i, &
    2609              :          n_intervals_inner_loop_atoms, n_intervals_j, u
    2610              :       INTEGER(KIND=int_8)                                :: input_memory_per_proc
    2611              : 
    2612           84 :       CALL timeset(routineN, handle)
    2613              : 
    2614              :       ! heuristic parameter to prevent out of memory
    2615           84 :       bs_env%safety_factor_memory = 0.10_dp
    2616              : 
    2617           84 :       input_memory_per_proc = INT(bs_env%input_memory_per_proc_GB*1.0E9_dp, KIND=int_8)
    2618              : 
    2619              :       ! choose atomic range for λ ("i_atom"), ν ("j_atom") in
    2620              :       ! M_λνP(iτ) = sum_µ (µν|P) G^occ_µλ(i|τ|,k=0)
    2621              :       ! N_νλQ(iτ) = sum_σ (σλ|Q) G^vir_σν(i|τ|,k=0)
    2622              :       ! such that M and N fit into the memory
    2623              :       n_atom_per_ivl = INT(SQRT(bs_env%safety_factor_memory*input_memory_per_proc &
    2624              :                                 *bs_env%group_size_tensor/24/bs_env%n_RI &
    2625           84 :                                 /SQRT(bs_env%occupation_3c_int)))/bs_env%max_AO_bf_per_atom
    2626              : 
    2627           84 :       n_intervals_i = (bs_env%n_atom_i - 1)/n_atom_per_ivl + 1
    2628           84 :       n_intervals_j = (bs_env%n_atom_j - 1)/n_atom_per_ivl + 1
    2629              : 
    2630           84 :       bs_env%n_intervals_i = n_intervals_i
    2631           84 :       bs_env%n_intervals_j = n_intervals_j
    2632              : 
    2633          252 :       ALLOCATE (bs_env%i_atom_intervals(2, n_intervals_i))
    2634          252 :       ALLOCATE (bs_env%j_atom_intervals(2, n_intervals_j))
    2635              : 
    2636          168 :       DO i_ivl = 1, n_intervals_i
    2637           84 :          bs_env%i_atom_intervals(1, i_ivl) = (i_ivl - 1)*n_atom_per_ivl + bs_env%atoms_i(1)
    2638              :          bs_env%i_atom_intervals(2, i_ivl) = MIN(i_ivl*n_atom_per_ivl + bs_env%atoms_i(1) - 1, &
    2639          168 :                                                  bs_env%atoms_i(2))
    2640              :       END DO
    2641              : 
    2642          168 :       DO j_ivl = 1, n_intervals_j
    2643           84 :          bs_env%j_atom_intervals(1, j_ivl) = (j_ivl - 1)*n_atom_per_ivl + bs_env%atoms_j(1)
    2644              :          bs_env%j_atom_intervals(2, j_ivl) = MIN(j_ivl*n_atom_per_ivl + bs_env%atoms_j(1) - 1, &
    2645          168 :                                                  bs_env%atoms_j(2))
    2646              :       END DO
    2647              : 
    2648          336 :       ALLOCATE (bs_env%skip_Sigma_occ(n_intervals_i, n_intervals_j))
    2649          252 :       ALLOCATE (bs_env%skip_Sigma_vir(n_intervals_i, n_intervals_j))
    2650          252 :       bs_env%skip_Sigma_occ(:, :) = .FALSE.
    2651          252 :       bs_env%skip_Sigma_vir(:, :) = .FALSE.
    2652           84 :       bs_env%n_skip_chi = 0
    2653              : 
    2654          252 :       ALLOCATE (bs_env%skip_chi(n_intervals_i, n_intervals_j))
    2655          252 :       bs_env%skip_chi(:, :) = .FALSE.
    2656           84 :       bs_env%n_skip_sigma = 0
    2657              : 
    2658              :       ! choose atomic range for µ and σ ("inner loop (IL) atom") in
    2659              :       ! M_λνP(iτ) = sum_µ (µν|P) G^occ_µλ(i|τ|,k=0)
    2660              :       ! N_νλQ(iτ) = sum_σ (σλ|Q) G^vir_σν(i|τ|,k=0)
    2661              :       n_atom_per_IL_ivl = MIN(INT(bs_env%safety_factor_memory*input_memory_per_proc &
    2662              :                                   *bs_env%group_size_tensor/n_atom_per_ivl &
    2663              :                                   /bs_env%max_AO_bf_per_atom &
    2664              :                                   /bs_env%n_RI/8/SQRT(bs_env%occupation_3c_int) &
    2665           84 :                                   /bs_env%max_AO_bf_per_atom), bs_env%n_atom)
    2666              : 
    2667           84 :       n_intervals_inner_loop_atoms = (bs_env%n_atom - 1)/n_atom_per_IL_ivl + 1
    2668              : 
    2669           84 :       bs_env%n_intervals_inner_loop_atoms = n_intervals_inner_loop_atoms
    2670              : 
    2671          252 :       ALLOCATE (bs_env%inner_loop_atom_intervals(2, n_intervals_inner_loop_atoms))
    2672          168 :       DO IL_ivl = 1, n_intervals_inner_loop_atoms
    2673           84 :          bs_env%inner_loop_atom_intervals(1, IL_ivl) = (IL_ivl - 1)*n_atom_per_IL_ivl + 1
    2674          168 :          bs_env%inner_loop_atom_intervals(2, IL_ivl) = MIN(IL_ivl*n_atom_per_IL_ivl, bs_env%n_atom)
    2675              :       END DO
    2676              : 
    2677           84 :       u = bs_env%unit_nr
    2678           84 :       IF (u > 0) THEN
    2679           42 :          WRITE (u, '(T2,A)') ''
    2680           42 :          WRITE (u, '(T2,A,I33)') 'Number of i and j atoms in M_λνP(τ), N_νλQ(τ):', n_atom_per_ivl
    2681           42 :          WRITE (u, '(T2,A,I18)') 'Number of inner loop atoms for µ in M_λνP = sum_µ (µν|P) G_µλ', &
    2682           84 :             n_atom_per_IL_ivl
    2683              :       END IF
    2684              : 
    2685           84 :       CALL timestop(handle)
    2686              : 
    2687           84 :    END SUBROUTINE set_sparsity_parallelization_parameters
    2688              : 
    2689              : ! **************************************************************************************************
    2690              : !> \brief ...
    2691              : !> \param qs_env ...
    2692              : !> \param bs_env ...
    2693              : ! **************************************************************************************************
    2694          126 :    SUBROUTINE check_for_restart_files(qs_env, bs_env)
    2695              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2696              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2697              : 
    2698              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'check_for_restart_files'
    2699              : 
    2700              :       CHARACTER(LEN=9)                                   :: frmt
    2701              :       CHARACTER(len=default_path_length)                 :: f_chi, f_s_n, f_s_p, f_s_x, f_w_t, &
    2702              :                                                             prefix, project_name, Z_lP_name
    2703              :       INTEGER                                            :: handle, i_spin, i_t_or_w, ind, n_spin, &
    2704              :                                                             num_time_freq_points
    2705              :       LOGICAL                                            :: chi_exists, Sigma_neg_time_exists, &
    2706              :                                                             Sigma_pos_time_exists, &
    2707              :                                                             Sigma_x_spin_exists, W_time_exists, &
    2708              :                                                             Z_lP_exists
    2709              :       TYPE(cp_logger_type), POINTER                      :: logger
    2710              :       TYPE(section_vals_type), POINTER                   :: input, print_key
    2711              : 
    2712          126 :       CALL timeset(routineN, handle)
    2713              : 
    2714          126 :       num_time_freq_points = bs_env%num_time_freq_points
    2715          126 :       n_spin = bs_env%n_spin
    2716              : 
    2717          378 :       ALLOCATE (bs_env%read_chi(num_time_freq_points))
    2718          252 :       ALLOCATE (bs_env%calc_chi(num_time_freq_points))
    2719          504 :       ALLOCATE (bs_env%Sigma_c_exists(num_time_freq_points, n_spin))
    2720              : 
    2721          126 :       CALL get_qs_env(qs_env, input=input)
    2722              : 
    2723          126 :       logger => cp_get_default_logger()
    2724          126 :       print_key => section_vals_get_subs_vals(input, 'PROPERTIES%BANDSTRUCTURE%GW%PRINT%RESTART')
    2725              :       project_name = cp_print_key_generate_filename(logger, print_key, extension="", &
    2726          126 :                                                     my_local=.FALSE.)
    2727          126 :       WRITE (prefix, '(2A)') TRIM(project_name), "-RESTART_"
    2728          126 :       bs_env%prefix = prefix
    2729              : 
    2730          126 :       bs_env%all_W_exist = .TRUE.
    2731              : 
    2732         2142 :       DO i_t_or_w = 1, num_time_freq_points
    2733              : 
    2734         2016 :          IF (i_t_or_w < 10) THEN
    2735         1100 :             WRITE (frmt, '(A)') '(3A,I1,A)'
    2736         1100 :             WRITE (f_chi, frmt) TRIM(prefix), bs_env%chi_name, "_0", i_t_or_w, ".matrix"
    2737         1100 :             WRITE (f_W_t, frmt) TRIM(prefix), bs_env%W_time_name, "_0", i_t_or_w, ".matrix"
    2738          916 :          ELSE IF (i_t_or_w < 100) THEN
    2739          916 :             WRITE (frmt, '(A)') '(3A,I2,A)'
    2740          916 :             WRITE (f_chi, frmt) TRIM(prefix), bs_env%chi_name, "_", i_t_or_w, ".matrix"
    2741          916 :             WRITE (f_W_t, frmt) TRIM(prefix), bs_env%W_time_name, "_", i_t_or_w, ".matrix"
    2742              :          ELSE
    2743            0 :             CPABORT('Please implement more than 99 time/frequency points.')
    2744              :          END IF
    2745              : 
    2746         2016 :          INQUIRE (file=TRIM(f_chi), exist=chi_exists)
    2747         2016 :          INQUIRE (file=TRIM(f_W_t), exist=W_time_exists)
    2748              : 
    2749         2016 :          bs_env%read_chi(i_t_or_w) = chi_exists
    2750         2016 :          bs_env%calc_chi(i_t_or_w) = .NOT. chi_exists
    2751              : 
    2752         2016 :          bs_env%all_W_exist = bs_env%all_W_exist .AND. W_time_exists
    2753              : 
    2754              :          ! the self-energy is spin-dependent
    2755         4438 :          DO i_spin = 1, n_spin
    2756              : 
    2757         2296 :             ind = i_t_or_w + (i_spin - 1)*num_time_freq_points
    2758              : 
    2759         2296 :             IF (ind < 10) THEN
    2760         1100 :                WRITE (frmt, '(A)') '(3A,I1,A)'
    2761         1100 :                WRITE (f_S_p, frmt) TRIM(prefix), bs_env%Sigma_p_name, "_0", ind, ".matrix"
    2762         1100 :                WRITE (f_S_n, frmt) TRIM(prefix), bs_env%Sigma_n_name, "_0", ind, ".matrix"
    2763         1196 :             ELSE IF (ind < 100) THEN
    2764         1196 :                WRITE (frmt, '(A)') '(3A,I2,A)'
    2765         1196 :                WRITE (f_S_p, frmt) TRIM(prefix), bs_env%Sigma_p_name, "_", ind, ".matrix"
    2766         1196 :                WRITE (f_S_n, frmt) TRIM(prefix), bs_env%Sigma_n_name, "_", ind, ".matrix"
    2767              :             ELSE
    2768            0 :                CPABORT('Please implement more than 99 combined spin+freq indices.')
    2769              :             END IF
    2770              : 
    2771         2296 :             INQUIRE (file=TRIM(f_S_p), exist=Sigma_pos_time_exists)
    2772         2296 :             INQUIRE (file=TRIM(f_S_n), exist=Sigma_neg_time_exists)
    2773              : 
    2774              :             bs_env%Sigma_c_exists(i_t_or_w, i_spin) = Sigma_pos_time_exists .AND. &
    2775         6488 :                                                       Sigma_neg_time_exists
    2776              : 
    2777              :          END DO
    2778              : 
    2779              :       END DO
    2780              : 
    2781              :       ! Marek : In the RTBSE run, check also for zero frequency W
    2782          126 :       IF (bs_env%rtp_method == rtp_method_bse .OR. &
    2783              :           bs_env%rtp_method == rtp_method_bse_linearized) THEN
    2784           72 :          WRITE (f_W_t, '(3A,I1,A)') TRIM(prefix), "W_freq_rtp", "_0", 0, ".matrix"
    2785           72 :          INQUIRE (file=TRIM(f_W_t), exist=W_time_exists)
    2786          144 :          bs_env%all_W_exist = bs_env%all_W_exist .AND. W_time_exists
    2787              :       END IF
    2788              : 
    2789              :       ! Check for Restart Z_lP file
    2790          126 :       IF (bs_env%do_gw_ri_rs) THEN
    2791           42 :          WRITE (Z_lP_name, '(3A)') TRIM(prefix), "Z_lP", ".matrix"
    2792           42 :          INQUIRE (file=TRIM(Z_lP_name), exist=Z_lP_exists)
    2793           42 :          bs_env%ri_rs%Z_lP_exists = Z_lP_exists
    2794              :       END IF
    2795              : 
    2796          126 :       IF (bs_env%all_W_exist) THEN
    2797            0 :          bs_env%read_chi(:) = .FALSE.
    2798            0 :          bs_env%calc_chi(:) = .FALSE.
    2799              :       END IF
    2800              : 
    2801          126 :       bs_env%Sigma_x_exists = .TRUE.
    2802          270 :       DO i_spin = 1, n_spin
    2803          144 :          WRITE (f_S_x, '(3A,I1,A)') TRIM(prefix), bs_env%Sigma_x_name, "_0", i_spin, ".matrix"
    2804          144 :          INQUIRE (file=TRIM(f_S_x), exist=Sigma_x_spin_exists)
    2805          406 :          bs_env%Sigma_x_exists = bs_env%Sigma_x_exists .AND. Sigma_x_spin_exists
    2806              :       END DO
    2807              : 
    2808              :       ! static COHSEX: Σ^c(iω=0,k=0) restart, one file per spin; if present, χ and W are not needed
    2809          126 :       bs_env%Sigma_c_freq_zero_exists = bs_env%do_static_cohsex
    2810          270 :       DO i_spin = 1, n_spin
    2811          144 :          WRITE (f_S_x, '(3A,I1,A)') TRIM(prefix), bs_env%Sigma_c_freq_zero_name, "_0", i_spin, ".matrix"
    2812          144 :          INQUIRE (file=TRIM(f_S_x), exist=Sigma_x_spin_exists)
    2813          414 :          bs_env%Sigma_c_freq_zero_exists = bs_env%Sigma_c_freq_zero_exists .AND. Sigma_x_spin_exists
    2814              :       END DO
    2815              : 
    2816              :       ! If any restart files are read, check if the SCF converged in 1 step.
    2817              :       ! This is important because a re-iterated SCF can lead to spurious GW results
    2818              :       IF (ANY(bs_env%read_chi(:)) &
    2819              :           .OR. ANY(bs_env%Sigma_c_exists) &
    2820              :           .OR. bs_env%all_W_exist &
    2821              :           .OR. bs_env%Sigma_x_exists &
    2822         4454 :           .OR. bs_env%Sigma_c_freq_zero_exists &
    2823              :           ) THEN
    2824              : 
    2825            6 :          IF (qs_env%scf_env%iter_count /= 1) THEN
    2826              :             CALL cp_warn(__LOCATION__, "SCF needed more than 1 step, "// &
    2827            6 :                          "which might lead to spurious GW results when using GW restart files. ")
    2828              :          END IF
    2829              :       END IF
    2830              : 
    2831          126 :       CALL timestop(handle)
    2832              : 
    2833          126 :    END SUBROUTINE check_for_restart_files
    2834              : 
    2835              : ! **************************************************************************************************
    2836              : !> \brief ...
    2837              : !> \param qs_env ...
    2838              : !> \param bs_env ...
    2839              : ! **************************************************************************************************
    2840           16 :    SUBROUTINE compute_3c_integrals(qs_env, bs_env)
    2841              : 
    2842              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2843              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2844              : 
    2845              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_3c_integrals'
    2846              : 
    2847              :       INTEGER                                            :: handle, j_cell, k_cell, nimages_3c
    2848              : 
    2849           16 :       CALL timeset(routineN, handle)
    2850              : 
    2851           16 :       nimages_3c = bs_env%nimages_3c
    2852         2436 :       ALLOCATE (bs_env%t_3c_int(nimages_3c, nimages_3c))
    2853          194 :       DO j_cell = 1, nimages_3c
    2854         2260 :          DO k_cell = 1, nimages_3c
    2855         2244 :             CALL dbt_create(bs_env%t_RI_AO__AO, bs_env%t_3c_int(j_cell, k_cell))
    2856              :          END DO
    2857              :       END DO
    2858              : 
    2859              :       CALL build_3c_integrals(bs_env%t_3c_int, &
    2860              :                               bs_env%eps_filter, &
    2861              :                               qs_env, &
    2862              :                               bs_env%nl_3c, &
    2863              :                               int_eps=bs_env%eps_filter*0.05_dp, &
    2864              :                               basis_i=bs_env%basis_set_RI, &
    2865              :                               basis_j=bs_env%basis_set_AO, &
    2866              :                               basis_k=bs_env%basis_set_AO, &
    2867              :                               potential_parameter=bs_env%ri_metric, &
    2868              :                               desymmetrize=.FALSE., do_kpoints=.TRUE., cell_sym=.TRUE., &
    2869           16 :                               cell_to_index_ext=bs_env%cell_to_index_3c)
    2870              : 
    2871           16 :       CALL bs_env%para_env%sync()
    2872              : 
    2873           16 :       CALL timestop(handle)
    2874              : 
    2875           16 :    END SUBROUTINE compute_3c_integrals
    2876              : 
    2877              : ! **************************************************************************************************
    2878              : !> \brief ...
    2879              : !> \param bs_env ...
    2880              : ! **************************************************************************************************
    2881           16 :    SUBROUTINE setup_cells_Delta_R(bs_env)
    2882              : 
    2883              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2884              : 
    2885              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_cells_Delta_R'
    2886              : 
    2887              :       INTEGER                                            :: handle
    2888              : 
    2889           16 :       CALL timeset(routineN, handle)
    2890              : 
    2891              :       ! cell sums batch wise for fixed ΔR = S_1 - R_1; for example:
    2892              :       ! Σ_λσ^R = sum_PR1νS1 M^G_λ0,νS1,PR1 M^W_σR,νS1,PR1
    2893              : 
    2894              :       CALL sum_two_R_grids(bs_env%index_to_cell_3c, &
    2895              :                            bs_env%index_to_cell_3c, &
    2896              :                            bs_env%nimages_3c, bs_env%nimages_3c, &
    2897              :                            bs_env%index_to_cell_Delta_R, &
    2898              :                            bs_env%cell_to_index_Delta_R, &
    2899           16 :                            bs_env%nimages_Delta_R)
    2900              : 
    2901           16 :       IF (bs_env%unit_nr > 0) THEN
    2902            8 :          WRITE (bs_env%unit_nr, FMT="(T2,A,I61)") "Number of cells ΔR", bs_env%nimages_Delta_R
    2903              :       END IF
    2904              : 
    2905           16 :       CALL timestop(handle)
    2906              : 
    2907           16 :    END SUBROUTINE setup_cells_Delta_R
    2908              : 
    2909              : ! **************************************************************************************************
    2910              : !> \brief ...
    2911              : !> \param index_to_cell_1 ...
    2912              : !> \param index_to_cell_2 ...
    2913              : !> \param nimages_1 ...
    2914              : !> \param nimages_2 ...
    2915              : !> \param index_to_cell ...
    2916              : !> \param cell_to_index ...
    2917              : !> \param nimages ...
    2918              : ! **************************************************************************************************
    2919           16 :    SUBROUTINE sum_two_R_grids(index_to_cell_1, index_to_cell_2, nimages_1, nimages_2, &
    2920              :                               index_to_cell, cell_to_index, nimages)
    2921              : 
    2922              :       INTEGER, DIMENSION(:, :)                           :: index_to_cell_1, index_to_cell_2
    2923              :       INTEGER                                            :: nimages_1, nimages_2
    2924              :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: index_to_cell
    2925              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    2926              :       INTEGER                                            :: nimages
    2927              : 
    2928              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'sum_two_R_grids'
    2929              : 
    2930              :       INTEGER                                            :: handle, i_dim, img_1, img_2, nimages_max
    2931           16 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: index_to_cell_tmp
    2932              :       INTEGER, DIMENSION(3)                              :: cell_1, cell_2, R, R_max, R_min
    2933              : 
    2934           16 :       CALL timeset(routineN, handle)
    2935              : 
    2936           64 :       DO i_dim = 1, 3
    2937         1116 :          R_min(i_dim) = MINVAL(index_to_cell_1(i_dim, :)) + MINVAL(index_to_cell_2(i_dim, :))
    2938         1180 :          R_max(i_dim) = MAXVAL(index_to_cell_1(i_dim, :)) + MAXVAL(index_to_cell_2(i_dim, :))
    2939              :       END DO
    2940              : 
    2941           16 :       nimages_max = (R_max(1) - R_min(1) + 1)*(R_max(2) - R_min(2) + 1)*(R_max(3) - R_min(3) + 1)
    2942              : 
    2943           48 :       ALLOCATE (index_to_cell_tmp(3, nimages_max))
    2944         2176 :       index_to_cell_tmp(:, :) = -1
    2945              : 
    2946           80 :       ALLOCATE (cell_to_index(R_min(1):R_max(1), R_min(2):R_max(2), R_min(3):R_max(3)))
    2947         1156 :       cell_to_index(:, :, :) = -1
    2948              : 
    2949           16 :       nimages = 0
    2950              : 
    2951          194 :       DO img_1 = 1, nimages_1
    2952              : 
    2953         2260 :          DO img_2 = 1, nimages_2
    2954              : 
    2955         8264 :             cell_1(1:3) = index_to_cell_1(1:3, img_1)
    2956         8264 :             cell_2(1:3) = index_to_cell_2(1:3, img_2)
    2957              : 
    2958         8264 :             R(1:3) = cell_1(1:3) + cell_2(1:3)
    2959              : 
    2960              :             ! check whether we have found a new cell
    2961         2244 :             IF (cell_to_index(R(1), R(2), R(3)) == -1) THEN
    2962              : 
    2963          516 :                nimages = nimages + 1
    2964          516 :                cell_to_index(R(1), R(2), R(3)) = nimages
    2965         2064 :                index_to_cell_tmp(1:3, nimages) = R(1:3)
    2966              : 
    2967              :             END IF
    2968              : 
    2969              :          END DO
    2970              : 
    2971              :       END DO
    2972              : 
    2973           48 :       ALLOCATE (index_to_cell(3, nimages))
    2974         2080 :       index_to_cell(:, :) = index_to_cell_tmp(1:3, 1:nimages)
    2975              : 
    2976           16 :       CALL timestop(handle)
    2977              : 
    2978           32 :    END SUBROUTINE sum_two_R_grids
    2979              : 
    2980              : ! **************************************************************************************************
    2981              : !> \brief ...
    2982              : !> \param bs_env ...
    2983              : ! **************************************************************************************************
    2984           16 :    SUBROUTINE setup_parallelization_Delta_R(bs_env)
    2985              : 
    2986              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    2987              : 
    2988              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_parallelization_Delta_R'
    2989              : 
    2990              :       INTEGER                                            :: handle, i_cell_Delta_R, i_task_local, &
    2991              :                                                             n_tasks_local
    2992           16 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: i_cell_Delta_R_group, &
    2993           16 :                                                             n_tensor_ops_Delta_R
    2994              : 
    2995           16 :       CALL timeset(routineN, handle)
    2996              : 
    2997           16 :       CALL compute_n_tensor_ops_Delta_R(bs_env, n_tensor_ops_Delta_R)
    2998              : 
    2999           16 :       CALL compute_Delta_R_dist(bs_env, n_tensor_ops_Delta_R, i_cell_Delta_R_group, n_tasks_local)
    3000              : 
    3001           16 :       bs_env%n_tasks_Delta_R_local = n_tasks_local
    3002              : 
    3003           48 :       ALLOCATE (bs_env%task_Delta_R(n_tasks_local))
    3004              : 
    3005           16 :       i_task_local = 0
    3006          532 :       DO i_cell_Delta_R = 1, bs_env%nimages_Delta_R
    3007              : 
    3008          516 :          IF (i_cell_Delta_R_group(i_cell_Delta_R) /= bs_env%tensor_group_color) CYCLE
    3009              : 
    3010          223 :          i_task_local = i_task_local + 1
    3011              : 
    3012          532 :          bs_env%task_Delta_R(i_task_local) = i_cell_Delta_R
    3013              : 
    3014              :       END DO
    3015              : 
    3016           32 :       ALLOCATE (bs_env%skip_DR_chi(n_tasks_local))
    3017          239 :       bs_env%skip_DR_chi(:) = .FALSE.
    3018           32 :       ALLOCATE (bs_env%skip_DR_Sigma(n_tasks_local))
    3019          239 :       bs_env%skip_DR_Sigma(:) = .FALSE.
    3020              : 
    3021           16 :       CALL allocate_skip_3xR(bs_env%skip_DR_R12_S_Goccx3c_chi, bs_env)
    3022           16 :       CALL allocate_skip_3xR(bs_env%skip_DR_R12_S_Gvirx3c_chi, bs_env)
    3023           16 :       CALL allocate_skip_3xR(bs_env%skip_DR_R_R2_MxM_chi, bs_env)
    3024              : 
    3025           16 :       CALL allocate_skip_3xR(bs_env%skip_DR_R1_S2_Gx3c_Sigma, bs_env)
    3026           16 :       CALL allocate_skip_3xR(bs_env%skip_DR_R1_R_MxM_Sigma, bs_env)
    3027              : 
    3028           16 :       CALL timestop(handle)
    3029              : 
    3030           32 :    END SUBROUTINE setup_parallelization_Delta_R
    3031              : 
    3032              : ! **************************************************************************************************
    3033              : !> \brief ...
    3034              : !> \param bs_env ...
    3035              : !> \param n_tensor_ops_Delta_R ...
    3036              : ! **************************************************************************************************
    3037           16 :    SUBROUTINE compute_n_tensor_ops_Delta_R(bs_env, n_tensor_ops_Delta_R)
    3038              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3039              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: n_tensor_ops_Delta_R
    3040              : 
    3041              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_n_tensor_ops_Delta_R'
    3042              : 
    3043              :       INTEGER :: handle, i_cell_Delta_R, i_cell_R, i_cell_R1, i_cell_R1_minus_R, i_cell_R2, &
    3044              :          i_cell_R2_m_R1, i_cell_S1, i_cell_S1_m_R1_p_R2, i_cell_S1_minus_R, i_cell_S2, &
    3045              :          nimages_Delta_R
    3046              :       INTEGER, DIMENSION(3) :: cell_DR, cell_m_R1, cell_R, cell_R1, cell_R1_minus_R, cell_R2, &
    3047              :          cell_R2_m_R1, cell_S1, cell_S1_m_R2_p_R1, cell_S1_minus_R, cell_S1_p_S2_m_R1, cell_S2
    3048              :       LOGICAL                                            :: cell_found
    3049              : 
    3050           16 :       CALL timeset(routineN, handle)
    3051              : 
    3052           16 :       nimages_Delta_R = bs_env%nimages_Delta_R
    3053              : 
    3054           48 :       ALLOCATE (n_tensor_ops_Delta_R(nimages_Delta_R))
    3055           16 :       n_tensor_ops_Delta_R(:) = 0
    3056              : 
    3057              :       ! compute number of tensor operations for specific Delta_R
    3058          532 :       DO i_cell_Delta_R = 1, nimages_Delta_R
    3059              : 
    3060          516 :          IF (MODULO(i_cell_Delta_R, bs_env%num_tensor_groups) /= bs_env%tensor_group_color) CYCLE
    3061              : 
    3062         3279 :          DO i_cell_R1 = 1, bs_env%nimages_3c
    3063              : 
    3064        12020 :             cell_R1(1:3) = bs_env%index_to_cell_3c(1:3, i_cell_R1)
    3065        12020 :             cell_DR(1:3) = bs_env%index_to_cell_Delta_R(1:3, i_cell_Delta_R)
    3066              : 
    3067              :             ! S_1 = R_1 + ΔR (from ΔR = S_1 - R_1)
    3068              :             CALL add_R(cell_R1, cell_DR, bs_env%index_to_cell_3c, cell_S1, &
    3069         3005 :                        cell_found, bs_env%cell_to_index_3c, i_cell_S1)
    3070         3005 :             IF (.NOT. cell_found) CYCLE
    3071              : 
    3072         9700 :             DO i_cell_R2 = 1, bs_env%nimages_scf_desymm
    3073              : 
    3074        34920 :                cell_R2(1:3) = bs_env%kpoints_scf_desymm%index_to_cell(1:3, i_cell_R2)
    3075              : 
    3076              :                ! R_2 - R_1
    3077              :                CALL add_R(cell_R2, -cell_R1, bs_env%index_to_cell_3c, cell_R2_m_R1, &
    3078        34920 :                           cell_found, bs_env%cell_to_index_3c, i_cell_R2_m_R1)
    3079         8730 :                IF (.NOT. cell_found) CYCLE
    3080              : 
    3081              :                ! S_1 - R_1 + R_2
    3082              :                CALL add_R(cell_S1, cell_R2_m_R1, bs_env%index_to_cell_3c, cell_S1_m_R2_p_R1, &
    3083         5250 :                           cell_found, bs_env%cell_to_index_3c, i_cell_S1_m_R1_p_R2)
    3084         5250 :                IF (.NOT. cell_found) CYCLE
    3085              : 
    3086        13208 :                n_tensor_ops_Delta_R(i_cell_Delta_R) = n_tensor_ops_Delta_R(i_cell_Delta_R) + 1
    3087              : 
    3088              :             END DO ! i_cell_R2
    3089              : 
    3090         9700 :             DO i_cell_S2 = 1, bs_env%nimages_scf_desymm
    3091              : 
    3092        34920 :                cell_S2(1:3) = bs_env%kpoints_scf_desymm%index_to_cell(1:3, i_cell_S2)
    3093        34920 :                cell_m_R1(1:3) = -cell_R1(1:3)
    3094        34920 :                cell_S1_p_S2_m_R1(1:3) = cell_S1(1:3) + cell_S2(1:3) - cell_R1(1:3)
    3095              : 
    3096         8730 :                CALL is_cell_in_index_to_cell(cell_m_R1, bs_env%index_to_cell_3c, cell_found)
    3097         8730 :                IF (.NOT. cell_found) CYCLE
    3098              : 
    3099         7029 :                CALL is_cell_in_index_to_cell(cell_S1_p_S2_m_R1, bs_env%index_to_cell_3c, cell_found)
    3100          970 :                IF (.NOT. cell_found) CYCLE
    3101              : 
    3102              :             END DO ! i_cell_S2
    3103              : 
    3104        13221 :             DO i_cell_R = 1, bs_env%nimages_scf_desymm
    3105              : 
    3106        34920 :                cell_R = bs_env%kpoints_scf_desymm%index_to_cell(1:3, i_cell_R)
    3107              : 
    3108              :                ! R_1 - R
    3109              :                CALL add_R(cell_R1, -cell_R, bs_env%index_to_cell_3c, cell_R1_minus_R, &
    3110        34920 :                           cell_found, bs_env%cell_to_index_3c, i_cell_R1_minus_R)
    3111         8730 :                IF (.NOT. cell_found) CYCLE
    3112              : 
    3113              :                ! S_1 - R
    3114              :                CALL add_R(cell_S1, -cell_R, bs_env%index_to_cell_3c, cell_S1_minus_R, &
    3115        22764 :                           cell_found, bs_env%cell_to_index_3c, i_cell_S1_minus_R)
    3116         3005 :                IF (.NOT. cell_found) CYCLE
    3117              : 
    3118              :             END DO ! i_cell_R
    3119              : 
    3120              :          END DO ! i_cell_R1
    3121              : 
    3122              :       END DO ! i_cell_Delta_R
    3123              : 
    3124           16 :       CALL bs_env%para_env%sum(n_tensor_ops_Delta_R)
    3125              : 
    3126           16 :       CALL timestop(handle)
    3127              : 
    3128           16 :    END SUBROUTINE compute_n_tensor_ops_Delta_R
    3129              : 
    3130              : ! **************************************************************************************************
    3131              : !> \brief ...
    3132              : !> \param cell_1 ...
    3133              : !> \param cell_2 ...
    3134              : !> \param index_to_cell ...
    3135              : !> \param cell_1_plus_2 ...
    3136              : !> \param cell_found ...
    3137              : !> \param cell_to_index ...
    3138              : !> \param i_cell_1_plus_2 ...
    3139              : ! **************************************************************************************************
    3140       279284 :    SUBROUTINE add_R(cell_1, cell_2, index_to_cell, cell_1_plus_2, cell_found, &
    3141              :                     cell_to_index, i_cell_1_plus_2)
    3142              : 
    3143              :       INTEGER, DIMENSION(3)                              :: cell_1, cell_2
    3144              :       INTEGER, DIMENSION(:, :)                           :: index_to_cell
    3145              :       INTEGER, DIMENSION(3)                              :: cell_1_plus_2
    3146              :       LOGICAL                                            :: cell_found
    3147              :       INTEGER, DIMENSION(:, :, :), INTENT(IN), &
    3148              :          OPTIONAL, POINTER                               :: cell_to_index
    3149              :       INTEGER, INTENT(OUT), OPTIONAL                     :: i_cell_1_plus_2
    3150              : 
    3151              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'add_R'
    3152              : 
    3153              :       INTEGER                                            :: handle
    3154              : 
    3155       279284 :       CALL timeset(routineN, handle)
    3156              : 
    3157      1117136 :       cell_1_plus_2(1:3) = cell_1(1:3) + cell_2(1:3)
    3158              : 
    3159       279284 :       CALL is_cell_in_index_to_cell(cell_1_plus_2, index_to_cell, cell_found)
    3160              : 
    3161       279284 :       IF (PRESENT(i_cell_1_plus_2)) THEN
    3162       279284 :          IF (cell_found) THEN
    3163       160334 :             CPASSERT(PRESENT(cell_to_index))
    3164       160334 :             i_cell_1_plus_2 = cell_to_index(cell_1_plus_2(1), cell_1_plus_2(2), cell_1_plus_2(3))
    3165              :          ELSE
    3166       118950 :             i_cell_1_plus_2 = -1000
    3167              :          END IF
    3168              :       END IF
    3169              : 
    3170       279284 :       CALL timestop(handle)
    3171              : 
    3172       279284 :    END SUBROUTINE add_R
    3173              : 
    3174              : ! **************************************************************************************************
    3175              : !> \brief ...
    3176              : !> \param cell ...
    3177              : !> \param index_to_cell ...
    3178              : !> \param cell_found ...
    3179              : ! **************************************************************************************************
    3180       437679 :    SUBROUTINE is_cell_in_index_to_cell(cell, index_to_cell, cell_found)
    3181              :       INTEGER, DIMENSION(3)                              :: cell
    3182              :       INTEGER, DIMENSION(:, :)                           :: index_to_cell
    3183              :       LOGICAL                                            :: cell_found
    3184              : 
    3185              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'is_cell_in_index_to_cell'
    3186              : 
    3187              :       INTEGER                                            :: handle, i_cell, nimg
    3188              :       INTEGER, DIMENSION(3)                              :: cell_i
    3189              : 
    3190       437679 :       CALL timeset(routineN, handle)
    3191              : 
    3192       437679 :       nimg = SIZE(index_to_cell, 2)
    3193              : 
    3194       437679 :       cell_found = .FALSE.
    3195              : 
    3196      5604294 :       DO i_cell = 1, nimg
    3197              : 
    3198     20666460 :          cell_i(1:3) = index_to_cell(1:3, i_cell)
    3199              : 
    3200      5604294 :          IF (cell_i(1) == cell(1) .AND. cell_i(2) == cell(2) .AND. cell_i(3) == cell(3)) THEN
    3201       263631 :             cell_found = .TRUE.
    3202              :          END IF
    3203              : 
    3204              :       END DO
    3205              : 
    3206       437679 :       CALL timestop(handle)
    3207              : 
    3208       437679 :    END SUBROUTINE is_cell_in_index_to_cell
    3209              : 
    3210              : ! **************************************************************************************************
    3211              : !> \brief ...
    3212              : !> \param bs_env ...
    3213              : !> \param n_tensor_ops_Delta_R ...
    3214              : !> \param i_cell_Delta_R_group ...
    3215              : !> \param n_tasks_local ...
    3216              : ! **************************************************************************************************
    3217           16 :    SUBROUTINE compute_Delta_R_dist(bs_env, n_tensor_ops_Delta_R, i_cell_Delta_R_group, n_tasks_local)
    3218              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3219              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: n_tensor_ops_Delta_R, &
    3220              :                                                             i_cell_Delta_R_group
    3221              :       INTEGER                                            :: n_tasks_local
    3222              : 
    3223              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_Delta_R_dist'
    3224              : 
    3225              :       INTEGER                                            :: handle, i_Delta_R_max_op, i_group_min, &
    3226              :                                                             nimages_Delta_R, u
    3227           16 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: n_tensor_ops_Delta_R_in_group
    3228              : 
    3229           16 :       CALL timeset(routineN, handle)
    3230              : 
    3231           16 :       nimages_Delta_R = bs_env%nimages_Delta_R
    3232              : 
    3233           16 :       u = bs_env%unit_nr
    3234              : 
    3235           16 :       IF (u > 0 .AND. nimages_Delta_R < bs_env%num_tensor_groups) THEN
    3236            0 :          WRITE (u, FMT="(T2,A,I5,A,I5,A)") "There are only ", nimages_Delta_R, &
    3237            0 :             " tasks to work on but there are ", bs_env%num_tensor_groups, " groups."
    3238            0 :          WRITE (u, FMT="(T2,A)") "Please reduce the number of MPI processes."
    3239            0 :          WRITE (u, '(T2,A)') ''
    3240              :       END IF
    3241              : 
    3242           48 :       ALLOCATE (n_tensor_ops_Delta_R_in_group(bs_env%num_tensor_groups))
    3243           16 :       n_tensor_ops_Delta_R_in_group(:) = 0
    3244           48 :       ALLOCATE (i_cell_Delta_R_group(nimages_Delta_R))
    3245          532 :       i_cell_Delta_R_group(:) = -1
    3246              : 
    3247           16 :       n_tasks_local = 0
    3248              : 
    3249         1914 :       DO WHILE (ANY(n_tensor_ops_Delta_R(:) /= 0))
    3250              : 
    3251              :          ! get largest element of n_tensor_ops_Delta_R
    3252        15484 :          i_Delta_R_max_op = MAXLOC(n_tensor_ops_Delta_R, 1)
    3253              : 
    3254              :          ! distribute i_Delta_R_max_op to tensor group which has currently the smallest load
    3255         1784 :          i_group_min = MINLOC(n_tensor_ops_Delta_R_in_group, 1)
    3256              : 
    3257              :          ! the tensor groups are 0-index based; but i_group_min is 1-index based
    3258          446 :          i_cell_Delta_R_group(i_Delta_R_max_op) = i_group_min - 1
    3259              :          n_tensor_ops_Delta_R_in_group(i_group_min) = n_tensor_ops_Delta_R_in_group(i_group_min) + &
    3260          446 :                                                       n_tensor_ops_Delta_R(i_Delta_R_max_op)
    3261              : 
    3262              :          ! remove i_Delta_R_max_op from n_tensor_ops_Delta_R
    3263          446 :          n_tensor_ops_Delta_R(i_Delta_R_max_op) = 0
    3264              : 
    3265          462 :          IF (bs_env%tensor_group_color == i_group_min - 1) n_tasks_local = n_tasks_local + 1
    3266              : 
    3267              :       END DO
    3268              : 
    3269           16 :       CALL timestop(handle)
    3270              : 
    3271           32 :    END SUBROUTINE compute_Delta_R_dist
    3272              : 
    3273              : ! **************************************************************************************************
    3274              : !> \brief ...
    3275              : !> \param skip ...
    3276              : !> \param bs_env ...
    3277              : ! **************************************************************************************************
    3278           80 :    SUBROUTINE allocate_skip_3xR(skip, bs_env)
    3279              :       LOGICAL, ALLOCATABLE, DIMENSION(:, :, :)           :: skip
    3280              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3281              : 
    3282              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'allocate_skip_3xR'
    3283              : 
    3284              :       INTEGER                                            :: handle
    3285              : 
    3286           80 :       CALL timeset(routineN, handle)
    3287              : 
    3288          400 :       ALLOCATE (skip(bs_env%n_tasks_Delta_R_local, bs_env%nimages_3c, bs_env%nimages_scf_desymm))
    3289           80 :       skip(:, :, :) = .FALSE.
    3290              : 
    3291           80 :       CALL timestop(handle)
    3292              : 
    3293           80 :    END SUBROUTINE allocate_skip_3xR
    3294              : 
    3295              : ! **************************************************************************************************
    3296              : !> \brief ...
    3297              : !> \param qs_env ...
    3298              : !> \param bs_env ...
    3299              : ! **************************************************************************************************
    3300           16 :    SUBROUTINE allocate_matrices_small_cell_full_kp_tensor(qs_env, bs_env)
    3301              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3302              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3303              : 
    3304              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'allocate_matrices_small_cell_full_kp_tensor'
    3305              : 
    3306              :       INTEGER                                            :: handle, i_spin, i_t, img, n_spin, &
    3307              :                                                             nimages_scf, num_time_freq_points
    3308              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    3309              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3310              : 
    3311           16 :       CALL timeset(routineN, handle)
    3312              : 
    3313           16 :       nimages_scf = bs_env%nimages_scf_desymm
    3314           16 :       num_time_freq_points = bs_env%num_time_freq_points
    3315           16 :       n_spin = bs_env%n_spin
    3316              : 
    3317           16 :       CALL get_qs_env(qs_env, para_env=para_env, blacs_env=blacs_env)
    3318              : 
    3319          192 :       ALLOCATE (bs_env%fm_G_S(nimages_scf))
    3320          176 :       ALLOCATE (bs_env%fm_Sigma_x_R(nimages_scf))
    3321         1104 :       ALLOCATE (bs_env%fm_chi_R_t(nimages_scf, num_time_freq_points))
    3322         1088 :       ALLOCATE (bs_env%fm_MWM_R_t(nimages_scf, num_time_freq_points))
    3323         1136 :       ALLOCATE (bs_env%fm_Sigma_c_R_neg_tau(nimages_scf, num_time_freq_points, n_spin))
    3324         1120 :       ALLOCATE (bs_env%fm_Sigma_c_R_pos_tau(nimages_scf, num_time_freq_points, n_spin))
    3325          160 :       DO img = 1, nimages_scf
    3326          144 :          CALL cp_fm_create(bs_env%fm_G_S(img), bs_env%fm_work_mo(1)%matrix_struct)
    3327          144 :          CALL cp_fm_create(bs_env%fm_Sigma_x_R(img), bs_env%fm_work_mo(1)%matrix_struct)
    3328         1096 :          DO i_t = 1, num_time_freq_points
    3329          936 :             CALL cp_fm_create(bs_env%fm_chi_R_t(img, i_t), bs_env%fm_RI_RI%matrix_struct)
    3330          936 :             CALL cp_fm_create(bs_env%fm_MWM_R_t(img, i_t), bs_env%fm_RI_RI%matrix_struct)
    3331          936 :             CALL cp_fm_set_all(bs_env%fm_MWM_R_t(img, i_t), 0.0_dp)
    3332         2016 :             DO i_spin = 1, n_spin
    3333              :                CALL cp_fm_create(bs_env%fm_Sigma_c_R_neg_tau(img, i_t, i_spin), &
    3334          936 :                                  bs_env%fm_work_mo(1)%matrix_struct)
    3335              :                CALL cp_fm_create(bs_env%fm_Sigma_c_R_pos_tau(img, i_t, i_spin), &
    3336          936 :                                  bs_env%fm_work_mo(1)%matrix_struct)
    3337          936 :                CALL cp_fm_set_all(bs_env%fm_Sigma_c_R_neg_tau(img, i_t, i_spin), 0.0_dp)
    3338         1872 :                CALL cp_fm_set_all(bs_env%fm_Sigma_c_R_pos_tau(img, i_t, i_spin), 0.0_dp)
    3339              :             END DO
    3340              :          END DO
    3341              :       END DO
    3342              : 
    3343           16 :       CALL timestop(handle)
    3344              : 
    3345           16 :    END SUBROUTINE allocate_matrices_small_cell_full_kp_tensor
    3346              : 
    3347              : ! **************************************************************************************************
    3348              : !> \brief ...
    3349              : !> \param qs_env ...
    3350              : !> \param bs_env ...
    3351              : ! **************************************************************************************************
    3352           30 :    SUBROUTINE trafo_V_xc_R_to_kp(qs_env, bs_env)
    3353              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3354              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3355              : 
    3356              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'trafo_V_xc_R_to_kp'
    3357              : 
    3358              :       INTEGER                                            :: handle, ikp, img, ispin, n_ao
    3359              :       TYPE(cp_cfm_type)                                  :: cfm_kp_group, cfm_mo_coeff, cfm_V_xc
    3360              :       TYPE(cp_fm_type)                                   :: fm_V_xc_re
    3361           30 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks
    3362           30 :       TYPE(kpoint_operator_context_type)                 :: operators
    3363              :       TYPE(kpoint_type), POINTER                         :: kpoints_bs
    3364              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3365              : 
    3366           30 :       CALL timeset(routineN, handle)
    3367              : 
    3368           30 :       n_ao = bs_env%n_ao
    3369              : 
    3370           30 :       CALL get_qs_env(qs_env, para_env=para_env, matrix_ks_kp=matrix_ks)
    3371              : 
    3372           30 :       CALL cp_cfm_create(cfm_V_xc, bs_env%cfm_work_mo%matrix_struct)
    3373           30 :       CALL cp_cfm_create(cfm_mo_coeff, bs_env%cfm_work_mo%matrix_struct)
    3374           30 :       CALL cp_fm_create(fm_V_xc_re, bs_env%cfm_work_mo%matrix_struct)
    3375              : 
    3376         1424 :       DO img = 1, bs_env%nimages_scf
    3377         2818 :          DO ispin = 1, bs_env%n_spin
    3378              :             ! JW kind of hack because the format of matrix_ks remains dubious...
    3379         1394 :             CALL dbcsr_set(matrix_ks(ispin, img)%matrix, 0.0_dp)
    3380         2788 :             CALL copy_fm_to_dbcsr(bs_env%fm_V_xc_R(img, ispin), matrix_ks(ispin, img)%matrix)
    3381              :          END DO
    3382              :       END DO
    3383              : 
    3384           30 :       CALL create_operator_kpoints(qs_env, bs_env, kpoints_bs, cfm_kp_group)
    3385           30 :       CALL kpoint_operator_context_create(operators, kpoints_bs, bs_env%fm_work_mo(1), bs_env%n_spin)
    3386           30 :       CALL kpoint_operator_prepare(operators, matrix_ks, kpoint_slot_ks)
    3387              : 
    3388          150 :       ALLOCATE (bs_env%v_xc_n(n_ao, bs_env%nkp_bs_and_DOS, bs_env%n_spin))
    3389              : 
    3390           60 :       DO ispin = 1, bs_env%n_spin
    3391          668 :          DO ikp = 1, bs_env%nkp_bs_and_DOS
    3392              : 
    3393              :             ! v^xc^R -> v^xc(k)  (matrix_ks stores v^xc^R, see SUBROUTINE compute_V_xc)
    3394              :             CALL kpoint_operator_get(operators, ikp, ispin, matrix_ks, cmat=cfm_kp_group, &
    3395          608 :                                      matrix_row=ispin, slot=kpoint_slot_ks)
    3396          608 :             CALL cp_cfm_copy_general(cfm_kp_group, cfm_V_xc, para_env)
    3397              : 
    3398              :             ! get C_µn(k)
    3399          608 :             CALL cp_cfm_to_cfm(bs_env%cfm_mo_coeff_kp(ikp, ispin), cfm_mo_coeff)
    3400              : 
    3401              :             ! v^xc_nm(k_i) = sum_µν C^*_µn(k_i) v^xc_µν(k_i) C_νn(k_i)
    3402          608 :             CALL cfm_contract_ABA(cfm_mo_coeff, cfm_V_xc)
    3403              : 
    3404              :             ! get v^xc_nn(k_i) which is a real quantity as v^xc is Hermitian
    3405          608 :             CALL cp_cfm_to_fm(cfm_V_xc, fm_V_xc_re)
    3406          638 :             CALL cp_fm_get_diag(fm_V_xc_re, bs_env%v_xc_n(:, ikp, ispin))
    3407              : 
    3408              :          END DO
    3409              : 
    3410              :       END DO
    3411              : 
    3412           30 :       CALL kpoint_operator_context_release(operators)
    3413           30 :       CALL cp_cfm_release(cfm_kp_group)
    3414           30 :       CALL kpoint_release(kpoints_bs)
    3415              : 
    3416              :       ! just rebuild the overwritten KS matrix again
    3417           30 :       CALL build_periodic_ks_with_gapw_density(qs_env)
    3418              : 
    3419           30 :       CALL cp_cfm_release(cfm_V_xc)
    3420           30 :       CALL cp_cfm_release(cfm_mo_coeff)
    3421           30 :       CALL cp_fm_release(fm_V_xc_re)
    3422              : 
    3423           30 :       CALL timestop(handle)
    3424              : 
    3425          120 :    END SUBROUTINE trafo_V_xc_R_to_kp
    3426              : 
    3427              : ! **************************************************************************************************
    3428              : !> \brief ...
    3429              : !> \param qs_env ...
    3430              : !> \param bs_env ...
    3431              : ! **************************************************************************************************
    3432           16 :    SUBROUTINE heuristic_RI_regularization(qs_env, bs_env)
    3433              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3434              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3435              : 
    3436              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'heuristic_RI_regularization'
    3437              : 
    3438           16 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)  :: M
    3439              :       INTEGER                                            :: handle, ikp, ikp_local, n_RI, nkp, &
    3440              :                                                             nkp_local, u
    3441              :       REAL(KIND=dp)                                      :: cond_nr, cond_nr_max, max_ev, &
    3442              :                                                             max_ev_ikp, min_ev, min_ev_ikp
    3443           16 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: M_R
    3444              : 
    3445           16 :       CALL timeset(routineN, handle)
    3446              : 
    3447              :       ! compute M^R_PQ = <phi_P,0|V^tr(rc)|phi_Q,R> for RI metric
    3448           16 :       CALL get_V_tr_R(M_R, bs_env%ri_metric, 0.0_dp, bs_env, qs_env)
    3449              : 
    3450           16 :       nkp = bs_env%nkp_chi_eps_W_orig_plus_extra
    3451           16 :       n_RI = bs_env%n_RI
    3452              : 
    3453           16 :       nkp_local = 0
    3454        10256 :       DO ikp = 1, nkp
    3455              :          ! trivial parallelization over k-points
    3456        10240 :          IF (MODULO(ikp, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    3457        10256 :          nkp_local = nkp_local + 1
    3458              :       END DO
    3459              : 
    3460           80 :       ALLOCATE (M(n_RI, n_RI, nkp_local))
    3461              : 
    3462           16 :       ikp_local = 0
    3463           16 :       cond_nr_max = 0.0_dp
    3464           16 :       min_ev = 1000.0_dp
    3465           16 :       max_ev = -1000.0_dp
    3466              : 
    3467        10256 :       DO ikp = 1, nkp
    3468              : 
    3469              :          ! trivial parallelization
    3470        10240 :          IF (MODULO(ikp, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    3471              : 
    3472         5120 :          ikp_local = ikp_local + 1
    3473              : 
    3474              :          ! M(k) = sum_R e^ikR M^R
    3475              :          CALL rs_to_kp(M_R, M(:, :, ikp_local), &
    3476              :                        bs_env%kpoints_scf_desymm%index_to_cell, &
    3477         5120 :                        bs_env%kpoints_chi_eps_W%xkp(1:3, ikp))
    3478              : 
    3479              :          ! compute condition number of M_PQ(k)
    3480         5120 :          CALL local_complex_power(M(:, :, ikp_local), 1.0_dp, 0.0_dp, cond_nr, min_ev_ikp, max_ev_ikp)
    3481              : 
    3482         5120 :          IF (cond_nr > cond_nr_max) cond_nr_max = cond_nr
    3483         5120 :          IF (max_ev_ikp > max_ev) max_ev = max_ev_ikp
    3484         5136 :          IF (min_ev_ikp < min_ev) min_ev = min_ev_ikp
    3485              : 
    3486              :       END DO ! ikp
    3487              : 
    3488           16 :       CALL bs_env%para_env%max(cond_nr_max)
    3489           16 :       CALL bs_env%para_env%min(min_ev)
    3490           16 :       CALL bs_env%para_env%max(max_ev)
    3491              : 
    3492           16 :       u = bs_env%unit_nr
    3493           16 :       IF (u > 0) THEN
    3494            8 :          WRITE (u, FMT="(T2,A,ES34.1)") "Min. abs. eigenvalue of RI metric matrix M(k)", min_ev
    3495            8 :          WRITE (u, FMT="(T2,A,ES34.1)") "Max. abs. eigenvalue of RI metric matrix M(k)", max_ev
    3496            8 :          WRITE (u, FMT="(T2,A,ES50.1)") "Max. condition number of M(k)", cond_nr_max
    3497              :       END IF
    3498              : 
    3499           16 :       CALL timestop(handle)
    3500              : 
    3501           32 :    END SUBROUTINE heuristic_RI_regularization
    3502              : 
    3503              : ! **************************************************************************************************
    3504              : !> \brief ...
    3505              : !> \param bs_env ...
    3506              : ! **************************************************************************************************
    3507          156 :    SUBROUTINE setup_time_and_frequency_minimax_grid(bs_env)
    3508              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3509              : 
    3510              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_time_and_frequency_minimax_grid'
    3511              : 
    3512              :       INTEGER                                            :: handle, homo, ispin, n_mo, n_top, &
    3513              :                                                             num_time_freq_points, u
    3514              :       REAL(KIND=dp)                                      :: E_max, E_max_ispin, E_min, E_min_ispin, &
    3515              :                                                             E_range, max_error_min, max_error_sigma
    3516              : 
    3517          156 :       CALL timeset(routineN, handle)
    3518              : 
    3519          156 :       n_mo = bs_env%n_ao
    3520          156 :       num_time_freq_points = bs_env%num_time_freq_points
    3521              : 
    3522              :       ! minimum and maximum difference between eigenvalues of unoccupied and an occupied MOs
    3523          156 :       E_min = 1000.0_dp
    3524          156 :       E_max = -1000.0_dp
    3525          330 :       DO ispin = 1, bs_env%n_spin
    3526          174 :          homo = bs_env%n_occ(ispin)
    3527              : 
    3528              :          ! Highest index that is a real state. The canonical orthogonalization removes the
    3529              :          ! linearly dependent basis modes and parks them at the top of the spectrum with a
    3530              :          ! placeholder eigenvalue; n_mo_retained is how many real states it kept.
    3531          174 :          n_top = MAX(MIN(bs_env%n_mo_retained, n_mo), homo + 1)
    3532              : 
    3533          318 :          SELECT CASE (bs_env%gw_implementation)
    3534              :          CASE (tensor_large_cell_Gamma, ri_rs_large_cell_Gamma, ri_rs_non_periodic, tensor_static_cohsex)
    3535              :             E_min_ispin = bs_env%eigenval_scf_Gamma(homo + 1, ispin) - &
    3536          144 :                           bs_env%eigenval_scf_Gamma(homo, ispin)
    3537              :             E_max_ispin = bs_env%eigenval_scf_Gamma(n_top, ispin) - &
    3538          144 :                           bs_env%eigenval_scf_Gamma(1, ispin)
    3539              :          CASE (tensor_small_cell_full_kp, ri_rs_small_cell_full_kp)
    3540              :             E_min_ispin = MINVAL(bs_env%eigenval_scf(homo + 1, :, ispin)) - &
    3541         1246 :                           MAXVAL(bs_env%eigenval_scf(homo, :, ispin))
    3542              :             E_max_ispin = MAXVAL(bs_env%eigenval_scf(n_top, :, ispin)) - &
    3543         1420 :                           MINVAL(bs_env%eigenval_scf(1, :, ispin))
    3544              :          END SELECT
    3545          174 :          E_min = MIN(E_min, E_min_ispin)
    3546          330 :          E_max = MAX(E_max, E_max_ispin)
    3547              :       END DO
    3548              : 
    3549              :       ! Open-shell uses ONE minimax grid for the combined [min gap, max span] over both spins (the
    3550              :       ! superset covers each channel, so it is accurate; per-spin grids would only be more efficient).
    3551          156 :       IF (bs_env%n_spin > 1) THEN
    3552              :          CALL cp_hint(__LOCATION__, &
    3553              :                       "Open-shell GW uses one time-frequency grid spanning [min gap, max span] across both "// &
    3554              :                       "spin channels; raise NUM_TIME_FREQ_POINTS if QP convergence is marginal for "// &
    3555           18 :                       "strongly spin-asymmetric systems.")
    3556              :       END IF
    3557              : 
    3558          156 :       E_range = E_max/E_min
    3559              : 
    3560              :       CALL build_minimax_time_frequency_grid(num_time_freq_points, E_min, E_max, bs_env%regularization_minimax, &
    3561              :                                              bs_env%num_points_per_magnitude, bs_env%time_frequency_grid, &
    3562              :                                              build_frequency=.TRUE., build_time=.TRUE., build_transforms=.TRUE., &
    3563              :                                              build_sine=.TRUE., time_scaling=2.0_dp, time_weight_scaling=1.0_dp, &
    3564              :                                              max_fit_error=max_error_min, print_warning=.FALSE., unit_nr=0, &
    3565          156 :                                              prefer_external_backend=.FALSE.)
    3566              : 
    3567              :       ! Σ^c(iτ) -> Σ^c(iω) has its own weights: for NEVANLINNA, a truncated SVD keeps the samples
    3568              :       ! of Σ^c(iω) causal; χ and W keep the regularized weights and do not depend on the
    3569              :       ! analytic continuation
    3570          156 :       IF (bs_env%ac_method == gw_ac_nevanlinna) THEN
    3571              :          CALL build_minimax_time_frequency_grid(num_time_freq_points, E_min, E_max, bs_env%regularization_minimax, &
    3572              :                                                 bs_env%num_points_per_magnitude, bs_env%time_frequency_grid_sigma, &
    3573              :                                                 build_frequency=.TRUE., build_time=.TRUE., build_transforms=.TRUE., &
    3574              :                                                 build_sine=.TRUE., time_scaling=2.0_dp, time_weight_scaling=1.0_dp, &
    3575              :                                                 max_fit_error=max_error_sigma, print_warning=.FALSE., unit_nr=0, &
    3576              :                                                 prefer_external_backend=.FALSE., &
    3577          154 :                                                 rcond=bs_env%nevanlinna%rcond_weights)
    3578              :       ELSE
    3579            2 :          bs_env%time_frequency_grid_sigma = bs_env%time_frequency_grid
    3580              :       END IF
    3581              : 
    3582              :       ! determine number of fit points in the interval [0,ω_max] for virt, or [-ω_max,0] for occ
    3583         2580 :       bs_env%num_freq_points_fit = COUNT(bs_env%time_frequency_grid%frequency < bs_env%freq_max_fit)
    3584              : 
    3585              :       ! iω values for the analytic continuation Σ^c_n(iω,k) -> Σ^c_n(ϵ,k)
    3586          468 :       ALLOCATE (bs_env%imag_freq_points_fit(bs_env%num_freq_points_fit))
    3587              :       bs_env%imag_freq_points_fit(:) = PACK(bs_env%time_frequency_grid%frequency, &
    3588         3182 :                                             bs_env%time_frequency_grid%frequency < bs_env%freq_max_fit)
    3589              : 
    3590              :       ! reset the number of Padé parameters if smaller than the number of
    3591              :       ! imaginary-frequency points for the fit
    3592          156 :       IF (bs_env%num_freq_points_fit < bs_env%nparam_pade) THEN
    3593          148 :          bs_env%nparam_pade = bs_env%num_freq_points_fit
    3594              :       END IF
    3595              : 
    3596              :       ! the Nevanlinna interpolant goes through all imaginary frequencies; its Padé fallback keeps
    3597              :       ! the points below ω_max and the number of Padé parameters of the PADE continuation
    3598          156 :       bs_env%num_freq_points_pade = bs_env%num_freq_points_fit
    3599          156 :       IF (bs_env%ac_method == gw_ac_nevanlinna) THEN
    3600          154 :          bs_env%num_freq_points_fit = num_time_freq_points
    3601          154 :          DEALLOCATE (bs_env%imag_freq_points_fit)
    3602          462 :          ALLOCATE (bs_env%imag_freq_points_fit(num_time_freq_points))
    3603         2566 :          bs_env%imag_freq_points_fit(:) = bs_env%time_frequency_grid%frequency
    3604              :       END IF
    3605              : 
    3606          156 :       u = bs_env%unit_nr
    3607          156 :       IF (u > 0) THEN
    3608           78 :          WRITE (u, '(T2,A)') ''
    3609           78 :          WRITE (u, '(T2,A,F50.2)') 'SCF fundamental band gap (eV)', E_min*evolt
    3610           78 :          WRITE (u, '(T2,A,F53.2)') 'Max. SCF eigval diff. (eV)', E_max*evolt
    3611           78 :          WRITE (u, '(T2,A,F55.2)') 'E-Range for minimax grid', E_range
    3612           78 :          WRITE (u, '(T2,A,I27)') 'Number of Padé parameters for analytic continuation:', &
    3613          156 :             bs_env%nparam_pade
    3614           78 :          WRITE (u, '(T2,A)') ''
    3615              :       END IF
    3616              : 
    3617              :       ! in minimax grids, Fourier transforms t -> w and w -> t are split using
    3618              :       ! e^(iwt) = cos(wt) + i sin(wt); we thus calculate weights for trafos with a cos and
    3619              :       ! sine prefactor; details in Azizi, Wilhelm, Golze, Giantomassi, Panades-Barrueta,
    3620              :       ! Rinke, Draxl, Gonze et al., 2 publications
    3621              : 
    3622          156 :       CALL timestop(handle)
    3623              : 
    3624          156 :    END SUBROUTINE setup_time_and_frequency_minimax_grid
    3625              : 
    3626              : ! **************************************************************************************************
    3627              : !> \brief Releases the memory-heavy GW intermediates that cannot be freed in bs_env_release,
    3628              : !>        retaining the 3c neighbor list only when an AO-RI RT-BSE self-energy still needs it
    3629              : !> \param qs_env ...
    3630              : !> \param bs_env ...
    3631              : ! **************************************************************************************************
    3632          156 :    SUBROUTINE de_init_bs_env(qs_env, bs_env)
    3633              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3634              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3635              : 
    3636              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'de_init_bs_env'
    3637              : 
    3638              :       INTEGER                                            :: handle
    3639              :       LOGICAL                                            :: retain_nl_3c, rirs_kernel
    3640              : 
    3641          156 :       CALL timeset(routineN, handle)
    3642              :       ! deallocate quantities here which:
    3643              :       ! 1. cannot be deallocated in bs_env_release due to circular dependencies
    3644              :       ! 2. consume a lot of memory and should not be kept until the quantity is
    3645              :       !    deallocated in bs_env_release
    3646              : 
    3647              :       ! nl_3c feeds compute_3c_integrals after the GW: the AO-RI RT-BSE SEX self-energy (the RI-RS
    3648              :       ! path never reads it, and AO-RI Hartree builds its own blocks) and PROPERTIES%BSE (keep_3c_nl).
    3649          156 :       retain_nl_3c = bs_env%keep_3c_nl
    3650          156 :       IF (ASSOCIATED(bs_env%nl_3c%ij_list) .AND. (bs_env%rtp_method == rtp_method_bse)) THEN
    3651           72 :          CALL rtbse_resolve_rirs_flag(qs_env, bs_env, rirs_kernel=rirs_kernel)
    3652           72 :          retain_nl_3c = retain_nl_3c .OR. .NOT. rirs_kernel
    3653              :       END IF
    3654              : 
    3655           84 :       IF (retain_nl_3c) THEN
    3656           56 :          IF (bs_env%unit_nr > 0) WRITE (bs_env%unit_nr, *) "Keep nl_3c for BSE"
    3657              :       ELSE
    3658          100 :          CALL neighbor_list_3c_destroy(bs_env%nl_3c)
    3659              :       END IF
    3660              : 
    3661          156 :       CALL timestop(handle)
    3662              : 
    3663          156 :    END SUBROUTINE de_init_bs_env
    3664              : 
    3665              : ! **************************************************************************************************
    3666              : !> \brief Resolve the linRTBSE RI-RS kernel switch from the KERNEL_RI input and the GW default.
    3667              : !> \param qs_env ...
    3668              : !> \param bs_env ...
    3669              : !> \param rirs_kernel (optional) .TRUE. if the Hartree + SEX kernels use the RI-RS grid backend
    3670              : !> \author Maximilian Graml
    3671              : !> \note Single source of truth shared by create_rtbse_env (sets the flag) and de_init_bs_env
    3672              : !>       (decides whether to retain nl_3c). KERNEL_RI=DEFAULT follows bs_env%do_gw_ri_rs;
    3673              : !>       RS/AO force; forced .FALSE. for non-linearized (full) RT-BSE (warn on explicit RS).
    3674              : ! **************************************************************************************************
    3675          288 :    SUBROUTINE rtbse_resolve_rirs_flag(qs_env, bs_env, rirs_kernel)
    3676              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3677              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3678              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: rirs_kernel
    3679              : 
    3680              :       INTEGER                                            :: kernel_ri
    3681              :       LOGICAL                                            :: my_rirs_kernel
    3682              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3683              :       TYPE(section_vals_type), POINTER                   :: input
    3684              : 
    3685          144 :       NULLIFY (dft_control, input)
    3686          144 :       CALL get_qs_env(qs_env, dft_control=dft_control, input=input)
    3687              : 
    3688              :       CALL section_vals_val_get(input, "DFT%REAL_TIME_PROPAGATION%RTBSE%KERNEL_RI", &
    3689          144 :                                 i_val=kernel_ri)
    3690              :       SELECT CASE (kernel_ri)
    3691              :       CASE (rtp_bse_kernel_ri_rs)
    3692            0 :          my_rirs_kernel = .TRUE.
    3693              :       CASE (rtp_bse_kernel_ri_ao)
    3694            0 :          my_rirs_kernel = .FALSE.
    3695              :       CASE DEFAULT  ! rtp_bse_kernel_ri_default
    3696          144 :          my_rirs_kernel = bs_env%do_gw_ri_rs
    3697              :       END SELECT
    3698              : 
    3699              :       ! RI-RS kernels are implemented for linearized RT-BSE only; full RT-BSE always uses AO-RI.
    3700          144 :       IF (dft_control%rtp_control%rtp_method /= rtp_method_bse_linearized) THEN
    3701           28 :          IF (kernel_ri == rtp_bse_kernel_ri_rs) THEN
    3702            0 :             CPWARN("RI-RS kernels are implemented for linearized RT-BSE only; forcing AO")
    3703              :          END IF
    3704              :          my_rirs_kernel = .FALSE.
    3705              :       END IF
    3706              : 
    3707          144 :       IF (PRESENT(rirs_kernel)) rirs_kernel = my_rirs_kernel
    3708              : 
    3709          144 :    END SUBROUTINE rtbse_resolve_rirs_flag
    3710              : 
    3711              : ! **************************************************************************************************
    3712              : !> \brief ...
    3713              : !> \param bs_env ...
    3714              : !> \param Sigma_c_ikp_n_freq Complex diagonal self-energy at the signed fit frequencies.
    3715              : !> \param Sigma_x_ikp_n ...
    3716              : !> \param V_xc_ikp_n ...
    3717              : !> \param eigenval_scf ...
    3718              : !> \param ikp ...
    3719              : !> \param ispin ...
    3720              : !> \param summary Nevanlinna diagnostics, accumulated over one GW cycle.
    3721              : !> \param i_iter ...
    3722              : ! **************************************************************************************************
    3723          802 :    SUBROUTINE analyt_conti_and_print(bs_env, Sigma_c_ikp_n_freq, Sigma_x_ikp_n, V_xc_ikp_n, &
    3724          802 :                                      eigenval_scf, ikp, ispin, summary, i_iter)
    3725              : 
    3726              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3727              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(IN)      :: Sigma_c_ikp_n_freq
    3728              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: Sigma_x_ikp_n, V_xc_ikp_n, eigenval_scf
    3729              :       INTEGER, INTENT(IN)                                :: ikp, ispin
    3730              :       TYPE(gw_qp_summary_type), INTENT(INOUT)            :: summary
    3731              :       INTEGER, INTENT(IN), OPTIONAL                      :: i_iter
    3732              : 
    3733              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'analyt_conti_and_print'
    3734              :       INTEGER, PARAMETER                                 :: max_pade_orders = 7
    3735              : 
    3736              :       CHARACTER(len=3)                                   :: occ_vir
    3737              :       CHARACTER(len=default_path_length)                 :: fname
    3738              :       CHARACTER(len=default_string_length)               :: gw_label
    3739              :       INTEGER :: ac_used, first_mo, handle, i_central, i_mo, i_order, icycle, ikp_for_print, &
    3740              :          iunit, n_ac_pade, n_central, n_mo, n_orders, n_ranks, n_window, nkp
    3741          802 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: multi_count
    3742              :       INTEGER, DIMENSION(max_pade_orders)                :: order_index
    3743              :       LOGICAL                                            :: do_nevanlinna, is_bandstruc_kpoint, &
    3744              :                                                             multi_i, print_DOS_kpoints, print_ikp
    3745          802 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: multi, unstable
    3746              :       REAL(KIND=dp)                                      :: ac_pick, pick_min
    3747          802 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenval_G, m_value, Sigma_c_ikp_n_qp, &
    3748          802 :                                                             Sigma_x_minus_vxc, z_value
    3749          802 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: Sigma_c_orders
    3750              :       REAL(KIND=dp), DIMENSION(max_pade_orders)          :: Sigma_c_sorted
    3751              : 
    3752          802 :       CALL timeset(routineN, handle)
    3753              : 
    3754          802 :       icycle = 1
    3755          802 :       IF (PRESENT(i_iter)) icycle = i_iter
    3756              : 
    3757          802 :       n_mo = bs_env%n_ao
    3758          802 :       n_ranks = bs_env%para_env%num_pe
    3759              :       ! Under MODULO(i_mo, n_ranks) ownership, rank zero starts at band n_ranks.
    3760          802 :       first_mo = MODULO(bs_env%para_env%mepos - 1, n_ranks) + 1
    3761            0 :       ALLOCATE (z_value(n_mo), m_value(n_mo), Sigma_c_ikp_n_qp(n_mo), eigenval_G(n_mo), &
    3762         8020 :                 Sigma_x_minus_vxc(n_mo), unstable(n_mo), multi(n_mo))
    3763          802 :       Sigma_c_ikp_n_qp(:) = 0.0_dp
    3764         8422 :       Sigma_x_minus_vxc(:) = Sigma_x_ikp_n - V_xc_ikp_n
    3765          802 :       do_nevanlinna = (bs_env%ac_method == gw_ac_nevanlinna)
    3766          802 :       unstable(:) = .FALSE.
    3767          802 :       multi(:) = .FALSE.
    3768          802 :       n_window = 0
    3769          802 :       n_ac_pade = 0
    3770          802 :       pick_min = 0.0_dp
    3771              : 
    3772              :       ! Eigenvalues of the Green's function that produced Σ^c: the DFT ones for G0W0, the
    3773              :       ! previous cycle's quasiparticle energies for evGW0. They set the Newton start value,
    3774              :       ! the Z/m linearization point and the Hedin shift; the QP equation itself stays
    3775              :       ! referenced to the DFT eigenvalues through the Eigenval_scf argument below.
    3776          802 :       IF (bs_env%gw_flavour == evGW0 .AND. ALLOCATED(bs_env%eigenval_evGW0)) THEN
    3777          520 :          eigenval_G(:) = bs_env%eigenval_evGW0(:, ikp, ispin)
    3778              :       ELSE
    3779         7902 :          eigenval_G(:) = eigenval_scf(:)
    3780              :       END IF
    3781              : 
    3782          802 :       IF (do_nevanlinna) THEN
    3783              : 
    3784          770 :          IF (ikp == 1 .AND. ispin == 1) THEN
    3785          172 :             summary%start_time = m_walltime()
    3786          172 :             IF (bs_env%unit_nr > 0) THEN
    3787           86 :                WRITE (bs_env%unit_nr, '(/,T2,A)') 'Starting GW Nevanlinna analytic continuation'
    3788           86 :                CALL m_flush(bs_env%unit_nr)
    3789              :             END IF
    3790              :          END IF
    3791              : 
    3792          770 :          CALL cite_reference(Fei2021)
    3793         1540 :          ALLOCATE (multi_count(n_mo))
    3794          770 :          multi_count(:) = 0
    3795              : 
    3796              :          ! Nevanlinna continuation through all imaginary frequencies, then the median over fit
    3797              :          ! windows and the marks of unreliable (*) and multi-solution (m) levels
    3798              :          !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) IF (n_mo - first_mo >= n_ranks) &
    3799              :          !$OMP SHARED(bs_env, first_mo, n_mo, n_ranks, ispin, Sigma_c_ikp_n_qp, z_value, m_value, &
    3800              :          !$OMP        Sigma_c_ikp_n_freq, Sigma_x_minus_vxc, eigenval_G, eigenval_scf, multi_count) &
    3801          770 :          !$OMP PRIVATE(ac_used, ac_pick, multi_i) REDUCTION(+:n_ac_pade) REDUCTION(MIN:pick_min)
    3802              :          DO i_mo = first_mo, n_mo, n_ranks
    3803              :             CALL continuation_pade(Sigma_c_ikp_n_qp, &
    3804              :                                    bs_env%imag_freq_points_fit, z_value, m_value, &
    3805              :                                    Sigma_c_ikp_n_freq(:, 1:bs_env%num_freq_points_fit), &
    3806              :                                    Sigma_x_minus_vxc, &
    3807              :                                    eigenval_G(:), eigenval_scf(:), &
    3808              :                                    bs_env%do_hedin_shift, &
    3809              :                                    i_mo, bs_env%n_occ(ispin), bs_env%n_vir(ispin), &
    3810              :                                    bs_env%nparam_pade, bs_env%num_freq_points_fit, &
    3811              :                                    ri_rpa_g0w0_crossing_newton, bs_env%n_occ(ispin), &
    3812              :                                    0.0_dp, .TRUE., .FALSE., 1, e_fermi_ext=bs_env%e_fermi(ispin), &
    3813              :                                    ac_method=gw_ac_nevanlinna, ac_used=ac_used, ac_pick=ac_pick, &
    3814              :                                    num_fit_points_pade=bs_env%num_freq_points_pade, &
    3815              :                                    qp_start_eigenval=.TRUE., &
    3816              :                                    qp_newton_max_step=bs_env%nevanlinna%qp_newton_max_step, &
    3817              :                                    qp_maxz_radius=bs_env%nevanlinna%qp_maxz_radius, qp_multi=multi_i)
    3818              :             IF (multi_i) multi_count(i_mo) = 1
    3819              :             IF (ac_used /= gw_ac_nevanlinna) n_ac_pade = n_ac_pade + 1
    3820              :             pick_min = MIN(pick_min, ac_pick)
    3821              :          END DO
    3822              :          !$OMP END PARALLEL DO
    3823              : 
    3824          770 :          CALL bs_env%para_env%sum(Sigma_c_ikp_n_qp)
    3825          770 :          CALL bs_env%para_env%sum(n_ac_pade)
    3826          770 :          CALL bs_env%para_env%min(pick_min)
    3827          770 :          CALL bs_env%para_env%sum(multi_count)
    3828         7942 :          multi(:) = (multi_count(:) > 0)
    3829              : 
    3830              :          CALL qp_median_over_windows(bs_env, Sigma_c_ikp_n_freq, Sigma_x_minus_vxc, &
    3831              :                                      eigenval_G, eigenval_scf, first_mo, ispin, Sigma_c_ikp_n_qp, unstable, &
    3832          770 :                                      multi, n_window)
    3833          770 :          CALL propagate_unstable_marks(unstable, multi, bs_env%n_occ(ispin))
    3834              : 
    3835              :       ELSE
    3836              : 
    3837              :          ! Average the central Padé orders to discard outliers due to spurious poles near a QP root.
    3838           32 :          n_orders = MAX(1, MIN(max_pade_orders, bs_env%nparam_pade - 1))
    3839           32 :          n_central = MIN(n_orders, 3 - MODULO(n_orders + 1, 2))
    3840           32 :          i_central = (n_orders - n_central)/2 + 1
    3841          128 :          ALLOCATE (Sigma_c_orders(n_mo, n_orders))
    3842           32 :          Sigma_c_orders(:, :) = 0.0_dp
    3843              : 
    3844          256 :          DO i_mo = first_mo, n_mo, n_ranks
    3845          480 :             DO i_order = 1, n_orders
    3846              :                CALL continuation_pade(Sigma_c_orders(:, i_order), &
    3847              :                                       bs_env%imag_freq_points_fit, z_value, m_value, &
    3848              :                                       Sigma_c_ikp_n_freq(:, 1:bs_env%num_freq_points_fit), &
    3849              :                                       Sigma_x_minus_vxc, &
    3850              :                                       eigenval_G(:), eigenval_scf(:), &
    3851              :                                       bs_env%do_hedin_shift, &
    3852              :                                       i_mo, bs_env%n_occ(ispin), bs_env%n_vir(ispin), &
    3853              :                                       bs_env%nparam_pade - i_order + 1, bs_env%num_freq_points_fit, &
    3854              :                                       ri_rpa_g0w0_crossing_newton, bs_env%n_occ(ispin), &
    3855          448 :                                       0.0_dp, .TRUE., .FALSE., 1, e_fermi_ext=bs_env%e_fermi(ispin))
    3856              :             END DO
    3857              :          END DO
    3858              : 
    3859           32 :          CALL bs_env%para_env%sum(Sigma_c_orders)
    3860              : 
    3861          480 :          DO i_mo = 1, n_mo
    3862          896 :             Sigma_c_sorted(1:n_orders) = Sigma_c_orders(i_mo, 1:n_orders)
    3863          448 :             CALL sort(Sigma_c_sorted(1:n_orders), n_orders, order_index(1:n_orders))
    3864              :             Sigma_c_ikp_n_qp(i_mo) = SUM(Sigma_c_sorted(i_central:i_central + n_central - 1))/ &
    3865          928 :                                      REAL(n_central, KIND=dp)
    3866              :          END DO
    3867              : 
    3868              :       END IF
    3869              : 
    3870          802 :       CALL correct_obvious_fitting_fails(Sigma_c_ikp_n_qp, ispin, bs_env)
    3871              : 
    3872              :       bs_env%eigenval_GW(:, ikp, ispin) = eigenval_scf(:) + &
    3873              :                                           Sigma_c_ikp_n_qp(:) + &
    3874              :                                           Sigma_x_ikp_n(:) - &
    3875         8422 :                                           V_xc_ikp_n(:)
    3876              : 
    3877          802 :       IF (ALLOCATED(bs_env%eigenval_G0W0) .AND. icycle == 1) THEN
    3878         7962 :          bs_env%eigenval_G0W0(:, ikp, ispin) = bs_env%eigenval_GW(:, ikp, ispin)
    3879              :       END IF
    3880              : 
    3881         8422 :       bs_env%eigenval_HF(:, ikp, ispin) = eigenval_scf(:) + Sigma_x_ikp_n(:) - V_xc_ikp_n(:)
    3882              : 
    3883              :       ! only print eigenvalues of DOS k-points in case no bandstructure path has been given
    3884          802 :       print_DOS_kpoints = (bs_env%nkp_only_bs <= 0)
    3885              :       ! in kpoints_DOS, the last nkp_only_bs are bandstructure k-points
    3886          802 :       is_bandstruc_kpoint = (ikp > bs_env%nkp_only_DOS)
    3887          802 :       print_ikp = print_DOS_kpoints .OR. is_bandstruc_kpoint
    3888              : 
    3889          802 :       IF (bs_env%para_env%is_source() .AND. print_ikp) THEN
    3890              : 
    3891          261 :          IF (print_DOS_kpoints) THEN
    3892          209 :             nkp = bs_env%nkp_only_DOS
    3893          209 :             ikp_for_print = ikp
    3894              :          ELSE
    3895           52 :             nkp = bs_env%nkp_only_bs
    3896           52 :             ikp_for_print = ikp - bs_env%nkp_only_DOS
    3897              :          END IF
    3898              : 
    3899          261 :          fname = "bandstructure_SCF_and_G0W0"
    3900              : 
    3901              :          ! in an evGW0 run the spectrum of every cycle is appended, so only the very first
    3902              :          ! cycle replaces the file
    3903          261 :          IF (ikp_for_print == 1 .AND. ispin == 1 .AND. icycle == 1) THEN
    3904              :             CALL open_file(TRIM(fname), unit_number=iunit, file_status="REPLACE", &
    3905           74 :                            file_action="WRITE")
    3906              :          ELSE
    3907              :             CALL open_file(TRIM(fname), unit_number=iunit, file_status="OLD", &
    3908          187 :                            file_action="WRITE", file_position="APPEND")
    3909              :          END IF
    3910              : 
    3911          261 :          IF (bs_env%gw_flavour == evGW0 .AND. ikp_for_print == 1 .AND. ispin == 1) THEN
    3912           15 :             WRITE (iunit, "(A)") " "
    3913           15 :             WRITE (iunit, "(A,I0)") "evGW0 cycle: ", icycle
    3914           15 :             IF (icycle == 1) THEN
    3915            2 :                WRITE (iunit, '(A)') '# G0W0 spectrum (first cycle, without SOC)'
    3916              :             END IF
    3917              :          END IF
    3918              : 
    3919          261 :          WRITE (iunit, "(A)") " "
    3920          261 :          WRITE (iunit, "(A10,I7,A25,3F10.4,T90,A7,I2)") "kpoint: ", ikp_for_print, "coordinate: ", &
    3921         1305 :             bs_env%kpoints_DOS%xkp(:, ikp), "spin: ", ispin
    3922          261 :          WRITE (iunit, "(A)") " "
    3923          261 :          IF (do_nevanlinna) THEN
    3924          245 :             WRITE (iunit, "(A,I6,A,I6,A,ES10.2)") " analytic continuation: Nevanlinna for", &
    3925          245 :                n_mo - n_ac_pade, " level(s), Padé fallback for", n_ac_pade, &
    3926          490 :                " level(s); smallest relative Pick eigenvalue", pick_min
    3927          245 :             WRITE (iunit, "(A)") " "
    3928              :          END IF
    3929          261 :          gw_label = "ϵ_nk^"//TRIM(gw_flavour_label(bs_env))//" (eV)"
    3930          261 :          IF (bs_env%gw_flavour == evGW0 .AND. icycle == 1) THEN
    3931            3 :             gw_label = "ϵ_nk^G0W0 (eV)"
    3932              :          END IF
    3933          261 :          WRITE (iunit, "(A5,A12,3A17,A16,A18)") "n", "k", "ϵ_nk^DFT (eV)", "Σ^c_nk (eV)", &
    3934          522 :             "Σ^x_nk (eV)", "v_nk^xc (eV)", TRIM(gw_label)
    3935          261 :          WRITE (iunit, "(A)") " "
    3936              : 
    3937         3251 :          DO i_mo = 1, n_mo
    3938         2990 :             IF (i_mo <= bs_env%n_occ(ispin)) occ_vir = 'occ'
    3939         2990 :             IF (i_mo > bs_env%n_occ(ispin)) occ_vir = 'vir'
    3940         2990 :             WRITE (iunit, "(I5,3A,I5,4F16.3,F17.3,A)") i_mo, ' (', occ_vir, ') ', ikp_for_print, &
    3941         2990 :                eigenval_scf(i_mo)*evolt, &
    3942         2990 :                Sigma_c_ikp_n_qp(i_mo)*evolt, &
    3943         2990 :                Sigma_x_ikp_n(i_mo)*evolt, &
    3944         2990 :                V_xc_ikp_n(i_mo)*evolt, &
    3945         2990 :                bs_env%eigenval_GW(i_mo, ikp, ispin)*evolt, &
    3946         9776 :                TRIM(MERGE('  *', '   ', unstable(i_mo)))//TRIM(MERGE('  m', '   ', multi(i_mo)))
    3947              :          END DO
    3948              : 
    3949          261 :          WRITE (iunit, "(A)") " "
    3950          602 :          IF (ANY(unstable)) WRITE (iunit, "(A)") &
    3951              :             " * not reliable: the fit windows disagree, or an unstable or multi-solution level "// &
    3952          245 :             "lies between this level and the HOMO (occupied) or the LUMO (virtual)"
    3953         3251 :          IF (ANY(multi)) WRITE (iunit, "(A)") &
    3954              :             " m multi-solution level: a second quasiparticle solution carries more than a quarter "// &
    3955            0 :             "of the weight"
    3956              : 
    3957          261 :          CALL close_file(iunit)
    3958              : 
    3959              :       END IF
    3960              : 
    3961          802 :       IF (do_nevanlinna) CALL report_nevanlinna_progress(bs_env, summary, unstable, multi, &
    3962          770 :                                                          n_window, n_ac_pade, ikp, ispin)
    3963              : 
    3964          802 :       CALL timestop(handle)
    3965              : 
    3966         1604 :    END SUBROUTINE analyt_conti_and_print
    3967              : 
    3968              : ! **************************************************************************************************
    3969              : !> \brief quasiparticle energies as median over Nevanlinna continuations from fit windows; each
    3970              : !>        window consists of the lowest k imaginary frequencies, k >= window_min_points, with the
    3971              : !>        highest frequency in [window_freq_min, window_freq_max] (bs_env%nevanlinna)
    3972              : !> \param bs_env ...
    3973              : !> \param Sigma_c_ikp_n_freq Sigma^c(iω) of all levels
    3974              : !> \param Sigma_x_minus_vxc Exchange self-energy minus the exchange-correlation potential.
    3975              : !> \param eigenval_G eigenvalues of the Green's function that produced Σ^c
    3976              : !> \param eigenval_scf ...
    3977              : !> \param first_mo First band owned by this MPI rank.
    3978              : !> \param ispin ...
    3979              : !> \param Sigma_c_ikp_n_qp Sigma^c at the quasiparticle energy; replaced by the window median
    3980              : !> \param unstable the window solutions of the level spread more than window_spread
    3981              : !> \param multi more than half of the windows find a second solution of comparable weight
    3982              : !> \param n_window number of fit windows, zero if none are available
    3983              : ! **************************************************************************************************
    3984          770 :    SUBROUTINE qp_median_over_windows(bs_env, Sigma_c_ikp_n_freq, Sigma_x_minus_vxc, &
    3985          770 :                                      eigenval_G, eigenval_scf, first_mo, ispin, Sigma_c_ikp_n_qp, &
    3986         1540 :                                      unstable, multi, n_window)
    3987              : 
    3988              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    3989              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(IN)      :: Sigma_c_ikp_n_freq
    3990              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: Sigma_x_minus_vxc, eigenval_G, &
    3991              :                                                             eigenval_scf
    3992              :       INTEGER, INTENT(IN)                                :: first_mo, ispin
    3993              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT)         :: Sigma_c_ikp_n_qp
    3994              :       LOGICAL, DIMENSION(:), INTENT(INOUT)               :: unstable, multi
    3995              :       INTEGER, INTENT(OUT)                               :: n_window
    3996              : 
    3997              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qp_median_over_windows'
    3998              :       REAL(KIND=dp), PARAMETER                           :: max_abs_sigma = 1.0E3_dp
    3999              : 
    4000          770 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: sig_sel
    4001              :       INTEGER                                            :: handle, i_mo, i_win, j, k_w, n_mo, &
    4002              :                                                             n_ranks, n_valid, n_w
    4003          770 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: multi_count, order, window_size
    4004              :       LOGICAL                                            :: multi_i
    4005              :       REAL(KIND=dp)                                      :: v
    4006          770 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: m_dummy, q_sorted, w_sel, z_dummy
    4007          770 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: q_win
    4008          770 :       TYPE(nevanlinna_type), ALLOCATABLE, DIMENSION(:)   :: fits
    4009          770 :       TYPE(nevanlinna_window_grid_type)                  :: window_grid
    4010              : 
    4011          770 :       CALL timeset(routineN, handle)
    4012              : 
    4013          770 :       n_mo = bs_env%n_ao
    4014          770 :       n_w = bs_env%num_time_freq_points
    4015          770 :       n_ranks = bs_env%para_env%num_pe
    4016              : 
    4017         4620 :       ALLOCATE (order(n_w), window_size(n_w), w_sel(n_w))
    4018        13702 :       w_sel(:) = bs_env%time_frequency_grid%frequency(1:n_w)
    4019          770 :       CALL sort(w_sel, n_w, order)
    4020              : 
    4021          770 :       n_window = 0
    4022         9852 :       DO j = bs_env%nevanlinna%window_min_points, n_w
    4023         9082 :          v = w_sel(j)
    4024         9852 :          IF (v >= bs_env%nevanlinna%window_freq_min .AND. v <= bs_env%nevanlinna%window_freq_max) THEN
    4025         2706 :             n_window = n_window + 1
    4026         2706 :             window_size(n_window) = j
    4027              :          END IF
    4028              :       END DO
    4029              : 
    4030          770 :       IF (n_window == 0) THEN
    4031         3072 :          unstable(:) = .TRUE.
    4032          200 :          CALL timestop(handle)
    4033          200 :          RETURN
    4034              :       END IF
    4035              : 
    4036              :       ! Every window takes a prefix of these samples.
    4037          570 :       CALL nevanlinna_prepare_window_grid(window_grid, w_sel(1:window_size(n_window)))
    4038         2280 :       ALLOCATE (sig_sel(n_mo, window_size(n_window)))
    4039         9030 :       DO j = 1, SIZE(sig_sel, 2)
    4040        67988 :          sig_sel(:, j) = Sigma_c_ikp_n_freq(:, order(j))
    4041              :       END DO
    4042         6270 :       ALLOCATE (q_win(n_mo, n_window), q_sorted(n_window), multi_count(n_mo), z_dummy(n_mo), m_dummy(n_mo))
    4043          570 :       q_win(:, :) = 0.0_dp
    4044          570 :       multi_count(:) = 0
    4045              : 
    4046         4416 :       ALLOCATE (fits(n_window))
    4047              :       !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) IF (n_mo - first_mo >= n_ranks) &
    4048              :       !$OMP SHARED(bs_env, first_mo, n_mo, n_ranks, ispin, window_grid, n_window, window_size, w_sel, &
    4049              :       !$OMP        z_dummy, m_dummy, sig_sel, Sigma_x_minus_vxc, eigenval_G, eigenval_scf, q_win, multi_count) &
    4050          570 :       !$OMP PRIVATE(fits, i_win, k_w, multi_i)
    4051              :       DO i_mo = first_mo, n_mo, n_ranks
    4052              :          CALL nevanlinna_create_windows(fits, window_grid, sig_sel(i_mo, :), i_mo <= bs_env%n_occ(ispin), window_size(1:n_window))
    4053              :          DO i_win = 1, n_window
    4054              :             k_w = window_size(i_win)
    4055              :             CALL continuation_pade(q_win(:, i_win), w_sel(1:k_w), z_dummy, m_dummy, sig_sel(:, 1:k_w), &
    4056              :                                    Sigma_x_minus_vxc, eigenval_G, eigenval_scf, &
    4057              :                                    bs_env%do_hedin_shift, &
    4058              :                                    i_mo, bs_env%n_occ(ispin), bs_env%n_vir(ispin), &
    4059              :                                    k_w, k_w, &
    4060              :                                    ri_rpa_g0w0_crossing_newton, bs_env%n_occ(ispin), &
    4061              :                                    0.0_dp, .TRUE., .FALSE., 1, e_fermi_ext=bs_env%e_fermi(ispin), &
    4062              :                                    ac_method=gw_ac_nevanlinna, qp_start_eigenval=.TRUE., &
    4063              :                                    qp_newton_max_step=bs_env%nevanlinna%qp_newton_max_step, &
    4064              :                                    qp_maxz_radius=bs_env%nevanlinna%qp_maxz_radius, qp_multi=multi_i, window_fit=fits(i_win))
    4065              :             IF (multi_i) multi_count(i_mo) = multi_count(i_mo) + 1
    4066              :          END DO
    4067              :       END DO
    4068              :       !$OMP END PARALLEL DO
    4069              : 
    4070          570 :       CALL bs_env%para_env%sum(q_win)
    4071          570 :       CALL bs_env%para_env%sum(multi_count)
    4072         4870 :       multi(:) = (2*multi_count(:) > n_window)
    4073              : 
    4074         4870 :       DO i_mo = 1, n_mo
    4075              :          ! sort the valid window solutions
    4076              :          n_valid = 0
    4077        24190 :          DO i_win = 1, n_window
    4078        19890 :             v = q_win(i_mo, i_win)
    4079        19890 :             IF (.NOT. (v == v) .OR. ABS(v) > max_abs_sigma) CYCLE
    4080        19890 :             n_valid = n_valid + 1
    4081        19890 :             j = n_valid
    4082        52598 :             DO WHILE (j > 1)
    4083        43416 :                IF (q_sorted(j - 1) <= v) EXIT
    4084        32708 :                q_sorted(j) = q_sorted(j - 1)
    4085        43416 :                j = j - 1
    4086              :             END DO
    4087        24190 :             q_sorted(j) = v
    4088              :          END DO
    4089              :          ! a level without two valid window solutions has no error estimate
    4090         4300 :          IF (n_valid < 2) unstable(i_mo) = .TRUE.
    4091          740 :          IF (n_valid == 0) CYCLE
    4092         4300 :          IF (MODULO(n_valid, 2) == 1) THEN
    4093         1882 :             Sigma_c_ikp_n_qp(i_mo) = q_sorted((n_valid + 1)/2)
    4094              :          ELSE
    4095         2418 :             Sigma_c_ikp_n_qp(i_mo) = 0.5_dp*(q_sorted(n_valid/2) + q_sorted(n_valid/2 + 1))
    4096              :          END IF
    4097         4870 :          IF (n_valid > 1) unstable(i_mo) = (q_sorted(n_valid) - q_sorted(1) > bs_env%nevanlinna%window_spread)
    4098              :       END DO
    4099              : 
    4100          570 :       CALL timestop(handle)
    4101              : 
    4102         4246 :    END SUBROUTINE qp_median_over_windows
    4103              : 
    4104              : ! **************************************************************************************************
    4105              : !> \brief counted from the HOMO downwards and from the LUMO upwards, all levels beyond the first
    4106              : !>        unstable or multi-solution level are marked unstable: the quasiparticle solution of a
    4107              : !>        deeper level cannot be trusted once a closer level is not reliable
    4108              : !> \param unstable ...
    4109              : !> \param multi ...
    4110              : !> \param homo ...
    4111              : ! **************************************************************************************************
    4112          770 :    SUBROUTINE propagate_unstable_marks(unstable, multi, homo)
    4113              : 
    4114              :       LOGICAL, DIMENSION(:), INTENT(INOUT)               :: unstable
    4115              :       LOGICAL, DIMENSION(:), INTENT(IN)                  :: multi
    4116              :       INTEGER, INTENT(IN)                                :: homo
    4117              : 
    4118              :       INTEGER                                            :: i_mo
    4119              :       LOGICAL                                            :: beyond_mark
    4120              : 
    4121          770 :       beyond_mark = .FALSE.
    4122         2922 :       DO i_mo = homo, 1, -1
    4123         2152 :          IF (beyond_mark) unstable(i_mo) = .TRUE.
    4124         2922 :          IF (unstable(i_mo) .OR. multi(i_mo)) beyond_mark = .TRUE.
    4125              :       END DO
    4126              : 
    4127          770 :       beyond_mark = .FALSE.
    4128         5790 :       DO i_mo = homo + 1, SIZE(unstable)
    4129         5020 :          IF (beyond_mark) unstable(i_mo) = .TRUE.
    4130         5790 :          IF (unstable(i_mo) .OR. multi(i_mo)) beyond_mark = .TRUE.
    4131              :       END DO
    4132              : 
    4133          770 :    END SUBROUTINE propagate_unstable_marks
    4134              : 
    4135              : ! **************************************************************************************************
    4136              : !> \brief Report progress over k-points and spins, then summarize the Nevanlinna diagnostics.
    4137              : !> \param bs_env Band-structure environment.
    4138              : !> \param summary Diagnostics accumulated over the current GW cycle.
    4139              : !> \param unstable Levels marked unreliable at this k-point and spin.
    4140              : !> \param multi Levels with a second quasiparticle solution of comparable weight.
    4141              : !> \param n_window Number of fit windows.
    4142              : !> \param n_pade Number of full-frequency fits that fell back to Padé.
    4143              : !> \param ikp Current k-point index.
    4144              : !> \param ispin Current spin index.
    4145              : ! **************************************************************************************************
    4146          770 :    SUBROUTINE report_nevanlinna_progress(bs_env, summary, unstable, multi, n_window, n_pade, ikp, ispin)
    4147              : 
    4148              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    4149              :       TYPE(gw_qp_summary_type), INTENT(INOUT)            :: summary
    4150              :       LOGICAL, DIMENSION(:), INTENT(IN)                  :: unstable, multi
    4151              :       INTEGER, INTENT(IN)                                :: n_window, n_pade, ikp, ispin
    4152              : 
    4153              :       INTEGER, PARAMETER                                 :: n_progress_steps = 10
    4154              : 
    4155              :       CHARACTER(LEN=20)                                  :: count_text
    4156              :       CHARACTER(LEN=64)                                  :: count_format, pade_format
    4157              :       INTEGER                                            :: count_width, nkp, u
    4158              :       INTEGER(KIND=int_8)                                :: done, n_levels, step, total
    4159              : 
    4160          770 :       nkp = summary%n_kpoints
    4161          770 :       done = INT(ispin - 1, KIND=int_8)*nkp + ikp
    4162          770 :       total = INT(nkp, KIND=int_8)*bs_env%n_spin
    4163          770 :       u = bs_env%unit_nr
    4164              : 
    4165          770 :       IF (done == 1 .AND. n_window < 2) THEN
    4166              :          CALL cp_warn(__LOCATION__, &
    4167              :                       "Fewer than two Nevanlinna fit windows. All GW levels are marked unreliable. "// &
    4168           72 :                       "Increase NUM_TIME_FREQ_POINTS to obtain an error estimate.")
    4169              :       END IF
    4170              : 
    4171         7942 :       summary%n_reliable = summary%n_reliable + COUNT(.NOT. (unstable .OR. multi))
    4172         7942 :       summary%n_unstable = summary%n_unstable + COUNT(unstable)
    4173         7942 :       summary%n_multi = summary%n_multi + COUNT(multi)
    4174          770 :       summary%n_pade = summary%n_pade + n_pade
    4175              : 
    4176          770 :       IF (u > 0 .AND. total >= n_progress_steps) THEN
    4177          274 :          step = (n_progress_steps*done)/total
    4178          274 :          IF (step > (n_progress_steps*(done - 1))/total) THEN
    4179          120 :             WRITE (u, '(T2,A,I3,A,I0,A,I0,A,T60,A,T71,F8.1,A)') 'GW analytic continuation: ', &
    4180          120 :                (100*step)/n_progress_steps, ' % (', done, ' / ', total, ')', &
    4181          240 :                'Total time:', m_walltime() - summary%start_time, ' s'
    4182          120 :             CALL m_flush(u)
    4183              :          END IF
    4184              :       END IF
    4185              : 
    4186          770 :       IF (done /= total) RETURN
    4187              : 
    4188          172 :       IF (u > 0) THEN
    4189              :          ! counts right-aligned at column 80; é of Padé takes one byte more than one column
    4190           86 :          n_levels = total*SIZE(unstable)
    4191           86 :          WRITE (count_text, '(I0)') n_levels
    4192           86 :          count_width = LEN_TRIM(count_text)
    4193           86 :          WRITE (count_format, '(A,I0,A,I0,A,I0,A)') '(T4,A,T', 68 - 2*count_width, ',I', count_width, &
    4194          172 :             ',A,I', count_width, ',F8.1,A)'
    4195           86 :          WRITE (pade_format, '(A,I0,A,I0,A,I0,A)') '(T4,A,T', 69 - 2*count_width, ',I', count_width, &
    4196          172 :             ',A,I', count_width, ',F8.1,A)'
    4197           86 :          WRITE (u, '(/,T2,A,I0,A)') 'GW Nevanlinna, accuracy for ', n_window, ' fit windows:'
    4198           86 :          WRITE (u, count_format) 'Reliable levels', summary%n_reliable, ' / ', n_levels, &
    4199          172 :             100.0_dp*REAL(summary%n_reliable, dp)/REAL(n_levels, dp), ' %'
    4200           86 :          WRITE (u, count_format) 'Unreliable levels (*)', summary%n_unstable, ' / ', n_levels, &
    4201          172 :             100.0_dp*REAL(summary%n_unstable, dp)/REAL(n_levels, dp), ' %'
    4202           86 :          WRITE (u, count_format) 'Multi-solution levels (m)', summary%n_multi, ' / ', n_levels, &
    4203          172 :             100.0_dp*REAL(summary%n_multi, dp)/REAL(n_levels, dp), ' %'
    4204           86 :          WRITE (u, pade_format) 'Padé fallback of the full-frequency fit', summary%n_pade, ' / ', n_levels, &
    4205          172 :             100.0_dp*REAL(summary%n_pade, dp)/REAL(n_levels, dp), ' %'
    4206           86 :          CALL m_flush(u)
    4207              :       END IF
    4208              : 
    4209              :    END SUBROUTINE report_nevanlinna_progress
    4210              : 
    4211              : ! **************************************************************************************************
    4212              : !> \brief ...
    4213              : !> \param Sigma_c_ikp_n_qp ...
    4214              : !> \param ispin ...
    4215              : !> \param bs_env ...
    4216              : ! **************************************************************************************************
    4217          802 :    SUBROUTINE correct_obvious_fitting_fails(Sigma_c_ikp_n_qp, ispin, bs_env)
    4218              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: Sigma_c_ikp_n_qp
    4219              :       INTEGER                                            :: ispin
    4220              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    4221              : 
    4222              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'correct_obvious_fitting_fails'
    4223              : 
    4224              :       INTEGER                                            :: handle, homo, i_mo, j_mo, &
    4225              :                                                             n_levels_scissor, n_mo
    4226              :       LOGICAL                                            :: is_occ, is_vir
    4227              :       REAL(KIND=dp)                                      :: sum_Sigma_c
    4228              : 
    4229          802 :       CALL timeset(routineN, handle)
    4230              : 
    4231          802 :       n_mo = bs_env%n_ao
    4232          802 :       homo = bs_env%n_occ(ispin)
    4233              : 
    4234         8422 :       DO i_mo = 1, n_mo
    4235              : 
    4236              :          ! if |𝚺^c| > 13 eV, we use a scissors shift
    4237         8422 :          IF (ABS(Sigma_c_ikp_n_qp(i_mo)) > 13.0_dp/evolt) THEN
    4238              : 
    4239            0 :             is_occ = (i_mo <= homo)
    4240            0 :             is_vir = (i_mo > homo)
    4241              : 
    4242            0 :             n_levels_scissor = 0
    4243            0 :             sum_Sigma_c = 0.0_dp
    4244              : 
    4245              :             ! compute scissor
    4246            0 :             DO j_mo = 1, n_mo
    4247              : 
    4248              :                ! only compute scissor from other GW levels close in energy
    4249            0 :                IF (is_occ .AND. j_mo > homo) CYCLE
    4250            0 :                IF (is_vir .AND. j_mo <= homo) CYCLE
    4251            0 :                IF (ABS(i_mo - j_mo) > 10) CYCLE
    4252            0 :                IF (i_mo == j_mo) CYCLE
    4253              : 
    4254            0 :                n_levels_scissor = n_levels_scissor + 1
    4255            0 :                sum_Sigma_c = sum_Sigma_c + Sigma_c_ikp_n_qp(j_mo)
    4256              : 
    4257              :             END DO
    4258              : 
    4259              :             ! overwrite the self-energy with scissor shift
    4260            0 :             Sigma_c_ikp_n_qp(i_mo) = sum_Sigma_c/REAL(n_levels_scissor, KIND=dp)
    4261              : 
    4262              :          END IF
    4263              : 
    4264              :       END DO ! i_mo
    4265              : 
    4266          802 :       CALL timestop(handle)
    4267              : 
    4268          802 :    END SUBROUTINE correct_obvious_fitting_fails
    4269              : 
    4270              : ! **************************************************************************************************
    4271              : !> \brief Build the real Gamma occupied or virtual one-particle propagator.
    4272              : !> \param bs_env MO coefficients, eigenvalues and reusable work matrix
    4273              : !> \param tau imaginary time
    4274              : !> \param fm_G_Gamma output AO propagator
    4275              : !> \param ispin spin channel
    4276              : !> \param occ select the occupied sector
    4277              : !> \param vir select the virtual sector
    4278              : ! **************************************************************************************************
    4279         9872 :    SUBROUTINE G_occ_vir(bs_env, tau, fm_G_Gamma, ispin, occ, vir)
    4280              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    4281              :       REAL(KIND=dp)                                      :: tau
    4282              :       TYPE(cp_fm_type)                                   :: fm_G_Gamma
    4283              :       INTEGER                                            :: ispin
    4284              :       LOGICAL                                            :: occ, vir
    4285              : 
    4286              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'G_occ_vir'
    4287              : 
    4288              :       INTEGER                                            :: first_mo, handle, homo, i_mo, last_mo
    4289              :       REAL(KIND=dp)                                      :: tau_E
    4290              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: column_factors
    4291              : 
    4292         9872 :       CALL timeset(routineN, handle)
    4293              : 
    4294         9872 :       CPASSERT(occ .NEQV. vir)
    4295              : 
    4296         9872 :       homo = bs_env%n_occ(ispin)
    4297         9872 :       first_mo = 1
    4298              :       ! Canonical orthogonalization removes the modes above n_mo_retained.
    4299         9872 :       last_mo = MIN(bs_env%n_ao, bs_env%n_mo_retained)
    4300         9872 :       IF (occ) THEN
    4301         5004 :          last_mo = MIN(last_mo, homo)
    4302              :       ELSE
    4303         4868 :          first_mo = homo + 1
    4304              :       END IF
    4305        29616 :       ALLOCATE (column_factors(first_mo:last_mo))
    4306        64156 :       DO i_mo = first_mo, last_mo
    4307        54284 :          tau_E = ABS(tau*0.5_dp*(bs_env%eigenval_scf_Gamma(i_mo, ispin) - bs_env%e_fermi(ispin)))
    4308        64156 :          IF (tau_E < bs_env%stabilize_exp) THEN
    4309        53916 :             column_factors(i_mo) = EXP(-tau_E)
    4310              :          ELSE
    4311          368 :             column_factors(i_mo) = 0.0_dp
    4312              :          END IF
    4313              :       END DO
    4314              : 
    4315              :       CALL build_ao_propagator(bs_env%fm_mo_coeff_Gamma(ispin), column_factors, first_mo, &
    4316         9872 :                                bs_env%fm_work_mo(1), fm_G_Gamma)
    4317         9872 :       DEALLOCATE (column_factors)
    4318              : 
    4319         9872 :       CALL timestop(handle)
    4320              : 
    4321         9872 :    END SUBROUTINE G_occ_vir
    4322              : 
    4323            0 : END MODULE gw_utils
        

Generated by: LCOV version 2.0-1