LCOV - code coverage report
Current view: top level - src - gw_large_cell_gamma_ri_rs.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:71c3ab0) Lines: 0.0 % 584 0
Test Date: 2026-07-25 06:35:44 Functions: 0.0 % 18 0

            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 GW using RI-RS Approximation for molecules
      10              : !> \par History
      11              : !>      04.2026 created [Ritaj Tyagi]
      12              : ! **************************************************************************************************
      13              : MODULE gw_large_cell_Gamma_ri_rs
      14              :    USE atomic_kind_types,               ONLY: atomic_kind_type
      15              :    USE basis_set_types,                 ONLY: gto_basis_set_type
      16              :    USE cell_types,                      ONLY: cell_type,&
      17              :                                               get_cell,&
      18              :                                               pbc
      19              :    USE constants_operator,              ONLY: operator_coulomb
      20              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      21              :                                               cp_blacs_env_release,&
      22              :                                               cp_blacs_env_type
      23              :    USE cp_dbcsr_api,                    ONLY: &
      24              :         dbcsr_add, dbcsr_binary_read, dbcsr_binary_write, dbcsr_copy, dbcsr_create, &
      25              :         dbcsr_deallocate_matrix, dbcsr_distribution_get, dbcsr_distribution_new, &
      26              :         dbcsr_distribution_release, dbcsr_distribution_type, dbcsr_finalize, dbcsr_get_block_p, &
      27              :         dbcsr_get_info, dbcsr_iterator_blocks_left, dbcsr_iterator_next_block, &
      28              :         dbcsr_iterator_start, dbcsr_iterator_stop, dbcsr_iterator_type, dbcsr_multiply, &
      29              :         dbcsr_p_type, dbcsr_put_block, dbcsr_release, dbcsr_scale, dbcsr_set, dbcsr_type, &
      30              :         dbcsr_type_no_symmetry
      31              :    USE cp_dbcsr_contrib,                ONLY: dbcsr_reserve_all_blocks
      32              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      33              :                                               copy_fm_to_dbcsr,&
      34              :                                               dbcsr_deallocate_matrix_set,&
      35              :                                               max_elements_per_block
      36              :    USE cp_fm_basic_linalg,              ONLY: cp_fm_scale_and_add,&
      37              :                                               cp_fm_uplo_to_full
      38              :    USE cp_fm_cholesky,                  ONLY: cp_fm_cholesky_decompose,&
      39              :                                               cp_fm_cholesky_invert
      40              :    USE cp_fm_diag,                      ONLY: cp_fm_power
      41              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_type
      42              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      43              :                                               cp_fm_get_info,&
      44              :                                               cp_fm_release,&
      45              :                                               cp_fm_set_all,&
      46              :                                               cp_fm_to_fm,&
      47              :                                               cp_fm_type
      48              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      49              :                                               cp_logger_type
      50              :    USE cp_output_handling,              ONLY: cp_p_file,&
      51              :                                               cp_print_key_should_output
      52              :    USE gw_integrals,                    ONLY: build_3c_integral_block_ctx,&
      53              :                                               gw_3c_ctx_create,&
      54              :                                               gw_3c_ctx_release,&
      55              :                                               gw_3c_ctx_type,&
      56              :                                               gw_3c_ws_create,&
      57              :                                               gw_3c_ws_release,&
      58              :                                               gw_3c_ws_type
      59              :    USE gw_large_cell_gamma,             ONLY: &
      60              :         Fourier_transform_w_to_t, G_occ_vir, compute_QP_energies, compute_fm_chi_Gamma_freq, &
      61              :         create_fm_W_MIC_time, delete_unnecessary_files, fill_fm_Sigma_c_Gamma_time, fm_write, &
      62              :         get_W_MIC, multiply_fm_W_MIC_time_with_Minv_Gamma
      63              :    USE gw_non_periodic_ri_rs,           ONLY: get_basis_offsets,&
      64              :                                               precompute_ri_rs_radii,&
      65              :                                               ri_rs_grid_assembler,&
      66              :                                               solve_D_lp_distributed
      67              :    USE gw_utils,                        ONLY: de_init_bs_env
      68              :    USE input_constants,                 ONLY: rtp_method_bse
      69              :    USE input_section_types,             ONLY: section_vals_type
      70              :    USE kinds,                           ONLY: dp
      71              :    USE kpoint_coulomb_2c,               ONLY: build_2c_coulomb_matrix_kp
      72              :    USE machine,                         ONLY: m_walltime
      73              :    USE message_passing,                 ONLY: mp_para_env_type
      74              :    USE mp2_ri_2c,                       ONLY: RI_2c_integral_mat
      75              :    USE orbital_pointers,                ONLY: indco,&
      76              :                                               ncoset
      77              :    USE parallel_gemm_api,               ONLY: parallel_gemm
      78              :    USE particle_types,                  ONLY: particle_type
      79              :    USE post_scf_bandstructure_types,    ONLY: post_scf_bandstructure_type
      80              :    USE qs_environment_types,            ONLY: get_qs_env,&
      81              :                                               qs_environment_type
      82              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
      83              :                                               qs_kind_type
      84              : #include "./base/base_uses.f90"
      85              : 
      86              :    IMPLICIT NONE
      87              : 
      88              :    PRIVATE
      89              : 
      90              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'gw_large_cell_Gamma_ri_rs'
      91              : 
      92              :    PUBLIC :: gw_calc_large_cell_Gamma_ri_rs
      93              : 
      94              : CONTAINS
      95              : 
      96              : ! **************************************************************************************************
      97              : !> \brief GW calculation using RI-RS formalism for molecules
      98              : !> \param qs_env ...
      99              : !> \param bs_env ...
     100              : ! **************************************************************************************************
     101              : 
     102            0 :    SUBROUTINE gw_calc_large_cell_Gamma_ri_rs(qs_env, bs_env)
     103              : 
     104              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     105              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     106              : 
     107              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'gw_calc_large_cell_Gamma_ri_rs'
     108              : 
     109              :       INTEGER                                            :: handle
     110            0 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: fm_Sigma_x_Gamma, fm_W_time
     111            0 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :, :)  :: fm_Sigma_c_Gamma_time
     112              : 
     113            0 :       CALL timeset(routineN, handle)
     114              : 
     115              :        !!========================================================================
     116              :        !! 0. Precompute AO and RI Radii
     117              :        !!    Per-atom cutoff radii from the most diffuse Gaussian primitives in
     118              :        !!    the AO and RI auxiliary basis sets. Stored in bs_env%ri_rs%
     119              :        !!    radius_ao_per_atom and radius_ri_per_atom, used for sphere-cutoff
     120              :        !!    and phi_local screening.
     121              :        !!========================================================================
     122            0 :       CALL precompute_ri_rs_radii(qs_env, bs_env)
     123              : 
     124              :        !!========================================================================
     125              :        !! 1. Grid Generation for RI-RS
     126              :        !!    (Modified Lebedev grids from Ivan Duchemin and Xavier Blase)
     127              :        !!    Generate flattened 1D array of grid points for RI-RS.
     128              :        !!    Equation: r_g(k) = R_A + r_g(A)
     129              :        !!========================================================================
     130            0 :       CALL ri_rs_grid_assembler(qs_env, bs_env, bs_env%ri_rs%grid_points)
     131              : 
     132              :        !!========================================================================
     133              :        !! 2. Atomic Basis Evaluation
     134              :        !!    Compute values of spherical atomic basis functions at grid points.
     135              :        !!    Expression: Φ_μl = Φ_μ(r_l) (mat_phi_mu_l)
     136              :        !!========================================================================
     137              :       CALL atomic_basis_at_grid_point(qs_env, bs_env, bs_env%ri_rs%grid_points, &
     138            0 :                                       bs_env%ri_rs%mat_phi_mu_l)
     139              : 
     140              :        !!========================================================================
     141              :        !! 3. Compute RI-RS Coefficients (Z_lp)
     142              :        !!    Solve the regularized system for each atom P, where the grid domain
     143              :        !!    is restricted to r_l within a cutoff distance of atom P:
     144              :        !!    a. D_ll' = [ Σ_μ Φ_μ(r_l) Φ_μ(r_l') ]^2 (Equation 13)
     145              :        !!    b. D_lP  = Σ_{μν} Φ_μ(r_l) Φ_ν(r_l) (μν|P) (Equation 15)
     146              :        !!    c. Conditioning:
     147              :        !!       Dvec_l   = 1 / sqrt(D_ll)  (Diagonal scaling vector)
     148              :        !!       D'_ll' = Dvec_l * D_ll' * Dvec_l' + λδ_ll'
     149              :        !!       D'_lP  = Dvec_l * D_lP
     150              :        !!    d. Solve: Σ_l' D'_ll' * Z'_l'P = D'_lP (Equation 14)
     151              :        !!    e. Rescale: Z_lP = Z'_lP * Dvec_l   (Z_lP stored in mat_Z_lP)
     152              :        !!========================================================================
     153              :       CALL compute_coeff_Z_lP(qs_env, bs_env, bs_env%ri_rs%grid_points, &
     154            0 :                               bs_env%ri_rs%mat_phi_mu_l, bs_env%ri_rs%mat_Z_lP)
     155              : 
     156              :        !!========================================================================
     157              :        !! 4. Compute Independent-Particle Polarizability (χ)
     158              :        !!    G^occ_µλ(i|τ|)  = sum_n^occ C_µn e^(-|(ϵ_n-ϵ_F)τ|) C_λn
     159              :        !!    G^vir_µλ(i|τ|)  = sum_n^vir C_µn e^(-|(ϵ_n-ϵ_F)τ|) C_λn
     160              :        !!    G^occ_ll'(i|τ|) = sum_µν Φ_µ(r_l) G^occ_µν Φ_ν(r_l')
     161              :        !!    G^vir_ll'(i|τ|) = sum_µν Φ_µ(r_l) G^vir_µν Φ_ν(r_l')
     162              :        !!    χ_ll'(iτ)       = G^occ_ll'(i|τ|) * G^vir_ll'(i|τ|)
     163              :        !!    χ_PQ(iτ)        = sum_ll' Z_lP χ_ll'(iτ) Z_l'Q
     164              :        !!========================================================================
     165              :       CALL get_mat_chi_Gamma_tau(bs_env, bs_env%mat_chi_Gamma_tau, &
     166            0 :                                  bs_env%ri_rs%mat_phi_mu_l, bs_env%ri_rs%mat_Z_lP)
     167              : 
     168              :        !!========================================================================
     169              :        !! 5. Compute Screened Interaction (W^MIC)
     170              :        !!    χ_PQ(iτ) -> χ_PQ(iω) -> ε_PQ(iω) -> W_PQ(iω) -> W^MIC_PQ(iτ)
     171              :        !!========================================================================
     172            0 :       CALL get_W_MIC(bs_env, qs_env, bs_env%mat_chi_Gamma_tau, fm_W_time)
     173              : 
     174              :        !!========================================================================
     175              :        !! 6. Compute Exact Exchange Self-Energy (Σ^x)
     176              :        !!    D_µν          = sum_n^occ C_µn C_νn
     177              :        !!    D_ll'         = sum_µν Φ_µ(r_l) D_µν Φ_ν(r_l')
     178              :        !!    V^trunc_ll'   = sum_PQ Z_lP V^trunc_PQ Z_l'Q
     179              :        !!    Σ^x_ll'       = D_ll' * V^trunc_ll'
     180              :        !!    Σ^x_λσ(k=0)   = -sum_ll' Φ_λ(r_l) Σ^x_ll' Φ_σ(r_l')
     181              :        !!========================================================================
     182              :       CALL compute_Sigma_x(bs_env, qs_env, bs_env%ri_rs%mat_phi_mu_l, &
     183            0 :                            bs_env%ri_rs%mat_Z_lP, fm_Sigma_x_Gamma)
     184              : 
     185              :        !!========================================================================
     186              :        !! 7. Compute Correlation Self-Energy (Σ^c)
     187              :        !!    W^MIC_ll'(iτ) =  sum_PQ Z_lP W^MIC_PQ(iτ) Z_l'Q
     188              :        !!    Σ^c_ll'(iτ)   = -G^occ_ll'(i|τ|) * W^MIC_ll'(iτ), for τ < 0
     189              :        !!    Σ^c_ll'(iτ)   =  G^vir_ll'(i|τ|) * W^MIC_ll'(iτ), for τ > 0
     190              :        !!    Σ^c_λσ(iτ)    =  sum_ll' Φ_λ(r_l) Σ^c_ll'(iτ) Φ_σ(r_l')
     191              :        !!========================================================================
     192              :       CALL compute_Sigma_c(bs_env, fm_W_time, bs_env%ri_rs%mat_phi_mu_l, &
     193            0 :                            bs_env%ri_rs%mat_Z_lP, fm_Sigma_c_Gamma_time)
     194              : 
     195              :        !!========================================================================
     196              :        !! 8. Compute Quasiparticle Energies
     197              :        !!    Σ^c_λσ(iτ) -> Σ^c_nn(ϵ)
     198              :        !!    ϵ_nk^GW = ϵ_nk^DFT + Σ^c_nn(ϵ) + Σ^x_nn - v^xc_nn
     199              :        !!========================================================================
     200            0 :       CALL compute_QP_energies(bs_env, qs_env, fm_Sigma_x_Gamma, fm_Sigma_c_Gamma_time)
     201              : 
     202            0 :       CALL de_init_bs_env(bs_env)
     203              : 
     204            0 :       CALL timestop(handle)
     205              : 
     206            0 :    END SUBROUTINE gw_calc_large_cell_Gamma_ri_rs
     207              : 
     208              : ! **************************************************************************************************
     209              : !> \brief Evaluates atomic basis functions on a real-space grid and builds a sparse DBCSR matrix.
     210              : !> \param qs_env ...
     211              : !> \param bs_env ...
     212              : !> \param ri_rs_grid_points ...
     213              : !> \param mat_phi_mu_l ...
     214              : ! **************************************************************************************************
     215              : 
     216            0 :    SUBROUTINE atomic_basis_at_grid_point(qs_env, bs_env, ri_rs_grid_points, mat_phi_mu_l)
     217              : 
     218              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     219              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     220              :       REAL(KIND=dp), ALLOCATABLE, INTENT(INOUT)          :: ri_rs_grid_points(:, :)
     221              :       TYPE(dbcsr_type), INTENT(OUT)                      :: mat_phi_mu_l
     222              : 
     223              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'atomic_basis_at_grid_point'
     224              : 
     225              :       INTEGER :: c_size, chunk_size, dimen_ORB, handle, i, i_blk, iatom, natom, npcol, nprow, &
     226              :          num_grid_chunks, r_end, r_start, total_grid_npts
     227              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: first_sgf
     228            0 :       INTEGER, DIMENSION(:), POINTER                     :: c_blk_sizes, col_dist, r_blk_sizes, &
     229            0 :                                                             row_dist
     230            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: atom_col_buffer
     231            0 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     232              :       TYPE(cell_type), POINTER                           :: cell
     233              :       TYPE(dbcsr_distribution_type)                      :: dist
     234              :       TYPE(dbcsr_distribution_type), POINTER             :: dbcsr_dist_ks
     235              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     236            0 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     237            0 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     238              : 
     239            0 :       CALL timeset(routineN, handle)
     240              : 
     241              :       ! Setup Grid Blocking
     242            0 :       chunk_size = max_elements_per_block
     243              : 
     244              :       ! Extract environment variables
     245              :       CALL get_qs_env(qs_env, cell=cell, atomic_kind_set=atomic_kind_set, &
     246              :                       qs_kind_set=qs_kind_set, particle_set=particle_set, &
     247            0 :                       para_env=para_env)
     248              : 
     249            0 :       natom = SIZE(particle_set)
     250            0 :       total_grid_npts = SIZE(ri_rs_grid_points, 2)
     251              : 
     252              :       ! Map the starting indices of spherical gaussian functions (SGF) for each atom
     253            0 :       ALLOCATE (first_sgf(natom + 1))
     254            0 :       CALL get_basis_offsets(particle_set, qs_kind_set, first_sgf, dimen_ORB)
     255              : 
     256              :       ! =========================================================================
     257              :       ! 1. SETUP DBCSR MATRIX TOPOLOGY
     258              :       ! =========================================================================
     259              : 
     260              :       ! A. Define Column Block Sizes (1 Block = 1 Atom's full basis set)
     261            0 :       ALLOCATE (c_blk_sizes(natom))
     262            0 :       DO iatom = 1, natom
     263            0 :          c_blk_sizes(iatom) = first_sgf(iatom + 1) - first_sgf(iatom)
     264              :       END DO
     265              : 
     266              :       ! B. Define Row Block Sizes (Grid chunks of max size 256)
     267            0 :       num_grid_chunks = CEILING(REAL(total_grid_npts, KIND=dp)/REAL(chunk_size, KIND=dp))
     268            0 :       ALLOCATE (r_blk_sizes(num_grid_chunks))
     269            0 :       r_blk_sizes = chunk_size
     270            0 :       IF (MOD(total_grid_npts, chunk_size) /= 0) THEN
     271            0 :          r_blk_sizes(num_grid_chunks) = MOD(total_grid_npts, chunk_size)
     272              :       END IF
     273              : 
     274              :       ! C. Fetch CP2K's Default Process Grid Configuration
     275            0 :       CALL get_qs_env(qs_env, dbcsr_dist=dbcsr_dist_ks)
     276            0 :       CALL dbcsr_distribution_get(dbcsr_dist_ks, nprows=nprow, npcols=npcol)
     277              : 
     278              :       ! D. Build Custom Mappings using Round-Robin across the 2D process grid
     279              : 
     280            0 :       ALLOCATE (row_dist(num_grid_chunks))
     281            0 :       DO i = 1, num_grid_chunks
     282            0 :          row_dist(i) = MOD(i - 1, nprow)
     283              :       END DO
     284              : 
     285            0 :       ALLOCATE (col_dist(natom))
     286            0 :       DO i = 1, natom
     287            0 :          col_dist(i) = MOD(i - 1, npcol)
     288              :       END DO
     289              : 
     290              :       ! E. Create the DBCSR Distribution and Initialize the Matrix
     291              :       CALL dbcsr_distribution_new(dist, template=dbcsr_dist_ks, &
     292            0 :                                   row_dist=row_dist, col_dist=col_dist)
     293              : 
     294              :       CALL dbcsr_create(mat_phi_mu_l, name="phi_val_sparse", dist=dist, &
     295              :                         matrix_type=dbcsr_type_no_symmetry, &
     296            0 :                         row_blk_size=r_blk_sizes, col_blk_size=c_blk_sizes)
     297              : 
     298              :       ! =========================================================================
     299              :       ! 2. STREAM DATA DIRECTLY INTO SPARSE MATRIX
     300              :       ! =========================================================================
     301              :       ! Iterate over the atoms assigned to this specific MPI rank
     302            0 :       DO iatom = para_env%mepos + 1, natom, para_env%num_pe
     303              : 
     304            0 :          c_size = c_blk_sizes(iatom)
     305              : 
     306              :          ! Allocate a temporary dense buffer just for this specific atom
     307            0 :          ALLOCATE (atom_col_buffer(total_grid_npts, c_size))
     308            0 :          atom_col_buffer = 0.0_dp
     309              : 
     310              :          ! Evaluate the basis functions on the grid. Skip grid points outside the spatial
     311              :          ! extent of the most diffuse AO Gaussian on iatom; beyond that radius the contribution
     312              :          ! is guaranteed below eps_filter.
     313              :          CALL fill_phi_for_atom(atom_col_buffer, ri_rs_grid_points, total_grid_npts, &
     314              :                                 iatom, particle_set, qs_kind_set, cell, &
     315            0 :                                 r2_threshold=bs_env%ri_rs%radius_ao_per_atom(iatom)**2)
     316              : 
     317              :          ! Slice the dense column into chunks and insert into DBCSR
     318            0 :          DO i_blk = 1, num_grid_chunks
     319            0 :             r_start = (i_blk - 1)*chunk_size + 1
     320            0 :             r_end = MIN(i_blk*chunk_size, total_grid_npts)
     321              : 
     322              :             ! Apply dynamic sparsity filtering: Only store blocks with physical significance
     323            0 :             IF (MAXVAL(ABS(atom_col_buffer(r_start:r_end, 1:c_size))) > bs_env%eps_filter) THEN
     324              :                CALL dbcsr_put_block(mat_phi_mu_l, row=i_blk, col=iatom, &
     325            0 :                                     block=atom_col_buffer(r_start:r_end, 1:c_size))
     326              :             END IF
     327              :          END DO
     328              : 
     329            0 :          DEALLOCATE (atom_col_buffer)
     330              : 
     331              :       END DO
     332              : 
     333              :       ! Finalize triggers internal MPI communication to route blocks to their correct 2D process owners
     334            0 :       CALL dbcsr_finalize(mat_phi_mu_l)
     335              : 
     336            0 :       IF (bs_env%unit_nr > 0) THEN
     337            0 :          WRITE (bs_env%unit_nr, *) "Done with evaluation of phi"
     338              :       END IF
     339              : 
     340              :       ! -------------------------------------------------------------------------
     341              :       ! CLEANUP
     342              :       ! -------------------------------------------------------------------------
     343            0 :       DEALLOCATE (first_sgf, r_blk_sizes, c_blk_sizes, row_dist, col_dist)
     344            0 :       CALL dbcsr_distribution_release(dist)
     345              : 
     346            0 :       CALL timestop(handle)
     347              : 
     348            0 :    END SUBROUTINE atomic_basis_at_grid_point
     349              : 
     350              : ! **************************************************************************************************
     351              : !> \brief Compute value of all basis functions for a single atom across all grid points.
     352              : !>        Sums contributions from periodic images of `iatom` (loop over (ix, iy, iz) cells gated
     353              : !>        by `cell%perd`). Each per-image squared distance is compared against `r2_threshold`
     354              : !>        (per-atom AO Gaussian extent²); images beyond that radius contribute below eps_filter
     355              : !>        and are skipped.
     356              : !> \param phi_val ...
     357              : !> \param ri_rs_grid ...
     358              : !> \param npts ...
     359              : !> \param iatom ...
     360              : !> \param particle_set ...
     361              : !> \param qs_kind_set ...
     362              : !> \param cell ...
     363              : !> \param r2_threshold per-image squared-distance threshold; CYCLE if r² > r2_threshold. Pass
     364              : !>        HUGE(1.0_dp) to disable.
     365              : ! **************************************************************************************************
     366              : 
     367            0 :    SUBROUTINE fill_phi_for_atom(phi_val, ri_rs_grid, npts, iatom, &
     368              :                                 particle_set, qs_kind_set, cell, r2_threshold)
     369              : 
     370              :       REAL(KIND=dp), INTENT(INOUT)                       :: phi_val(:, :)
     371              :       INTEGER, INTENT(IN)                                :: npts
     372              :       REAL(KIND=dp), INTENT(IN)                          :: ri_rs_grid(3, npts)
     373              :       INTEGER, INTENT(IN)                                :: iatom
     374              :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     375              :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     376              :       TYPE(cell_type), POINTER                           :: cell
     377              :       REAL(KIND=dp), INTENT(IN)                          :: r2_threshold
     378              : 
     379              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'fill_phi_for_atom'
     380              : 
     381              :       INTEGER :: first_sgf, handle, i_pt, ico, iend_co, ikind, ipgf, iset, isgf, ishell, &
     382              :          istart_co, ix, ix_max, ix_min, iy, iy_max, iy_min, iz, iz_max, iz_min, l, last_sgf, lx, &
     383              :          ly, lz, n_cart_total, row_idx
     384              :       REAL(KIND=dp)                                      :: alpha, cell_vector(3), dist_vec(3), &
     385              :                                                             dist_vec_raw(3), exp_val, poly, r2, &
     386              :                                                             r_atom(3), weight
     387              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: hmat
     388              :       TYPE(gto_basis_set_type), POINTER                  :: orb_basis_set
     389              : 
     390            0 :       CALL timeset(routineN, handle)
     391              : 
     392              :       ! Get Atom Info
     393            0 :       ikind = particle_set(iatom)%atomic_kind%kind_number
     394            0 :       CALL get_qs_kind(qs_kind_set(ikind), basis_set=orb_basis_set, basis_type="ORB")
     395            0 :       CALL get_cell(cell=cell, h=hmat)
     396              : 
     397            0 :       IF (.NOT. ASSOCIATED(orb_basis_set)) THEN
     398            0 :          CALL timestop(handle)
     399            0 :          RETURN
     400              :       END IF
     401              : 
     402            0 :       IF (cell%perd(1) == 1) THEN; ix_min = -1; ix_max = 1; ELSE; ix_min = 0; ix_max = 0
     403              :       END IF
     404            0 :       IF (cell%perd(2) == 1) THEN; iy_min = -1; iy_max = 1; ELSE; iy_min = 0; iy_max = 0
     405              :       END IF
     406            0 :       IF (cell%perd(3) == 1) THEN; iz_min = -1; iz_max = 1; ELSE; iz_min = 0; iz_max = 0
     407              :       END IF
     408              : 
     409            0 :       r_atom = particle_set(iatom)%r
     410              : 
     411              :       !$OMP PARALLEL DO DEFAULT(NONE) &
     412              :       !$OMP SHARED(phi_val, ri_rs_grid, npts, orb_basis_set, r_atom, hmat, &
     413              :       !$OMP        ncoset, indco, cell, ix_min, ix_max, &
     414              :       !$OMP        iy_min, iy_max, iz_min, iz_max, r2_threshold) &
     415              :       !$OMP PRIVATE(i_pt, dist_vec_raw, ix, iy, iz, cell_vector, dist_vec, r2, iset, &
     416              :       !$OMP         n_cart_total, ishell, l, istart_co, iend_co, first_sgf, last_sgf, &
     417              :       !$OMP         ipgf, alpha, exp_val, isgf, ico, row_idx, weight, lx, ly, lz, poly) &
     418            0 :       !$OMP SCHEDULE(DYNAMIC)
     419              : 
     420              :       DO i_pt = 1, npts
     421              : 
     422              :          dist_vec_raw = ri_rs_grid(:, i_pt) - r_atom
     423              : 
     424              :          DO ix = ix_min, ix_max
     425              :          DO iy = iy_min, iy_max
     426              :          DO iz = iz_min, iz_max
     427              : 
     428              :             cell_vector(1:3) = MATMUL(hmat, REAL([ix, iy, iz], dp))
     429              : 
     430              :             dist_vec = dist_vec_raw - cell_vector
     431              : 
     432              :             r2 = DOT_PRODUCT(dist_vec, dist_vec)
     433              : 
     434              :             IF (r2 > r2_threshold) CYCLE
     435              : 
     436              :             DO iset = 1, orb_basis_set%nset
     437              :                n_cart_total = ncoset(orb_basis_set%lmax(iset))
     438              : 
     439              :                DO ishell = 1, orb_basis_set%nshell(iset)
     440              :                   l = orb_basis_set%l(ishell, iset)
     441              :                   istart_co = ncoset(l - 1) + 1
     442              :                   iend_co = ncoset(l)
     443              : 
     444              :                   first_sgf = orb_basis_set%first_sgf(ishell, iset)
     445              :                   last_sgf = orb_basis_set%last_sgf(ishell, iset)
     446              : 
     447              :                   DO ipgf = 1, orb_basis_set%npgf(iset)
     448              :                      alpha = orb_basis_set%zet(ipgf, iset)
     449              :                      exp_val = EXP(-alpha*r2)
     450              : 
     451              :                      DO isgf = first_sgf, last_sgf
     452              :                         DO ico = istart_co, iend_co
     453              :                            row_idx = (ipgf - 1)*n_cart_total + ico
     454              :                            weight = orb_basis_set%sphi(row_idx, isgf)
     455              :                            lx = indco(1, ico)
     456              :                            ly = indco(2, ico)
     457              :                            lz = indco(3, ico)
     458              :                            poly = (dist_vec(1)**lx)*(dist_vec(2)**ly)*(dist_vec(3)**lz)
     459              : 
     460              :                            phi_val(i_pt, isgf) = phi_val(i_pt, isgf) + (weight*poly*exp_val)
     461              : 
     462              :                         END DO
     463              :                      END DO
     464              :                   END DO
     465              :                END DO
     466              :             END DO
     467              :          END DO
     468              :          END DO
     469              :          END DO
     470              :       END DO
     471              :       !$OMP END PARALLEL DO
     472              : 
     473            0 :       CALL timestop(handle)
     474              : 
     475              :    END SUBROUTINE fill_phi_for_atom
     476              : 
     477              : ! **************************************************************************************************
     478              : !> \brief Compute RI-RS Coefficients (Z_lP)
     479              : !> \param qs_env ...
     480              : !> \param bs_env ...
     481              : !> \param ri_rs_grid_points ...
     482              : !> \param mat_phi_mu_l ...
     483              : !> \param mat_Z_lP ...
     484              : ! **************************************************************************************************
     485              : 
     486            0 :    SUBROUTINE compute_coeff_Z_lP(qs_env, bs_env, ri_rs_grid_points, mat_phi_mu_l, mat_Z_lP)
     487              : 
     488              :       ! Arguments
     489              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     490              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     491              :       REAL(KIND=dp), ALLOCATABLE, INTENT(INOUT)          :: ri_rs_grid_points(:, :)
     492              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: mat_phi_mu_l
     493              :       TYPE(dbcsr_type), INTENT(OUT)                      :: mat_Z_lP
     494              : 
     495              :       CHARACTER(LEN=*), PARAMETER :: key = 'PROPERTIES%BANDSTRUCTURE%GW%PRINT%RESTART', &
     496              :          routineN = 'compute_coeff_Z_lP'
     497              : 
     498              :       INTEGER :: atom_j_mepos, atom_j_stride, atom_P, atom_P_start, atom_P_stride, col_end, &
     499              :          col_start, current_chunk_size, g, group_handle, handle, handle_dpotrf, handle_dpotrs, &
     500              :          handle_dsyrk, i, i_blk, ikind, info, j, j_ri, l, loc_idx, loc_ptr, max_ao_size, &
     501              :          max_loc_ri, my_group, n_ao_total, n_grid_total, n_groups, n_loc_ri, n_local_grid, &
     502              :          n_procs_per_atom, natom, nkind, npcol_phi, num_grid_chunks, P_loop_atom, r_end, r_start, &
     503              :          source_atom
     504            0 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: local_grid_idx, row_offset
     505            0 :       INTEGER, DIMENSION(:), POINTER                     :: col_dist_ri, r_blk_sizes, ri_blk_sizes, &
     506            0 :                                                             row_dist_grid
     507              :       REAL(KIND=dp)                                      :: cutoff_ri, cutoff_ri_2, d_sP, dist2_min, &
     508              :                                                             r2_threshold, r_c, t1, t2, t3
     509            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: cutoff_ri_per_atom, cutoff_ri_per_kind, &
     510            0 :                                                             d_vec_local
     511            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: D_local, d_lp_local, phi_local, &
     512            0 :                                                             sphere_grid, Z_blk
     513              :       REAL(KIND=dp), DIMENSION(3)                        :: dist_vec_raw, pos_P
     514            0 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     515              :       TYPE(cell_type), POINTER                           :: cell
     516              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env_sub
     517              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct_b, fm_struct_D
     518              :       TYPE(cp_fm_type)                                   :: fm_b, fm_D
     519              :       TYPE(cp_logger_type), POINTER                      :: logger
     520              :       TYPE(dbcsr_distribution_type)                      :: dist_phi, dist_Z
     521            0 :       TYPE(gw_3c_ctx_type)                               :: ctx_3c
     522              :       TYPE(mp_para_env_type), POINTER                    :: para_env, para_env_sub
     523            0 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     524            0 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     525              :       TYPE(section_vals_type), POINTER                   :: input
     526              : 
     527            0 :       CALL timeset(routineN, handle)
     528              : 
     529            0 :       t1 = m_walltime()
     530              : 
     531              :       CALL get_qs_env(qs_env, para_env=para_env, particle_set=particle_set, input=input, &
     532            0 :                       cell=cell, qs_kind_set=qs_kind_set, atomic_kind_set=atomic_kind_set)
     533              : 
     534              :       ! ---------------------------------------------------------------------
     535              :       ! Subgroup setup. Default G=1 keeps the single-rank BLAS path; G>1 splits
     536              :       ! ranks into atom-groups so the Cholesky on D_local distributes across G
     537              :       ! ranks (memory ~1/G) and the compute_d_lp build also splits across the
     538              :       ! subgroup. G=1 leaves para_env_sub / blacs_env_sub NULL — no subgroup
     539              :       ! comms created, atom_P loop uses per-rank round-robin, compute_d_lp runs
     540              :       ! its full atom_j range on each rank, no allreduce.
     541              :       ! ---------------------------------------------------------------------
     542            0 :       n_procs_per_atom = MIN(bs_env%ri_rs%n_procs_per_atom_z_lp, para_env%num_pe)
     543            0 :       IF (n_procs_per_atom < 1) n_procs_per_atom = 1
     544              : 
     545            0 :       NULLIFY (para_env_sub, blacs_env_sub)
     546            0 :       IF (n_procs_per_atom > 1) THEN
     547            0 :          n_groups = para_env%num_pe/n_procs_per_atom
     548            0 :          my_group = MIN(para_env%mepos/n_procs_per_atom, n_groups - 1)
     549            0 :          ALLOCATE (para_env_sub)
     550            0 :          CALL para_env_sub%from_split(para_env, my_group)
     551            0 :          CALL cp_blacs_env_create(blacs_env=blacs_env_sub, para_env=para_env_sub)
     552            0 :          atom_P_start = my_group + 1
     553            0 :          atom_P_stride = n_groups
     554            0 :          atom_j_mepos = para_env_sub%mepos
     555            0 :          atom_j_stride = para_env_sub%num_pe
     556              :       ELSE
     557            0 :          atom_P_start = para_env%mepos + 1
     558            0 :          atom_P_stride = para_env%num_pe
     559            0 :          atom_j_mepos = 0
     560            0 :          atom_j_stride = 1
     561              :       END IF
     562              : 
     563            0 :       natom = SIZE(bs_env%i_RI_start_from_atom)
     564            0 :       n_ao_total = bs_env%i_ao_end_from_atom(natom)
     565            0 :       n_grid_total = SIZE(ri_rs_grid_points, 2)
     566              : 
     567              :       ! =========================================================================
     568              :       ! 1. SETUP DBCSR TOPOLOGY & EXACT OFFSETS
     569              :       ! =========================================================================
     570            0 :       CALL dbcsr_get_info(mat_phi_mu_l, row_blk_size=r_blk_sizes, distribution=dist_phi)
     571              :       CALL dbcsr_distribution_get(dist_phi, row_dist=row_dist_grid, &
     572            0 :                                   group=group_handle, npcols=npcol_phi)
     573              : 
     574            0 :       num_grid_chunks = SIZE(r_blk_sizes)
     575              : 
     576            0 :       ALLOCATE (row_offset(num_grid_chunks))
     577            0 :       row_offset(1) = 0
     578            0 :       DO i_blk = 2, num_grid_chunks
     579            0 :          row_offset(i_blk) = row_offset(i_blk - 1) + r_blk_sizes(i_blk - 1)
     580              :       END DO
     581              : 
     582            0 :       ALLOCATE (ri_blk_sizes(natom), col_dist_ri(natom))
     583            0 :       DO atom_P = 1, natom
     584            0 :          ri_blk_sizes(atom_P) = bs_env%i_RI_end_from_atom(atom_P) - bs_env%i_RI_start_from_atom(atom_P) + 1
     585            0 :          col_dist_ri(atom_P) = MOD(atom_P - 1, npcol_phi)
     586              :       END DO
     587              : 
     588            0 :       CALL dbcsr_distribution_new(dist_Z, template=dist_phi, row_dist=row_dist_grid, col_dist=col_dist_ri)
     589              : 
     590            0 :       IF (bs_env%ri_rs%Z_lP_exists) THEN
     591              :          CALL dbcsr_binary_read(filepath=TRIM(bs_env%prefix)//"Z_lP.matrix", &
     592              :                                 distribution=dist_Z, &
     593            0 :                                 matrix_new=mat_Z_lP)
     594            0 :          IF (bs_env%unit_nr > 0) THEN
     595              :             WRITE (bs_env%unit_nr, '(T2,A,T57,A,F7.1,A)') &
     596            0 :                'Read Z_lP from file ', ' Execution time', m_walltime() - t1, ' s'
     597            0 :             WRITE (bs_env%unit_nr, '(A)') ' '
     598              :          END IF
     599              :       ELSE
     600              : 
     601              :          CALL dbcsr_create(mat_Z_lP, name="mat_Z_lP", dist=dist_Z, &
     602              :                            matrix_type=dbcsr_type_no_symmetry, &
     603            0 :                            row_blk_size=r_blk_sizes, col_blk_size=ri_blk_sizes)
     604              : 
     605            0 :          max_ao_size = 0
     606            0 :          DO j = 1, SIZE(bs_env%i_ao_start_from_atom)
     607            0 :             max_ao_size = MAX(max_ao_size, bs_env%i_ao_end_from_atom(j) - bs_env%i_ao_start_from_atom(j) + 1)
     608              :          END DO
     609            0 :          max_loc_ri = MAXVAL(ri_blk_sizes)
     610              : 
     611              :          ! Per-atom RI-RS integration sphere:
     612              :          !   cutoff_ri(P) = r_c + r_AO(P)
     613              :          ! where r_c is the truncated-Coulomb cutoff of the RI metric. The
     614              :          ! CUTOFF_RADIUS_RI_RS keyword (when > 0) overrides the entire cutoff calculation.
     615            0 :          nkind = SIZE(atomic_kind_set)
     616            0 :          ALLOCATE (cutoff_ri_per_atom(natom))
     617              : 
     618            0 :          IF (bs_env%ri_rs%cutoff_radius_ri_rs > 0.0_dp) THEN
     619            0 :             cutoff_ri_per_atom(:) = bs_env%ri_rs%cutoff_radius_ri_rs
     620              :          ELSE
     621            0 :             r_c = bs_env%ri_metric%cutoff_radius
     622            0 :             DO P_loop_atom = 1, natom
     623              :                cutoff_ri_per_atom(P_loop_atom) = &
     624            0 :                   r_c + bs_env%ri_rs%radius_ao_per_atom(P_loop_atom)
     625              :             END DO
     626              :          END IF
     627              : 
     628            0 :          ALLOCATE (cutoff_ri_per_kind(nkind))
     629            0 :          cutoff_ri_per_kind(:) = 0.0_dp
     630            0 :          IF (bs_env%unit_nr > 0) THEN
     631            0 :             DO P_loop_atom = 1, natom
     632            0 :                ikind = particle_set(P_loop_atom)%atomic_kind%kind_number
     633              :                cutoff_ri_per_kind(ikind) = MAX(cutoff_ri_per_kind(ikind), &
     634            0 :                                                cutoff_ri_per_atom(P_loop_atom))
     635              :             END DO
     636            0 :             WRITE (bs_env%unit_nr, '(T2,A)') 'Per-kind maximum RI-RS sphere cutoff (Bohr):'
     637            0 :             WRITE (bs_env%unit_nr, '(T4,A4,A14)') 'Kind', 'max cutoff_ri'
     638            0 :             DO ikind = 1, nkind
     639              :                WRITE (bs_env%unit_nr, '(T4,A4,F14.4)') &
     640            0 :                   atomic_kind_set(ikind)%element_symbol, &
     641            0 :                   cutoff_ri_per_kind(ikind)
     642              :             END DO
     643            0 :             WRITE (bs_env%unit_nr, '(A)') ' '
     644            0 :             DEALLOCATE (cutoff_ri_per_kind)
     645              :          END IF
     646              : 
     647              :          ! Shared 3c-integral context: hoists libint / t_c_g0 / md_ftable / contracted
     648              :          ! sphi tables out of the per-triple call so compute_d_lp threads only allocate
     649              :          ! a lightweight per-thread workspace. MPI-collective; must be outside any
     650              :          ! OMP region.
     651              :          CALL gw_3c_ctx_create(ctx_3c, qs_env, bs_env%ri_metric, &
     652              :                                basis_j=bs_env%basis_set_AO, basis_k=bs_env%basis_set_AO, &
     653            0 :                                basis_i=bs_env%basis_set_RI)
     654              : 
     655              :          ! =========================================================================
     656              :          ! 2. MPI LOOP OVER ATOMS (Fully independent, no MPI barriers inside)
     657              :          ! phi_local for each atom_P's cutoff sphere is built on the fly via
     658              :          ! fill_phi_for_atom — no dense replicated phi_global, no allreduce.
     659              :          ! =========================================================================
     660            0 :          DO atom_P = atom_P_start, natom, atom_P_stride
     661              : 
     662            0 :             n_loc_ri = ri_blk_sizes(atom_P)
     663            0 :             pos_P(:) = particle_set(atom_P)%r(:)
     664              : 
     665            0 :             cutoff_ri = cutoff_ri_per_atom(atom_P)
     666            0 :             cutoff_ri_2 = cutoff_ri**2
     667              : 
     668              :             ! ---------------------------------------------------------------------
     669              :             ! A. Determine Local Grid Domain based on cutoff_ri (PBC distance)
     670              :             ! ---------------------------------------------------------------------
     671            0 :             n_local_grid = 0
     672            0 :             DO l = 1, n_grid_total
     673            0 :                dist_vec_raw = pbc(ri_rs_grid_points(1:3, l), pos_P(1:3), cell)
     674            0 :                dist2_min = DOT_PRODUCT(dist_vec_raw, dist_vec_raw)
     675            0 :                IF (dist2_min <= cutoff_ri_2) n_local_grid = n_local_grid + 1
     676              :             END DO
     677              : 
     678            0 :             ALLOCATE (local_grid_idx(n_local_grid))
     679              : 
     680            0 :             n_local_grid = 0
     681            0 :             DO l = 1, n_grid_total
     682            0 :                dist_vec_raw = pbc(ri_rs_grid_points(1:3, l), pos_P(1:3), cell)
     683            0 :                dist2_min = DOT_PRODUCT(dist_vec_raw, dist_vec_raw)
     684            0 :                IF (dist2_min <= cutoff_ri_2) THEN
     685            0 :                   n_local_grid = n_local_grid + 1
     686            0 :                   local_grid_idx(n_local_grid) = l
     687              :                END IF
     688              :             END DO
     689              : 
     690              :             ! ---------------------------------------------------------------------
     691              :             ! B. Build phi_local on the fly via fill_phi_for_atom.
     692              :             !    Only source atoms whose AO basis can reach the cutoff sphere of
     693              :             !    atom_P (MIC distance) contribute; the rest are pruned. The
     694              :             !    periodic fill_phi_for_atom sums over (ix, iy, iz) images of
     695              :             !    source_atom internally.
     696              :             ! ---------------------------------------------------------------------
     697            0 :             ALLOCATE (sphere_grid(3, n_local_grid))
     698            0 :             DO loc_idx = 1, n_local_grid
     699            0 :                sphere_grid(:, loc_idx) = ri_rs_grid_points(:, local_grid_idx(loc_idx))
     700              :             END DO
     701              : 
     702            0 :             ALLOCATE (phi_local(n_local_grid, n_ao_total))
     703            0 :             phi_local = 0.0_dp
     704              : 
     705            0 :             DO source_atom = 1, natom
     706            0 :                dist_vec_raw = pbc(particle_set(source_atom)%r(:), pos_P(:), cell)
     707            0 :                d_sP = NORM2(dist_vec_raw)
     708            0 :                IF (d_sP > bs_env%ri_rs%radius_ao_per_atom(source_atom) + cutoff_ri) CYCLE
     709              : 
     710            0 :                col_start = bs_env%i_ao_start_from_atom(source_atom)
     711            0 :                col_end = bs_env%i_ao_end_from_atom(source_atom)
     712            0 :                r2_threshold = bs_env%ri_rs%radius_ao_per_atom(source_atom)**2
     713              : 
     714              :                CALL fill_phi_for_atom(phi_local(:, col_start:col_end), sphere_grid, &
     715              :                                       n_local_grid, source_atom, particle_set, qs_kind_set, &
     716            0 :                                       cell, r2_threshold)
     717              :             END DO
     718              : 
     719            0 :             DEALLOCATE (sphere_grid)
     720              : 
     721              :             ! ---------------------------------------------------------------------
     722              :             ! C. Build Local RHS Matrix (d_lp_local) first so the subgroup-
     723              :             !    distributed compute_d_lp + allreduce is not entangled with the LHS
     724              :             !    build. compute_d_lp does not depend on D_local or d_vec_local.
     725              :             ! ---------------------------------------------------------------------
     726            0 :             ALLOCATE (d_lp_local(n_local_grid, n_loc_ri))
     727            0 :             d_lp_local = 0.0_dp
     728              : 
     729            0 :             t2 = m_walltime()
     730              : 
     731              :             CALL compute_d_lp(bs_env, ctx_3c, cell, phi_local, d_lp_local, n_local_grid, &
     732            0 :                               n_loc_ri, atom_P, max_ao_size, atom_j_mepos, atom_j_stride)
     733              : 
     734              :             ! Reduce per-subgroup-rank partials into the replicated d_lp_local.
     735              :             ! Skipped for G=1 (BLAS path): each rank has the full sum locally.
     736            0 :             IF (n_procs_per_atom > 1) THEN
     737            0 :                CALL para_env_sub%sum(d_lp_local)
     738              :             END IF
     739              : 
     740            0 :             t3 = m_walltime()
     741              : 
     742              :             ! ---------------------------------------------------------------------
     743              :             ! D. Build d_vec_local (Jacobi diagonal) + LHS — BLAS or ScaLAPACK
     744              :             ! ---------------------------------------------------------------------
     745            0 :             ALLOCATE (d_vec_local(n_local_grid))
     746              : 
     747            0 :             IF (n_procs_per_atom == 1) THEN
     748              :                ! BLAS path: build D_local densely, compute d_vec as side-effect
     749              :                ! of the Jacobi step (preserves bit-identical arithmetic with the
     750              :                ! previous branch).
     751            0 :                ALLOCATE (D_local(n_local_grid, n_local_grid))
     752            0 :                D_local = 0.0_dp
     753              : 
     754            0 :                CALL timeset(routineN//"_dsyrk", handle_dsyrk)
     755              :                CALL dsyrk("L", "N", n_local_grid, n_ao_total, 1.0_dp, phi_local, &
     756            0 :                           n_local_grid, 0.0_dp, D_local, n_local_grid)
     757            0 :                CALL timestop(handle_dsyrk)
     758              : 
     759              :                !$OMP PARALLEL DO DEFAULT(NONE) &
     760              :                !$OMP SHARED(n_local_grid, D_local, d_vec_local, bs_env) &
     761              :                !$OMP PRIVATE(i) &
     762            0 :                !$OMP SCHEDULE(STATIC)
     763              :                DO i = 1, n_local_grid
     764              :                   D_local(i, i) = D_local(i, i)**2
     765              :                   d_vec_local(i) = 1.0_dp/SQRT(MAX(D_local(i, i), 1.0E-16_dp))
     766              :                   D_local(i, i) = (D_local(i, i)*d_vec_local(i)**2) + bs_env%ri_rs%tikhonov
     767              :                END DO
     768              :                !$OMP END PARALLEL DO
     769              : 
     770              :                !$OMP PARALLEL DO DEFAULT(NONE) &
     771              :                !$OMP SHARED(n_local_grid, D_local, d_vec_local) &
     772              :                !$OMP PRIVATE(j, i) &
     773            0 :                !$OMP SCHEDULE(DYNAMIC)
     774              :                DO j = 1, n_local_grid
     775              :                   DO i = j + 1, n_local_grid
     776              :                      D_local(i, j) = D_local(i, j)**2
     777              :                      D_local(i, j) = D_local(i, j)*d_vec_local(i)*d_vec_local(j)
     778              :                      D_local(j, i) = D_local(i, j)
     779              :                   END DO
     780              :                END DO
     781              :                !$OMP END PARALLEL DO
     782              :             ELSE
     783              :                ! ScaLAPACK path: d_vec computed directly from phi (= 1/||phi_i||^2);
     784              :                ! solve_D_lp_distributed builds D block-cyclic internally with
     785              :                ! the squared+scaled values, so no dense D_local on this rank.
     786              :                !$OMP PARALLEL DO DEFAULT(NONE) &
     787              :                !$OMP SHARED(n_local_grid, n_ao_total, phi_local, d_vec_local) &
     788              :                !$OMP PRIVATE(i, j) &
     789            0 :                !$OMP SCHEDULE(STATIC)
     790              :                DO i = 1, n_local_grid
     791              :                   d_vec_local(i) = 0.0_dp
     792              :                   DO j = 1, n_ao_total
     793              :                      d_vec_local(i) = d_vec_local(i) + phi_local(i, j)*phi_local(i, j)
     794              :                   END DO
     795              :                   d_vec_local(i) = 1.0_dp/MAX(d_vec_local(i), 1.0E-16_dp)
     796              :                END DO
     797              :                !$OMP END PARALLEL DO
     798              :             END IF
     799              : 
     800              :             ! ---------------------------------------------------------------------
     801              :             ! E. Pre-scale d_lp by d_vec
     802              :             ! ---------------------------------------------------------------------
     803              :             !$OMP PARALLEL DO DEFAULT(NONE) &
     804              :             !$OMP SHARED(n_loc_ri, n_local_grid, d_lp_local, d_vec_local) &
     805              :             !$OMP PRIVATE(j_ri, i) &
     806            0 :             !$OMP SCHEDULE(STATIC)
     807              :             DO j_ri = 1, n_loc_ri
     808              :                DO i = 1, n_local_grid
     809              :                   d_lp_local(i, j_ri) = d_lp_local(i, j_ri)*d_vec_local(i)
     810              :                END DO
     811              :             END DO
     812              :             !$OMP END PARALLEL DO
     813              : 
     814              :             ! ---------------------------------------------------------------------
     815              :             ! F. Solve — BLAS dpotrf/dpotrs or ScaLAPACK pdpotrf/pdpotrs
     816              :             ! ---------------------------------------------------------------------
     817            0 :             IF (n_procs_per_atom == 1) THEN
     818            0 :                CALL timeset(routineN//"_dpotrf", handle_dpotrf)
     819            0 :                CALL dpotrf('L', n_local_grid, D_local, n_local_grid, info)
     820            0 :                CALL timestop(handle_dpotrf)
     821            0 :                CALL timeset(routineN//"_dpotrs", handle_dpotrs)
     822              :                CALL dpotrs('L', n_local_grid, n_loc_ri, D_local, n_local_grid, &
     823            0 :                            d_lp_local, n_local_grid, info)
     824            0 :                CALL timestop(handle_dpotrs)
     825            0 :                DEALLOCATE (D_local)
     826              :             ELSE
     827              :                CALL solve_D_lp_distributed(phi_local, d_vec_local, d_lp_local, &
     828              :                                            n_local_grid, n_ao_total, n_loc_ri, &
     829              :                                            bs_env%ri_rs%tikhonov, &
     830              :                                            para_env_sub, blacs_env_sub, &
     831            0 :                                            fm_struct_D, fm_struct_b, fm_D, fm_b, info)
     832              :             END IF
     833              : 
     834              :             ! ---------------------------------------------------------------------
     835              :             ! G. Post-scale solution by d_vec (common to both paths)
     836              :             ! ---------------------------------------------------------------------
     837              :             !$OMP PARALLEL DO DEFAULT(NONE) &
     838              :             !$OMP SHARED(n_loc_ri, n_local_grid, d_lp_local, d_vec_local) &
     839              :             !$OMP PRIVATE(j_ri, i) &
     840            0 :             !$OMP SCHEDULE(STATIC)
     841              :             DO j_ri = 1, n_loc_ri
     842              :                DO i = 1, n_local_grid
     843              :                   d_lp_local(i, j_ri) = d_lp_local(i, j_ri)*d_vec_local(i)
     844              :                END DO
     845              :             END DO
     846              :             !$OMP END PARALLEL DO
     847              : 
     848              :             ! ---------------------------------------------------------------------
     849              :             ! H. Scatter Local Solution Back to Global DBCSR Matrix.
     850              :             !    Under ScaLAPACK (G>1) the d_lp_local solution is identical on all
     851              :             !    G subgroup ranks (gathered via cp_fm_get_submatrix); only the
     852              :             !    subgroup root writes to mat_Z_lP so each atom column is emitted
     853              :             !    exactly once. DBCSR routes blocks to their global owner on finalize.
     854              :             !    local_grid_idx is ascending (built by the ordered scan above), so
     855              :             !    a single walking pointer over chunks works.
     856              :             ! ---------------------------------------------------------------------
     857            0 :             IF (n_procs_per_atom == 1 .OR. para_env_sub%mepos == 0) THEN
     858            0 :                ALLOCATE (Z_blk(MAXVAL(r_blk_sizes), n_loc_ri))
     859            0 :                loc_ptr = 1
     860              : 
     861            0 :                DO i_blk = 1, num_grid_chunks
     862            0 :                   r_start = row_offset(i_blk) + 1
     863            0 :                   r_end = row_offset(i_blk) + r_blk_sizes(i_blk)
     864            0 :                   current_chunk_size = r_blk_sizes(i_blk)
     865              : 
     866            0 :                   Z_blk = 0.0_dp
     867              : 
     868            0 :                   DO WHILE (loc_ptr <= n_local_grid)
     869            0 :                      g = local_grid_idx(loc_ptr)
     870            0 :                      IF (g > r_end) EXIT
     871            0 :                      Z_blk(g - r_start + 1, 1:n_loc_ri) = d_lp_local(loc_ptr, 1:n_loc_ri)
     872            0 :                      loc_ptr = loc_ptr + 1
     873              :                   END DO
     874              : 
     875            0 :                   IF (MAXVAL(ABS(Z_blk(1:current_chunk_size, 1:n_loc_ri))) > bs_env%eps_filter) THEN
     876              :                      CALL dbcsr_put_block(mat_Z_lP, row=i_blk, col=atom_P, &
     877            0 :                                           block=Z_blk(1:current_chunk_size, 1:n_loc_ri))
     878              :                   END IF
     879              :                END DO
     880              : 
     881            0 :                DEALLOCATE (Z_blk)
     882              :             END IF
     883              : 
     884            0 :             DEALLOCATE (d_vec_local, d_lp_local)
     885            0 :             DEALLOCATE (local_grid_idx, phi_local)
     886              : 
     887              :          END DO
     888              : 
     889            0 :          DEALLOCATE (cutoff_ri_per_atom)
     890            0 :          CALL gw_3c_ctx_release(ctx_3c)
     891              : 
     892            0 :          CALL dbcsr_finalize(mat_Z_lP)
     893              : 
     894            0 :          IF (bs_env%unit_nr > 0) THEN
     895              :             WRITE (bs_env%unit_nr, '(T2,A,T57,A,F7.1,A)') &
     896            0 :                'Computed Z_lP ', ' Execution time', m_walltime() - t1, ' s'
     897            0 :             WRITE (bs_env%unit_nr, '(A)') ' '
     898              :          END IF
     899              : 
     900            0 :          logger => cp_get_default_logger()
     901              : 
     902            0 :          IF (BTEST(cp_print_key_should_output(logger%iter_info, input, key), cp_p_file)) THEN
     903            0 :             CALL dbcsr_binary_write(matrix=mat_Z_lP, filepath=TRIM(bs_env%prefix)//"Z_lP.matrix")
     904              :          END IF
     905              : 
     906              :       END IF
     907              : 
     908            0 :       DEALLOCATE (row_offset, ri_blk_sizes, col_dist_ri)
     909            0 :       CALL dbcsr_distribution_release(dist_Z)
     910              : 
     911            0 :       IF (n_procs_per_atom > 1) THEN
     912            0 :          CALL cp_blacs_env_release(blacs_env_sub)
     913            0 :          CALL para_env_sub%free()
     914            0 :          DEALLOCATE (para_env_sub)
     915              :       END IF
     916              : 
     917            0 :       DEALLOCATE (ri_rs_grid_points)
     918              : 
     919            0 :       CALL timestop(handle)
     920              : 
     921            0 :    END SUBROUTINE compute_coeff_Z_lP
     922              : 
     923              : ! **************************************************************************************************
     924              : !> \brief Computes the dense localized RHS d_lp(l,P) = Σ_{μν,R,S} Φ_μ(r_l)·Φ_ν(r_l)·(μν|P) for one
     925              : !>        RI atom P. OMP-threaded over (atom_j, atom_k) AO-pair blocks: per thread, sweep all
     926              : !>        (cell_R, cell_S) periodic images of (atom_j, atom_k) about atom_P at cell (0,0,0); each
     927              : !>        3c block is built by build_3c_integral_block_ctx (cached libint / sphi tables in ctx,
     928              : !>        kind-radius triangle screen → `screened` short-circuits negligible image triples), and
     929              : !>        grid-chunked pair densities are contracted into a private d_lp partial that is reduced
     930              : !>        into d_lp at the end of the parallel region.
     931              : !> \param bs_env ...
     932              : !> \param ctx shared 3c-integral context (gw_3c_ctx_create)
     933              : !> \param cell ...
     934              : !> \param phi_val Φ_μ(r_l) on the local-sphere grid (n_grid_total × n_ao)
     935              : !> \param d_lp output (n_grid_total × n_loc_ri), zeroed by the caller, accumulated here
     936              : !> \param n_grid_total number of local-sphere grid rows
     937              : !> \param n_loc_ri number of RI functions of atom_P
     938              : !> \param atom_P RI atom (pinned to cell (0,0,0))
     939              : !> \param max_ao_size ...
     940              : !> \param atom_j_mepos ...
     941              : !> \param atom_j_stride ...
     942              : ! **************************************************************************************************
     943              : 
     944            0 :    SUBROUTINE compute_d_lp(bs_env, ctx, cell, phi_val, d_lp, n_grid_total, n_loc_ri, atom_P, &
     945              :                            max_ao_size, atom_j_mepos, atom_j_stride)
     946              : 
     947              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     948              :       TYPE(gw_3c_ctx_type), INTENT(IN)                   :: ctx
     949              :       TYPE(cell_type), POINTER                           :: cell
     950              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: phi_val
     951              :       INTEGER, INTENT(IN)                                :: n_grid_total, n_loc_ri
     952              :       REAL(KIND=dp), INTENT(INOUT)                       :: d_lp(n_grid_total, n_loc_ri)
     953              :       INTEGER, INTENT(IN)                                :: atom_P, max_ao_size, atom_j_mepos, &
     954              :                                                             atom_j_stride
     955              : 
     956              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_d_lp'
     957              :       INTEGER, PARAMETER                                 :: grid_chunk = 1024
     958              : 
     959              :       INTEGER :: atom_j, atom_k, c, handle, handle_dgemm, ix_max, ix_min, ix_R, ix_S, iy_max, &
     960              :          iy_min, iy_R, iy_S, iz_max, iz_min, iz_R, iz_S, j, jk_idx, jsize, jstart, k, ksize, &
     961              :          kstart, l, l0, natom, ri
     962              :       INTEGER, DIMENSION(3)                              :: cell_R_vec, cell_S_vec
     963              :       LOGICAL                                            :: any_kept, screened
     964            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: d_lp_prv, int_2d_prv, rho_chunk
     965            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: int_3c_prv, int_3c_sum
     966            0 :       TYPE(gw_3c_ws_type)                                :: ws
     967              : 
     968            0 :       CALL timeset(routineN, handle)
     969              : 
     970            0 :       natom = SIZE(bs_env%i_ao_start_from_atom)
     971              : 
     972            0 :       IF (cell%perd(1) == 1) THEN; ix_min = -1; ix_max = 1; ELSE; ix_min = 0; ix_max = 0
     973              :       END IF
     974            0 :       IF (cell%perd(2) == 1) THEN; iy_min = -1; iy_max = 1; ELSE; iy_min = 0; iy_max = 0
     975              :       END IF
     976            0 :       IF (cell%perd(3) == 1) THEN; iz_min = -1; iz_max = 1; ELSE; iz_min = 0; iz_max = 0
     977              :       END IF
     978              : 
     979              :       !$OMP PARALLEL DEFAULT(NONE) &
     980              :       !$OMP SHARED(bs_env, ctx, phi_val, d_lp, n_grid_total, n_loc_ri, atom_P, max_ao_size, &
     981              :       !$OMP        natom, ix_min, ix_max, iy_min, iy_max, iz_min, iz_max, &
     982              :       !$OMP        atom_j_mepos, atom_j_stride) &
     983              :       !$OMP PRIVATE(any_kept, atom_j, atom_k, c, handle_dgemm, j, jk_idx, jsize, jstart, k, &
     984              :       !$OMP         ksize, kstart, l, l0, ri, ix_R, iy_R, iz_R, ix_S, iy_S, iz_S, cell_R_vec, &
     985            0 :       !$OMP         cell_S_vec, screened, d_lp_prv, int_2d_prv, rho_chunk, int_3c_prv, int_3c_sum, ws)
     986              : 
     987              :       CALL gw_3c_ws_create(ws, ctx)
     988              :       ALLOCATE (int_3c_prv(max_ao_size, max_ao_size, n_loc_ri))
     989              :       ALLOCATE (int_3c_sum(max_ao_size, max_ao_size, n_loc_ri))
     990              :       ALLOCATE (int_2d_prv(max_ao_size*max_ao_size, n_loc_ri))
     991              :       ALLOCATE (rho_chunk(grid_chunk, max_ao_size*max_ao_size))
     992              :       ALLOCATE (d_lp_prv(n_grid_total, n_loc_ri))
     993              :       d_lp_prv(:, :) = 0.0_dp
     994              : 
     995              :       ! atom_P pinned at cell (0,0,0); enumerate (atom_j, cell_R) × (atom_k, cell_S). The ctx
     996              :       ! integral builder's kind_radius triangle screen sets screened=.TRUE. for the bulk of
     997              :       ! image triples (one or both AO atoms beyond the truncated-Coulomb reach of atom_P),
     998              :       ! so the 27 × 27 = 729 candidate cells collapse to "adjacent cells" in practice.
     999              :       ! MPI-stride atom_j over the subgroup (atom_j_stride = 1 for the BLAS path, > 1 for the
    1000              :       ! ScaLAPACK path). COLLAPSE(2) dropped because the outer stride is non-unit under
    1001              :       ! ScaLAPACK; the inner atom_k loop carries enough work for DYNAMIC.
    1002              :       !$OMP DO SCHEDULE(DYNAMIC)
    1003              :       DO atom_j = atom_j_mepos + 1, natom, atom_j_stride
    1004              :          DO atom_k = 1, natom
    1005              :             jstart = bs_env%i_ao_start_from_atom(atom_j)
    1006              :             jsize = bs_env%i_ao_end_from_atom(atom_j) - jstart + 1
    1007              :             kstart = bs_env%i_ao_start_from_atom(atom_k)
    1008              :             ksize = bs_env%i_ao_end_from_atom(atom_k) - kstart + 1
    1009              : 
    1010              :             int_3c_sum(1:jsize, 1:ksize, 1:n_loc_ri) = 0.0_dp
    1011              :             any_kept = .FALSE.
    1012              : 
    1013              :             DO ix_R = ix_min, ix_max
    1014              :             DO iy_R = iy_min, iy_max
    1015              :             DO iz_R = iz_min, iz_max
    1016              :                cell_R_vec = [ix_R, iy_R, iz_R]
    1017              :                DO ix_S = ix_min, ix_max
    1018              :                DO iy_S = iy_min, iy_max
    1019              :                DO iz_S = iz_min, iz_max
    1020              :                   cell_S_vec = [ix_S, iy_S, iz_S]
    1021              : 
    1022              :                   int_3c_prv(1:jsize, 1:ksize, 1:n_loc_ri) = 0.0_dp
    1023              : 
    1024              :                   CALL build_3c_integral_block_ctx( &
    1025              :                      int_3c_prv(1:jsize, 1:ksize, 1:n_loc_ri), ctx, ws, &
    1026              :                      atom_j=atom_j, atom_k=atom_k, atom_i=atom_P, &
    1027              :                      cell_j=cell_R_vec, cell_k=cell_S_vec, cell_i=[0, 0, 0], &
    1028              :                      screened=screened)
    1029              :                   IF (screened) CYCLE
    1030              : 
    1031              :                   any_kept = .TRUE.
    1032              :                   int_3c_sum(1:jsize, 1:ksize, 1:n_loc_ri) = &
    1033              :                      int_3c_sum(1:jsize, 1:ksize, 1:n_loc_ri) + &
    1034              :                      int_3c_prv(1:jsize, 1:ksize, 1:n_loc_ri)
    1035              :                END DO
    1036              :                END DO
    1037              :                END DO
    1038              :             END DO
    1039              :             END DO
    1040              :             END DO
    1041              : 
    1042              :             IF (.NOT. any_kept) CYCLE
    1043              : 
    1044              :             ! Flatten 3D B_{μν,P} → 2D B_{(μν),P}
    1045              :             DO ri = 1, n_loc_ri
    1046              :                DO k = 1, ksize
    1047              :                   DO j = 1, jsize
    1048              :                      jk_idx = (k - 1)*jsize + j
    1049              :                      int_2d_prv(jk_idx, ri) = int_3c_sum(j, k, ri)
    1050              :                   END DO
    1051              :                END DO
    1052              :             END DO
    1053              : 
    1054              :             ! Pair density ρ(l,μν) = Φ_μ(r_l)Φ_ν(r_l) in grid chunks, contracted on the fly:
    1055              :             ! d_{l,P} += ρ(l,μν) B_{(μν),P}  (dgemm runs serially inside the parallel region)
    1056              :             DO l0 = 1, n_grid_total, grid_chunk
    1057              :                c = MIN(grid_chunk, n_grid_total - l0 + 1)
    1058              :                DO k = 1, ksize
    1059              :                   DO j = 1, jsize
    1060              :                      jk_idx = (k - 1)*jsize + j
    1061              :                      DO l = 1, c
    1062              :                         rho_chunk(l, jk_idx) = phi_val(l0 + l - 1, jstart + j - 1)* &
    1063              :                                                phi_val(l0 + l - 1, kstart + k - 1)
    1064              :                      END DO
    1065              :                   END DO
    1066              :                END DO
    1067              :                CALL timeset(routineN//"_dgemm", handle_dgemm)
    1068              :                CALL dgemm("N", "N", c, n_loc_ri, jsize*ksize, &
    1069              :                           1.0_dp, rho_chunk, grid_chunk, &
    1070              :                           int_2d_prv, max_ao_size*max_ao_size, &
    1071              :                           1.0_dp, d_lp_prv(l0, 1), n_grid_total)
    1072              :                CALL timestop(handle_dgemm)
    1073              :             END DO
    1074              :          END DO
    1075              :       END DO
    1076              :       !$OMP END DO
    1077              : 
    1078              :       !$OMP CRITICAL (compute_d_lp_reduce)
    1079              :       d_lp(1:n_grid_total, 1:n_loc_ri) = d_lp(1:n_grid_total, 1:n_loc_ri) + &
    1080              :                                          d_lp_prv(1:n_grid_total, 1:n_loc_ri)
    1081              :       !$OMP END CRITICAL (compute_d_lp_reduce)
    1082              : 
    1083              :       DEALLOCATE (int_3c_prv, int_3c_sum, int_2d_prv, rho_chunk, d_lp_prv)
    1084              :       CALL gw_3c_ws_release(ws)
    1085              : 
    1086              :       !$OMP END PARALLEL
    1087              : 
    1088            0 :       CALL timestop(handle)
    1089              : 
    1090            0 :    END SUBROUTINE compute_d_lp
    1091              : 
    1092              : ! **************************************************************************************************
    1093              : !> \brief Computes the χ(iτ, k=0) matrix
    1094              : !> \param bs_env ...
    1095              : !> \param mat_chi_Gamma_tau ...
    1096              : !> \param mat_phi_mu_l ...
    1097              : !> \param mat_Z_lP ...
    1098              : ! **************************************************************************************************
    1099              : 
    1100            0 :    SUBROUTINE get_mat_chi_Gamma_tau(bs_env, mat_chi_Gamma_tau, mat_phi_mu_l, mat_Z_lP)
    1101              : 
    1102              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1103              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mat_chi_Gamma_tau
    1104              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: mat_phi_mu_l, mat_Z_lP
    1105              : 
    1106              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_mat_chi_Gamma_tau'
    1107              : 
    1108              :       INTEGER                                            :: handle, i, i_t, ispin, npcol
    1109            0 :       INTEGER, DIMENSION(:), POINTER                     :: blk_ao, blk_grid, dist_col_grid, &
    1110            0 :                                                             dist_row_grid
    1111              :       REAL(KIND=dp)                                      :: t1, tau
    1112              :       TYPE(dbcsr_distribution_type)                      :: dist_grid_grid, dist_phi
    1113              :       TYPE(dbcsr_type)                                   :: matrix_chi_grid, matrix_chi_grid_spin, &
    1114              :                                                             matrix_G_occ_grid, matrix_G_vir_grid
    1115              : 
    1116            0 :       CALL timeset(routineN, handle)
    1117              : 
    1118              :       ! =========================================================================
    1119              :       ! 1. SETUP CORE TOPOLOGIES
    1120              :       ! =========================================================================
    1121            0 :       CALL dbcsr_get_info(mat_phi_mu_l, distribution=dist_phi, row_blk_size=blk_grid, col_blk_size=blk_ao)
    1122            0 :       CALL dbcsr_distribution_get(dist_phi, row_dist=dist_row_grid, npcols=npcol)
    1123              : 
    1124              :       ! Build a perfectly safe column distribution for the Grid dimension
    1125            0 :       ALLOCATE (dist_col_grid(SIZE(blk_grid)))
    1126            0 :       DO i = 1, SIZE(blk_grid)
    1127            0 :          dist_col_grid(i) = MOD(i - 1, npcol)
    1128              :       END DO
    1129              : 
    1130              :       CALL dbcsr_distribution_new(dist_grid_grid, template=dist_phi, &
    1131            0 :                                   row_dist=dist_row_grid, col_dist=dist_col_grid)
    1132              : 
    1133            0 :       CALL dbcsr_create(matrix_G_occ_grid, "G_occ_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1134            0 :       CALL dbcsr_create(matrix_G_vir_grid, "G_vir_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1135            0 :       CALL dbcsr_create(matrix_chi_grid, "chi_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1136            0 :       CALL dbcsr_create(matrix_chi_grid_spin, "chi_grid_spin", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1137              : 
    1138              :       ! =========================================================================
    1139              :       ! 2. MAIN IMAGINARY TIME LOOP
    1140              :       ! =========================================================================
    1141            0 :       DO i_t = 1, bs_env%num_time_freq_points
    1142            0 :          t1 = m_walltime()
    1143              : 
    1144            0 :          tau = bs_env%imag_time_points(i_t)
    1145            0 :          CALL dbcsr_set(matrix_chi_grid, 0.0_dp)
    1146              : 
    1147              :          ! ----------------------------------------------------------------------
    1148              :          ! A. SPIN LOOP (Allocations safely encapsulated in wrappers)
    1149              :          ! ----------------------------------------------------------------------
    1150            0 :          DO ispin = 1, bs_env%n_spin
    1151              : 
    1152              :             ! G^occ_µλ(i|τ|,k=0) = sum_n^occ C_µn(k=0) e^(-|(ϵ_nk=0-ϵ_F)τ|) C_λn(k=0)
    1153              :             ! G^occ_ll'(i|τ|,k=0) = sum_µν Φ_µ(r_l) G^occ_µν Φ_ν(r_l')
    1154              :             CALL build_G_grid(bs_env, tau, ispin, .TRUE., .FALSE., mat_phi_mu_l, &
    1155            0 :                               matrix_G_occ_grid, bs_env%eps_filter)
    1156              : 
    1157              :             ! G^vir_µλ(i|τ|,k=0) = sum_n^vir C_µn(k=0) e^(-|(ϵ_nk=0-ϵ_F)τ|) C_λn(k=0)
    1158              :             ! G^vir_ll'(i|τ|,k=0) = sum_µν Φ_µ(r_l) G^vir_µν Φ_ν(r_l')
    1159              :             CALL build_G_grid(bs_env, tau, ispin, .FALSE., .TRUE., mat_phi_mu_l, &
    1160            0 :                               matrix_G_vir_grid, bs_env%eps_filter)
    1161              : 
    1162              :             ! -------------------------------------------------------------------
    1163              :             ! B. ELEMENT-WISE HADAMARD PRODUCT
    1164              :             ! -------------------------------------------------------------------
    1165              :             ! χ_ll'(iτ,k=0) = G^occ_ll'(i|τ|,k=0) * G^vir_ll'(i|τ|,k=0)
    1166            0 :             CALL hadamard_product(matrix_G_occ_grid, matrix_G_vir_grid, matrix_chi_grid_spin, bs_env%spin_degeneracy)
    1167              : 
    1168              :             ! Accumulate spin contributions
    1169            0 :             CALL dbcsr_add(matrix_chi_grid, matrix_chi_grid_spin, 1.0_dp, 1.0_dp)
    1170              : 
    1171              :          END DO ! ispin
    1172              : 
    1173              :          ! ----------------------------------------------------------------------
    1174              :          ! C. TRANSFORM TO AUXILIARY BASIS & EXPORT DIRECTLY
    1175              :          ! χ_aux        = Z^T * χ_grid * Z
    1176              :          ! χ_PQ(iτ,k=0) = sum_ll' Z_lP χ_ll'(iτ,k=0) Z_l'Q
    1177              :          ! Result is dumped directly into the final array mat_chi_Gamma_tau!
    1178              :          ! ----------------------------------------------------------------------
    1179              :          CALL contract_A_B_A("T", "N", mat_Z_lP, matrix_chi_grid, &
    1180            0 :                              mat_chi_Gamma_tau(i_t)%matrix, bs_env%eps_filter)
    1181              : 
    1182            0 :          IF (bs_env%unit_nr > 0) THEN
    1183              :             WRITE (bs_env%unit_nr, '(T2,A,I13,A,I3,A,F7.1,A)') &
    1184            0 :                'Computed χ(iτ,k=0) for time point', i_t, ' /', bs_env%num_time_freq_points, &
    1185            0 :                ',    Execution time', m_walltime() - t1, ' s'
    1186              :          END IF
    1187              : 
    1188              :       END DO ! i_t
    1189              : 
    1190              :       ! =========================================================================
    1191              :       ! 3. FINAL CLEANUP
    1192              :       ! =========================================================================
    1193            0 :       CALL dbcsr_release(matrix_G_occ_grid)
    1194            0 :       CALL dbcsr_release(matrix_G_vir_grid)
    1195            0 :       CALL dbcsr_release(matrix_chi_grid)
    1196            0 :       CALL dbcsr_release(matrix_chi_grid_spin)
    1197            0 :       CALL dbcsr_distribution_release(dist_grid_grid)
    1198            0 :       DEALLOCATE (dist_col_grid)
    1199              : 
    1200            0 :       IF (bs_env%unit_nr > 0) WRITE (bs_env%unit_nr, '(A)') ' '
    1201              : 
    1202            0 :       CALL timestop(handle)
    1203              : 
    1204            0 :    END SUBROUTINE get_mat_chi_Gamma_tau
    1205              : 
    1206              : ! **************************************************************************************************
    1207              : !> \brief Computes Green's Function in grid basis
    1208              : !> \param bs_env ...
    1209              : !> \param tau ...
    1210              : !> \param ispin ...
    1211              : !> \param occ ...
    1212              : !> \param vir ...
    1213              : !> \param mat_phi_mu_l ...
    1214              : !> \param matrix_G_grid ...
    1215              : !> \param eps_filter ...
    1216              : ! **************************************************************************************************
    1217              : 
    1218            0 :    SUBROUTINE build_G_grid(bs_env, tau, ispin, occ, vir, mat_phi_mu_l, matrix_G_grid, eps_filter)
    1219              : 
    1220              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1221              :       REAL(KIND=dp), INTENT(IN)                          :: tau
    1222              :       INTEGER, INTENT(IN)                                :: ispin
    1223              :       LOGICAL, INTENT(IN)                                :: occ, vir
    1224              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: mat_phi_mu_l, matrix_G_grid
    1225              :       REAL(KIND=dp), INTENT(IN)                          :: eps_filter
    1226              : 
    1227              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'build_G_grid'
    1228              : 
    1229              :       INTEGER                                            :: handle
    1230            0 :       INTEGER, DIMENSION(:), POINTER                     :: blk_ao, dist_row_ao
    1231              :       TYPE(cp_fm_type), POINTER                          :: fm_G
    1232              :       TYPE(dbcsr_distribution_type)                      :: dist_ao_ao
    1233              :       TYPE(dbcsr_type)                                   :: matrix_G_ao
    1234              : 
    1235            0 :       CALL timeset(routineN, handle)
    1236              : 
    1237              :       ! 1. Select the correct FM matrix based on occ/vir flags
    1238            0 :       IF (occ) THEN
    1239            0 :          fm_G => bs_env%fm_Gocc
    1240              :       ELSE
    1241            0 :          fm_G => bs_env%fm_Gvir
    1242              :       END IF
    1243              : 
    1244              :       ! 2. Compute Dense FM Green's Function
    1245              :       ! G^occ/vir_µλ(i|τ|,k=0) = sum_G^occ/vir_µλn^occ/vir C_µn(k=0) e^(-|(ϵ_nk=0-ϵ_F)τ|) C_λn(k=0)
    1246            0 :       CALL G_occ_vir(bs_env, tau, fm_G, ispin, occ=occ, vir=vir)
    1247              : 
    1248              :       ! 3. Setup AO DBCSR Topology and Create Matrix dynamically
    1249            0 :       CALL setup_square_topology(mat_phi_mu_l, 'COL', dist_ao_ao, blk_ao, dist_row_ao)
    1250              : 
    1251              :       CALL dbcsr_create(matrix_G_ao, name="G_ao", dist=dist_ao_ao, &
    1252              :                         matrix_type=dbcsr_type_no_symmetry, &
    1253            0 :                         row_blk_size=blk_ao, col_blk_size=blk_ao)
    1254              : 
    1255              :       ! 4. Convert FM to Sparse DBCSR
    1256            0 :       CALL copy_fm_to_dbcsr(fm_G, matrix_G_ao, keep_sparsity=.FALSE.)
    1257              : 
    1258              :       ! 5. Transform to Grid Basis: G_grid = phi * G_ao * phi^T
    1259              :       ! G^occ/vir_ll'(i|τ|,k=0) = sum_µν Φ_µ(r_l) G^occ/vir_µν Φ_ν(r_l')
    1260            0 :       CALL contract_A_B_A("N", "T", mat_phi_mu_l, matrix_G_ao, matrix_G_grid, eps_filter)
    1261              : 
    1262              :       ! 6. Release AO matrix and topology
    1263            0 :       CALL release_dbcsr_topology_and_matrices(dist=dist_ao_ao, mapped_dist=dist_row_ao, m1=matrix_G_ao)
    1264              : 
    1265            0 :       CALL timestop(handle)
    1266              : 
    1267            0 :    END SUBROUTINE build_G_grid
    1268              : 
    1269              : ! **************************************************************************************************
    1270              : !> \brief Generalized routine to compute OUT = A * B * A^T  OR  OUT = A^T * B * A using DBCSR
    1271              : !> \param transA_left ...
    1272              : !> \param transA_right ...
    1273              : !> \param matrix_A ...
    1274              : !> \param matrix_B ...
    1275              : !> \param matrix_out ...
    1276              : !> \param eps_filter ...
    1277              : ! **************************************************************************************************
    1278              : 
    1279            0 :    SUBROUTINE contract_A_B_A(transA_left, transA_right, matrix_A, matrix_B, matrix_out, eps_filter)
    1280              : 
    1281              :       CHARACTER(LEN=1), INTENT(IN)                       :: transA_left, transA_right
    1282              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: matrix_A, matrix_B, matrix_out
    1283              :       REAL(KIND=dp), INTENT(IN)                          :: eps_filter
    1284              : 
    1285              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'contract_A_B_A'
    1286              : 
    1287              :       INTEGER                                            :: handle
    1288              :       TYPE(dbcsr_type)                                   :: matrix_tmp
    1289              : 
    1290            0 :       CALL timeset(routineN, handle)
    1291              : 
    1292            0 :       CALL dbcsr_create(matrix_tmp, template=matrix_A)
    1293              : 
    1294            0 :       IF (transA_left == "N" .AND. transA_right == "T") THEN
    1295              :          ! Path 1: Out = A * B * A^T
    1296              :          CALL dbcsr_multiply("N", "N", 1.0_dp, matrix_A, matrix_B, &
    1297            0 :                              0.0_dp, matrix_tmp, filter_eps=eps_filter)
    1298              :          CALL dbcsr_multiply("N", "T", 1.0_dp, matrix_tmp, matrix_A, &
    1299            0 :                              0.0_dp, matrix_out, filter_eps=eps_filter)
    1300              : 
    1301            0 :       ELSE IF (transA_left == "T" .AND. transA_right == "N") THEN
    1302              :          ! Path 2: Out = A^T * B * A
    1303              :          CALL dbcsr_multiply("N", "N", 1.0_dp, matrix_B, matrix_A, &
    1304            0 :                              0.0_dp, matrix_tmp, filter_eps=eps_filter)
    1305              :          CALL dbcsr_multiply("T", "N", 1.0_dp, matrix_A, matrix_tmp, &
    1306            0 :                              0.0_dp, matrix_out, filter_eps=eps_filter)
    1307              :       ELSE
    1308            0 :          CPABORT("Unsupported transposition pair in contract_A_B_A")
    1309              :       END IF
    1310              : 
    1311            0 :       CALL dbcsr_release(matrix_tmp)
    1312              : 
    1313            0 :       CALL timestop(handle)
    1314              : 
    1315            0 :    END SUBROUTINE contract_A_B_A
    1316              : 
    1317              : ! **************************************************************************************************
    1318              : !> \brief Computes C = A ◦ B (Element-wise Hadamard product) for sparse DBCSR matrices.
    1319              : !> \param matrix_A ...
    1320              : !> \param matrix_B ...
    1321              : !> \param matrix_C ...
    1322              : !> \param fac (Scaling factor applied to the product)
    1323              : ! **************************************************************************************************
    1324              : 
    1325            0 :    SUBROUTINE hadamard_product(matrix_A, matrix_B, matrix_C, fac)
    1326              : 
    1327              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: matrix_A, matrix_B, matrix_C
    1328              :       REAL(KIND=dp), INTENT(IN)                          :: fac
    1329              : 
    1330              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'hadamard_product'
    1331              : 
    1332              :       INTEGER                                            :: col, handle, row
    1333              :       LOGICAL                                            :: found
    1334            0 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: blk_B, blk_C
    1335              :       TYPE(dbcsr_iterator_type)                          :: iter
    1336              : 
    1337            0 :       CALL timeset(routineN, handle)
    1338              : 
    1339            0 :       CALL dbcsr_copy(matrix_C, matrix_A)
    1340              : 
    1341            0 :       CALL dbcsr_iterator_start(iter, matrix_C)
    1342            0 :       DO WHILE (dbcsr_iterator_blocks_left(iter))
    1343            0 :          CALL dbcsr_iterator_next_block(iter, row, col, blk_C)
    1344              : 
    1345            0 :          CALL dbcsr_get_block_p(matrix_B, row, col, blk_B, found)
    1346              : 
    1347            0 :          IF (found) THEN
    1348            0 :             blk_C(:, :) = fac*blk_C(:, :)*blk_B(:, :)
    1349              :          ELSE
    1350              :             ! If B is sparse here, the product is zero
    1351            0 :             blk_C(:, :) = 0.0_dp
    1352              :          END IF
    1353              :       END DO
    1354            0 :       CALL dbcsr_iterator_stop(iter)
    1355              : 
    1356            0 :       CALL timestop(handle)
    1357              : 
    1358            0 :    END SUBROUTINE hadamard_product
    1359              : 
    1360              : ! **************************************************************************************************
    1361              : !> \brief Compute screened Coulomb interaction matrix
    1362              : !> \param bs_env ...
    1363              : !> \param qs_env ...
    1364              : !> \param mat_chi_Gamma_tau ...
    1365              : !> \param fm_W_time ...
    1366              : ! **************************************************************************************************
    1367              : 
    1368            0 :    SUBROUTINE compute_W(bs_env, qs_env, mat_chi_Gamma_tau, fm_W_time)
    1369              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1370              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1371              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mat_chi_Gamma_tau
    1372              :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: fm_W_time
    1373              : 
    1374              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_W'
    1375              : 
    1376              :       INTEGER                                            :: handle, i_t, j_w
    1377              :       REAL(KIND=dp)                                      :: t1
    1378              :       TYPE(cp_fm_type)                                   :: fm_M_inv_V_sqrt, fm_V, fm_V_sqrt
    1379              : 
    1380            0 :       CALL timeset(routineN, handle)
    1381              : 
    1382            0 :       t1 = m_walltime()
    1383              : 
    1384            0 :       CALL create_fm_W_MIC_time(bs_env, fm_W_time)
    1385              : 
    1386              :       ! 1. Allocate V and M matrices
    1387            0 :       CALL cp_fm_create(fm_V, bs_env%fm_RI_RI%matrix_struct)
    1388            0 :       CALL cp_fm_create(fm_V_sqrt, bs_env%fm_RI_RI%matrix_struct)
    1389            0 :       CALL cp_fm_create(fm_M_inv_V_sqrt, bs_env%fm_RI_RI%matrix_struct)
    1390              : 
    1391              :       ! Compute V and M^-1 * V^0.5
    1392            0 :       CALL compute_V_MinvVsqrt(bs_env, qs_env, fm_V, fm_V_sqrt, fm_M_inv_V_sqrt)
    1393              : 
    1394              :       ! 2. Loop over frequencies
    1395            0 :       DO j_w = 1, bs_env%num_time_freq_points
    1396              :          ! Fourier transformation of χ_PQ(iτ) to χ_PQ(iω_j)
    1397            0 :          CALL compute_fm_chi_Gamma_freq(bs_env, bs_env%fm_chi_Gamma_freq, j_w, mat_chi_Gamma_tau)
    1398              : 
    1399              :          ! ε(iω_j) = Id - V^0.5*M^-1*χ(iω_j)*M^-1*V^0.5
    1400              :          ! W(iω_j) = V^0.5*(ε^-1(iω_j)-Id)*V^0.5
    1401              :          CALL compute_fm_W_freq(bs_env, bs_env%fm_chi_Gamma_freq, fm_V_sqrt, &
    1402            0 :                                 fm_M_inv_V_sqrt, bs_env%fm_W_MIC_freq)
    1403              : 
    1404              :          ! Fourier transform from W_PQ^MIC(iω_j) to W_PQ^MIC(iτ)
    1405            0 :          CALL Fourier_transform_w_to_t(bs_env, fm_W_time, bs_env%fm_W_MIC_freq, j_w)
    1406              :       END DO
    1407              : 
    1408              :       ! M^-1*W^MIC(iτ)*M^-1
    1409            0 :       CALL multiply_fm_W_MIC_time_with_Minv_Gamma(bs_env, qs_env, fm_W_time)
    1410              : 
    1411            0 :       IF (bs_env%unit_nr > 0) THEN
    1412              :          WRITE (bs_env%unit_nr, '(T2,A,T55,A,F10.1,A)') &
    1413            0 :             'Computed W(iτ),', ' Execution time', m_walltime() - t1, ' s'
    1414              :       END IF
    1415              : 
    1416            0 :       CALL dbcsr_deallocate_matrix_set(mat_chi_Gamma_tau)
    1417              : 
    1418              :       ! Cleanup
    1419            0 :       CALL cp_fm_release(fm_V)
    1420            0 :       CALL cp_fm_release(fm_V_sqrt)
    1421            0 :       CALL cp_fm_release(fm_M_inv_V_sqrt)
    1422              : 
    1423              :       ! Marek : Fourier transform W^MIC(itau) back to get it at a specific im.frequency point - iomega = 0
    1424            0 :       IF (bs_env%rtp_method == rtp_method_bse) THEN
    1425            0 :          t1 = m_walltime()
    1426            0 :          CALL cp_fm_create(bs_env%fm_W_MIC_freq_zero, bs_env%fm_W_MIC_freq%matrix_struct)
    1427              :          ! Set to zero
    1428            0 :          CALL cp_fm_set_all(bs_env%fm_W_MIC_freq_zero, 0.0_dp)
    1429              :          ! Sum over all times
    1430            0 :          DO i_t = 1, bs_env%num_time_freq_points
    1431              :             ! Add the relevant structure with correct weight
    1432              :             CALL cp_fm_scale_and_add(1.0_dp, bs_env%fm_W_MIC_freq_zero, &
    1433            0 :                                      bs_env%imag_time_weights_freq_zero(i_t), fm_W_time(i_t))
    1434              :          END DO
    1435              :          ! Done, save to file
    1436            0 :          CALL fm_write(bs_env%fm_W_MIC_freq_zero, 0, "W_freq_rtp", qs_env)
    1437              :          ! Report calculation
    1438            0 :          IF (bs_env%unit_nr > 0) THEN
    1439              :             WRITE (bs_env%unit_nr, '(T2,A,T55,A,F10.1,A)') &
    1440            0 :                'Computed W(0),', ' Execution time', m_walltime() - t1, ' s'
    1441              :          END IF
    1442              :       END IF
    1443              : 
    1444            0 :       IF (bs_env%unit_nr > 0) WRITE (bs_env%unit_nr, '(A)') ' '
    1445              : 
    1446            0 :       CALL timestop(handle)
    1447              : 
    1448            0 :    END SUBROUTINE compute_W
    1449              : 
    1450              : ! **************************************************************************************************
    1451              : !> \brief Computes V, V^0.5, and M^-1 * V^0.5
    1452              : !> \param bs_env ...
    1453              : !> \param qs_env ...
    1454              : !> \param fm_V ...
    1455              : !> \param fm_V_sqrt ...
    1456              : !> \param fm_Minv_Vsqrt ...
    1457              : ! **************************************************************************************************
    1458              : 
    1459            0 :    SUBROUTINE compute_V_MinvVsqrt(bs_env, qs_env, fm_V, fm_V_sqrt, fm_Minv_Vsqrt)
    1460              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1461              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1462              :       TYPE(cp_fm_type), INTENT(INOUT)                    :: fm_V, fm_V_sqrt, fm_Minv_Vsqrt
    1463              : 
    1464              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_V_MinvVsqrt'
    1465              : 
    1466              :       INTEGER                                            :: handle, info, n_RI, ndep
    1467            0 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1468              :       TYPE(cell_type), POINTER                           :: cell
    1469              :       TYPE(cp_fm_type)                                   :: fm_work
    1470            0 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :)     :: fm_M
    1471            0 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: mat_V_kp
    1472            0 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1473            0 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1474              : 
    1475            0 :       CALL timeset(routineN, handle)
    1476              : 
    1477            0 :       n_RI = bs_env%n_RI
    1478            0 :       CALL cp_fm_create(fm_work, fm_V%matrix_struct)
    1479              : 
    1480              :       ! -----------------------------------------------------------------------
    1481              :       ! 1. Build Coulomb Matrix V(k=0) using the kp-routine but only for ikp=1
    1482              :       ! -----------------------------------------------------------------------
    1483              :       CALL get_qs_env(qs_env=qs_env, particle_set=particle_set, cell=cell, &
    1484            0 :                       qs_kind_set=qs_kind_set, atomic_kind_set=atomic_kind_set)
    1485              : 
    1486            0 :       ALLOCATE (mat_V_kp(1:1, 1:2))
    1487            0 :       NULLIFY (mat_V_kp(1, 1)%matrix, mat_V_kp(1, 2)%matrix)
    1488            0 :       ALLOCATE (mat_V_kp(1, 1)%matrix, mat_V_kp(1, 2)%matrix)
    1489              : 
    1490            0 :       CALL dbcsr_create(mat_V_kp(1, 1)%matrix, template=bs_env%mat_RI_RI%matrix)
    1491            0 :       CALL dbcsr_reserve_all_blocks(mat_V_kp(1, 1)%matrix)
    1492            0 :       CALL dbcsr_set(mat_V_kp(1, 1)%matrix, 0.0_dp)
    1493              : 
    1494              :       ! Dummy imaginary part just to satisfy the routine
    1495            0 :       CALL dbcsr_create(mat_V_kp(1, 2)%matrix, template=bs_env%mat_RI_RI%matrix)
    1496            0 :       CALL dbcsr_reserve_all_blocks(mat_V_kp(1, 2)%matrix)
    1497            0 :       CALL dbcsr_set(mat_V_kp(1, 2)%matrix, 0.0_dp)
    1498              : 
    1499            0 :       bs_env%kpoints_chi_eps_W%nkp_grid = bs_env%nkp_grid_chi_eps_W_orig
    1500              : 
    1501              :       CALL build_2c_coulomb_matrix_kp(mat_V_kp, bs_env%kpoints_chi_eps_W, "RI_AUX", cell, &
    1502              :                                       particle_set, qs_kind_set, atomic_kind_set, &
    1503            0 :                                       bs_env%size_lattice_sum_V, operator_coulomb, 1, 1)
    1504              : 
    1505              :       ! Copy real part to fm_V
    1506            0 :       CALL copy_dbcsr_to_fm(mat_V_kp(1, 1)%matrix, fm_V)
    1507              : 
    1508            0 :       CALL dbcsr_deallocate_matrix(mat_V_kp(1, 1)%matrix)
    1509            0 :       CALL dbcsr_deallocate_matrix(mat_V_kp(1, 2)%matrix)
    1510            0 :       DEALLOCATE (mat_V_kp)
    1511              : 
    1512              :       ! -----------------------------------------------------------------------
    1513              :       ! 2. Get RI-Metric Matrix M(k=0)
    1514              :       ! -----------------------------------------------------------------------
    1515              :       CALL RI_2c_integral_mat(qs_env, fm_M, fm_V, n_RI, bs_env%ri_metric, &
    1516            0 :                               do_kpoints=.FALSE., regularization_RI=bs_env%regularization_RI)
    1517              : 
    1518              :       ! -----------------------------------------------------------------------
    1519              :       ! 3. M -> M^-1
    1520              :       ! -----------------------------------------------------------------------
    1521            0 :       CALL cp_fm_cholesky_decompose(fm_M(1, 1), info_out=info)
    1522            0 :       IF (info == 0) THEN
    1523            0 :          CALL cp_fm_cholesky_invert(fm_M(1, 1))
    1524            0 :          CALL cp_fm_uplo_to_full(fm_M(1, 1), fm_work)
    1525              :       ELSE
    1526              :          ! Fallback if Cholesky fails due to conditioning
    1527            0 :          CALL cp_fm_power(fm_M(1, 1), fm_work, -1.0_dp, bs_env%eps_eigval_mat_RI, ndep)
    1528            0 :          CALL cp_fm_to_fm(fm_work, fm_M(1, 1))
    1529              :       END IF
    1530              : 
    1531              :       ! -----------------------------------------------------------------------
    1532              :       ! 4. V -> V^0.5
    1533              :       ! -----------------------------------------------------------------------
    1534            0 :       CALL cp_fm_to_fm(fm_V, fm_V_sqrt)
    1535            0 :       CALL cp_fm_cholesky_decompose(fm_V_sqrt, info_out=info)
    1536            0 :       IF (info == 0) THEN
    1537            0 :          CALL clean_lower_part(fm_V_sqrt)
    1538              :       ELSE
    1539            0 :          CALL cp_fm_power(fm_V, fm_V_sqrt, 0.5_dp, bs_env%eps_eigval_mat_RI, ndep)
    1540              :       END IF
    1541              : 
    1542              :       ! -----------------------------------------------------------------------
    1543              :       ! 5. M^-1 * V^0.5
    1544              :       ! -----------------------------------------------------------------------
    1545              :       CALL parallel_gemm("N", "T", n_RI, n_RI, n_RI, 1.0_dp, fm_M(1, 1), fm_V_sqrt, &
    1546            0 :                          0.0_dp, fm_Minv_Vsqrt)
    1547              : 
    1548            0 :       CALL cp_fm_release(fm_M)
    1549            0 :       CALL cp_fm_release(fm_work)
    1550              : 
    1551            0 :       CALL timestop(handle)
    1552              : 
    1553            0 :    END SUBROUTINE compute_V_MinvVsqrt
    1554              : 
    1555              : ! **************************************************************************************************
    1556              : !> \brief Computes W(iω) from χ_PQ(iω_j)
    1557              : !> \param bs_env ...
    1558              : !> \param fm_chi_freq_j ...
    1559              : !> \param fm_V_sqrt ...
    1560              : !> \param fm_Minv_Vsqrt ...
    1561              : !> \param fm_W_freq_j ...
    1562              : ! **************************************************************************************************
    1563              : 
    1564            0 :    SUBROUTINE compute_fm_W_freq(bs_env, fm_chi_freq_j, fm_V_sqrt, fm_Minv_Vsqrt, fm_W_freq_j)
    1565              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1566              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_chi_freq_j, fm_V_sqrt, fm_Minv_Vsqrt
    1567              :       TYPE(cp_fm_type), INTENT(INOUT)                    :: fm_W_freq_j
    1568              : 
    1569              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_fm_W_freq'
    1570              : 
    1571              :       INTEGER                                            :: handle, info, n_RI, ndep
    1572              :       TYPE(cp_fm_type)                                   :: fm_eps_freq_j, fm_work
    1573              : 
    1574            0 :       CALL timeset(routineN, handle)
    1575              : 
    1576            0 :       n_RI = bs_env%n_RI
    1577              : 
    1578            0 :       CALL cp_fm_create(fm_eps_freq_j, fm_chi_freq_j%matrix_struct)
    1579            0 :       CALL cp_fm_create(fm_work, fm_chi_freq_j%matrix_struct)
    1580              : 
    1581              :       ! -----------------------------------------------------------------------
    1582              :       ! 1. ε(iω_j) = Id - (M^-1 * V^0.5)^T * χ(iω_j) * (M^-1 * V^0.5)
    1583              :       ! -----------------------------------------------------------------------
    1584              :       ! work = χ(iω_j) * (M^-1 * V^0.5)
    1585              :       CALL parallel_gemm('N', 'N', n_RI, n_RI, n_RI, 1.0_dp, &
    1586            0 :                          fm_chi_freq_j, fm_Minv_Vsqrt, 0.0_dp, fm_work)
    1587              : 
    1588              :       ! eps_work = (M^-1 * V^0.5)^T * work
    1589              :       CALL parallel_gemm('T', 'N', n_RI, n_RI, n_RI, 1.0_dp, &
    1590            0 :                          fm_Minv_Vsqrt, fm_work, 0.0_dp, fm_eps_freq_j)
    1591              : 
    1592              :       ! ε(iω_j) = Id - eps_work  -->  -eps_work + Id
    1593            0 :       CALL fm_add_on_diag(fm_eps_freq_j, 1.0_dp)
    1594              : 
    1595              :       ! Force perfect symmetry before Cholesky to avoid info != 0 due to GEMM noise
    1596            0 :       CALL cp_fm_uplo_to_full(fm_eps_freq_j, fm_work)
    1597              : 
    1598              :       ! -----------------------------------------------------------------------
    1599              :       ! 2. W(iω_j) = V^0.5^T * (ε^-1(iω_j) - Id) * V^0.5
    1600              :       ! -----------------------------------------------------------------------
    1601              : 
    1602              :       ! a) Cholesky decomposition of ε(iω_j)
    1603            0 :       CALL cp_fm_cholesky_decompose(fm_eps_freq_j, info_out=info)
    1604              : 
    1605              :       ! b) Inversion
    1606            0 :       IF (info == 0) THEN
    1607            0 :          CALL cp_fm_cholesky_invert(fm_eps_freq_j)
    1608            0 :          CALL cp_fm_uplo_to_full(fm_eps_freq_j, fm_work)
    1609              :       ELSE
    1610              :          ! Fallback to expensive diagonalization if Cholesky fails
    1611            0 :          CALL cp_fm_power(fm_eps_freq_j, fm_work, -1.0_dp, bs_env%eps_eigval_mat_RI, ndep)
    1612            0 :          CALL cp_fm_to_fm(fm_work, fm_eps_freq_j)
    1613              :       END IF
    1614              : 
    1615              :       ! c) ε^-1(iω_j) - Id
    1616            0 :       CALL fm_add_on_diag(fm_eps_freq_j, -1.0_dp)
    1617              : 
    1618              :       ! d) work = (ε^-1(iω_j) - Id) * V^0.5
    1619              :       CALL parallel_gemm('N', 'N', n_RI, n_RI, n_RI, 1.0_dp, fm_eps_freq_j, fm_V_sqrt, &
    1620            0 :                          0.0_dp, fm_work)
    1621              : 
    1622              :       ! e) W(iw) = V^0.5^T * work
    1623              :       CALL parallel_gemm('T', 'N', n_RI, n_RI, n_RI, 1.0_dp, fm_V_sqrt, fm_work, &
    1624            0 :                          0.0_dp, fm_W_freq_j)
    1625              : 
    1626              :       ! Cleanup
    1627            0 :       CALL cp_fm_release(fm_work)
    1628            0 :       CALL cp_fm_release(fm_eps_freq_j)
    1629              : 
    1630            0 :       CALL timestop(handle)
    1631              : 
    1632            0 :    END SUBROUTINE compute_fm_W_freq
    1633              : 
    1634              : ! **************************************************************************************************
    1635              : !> \brief Adds a real scalar value to the diagonal of a real full matrix (fm)
    1636              : !> \param fm ...
    1637              : !> \param alpha ...
    1638              : ! **************************************************************************************************
    1639              : 
    1640            0 :    SUBROUTINE fm_add_on_diag(fm, alpha)
    1641              :       TYPE(cp_fm_type), INTENT(INOUT)                    :: fm
    1642              :       REAL(KIND=dp), INTENT(IN)                          :: alpha
    1643              : 
    1644              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'fm_add_on_diag'
    1645              : 
    1646              :       INTEGER                                            :: handle, i_global, i_row, j_col, &
    1647              :                                                             j_global, ncol_local, nrow_local
    1648            0 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1649              : 
    1650            0 :       CALL timeset(routineN, handle)
    1651              : 
    1652              :       CALL cp_fm_get_info(matrix=fm, &
    1653              :                           nrow_local=nrow_local, &
    1654              :                           ncol_local=ncol_local, &
    1655              :                           row_indices=row_indices, &
    1656            0 :                           col_indices=col_indices)
    1657              : 
    1658            0 :       DO j_col = 1, ncol_local
    1659            0 :          j_global = col_indices(j_col)
    1660            0 :          DO i_row = 1, nrow_local
    1661            0 :             i_global = row_indices(i_row)
    1662            0 :             IF (j_global == i_global) THEN
    1663            0 :                fm%local_data(i_row, j_col) = fm%local_data(i_row, j_col) + alpha
    1664              :             END IF
    1665              :          END DO
    1666              :       END DO
    1667              : 
    1668            0 :       CALL timestop(handle)
    1669              : 
    1670            0 :    END SUBROUTINE fm_add_on_diag
    1671              : 
    1672              : ! **************************************************************************************************
    1673              : !> \brief Zeroes out the strictly lower triangular part of a real matrix
    1674              : !> \param fm_mat ...
    1675              : ! **************************************************************************************************
    1676            0 :    SUBROUTINE clean_lower_part(fm_mat)
    1677              :       TYPE(cp_fm_type)                                   :: fm_mat
    1678              : 
    1679              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'clean_lower_part'
    1680              : 
    1681              :       INTEGER                                            :: handle, i_row, j_col, j_global, &
    1682              :                                                             ncol_local, nrow_local
    1683            0 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1684              : 
    1685            0 :       CALL timeset(routineN, handle)
    1686              : 
    1687              :       CALL cp_fm_get_info(matrix=fm_mat, &
    1688              :                           nrow_local=nrow_local, ncol_local=ncol_local, &
    1689            0 :                           row_indices=row_indices, col_indices=col_indices)
    1690              : 
    1691            0 :       DO j_col = 1, ncol_local
    1692            0 :          j_global = col_indices(j_col)
    1693            0 :          DO i_row = 1, nrow_local
    1694            0 :             IF (j_global < row_indices(i_row)) fm_mat%local_data(i_row, j_col) = 0.0_dp
    1695              :          END DO
    1696              :       END DO
    1697              : 
    1698            0 :       CALL timestop(handle)
    1699              : 
    1700            0 :    END SUBROUTINE clean_lower_part
    1701              : 
    1702              : ! **************************************************************************************************
    1703              : !> \brief Computes the exact exchange part of the GW self-energy
    1704              : !> \param bs_env ...
    1705              : !> \param qs_env ...
    1706              : !> \param mat_phi_mu_l ...
    1707              : !> \param mat_Z_lP ...
    1708              : !> \param fm_Sigma_x_Gamma ...
    1709              : ! **************************************************************************************************
    1710              : 
    1711            0 :    SUBROUTINE compute_Sigma_x(bs_env, qs_env, mat_phi_mu_l, mat_Z_lP, fm_Sigma_x_Gamma)
    1712              : 
    1713              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1714              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1715              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: mat_phi_mu_l, mat_Z_lP
    1716              :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: fm_Sigma_x_Gamma
    1717              : 
    1718              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_Sigma_x'
    1719              : 
    1720              :       INTEGER                                            :: handle, ispin
    1721            0 :       INTEGER, DIMENSION(:), POINTER                     :: blk_aux, blk_grid, dist_col_grid, &
    1722            0 :                                                             dist_row_aux
    1723              :       REAL(KIND=dp)                                      :: t1
    1724            0 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :)     :: fm_Vtr_Gamma
    1725              :       TYPE(dbcsr_distribution_type)                      :: dist_aux_aux, dist_grid_grid
    1726              :       TYPE(dbcsr_type)                                   :: mat_Sigma_x_Gamma, matrix_D_grid, &
    1727              :                                                             matrix_Sigma_x_grid, matrix_V_aux, &
    1728              :                                                             matrix_V_grid
    1729              : 
    1730            0 :       CALL timeset(routineN, handle)
    1731              : 
    1732            0 :       t1 = m_walltime()
    1733              : 
    1734            0 :       ALLOCATE (fm_Sigma_x_Gamma(bs_env%n_spin))
    1735            0 :       DO ispin = 1, bs_env%n_spin
    1736            0 :          CALL cp_fm_create(fm_Sigma_x_Gamma(ispin), bs_env%fm_s_Gamma%matrix_struct)
    1737              :       END DO
    1738              : 
    1739            0 :       CALL dbcsr_create(mat_Sigma_x_Gamma, template=bs_env%mat_ao_ao%matrix)
    1740              : 
    1741              :       ! =========================================================================
    1742              :       ! 1. SETUP CORE TOPOLOGIES
    1743              :       ! =========================================================================
    1744            0 :       CALL setup_square_topology(mat_phi_mu_l, 'ROW', dist_grid_grid, blk_grid, dist_col_grid)
    1745            0 :       CALL setup_square_topology(mat_Z_lP, 'COL', dist_aux_aux, blk_aux, dist_row_aux)
    1746              : 
    1747              :       ! =========================================================================
    1748              :       ! 2. COMPUTE V^tr_ll'
    1749              :       ! =========================================================================
    1750              :       CALL RI_2c_integral_mat(qs_env, fm_Vtr_Gamma, bs_env%fm_RI_RI, bs_env%n_RI, &
    1751            0 :                               bs_env%trunc_coulomb, do_kpoints=.FALSE.)
    1752              : 
    1753              :       ! M^-1 * V^tr * M^-1 directly modifies fm_Vtr_Gamma(:, 1)
    1754            0 :       CALL multiply_fm_W_MIC_time_with_Minv_Gamma(bs_env, qs_env, fm_Vtr_Gamma(:, 1))
    1755              : 
    1756            0 :       CALL dbcsr_create(matrix_V_aux, "V_aux", dist_aux_aux, dbcsr_type_no_symmetry, blk_aux, blk_aux)
    1757            0 :       CALL dbcsr_create(matrix_V_grid, "V_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1758              : 
    1759            0 :       CALL copy_fm_to_dbcsr(fm_Vtr_Gamma(1, 1), matrix_V_aux, keep_sparsity=.FALSE.)
    1760              : 
    1761              :       ! V^tr_ll' = sum_PQ Z_lP V^trunc_PQ Z_l'Q
    1762            0 :       CALL contract_A_B_A("N", "T", mat_Z_lP, matrix_V_aux, matrix_V_grid, bs_env%eps_filter)
    1763            0 :       CALL dbcsr_release(matrix_V_aux)
    1764              : 
    1765              :       ! =========================================================================
    1766              :       ! 3. SPIN LOOP FOR EXACT EXCHANGE
    1767              :       ! =========================================================================
    1768            0 :       DO ispin = 1, bs_env%n_spin
    1769              : 
    1770              :          ! Density matrix on grid is essentially G_occ at tau = 0.0
    1771              :          ! D_µν  = sum_n^occ C_µn(k=0) C_νn(k=0)
    1772              :          ! D_ll' = sum_µν Φ_µ(r_l) D_µν Φ_ν(r_l')
    1773            0 :          CALL dbcsr_create(matrix_D_grid, "D_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1774            0 :          CALL build_G_grid(bs_env, 0.0_dp, ispin, .TRUE., .FALSE., mat_phi_mu_l, matrix_D_grid, bs_env%eps_filter)
    1775              : 
    1776              :          ! Element-wise Hadamard product: Σ^x_grid = D_grid ◦ V_grid
    1777              :          ! Σ^x_ll' = D_ll' * V^tr_ll'
    1778            0 :          CALL dbcsr_create(matrix_Sigma_x_grid, template=matrix_V_grid)
    1779            0 :          CALL hadamard_product(matrix_D_grid, matrix_V_grid, matrix_Sigma_x_grid, 1.0_dp)
    1780              : 
    1781            0 :          CALL dbcsr_release(matrix_D_grid)
    1782              : 
    1783              :          ! Transform back to AO basis: Σ^x_ao = -1.0 * phi^T * Σ^x_grid * phi
    1784              :          ! Σ^x_λσ(k=0)   = -sum_ll' Φ_λ(r_l) Σ^x_ll' Φ_σ(r_l')
    1785            0 :          CALL contract_A_B_A("T", "N", mat_phi_mu_l, matrix_Sigma_x_grid, mat_Sigma_x_Gamma, bs_env%eps_filter)
    1786            0 :          CALL dbcsr_scale(mat_Sigma_x_Gamma, -1.0_dp)
    1787              : 
    1788            0 :          CALL dbcsr_release(matrix_Sigma_x_grid)
    1789              : 
    1790              :          ! Data I/O and Export to CP2K Full Matrices
    1791            0 :          CALL copy_dbcsr_to_fm(mat_Sigma_x_Gamma, fm_Sigma_x_Gamma(ispin))
    1792              : 
    1793              :       END DO ! ispin
    1794              : 
    1795            0 :       IF (bs_env%unit_nr > 0) THEN
    1796              :          WRITE (bs_env%unit_nr, '(T2,A,T58,A,F7.1,A)') &
    1797            0 :             'Computed Σ^x(k=0),', ' Execution time', m_walltime() - t1, ' s'
    1798            0 :          WRITE (bs_env%unit_nr, '(A)') ' '
    1799              :       END IF
    1800              : 
    1801              :       ! =========================================================================
    1802              :       ! 4. CLEANUP
    1803              :       ! =========================================================================
    1804              :       CALL release_dbcsr_topology_and_matrices(dist=dist_grid_grid, mapped_dist=dist_col_grid, &
    1805            0 :                                                m1=mat_Sigma_x_Gamma, m2=matrix_V_grid)
    1806            0 :       CALL release_dbcsr_topology_and_matrices(dist=dist_aux_aux, mapped_dist=dist_row_aux)
    1807              : 
    1808            0 :       CALL cp_fm_release(fm_Vtr_Gamma)
    1809              : 
    1810            0 :       CALL timestop(handle)
    1811              : 
    1812            0 :    END SUBROUTINE compute_Sigma_x
    1813              : 
    1814              : ! **************************************************************************************************
    1815              : !> \brief Computes the correlation part of the GW self-energy
    1816              : !> \param bs_env ...
    1817              : !> \param fm_W_time ...
    1818              : !> \param mat_phi_mu_l ...
    1819              : !> \param mat_Z_lP ...
    1820              : !> \param fm_Sigma_c_Gamma_time ...
    1821              : ! **************************************************************************************************
    1822              : 
    1823            0 :    SUBROUTINE compute_Sigma_c(bs_env, fm_W_time, mat_phi_mu_l, mat_Z_lP, fm_Sigma_c_Gamma_time)
    1824              : 
    1825              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1826              :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: fm_W_time
    1827              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: mat_phi_mu_l, mat_Z_lP
    1828              :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :, :)  :: fm_Sigma_c_Gamma_time
    1829              : 
    1830              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_Sigma_c'
    1831              : 
    1832              :       INTEGER                                            :: handle, i_t, ispin
    1833            0 :       INTEGER, DIMENSION(:), POINTER                     :: blk_aux, blk_grid, dist_col_grid, &
    1834            0 :                                                             dist_row_aux
    1835              :       REAL(KIND=dp)                                      :: t1, tau
    1836              :       TYPE(dbcsr_distribution_type)                      :: dist_aux_aux, dist_grid_grid
    1837            0 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: mat_Sigma_neg_tau, mat_Sigma_pos_tau
    1838              :       TYPE(dbcsr_type) :: matrix_G_occ_grid, matrix_G_vir_grid, matrix_Sigma_neg_grid, &
    1839              :          matrix_Sigma_pos_grid, matrix_W_aux, matrix_W_grid
    1840              : 
    1841            0 :       CALL timeset(routineN, handle)
    1842              : 
    1843              :       ! =========================================================================
    1844              :       ! 1. SETUP CORE TOPOLOGIES AND PRE-ALLOCATE OUTPUT ARRAYS
    1845              :       ! =========================================================================
    1846            0 :       CALL setup_square_topology(mat_phi_mu_l, 'ROW', dist_grid_grid, blk_grid, dist_col_grid)
    1847            0 :       CALL setup_square_topology(mat_Z_lP, 'COL', dist_aux_aux, blk_aux, dist_row_aux)
    1848              : 
    1849              :       ! Pre-allocate local DBCSR matrices to act as targets for final output
    1850            0 :       NULLIFY (mat_Sigma_neg_tau, mat_Sigma_pos_tau)
    1851            0 :       ALLOCATE (mat_Sigma_neg_tau(bs_env%num_time_freq_points, bs_env%n_spin))
    1852            0 :       ALLOCATE (mat_Sigma_pos_tau(bs_env%num_time_freq_points, bs_env%n_spin))
    1853              : 
    1854            0 :       DO i_t = 1, bs_env%num_time_freq_points
    1855            0 :          DO ispin = 1, bs_env%n_spin
    1856            0 :             ALLOCATE (mat_Sigma_neg_tau(i_t, ispin)%matrix)
    1857            0 :             ALLOCATE (mat_Sigma_pos_tau(i_t, ispin)%matrix)
    1858            0 :             CALL dbcsr_create(mat_Sigma_neg_tau(i_t, ispin)%matrix, template=bs_env%mat_ao_ao%matrix)
    1859            0 :             CALL dbcsr_create(mat_Sigma_pos_tau(i_t, ispin)%matrix, template=bs_env%mat_ao_ao%matrix)
    1860              :          END DO
    1861              :       END DO
    1862              : 
    1863              :       ! =========================================================================
    1864              :       ! 2. MAIN IMAGINARY TIME LOOP
    1865              :       ! =========================================================================
    1866            0 :       DO i_t = 1, bs_env%num_time_freq_points
    1867            0 :          tau = bs_env%imag_time_points(i_t)
    1868              : 
    1869              :          ! -------------------------------------------------------------------
    1870              :          ! Compute W_grid = Z * W_aux * Z^T
    1871              :          ! -------------------------------------------------------------------
    1872            0 :          CALL dbcsr_create(matrix_W_aux, "W_aux", dist_aux_aux, dbcsr_type_no_symmetry, blk_aux, blk_aux)
    1873            0 :          CALL dbcsr_create(matrix_W_grid, "W_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1874              : 
    1875            0 :          CALL copy_fm_to_dbcsr(fm_W_time(i_t), matrix_W_aux, keep_sparsity=.FALSE.)
    1876              : 
    1877              :          ! W^MIC_ll'(iτ,k=0) = sum_PQ Z_lP W^MIC_PQ(iτ) Z_l'Q
    1878            0 :          CALL contract_A_B_A("N", "T", mat_Z_lP, matrix_W_aux, matrix_W_grid, bs_env%eps_filter)
    1879              : 
    1880            0 :          CALL dbcsr_release(matrix_W_aux) ! Clean up aux basis immediately
    1881              : 
    1882            0 :          DO ispin = 1, bs_env%n_spin
    1883            0 :             t1 = m_walltime()
    1884              : 
    1885              :             ! -------------------------------------------------------------------
    1886              :             ! A. Transform Green's Functions to the Grid
    1887              :             ! -------------------------------------------------------------------
    1888            0 :             CALL dbcsr_create(matrix_G_occ_grid, "G_occ_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1889            0 :             CALL dbcsr_create(matrix_G_vir_grid, "G_vir_grid", dist_grid_grid, dbcsr_type_no_symmetry, blk_grid, blk_grid)
    1890              : 
    1891              :             ! G^occ_µλ(i|τ|,k=0) = sum_G^occ_µλn^occ C_µn(k=0) e^(-|(ϵ_nk=0-ϵ_F)τ|) C_λn(k=0)
    1892              :             ! G^occ_ll'(i|τ|,k=0) = sum_µν Φ_µ(r_l) G^occ_µν Φ_ν(r_l')
    1893            0 :             CALL build_G_grid(bs_env, tau, ispin, .TRUE., .FALSE., mat_phi_mu_l, matrix_G_occ_grid, bs_env%eps_filter)
    1894              : 
    1895              :             ! G^vir_µλ(i|τ|,k=0) = sum_n^vir C_µn(k=0) e^(-|(ϵ_nk=0-ϵ_F)τ|) C_λn(k=0)
    1896              :             ! G^vir_ll'(i|τ|,k=0) = sum_µν Φ_µ(r_l) G^vir_µν Φ_ν(r_l')
    1897            0 :             CALL build_G_grid(bs_env, tau, ispin, .FALSE., .TRUE., mat_phi_mu_l, matrix_G_vir_grid, bs_env%eps_filter)
    1898              : 
    1899              :             ! -------------------------------------------------------------------
    1900              :             ! B. Element-wise Hadamard Products for Sigma_c on Grid
    1901              :             ! Σ_neg_grid = G_occ_grid ◦ W_grid
    1902              :             ! Σ_pos_grid = G_vir_grid ◦ W_grid
    1903              :             ! -------------------------------------------------------------------
    1904            0 :             CALL dbcsr_create(matrix_Sigma_neg_grid, template=matrix_W_grid)
    1905            0 :             CALL dbcsr_create(matrix_Sigma_pos_grid, template=matrix_W_grid)
    1906              : 
    1907              :             ! Σ^c_ll'(iτ,k=0)   = -G^occ_ll'(i|τ|,k=0) * W^MIC_ll'(iτ,k=0), for τ < 0
    1908            0 :             CALL hadamard_product(matrix_G_occ_grid, matrix_W_grid, matrix_Sigma_neg_grid, 1.0_dp)
    1909              : 
    1910              :             ! Σ^c_ll'(iτ,k=0)   =  G^vir_ll'(i|τ|,k=0) * W^MIC_ll'(iτ,k=0), for τ > 0
    1911            0 :             CALL hadamard_product(matrix_G_vir_grid, matrix_W_grid, matrix_Sigma_pos_grid, 1.0_dp)
    1912              : 
    1913              :             ! Instantly purge massive G_grid arrays to save memory
    1914            0 :             CALL dbcsr_release(matrix_G_occ_grid)
    1915            0 :             CALL dbcsr_release(matrix_G_vir_grid)
    1916              : 
    1917              :             ! -------------------------------------------------------------------
    1918              :             ! C. Transform Sigma back to AO Basis
    1919              :             ! Σ_AO = phi^T * Σ_grid * phi
    1920              :             ! -------------------------------------------------------------------
    1921              : 
    1922              :             ! Σ^c_λσ(iτ,k=0)    = sum_ll' Φ_λ(r_l) Σ^c_ll'(iτ,k=0) Φ_σ(r_l'), for τ < 0
    1923              :             CALL contract_A_B_A("T", "N", mat_phi_mu_l, matrix_Sigma_neg_grid, &
    1924            0 :                                 mat_Sigma_neg_tau(i_t, ispin)%matrix, bs_env%eps_filter)
    1925            0 :             CALL dbcsr_scale(mat_Sigma_neg_tau(i_t, ispin)%matrix, -1.0_dp)
    1926              : 
    1927              :             ! Σ^c_λσ(iτ,k=0)    = sum_ll' Φ_λ(r_l) Σ^c_ll'(iτ,k=0) Φ_σ(r_l'), for τ > 0
    1928              :             CALL contract_A_B_A("T", "N", mat_phi_mu_l, matrix_Sigma_pos_grid, &
    1929            0 :                                 mat_Sigma_pos_tau(i_t, ispin)%matrix, bs_env%eps_filter)
    1930              : 
    1931              :             ! Purge Grid Sigma arrays
    1932            0 :             CALL dbcsr_release(matrix_Sigma_neg_grid)
    1933            0 :             CALL dbcsr_release(matrix_Sigma_pos_grid)
    1934              : 
    1935            0 :             IF (bs_env%unit_nr > 0) THEN
    1936              :                WRITE (bs_env%unit_nr, '(T2,A,I10,A,I3,A,F7.1,A)') &
    1937            0 :                   'Computed Σ^c(iτ,k=0) for time point ', i_t, ' /', bs_env%num_time_freq_points, &
    1938            0 :                   ',    Execution time', m_walltime() - t1, ' s'
    1939              :             END IF
    1940              : 
    1941              :          END DO ! ispin
    1942              : 
    1943              :          ! Release the W_grid for this time point
    1944            0 :          CALL dbcsr_release(matrix_W_grid)
    1945              : 
    1946              :       END DO ! i_t
    1947              : 
    1948            0 :       IF (bs_env%unit_nr > 0) WRITE (bs_env%unit_nr, '(A)') ' '
    1949              : 
    1950              :       ! -------------------------------------------------------------------------
    1951              :       ! 3. FINALIZE AND CLEANUP
    1952              :       ! -------------------------------------------------------------------------
    1953              :       CALL fill_fm_Sigma_c_Gamma_time(fm_Sigma_c_Gamma_time, bs_env, &
    1954            0 :                                       mat_Sigma_pos_tau, mat_Sigma_neg_tau)
    1955              : 
    1956            0 :       CALL cp_fm_release(fm_W_time)
    1957              : 
    1958            0 :       CALL dbcsr_deallocate_matrix_set(mat_Sigma_neg_tau)
    1959            0 :       CALL dbcsr_deallocate_matrix_set(mat_Sigma_pos_tau)
    1960              : 
    1961            0 :       CALL release_dbcsr_topology_and_matrices(dist=dist_grid_grid, mapped_dist=dist_col_grid)
    1962            0 :       CALL release_dbcsr_topology_and_matrices(dist=dist_aux_aux, mapped_dist=dist_row_aux)
    1963              : 
    1964            0 :       CALL delete_unnecessary_files(bs_env)
    1965            0 :       CALL timestop(handle)
    1966              : 
    1967            0 :    END SUBROUTINE compute_Sigma_c
    1968              : 
    1969              : ! **************************************************************************************************
    1970              : !> \brief DBCSR Topology Generation
    1971              : !> \param matrix_template ...
    1972              : !> \param dim_type ...
    1973              : !> \param square_dist ...
    1974              : !> \param blk_sizes ...
    1975              : !> \param mapped_dist ...
    1976              : ! **************************************************************************************************
    1977              : 
    1978            0 :    SUBROUTINE setup_square_topology(matrix_template, dim_type, square_dist, blk_sizes, mapped_dist)
    1979              : 
    1980              :       TYPE(dbcsr_type), INTENT(IN)                       :: matrix_template
    1981              :       CHARACTER(LEN=*), INTENT(IN)                       :: dim_type
    1982              :       TYPE(dbcsr_distribution_type), INTENT(OUT)         :: square_dist
    1983              :       INTEGER, DIMENSION(:), INTENT(OUT), POINTER        :: blk_sizes, mapped_dist
    1984              : 
    1985              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'setup_square_topology'
    1986              : 
    1987              :       INTEGER                                            :: handle, i, np, npcols, nprows
    1988            0 :       INTEGER, DIMENSION(:), POINTER                     :: col_blk, col_dist, row_blk, row_dist
    1989              :       TYPE(dbcsr_distribution_type)                      :: dist_template
    1990              : 
    1991            0 :       CALL timeset(routineN, handle)
    1992              : 
    1993              :       CALL dbcsr_get_info(matrix_template, distribution=dist_template, &
    1994            0 :                           row_blk_size=row_blk, col_blk_size=col_blk)
    1995              :       CALL dbcsr_distribution_get(dist_template, row_dist=row_dist, col_dist=col_dist, &
    1996            0 :                                   nprows=nprows, npcols=npcols)
    1997              : 
    1998            0 :       IF (TRIM(dim_type) == 'ROW') THEN
    1999              :          ! Creates ROW x ROW (e.g., Grid x Grid from mat_phi_mu_l)
    2000            0 :          blk_sizes => row_blk
    2001            0 :          np = npcols
    2002            0 :          ALLOCATE (mapped_dist(SIZE(blk_sizes)))
    2003            0 :          DO i = 1, SIZE(blk_sizes)
    2004            0 :             mapped_dist(i) = MOD(i - 1, np)
    2005              :          END DO
    2006              :          CALL dbcsr_distribution_new(square_dist, template=dist_template, &
    2007            0 :                                      row_dist=row_dist, col_dist=mapped_dist)
    2008              : 
    2009            0 :       ELSE IF (TRIM(dim_type) == 'COL') THEN
    2010              :          ! Creates COL x COL (e.g., Aux x Aux from mat_Z_lP)
    2011            0 :          blk_sizes => col_blk
    2012            0 :          np = nprows
    2013            0 :          ALLOCATE (mapped_dist(SIZE(blk_sizes)))
    2014            0 :          DO i = 1, SIZE(blk_sizes)
    2015            0 :             mapped_dist(i) = MOD(i - 1, np)
    2016              :          END DO
    2017              :          CALL dbcsr_distribution_new(square_dist, template=dist_template, &
    2018            0 :                                      row_dist=mapped_dist, col_dist=col_dist)
    2019              :       END IF
    2020              : 
    2021            0 :       CALL timestop(handle)
    2022              : 
    2023            0 :    END SUBROUTINE setup_square_topology
    2024              : 
    2025              : ! **************************************************************************************************
    2026              : !> \brief DBCSR matrices deallocation
    2027              : !> \param dist ...
    2028              : !> \param mapped_dist    ...
    2029              : !> \param m1 ...
    2030              : !> \param m2 ...
    2031              : !> \param m3 ...
    2032              : !> \param m4 ...
    2033              : ! **************************************************************************************************
    2034              : 
    2035            0 :    SUBROUTINE release_dbcsr_topology_and_matrices(dist, mapped_dist, m1, m2, m3, m4)
    2036              : 
    2037              :       TYPE(dbcsr_distribution_type), INTENT(INOUT), &
    2038              :          OPTIONAL                                        :: dist
    2039              :       INTEGER, DIMENSION(:), INTENT(INOUT), OPTIONAL, &
    2040              :          POINTER                                         :: mapped_dist
    2041              :       TYPE(dbcsr_type), INTENT(INOUT), OPTIONAL          :: m1, m2, m3, m4
    2042              : 
    2043              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'release_dbcsr_topology_and_matrices'
    2044              : 
    2045              :       INTEGER                                            :: handle
    2046              : 
    2047            0 :       CALL timeset(routineN, handle)
    2048              : 
    2049            0 :       IF (PRESENT(dist)) CALL dbcsr_distribution_release(dist)
    2050            0 :       IF (PRESENT(mapped_dist)) THEN
    2051            0 :          IF (ASSOCIATED(mapped_dist)) THEN
    2052            0 :             DEALLOCATE (mapped_dist)
    2053              :             NULLIFY (mapped_dist)
    2054              :          END IF
    2055              :       END IF
    2056            0 :       IF (PRESENT(m1)) CALL dbcsr_release(m1)
    2057            0 :       IF (PRESENT(m2)) CALL dbcsr_release(m2)
    2058            0 :       IF (PRESENT(m3)) CALL dbcsr_release(m3)
    2059            0 :       IF (PRESENT(m4)) CALL dbcsr_release(m4)
    2060              : 
    2061            0 :       CALL timestop(handle)
    2062              : 
    2063            0 :    END SUBROUTINE release_dbcsr_topology_and_matrices
    2064              : 
    2065              : END MODULE gw_large_cell_Gamma_ri_rs
        

Generated by: LCOV version 2.0-1