LCOV - code coverage report
Current view: top level - src - gw_ri_rs_small_cell_full_kp_lattice.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 92.5 % 308 285
Test Date: 2026-11-24 01:22:08 Functions: 100.0 % 14 14

            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 RI lattice matrices, real-space cells and data distribution shared by χ, W, Σ and the
      10              : !>        Gamma correction of periodic RI-RS GW.
      11              : !> \author Jan Wilhelm (with help of ChatGPT, GPT-6 Sol and GPT-6 Astra)
      12              : ! **************************************************************************************************
      13              : MODULE gw_ri_rs_small_cell_full_kp_lattice
      14              :    USE basis_set_types,                 ONLY: gto_basis_set_type
      15              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_type
      16              :    USE cp_cfm_types,                    ONLY: cp_cfm_get_info,&
      17              :                                               cp_cfm_type
      18              :    USE cp_dbcsr_api,                    ONLY: dbcsr_create,&
      19              :                                               dbcsr_distribution_release,&
      20              :                                               dbcsr_distribution_type,&
      21              :                                               dbcsr_release,&
      22              :                                               dbcsr_type,&
      23              :                                               dbcsr_type_no_symmetry
      24              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      25              :                                               cp_dbcsr_dist2d_to_dist
      26              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      27              :                                               cp_fm_struct_get,&
      28              :                                               cp_fm_struct_release,&
      29              :                                               cp_fm_struct_type
      30              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      31              :                                               cp_fm_get_info,&
      32              :                                               cp_fm_type
      33              :    USE distribution_2d_types,           ONLY: distribution_2d_type
      34              :    USE input_constants,                 ONLY: do_potential_short,&
      35              :                                               do_potential_truncated
      36              :    USE integral_library_types,          ONLY: coulomb_operator_type
      37              :    USE kinds,                           ONLY: dp,&
      38              :                                               dp_size,&
      39              :                                               int_8
      40              :    USE kpoint_types,                    ONLY: kpoint_type
      41              :    USE mathconstants,                   ONLY: pi,&
      42              :                                               twopi,&
      43              :                                               z_one,&
      44              :                                               z_zero
      45              :    USE message_passing,                 ONLY: mp_para_env_type
      46              :    USE orbital_pointers,                ONLY: indco,&
      47              :                                               ncoset
      48              :    USE particle_methods,                ONLY: get_particle_set
      49              :    USE particle_types,                  ONLY: particle_type
      50              :    USE post_scf_bandstructure_types,    ONLY: post_scf_bandstructure_type
      51              :    USE qs_environment_types,            ONLY: get_qs_env,&
      52              :                                               qs_environment_type
      53              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
      54              :                                               qs_kind_type
      55              :    USE qs_neighbor_list_types,          ONLY: get_iterator_info,&
      56              :                                               neighbor_list_iterate,&
      57              :                                               neighbor_list_iterator_create,&
      58              :                                               neighbor_list_iterator_p_type,&
      59              :                                               neighbor_list_iterator_release,&
      60              :                                               neighbor_list_set_p_type,&
      61              :                                               release_neighbor_list_sets
      62              :    USE qs_tensors,                      ONLY: build_2c_integrals,&
      63              :                                               build_2c_neighbor_lists
      64              : #include "./base/base_uses.f90"
      65              : 
      66              :    IMPLICIT NONE
      67              :    PRIVATE
      68              : 
      69              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'gw_ri_rs_small_cell_full_kp_lattice'
      70              : 
      71              :    PUBLIC :: assemble_AA_contraction, &
      72              :              block_range, &
      73              :              build_full_cell_grid, &
      74              :              build_ri_2c_lattice, &
      75              :              complex_bytes, &
      76              :              gamma_auxiliary_charges, &
      77              :              grid_pair_indices, &
      78              :              grid_pair_gemm_panel, &
      79              :              grid_pair_upper_multiply, &
      80              :              grid_pair_shift, &
      81              :              grid_pair_stencil_weight, &
      82              :              image_weight, &
      83              :              owned_mo_coefficients, &
      84              :              real_bytes, &
      85              :              ri_2c_lattice_to_kp, &
      86              :              ri_metric_head_zero
      87              : 
      88              :    ! Bytes per stored real and complex number.
      89              :    REAL(KIND=dp), PARAMETER :: real_bytes = REAL(dp_size, dp), complex_bytes = 2.0_dp*real_bytes
      90              :    INTEGER, PARAMETER, PUBLIC :: grid_pair_stencil_denominator = 4**3
      91              :    INTEGER, PARAMETER, PUBLIC :: grid_pair_panel_cols = 32
      92              : 
      93              : CONTAINS
      94              : 
      95              : ! **************************************************************************************************
      96              : !> \brief Decode an unordered grid pair p=i+j*(j-1)/2, 1<=i<=j.
      97              : !> Integer corrections keep the triangular boundaries exact for large grids.
      98              : !> \param ipair packed upper-triangle index
      99              : !> \param il row
     100              : !> \param ilp column
     101              : ! **************************************************************************************************
     102       110295 :    PURE SUBROUTINE grid_pair_indices(ipair, il, ilp)
     103              :       INTEGER, INTENT(IN)                                :: ipair
     104              :       INTEGER, INTENT(OUT)                               :: il, ilp
     105              : 
     106              :       INTEGER(KIND=int_8)                                :: column, pair
     107              : 
     108       110295 :       pair = INT(ipair, int_8)
     109       110295 :       column = INT((1.0_dp + SQRT(8.0_dp*REAL(pair, dp) - 7.0_dp))/2.0_dp, int_8)
     110       110295 :       DO WHILE (column*(column + 1_int_8)/2_int_8 < pair)
     111       110295 :          column = column + 1_int_8
     112              :       END DO
     113       110295 :       DO WHILE (column*(column - 1_int_8)/2_int_8 >= pair)
     114       110295 :          column = column - 1_int_8
     115              :       END DO
     116       110295 :       ilp = INT(column)
     117       110295 :       il = INT(pair - column*(column - 1_int_8)/2_int_8)
     118       110295 :    END SUBROUTINE grid_pair_indices
     119              : 
     120              : ! **************************************************************************************************
     121              : !> \brief Nearest lattice image of an unordered grid pair, including both half-cell ties.
     122              : !> \param il row of the unordered pair
     123              : !> \param ilp column of the unordered pair
     124              : !> \param fractional_grid periodic fractional grid coordinates
     125              : !> \param pair_shift lower nearest image on a tie
     126              : !> \param pair_tie directions with two equidistant images
     127              : ! **************************************************************************************************
     128       110295 :    PURE SUBROUTINE grid_pair_shift(il, ilp, fractional_grid, pair_shift, pair_tie)
     129              :       INTEGER, INTENT(IN)                                :: il, ilp
     130              :       REAL(KIND=dp), INTENT(IN)                          :: fractional_grid(:, :)
     131              :       INTEGER, INTENT(OUT)                               :: pair_shift(3)
     132              :       LOGICAL, INTENT(OUT)                               :: pair_tie(3)
     133              : 
     134              :       INTEGER                                            :: idir
     135              :       REAL(KIND=dp)                                      :: delta(3), half_boundary, tolerance
     136              : 
     137       441180 :       delta = fractional_grid(:, il) - fractional_grid(:, ilp)
     138       441180 :       pair_shift = NINT(delta)
     139       110295 :       pair_tie = .FALSE.
     140       441180 :       DO idir = 1, 3
     141       330885 :          half_boundary = ANINT(delta(idir) - 0.5_dp) + 0.5_dp
     142       330885 :          tolerance = 64.0_dp*EPSILON(1.0_dp)*MAX(1.0_dp, ABS(delta(idir)))
     143       441180 :          IF (ABS(delta(idir) - half_boundary) <= tolerance) THEN
     144            0 :             pair_shift(idir) = NINT(half_boundary - 0.5_dp)
     145            0 :             pair_tie(idir) = .TRUE.
     146              :          END IF
     147              :       END DO
     148       110295 :    END SUBROUTINE grid_pair_shift
     149              : 
     150              : ! **************************************************************************************************
     151              : !> \brief Compute a column panel of A B^H through its last diagonal.
     152              : !> \param n grid points
     153              : !> \param ninner contracted dimension
     154              : !> \param first first column of the panel
     155              : !> \param width number of columns
     156              : !> \param left A
     157              : !> \param right B; the caller supplies a Hermitian product
     158              : !> \param panel ...
     159              : ! **************************************************************************************************
     160         3645 :    SUBROUTINE grid_pair_gemm_panel(n, ninner, first, width, left, right, panel)
     161              :       INTEGER, INTENT(IN)                                :: n, ninner, first, width
     162              :       COMPLEX(KIND=dp), INTENT(IN)                       :: left(n, ninner), right(n, ninner)
     163              :       COMPLEX(KIND=dp), INTENT(OUT)                      :: panel(n, width)
     164              : 
     165              :       INTEGER                                            :: col, row
     166              : 
     167              :       CALL zgemm('N', 'C', first + width - 1, width, ninner, z_one, left, n, &
     168         3645 :                  right(first, 1), n, z_zero, panel, n)
     169        68283 :       DO col = 1, width
     170        64638 :          row = first + col - 1
     171        68283 :          panel(row, col) = CMPLX(REAL(panel(row, col), dp), 0.0_dp, dp)
     172              :       END DO
     173         3645 :    END SUBROUTINE grid_pair_gemm_panel
     174              : 
     175              : ! **************************************************************************************************
     176              : !> \brief Y=U Z with U=triu(H,1)+diag(H)/2, so that H=U+U^H.
     177              : !> Hermitian projections reconstruct the adjoint after contraction, saving the lower multiply.
     178              : !> \param n grid points
     179              : !> \param nrhs right-hand sides
     180              : !> \param pairs packed upper triangle of H
     181              : !> \param Z dense right-hand sides
     182              : !> \param Y result
     183              : !> \param panel reusable thread-local workspace
     184              : ! **************************************************************************************************
     185         1800 :    SUBROUTINE grid_pair_upper_multiply(n, nrhs, pairs, Z, Y, panel)
     186              :       INTEGER, INTENT(IN)                                :: n, nrhs
     187              :       COMPLEX(KIND=dp), INTENT(IN)                       :: pairs(:), Z(n, nrhs)
     188              :       COMPLEX(KIND=dp), INTENT(OUT) :: Y(n, nrhs), panel(n, MIN(grid_pair_panel_cols, n))
     189              : 
     190              :       INTEGER                                            :: col, first, j, offset, width
     191              : 
     192         1800 :       CPASSERT(SIZE(pairs, KIND=int_8) == INT(n, int_8)*(n + 1)/2)
     193       760568 :       Y = z_zero
     194         5328 :       DO first = 1, n, grid_pair_panel_cols
     195         3528 :          width = MIN(grid_pair_panel_cols, n - first + 1)
     196        66168 :          DO col = 1, width
     197        62640 :             j = first + col - 1
     198        62640 :             offset = INT(INT(j, int_8)*INT(j - 1, int_8)/2_int_8)
     199      1152360 :             panel(1:j - 1, col) = pairs(offset + 1:offset + j - 1)
     200        62640 :             panel(j, col) = CMPLX(0.5_dp*REAL(pairs(offset + j), dp), 0.0_dp, dp)
     201       934704 :             panel(j + 1:first + width - 1, col) = z_zero
     202              :          END DO
     203         5328 :          CALL zgemm('N', 'N', first + width - 1, nrhs, width, z_one, panel, n, Z(first, 1), n, z_one, Y, n)
     204              :       END DO
     205         1800 :    END SUBROUTINE grid_pair_upper_multiply
     206              : 
     207              : ! **************************************************************************************************
     208              : !> \brief Finite-supercell image weight, averaged over equidistant pair centers.
     209              : !> \param c image relative to the lower pair center
     210              : !> \param n_mesh mesh length
     211              : !> \param tie two equidistant centers
     212              : !> \param boundary weight of a supercell endpoint
     213              : !> \return image weight
     214              : ! **************************************************************************************************
     215      1603820 :    PURE REAL(KIND=dp) FUNCTION image_weight(c, n_mesh, tie, boundary) RESULT(weight)
     216              :       INTEGER, INTENT(IN)                                :: c, n_mesh
     217              :       LOGICAL, INTENT(IN)                                :: tie
     218              :       REAL(KIND=dp), INTENT(IN)                          :: boundary
     219              : 
     220              :       INTEGER                                            :: i_center, n_centers
     221              : 
     222      1603820 :       n_centers = MERGE(2, 1, tie)
     223      1603820 :       weight = 0.0_dp
     224      3207788 :       DO i_center = 0, n_centers - 1
     225      3207788 :          IF (2*ABS(c - i_center) < n_mesh) THEN
     226       561512 :             weight = weight + 1.0_dp/REAL(n_centers, dp)
     227      1042456 :          ELSE IF (2*ABS(c - i_center) == n_mesh) THEN
     228       481304 :             weight = weight + boundary/REAL(n_centers, dp)
     229              :          END IF
     230              :       END DO
     231      1603820 :    END FUNCTION image_weight
     232              : 
     233              : ! **************************************************************************************************
     234              : !> \brief Signed stencil numerator on an inversion-closed mesh, with denominator 64.
     235              : !> All centered images share exp(2*pi*i*offset*cell); their remaining phases are signs.
     236              : !> Each one-axis image weight is a multiple of 1/4, including half-cell averaging.
     237              : !> \param cell canonical source cell
     238              : !> \param shift lower pair center
     239              : !> \param tie half-cell ties
     240              : !> \param nmesh Born-von Karman mesh
     241              : !> \param half_shift twice the mesh-scaled reciprocal offset
     242              : !> \param displacement grid-point displacement in Cartesian coordinates
     243              : !> \param hmat lattice matrix
     244              : !> \param cutoff_squared squared distance cutoff; nonpositive disables truncation
     245              : !> \return signed image-weight numerator
     246              : ! **************************************************************************************************
     247       358095 :    PURE INTEGER FUNCTION grid_pair_stencil_weight(cell, shift, tie, nmesh, half_shift, &
     248              :                                                   displacement, hmat, cutoff_squared) RESULT(numerator)
     249              :       INTEGER, INTENT(IN)                                :: cell(3), shift(3)
     250              :       LOGICAL, INTENT(IN)                                :: tie(3)
     251              :       INTEGER, INTENT(IN)                                :: nmesh(3), half_shift(3)
     252              :       REAL(KIND=dp), INTENT(IN)                          :: displacement(3), hmat(3, 3), &
     253              :                                                             cutoff_squared
     254              : 
     255              :       INTEGER                                            :: base(3), ix, iy, iz, translated(3), &
     256              :                                                             weight, weights(0:1, 3)
     257              :       REAL(KIND=dp)                                      :: boundary(3), distance(3)
     258              : 
     259              :       ! Periodic image weights partition unity when every supercell phase is one.
     260       630660 :       IF (cutoff_squared <= 0.0_dp .AND. ALL(MODULO(half_shift, 2) == 0)) THEN
     261       358095 :          numerator = grid_pair_stencil_denominator
     262              :          RETURN
     263              :       END IF
     264      1068960 :       base = MODULO(cell - shift + nmesh/2, nmesh) - nmesh/2
     265      1068960 :       boundary = 0.5_dp*REAL(1 - MODULO(half_shift, 2), dp)
     266      1068960 :       DO ix = 1, 3
     267              :          weights(:, ix) = NINT(4.0_dp*[image_weight(base(ix), nmesh(ix), tie(ix), boundary(ix)), &
     268      2672400 :                                        image_weight(base(ix) + nmesh(ix), nmesh(ix), tie(ix), boundary(ix))])
     269              :       END DO
     270              :       ! Without a distance cutoff, the image sum separates into three one-axis sums.
     271       267240 :       IF (cutoff_squared <= 0.0_dp) THEN
     272      1068960 :          numerator = PRODUCT(weights(0, :) + (1 - 2*MODULO(half_shift, 2))*weights(1, :))
     273      1068960 :          IF (MODULO(DOT_PRODUCT(half_shift, (shift + base - cell)/nmesh), 2) /= 0) numerator = -numerator
     274       267240 :          RETURN
     275              :       END IF
     276              :       numerator = 0
     277            0 :       DO iz = 0, 1
     278            0 :          IF (weights(iz, 3) == 0) CYCLE
     279            0 :          DO iy = 0, 1
     280            0 :             IF (weights(iy, 2) == 0) CYCLE
     281            0 :             DO ix = 0, 1
     282            0 :                weight = weights(ix, 1)*weights(iy, 2)*weights(iz, 3)
     283            0 :                IF (weight == 0) CYCLE
     284            0 :                translated = shift + base + nmesh*[ix, iy, iz]
     285            0 :                distance = displacement - MATMUL(hmat, REAL(translated, dp))
     286            0 :                IF (SUM(distance**2) > cutoff_squared) CYCLE
     287            0 :                IF (MODULO(DOT_PRODUCT(half_shift, (translated - cell)/nmesh), 2) /= 0) weight = -weight
     288            0 :                numerator = numerator + weight
     289              :             END DO
     290              :          END DO
     291              :       END DO
     292              :    END FUNCTION grid_pair_stencil_weight
     293              : 
     294              : ! **************************************************************************************************
     295              : !> \brief Assembles the q-independent, atom-diagonal AA contraction from stored coefficients.
     296              : !> \param bs_env ...
     297              : !> \param U_Pp Atom-diagonal reference-to-optimized AA contraction.
     298              : ! **************************************************************************************************
     299           22 :    SUBROUTINE assemble_AA_contraction(bs_env, U_Pp)
     300              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     301              :       COMPLEX(KIND=dp), ALLOCATABLE, INTENT(OUT)         :: U_Pp(:, :)
     302              : 
     303              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'assemble_AA_contraction'
     304              : 
     305              :       INTEGER                                            :: first, first_opt, first_ref, handle, &
     306              :                                                             iatom, last, nopt, nref
     307              : 
     308           22 :       CALL timeset(routineN, handle)
     309              : 
     310           22 :       IF (.NOT. bs_env%auto_ri%ready .OR. &
     311              :           .NOT. ALLOCATED(bs_env%auto_ri%sizes_ref_RI)) THEN
     312            0 :          CPABORT('Periodic AUTO_RI contraction is not initialized')
     313              :       END IF
     314            0 :       ALLOCATE (U_Pp(SUM(bs_env%auto_ri%sizes_ref_RI), &
     315          176 :                      SUM(bs_env%auto_ri%sizes_opt_RI)), source=z_zero)
     316           22 :       first_ref = 1
     317           22 :       first_opt = 1
     318           66 :       DO iatom = 1, bs_env%n_atom
     319           44 :          nref = bs_env%auto_ri%sizes_ref_RI(iatom)
     320           44 :          nopt = bs_env%auto_ri%sizes_opt_RI(iatom)
     321           44 :          first = bs_env%auto_ri%U_Pp_atom_offset(iatom)
     322           44 :          last = first + nref*nopt - 1
     323              :          U_Pp(first_ref:first_ref + nref - 1, first_opt:first_opt + nopt - 1) = &
     324          988 :             RESHAPE(bs_env%auto_ri%U_Pp_atom(first:last), [nref, nopt])
     325           44 :          first_ref = first_ref + nref
     326           66 :          first_opt = first_opt + nopt
     327              :       END DO
     328         1658 :       IF (ANY(SUM(ABS(U_Pp)**2, DIM=1) <= TINY(1.0_dp))) THEN
     329            0 :          CPABORT('Periodic AUTO_RI contraction has an empty optimized direction')
     330              :       END IF
     331              : 
     332           22 :       CALL timestop(handle)
     333              : 
     334           22 :    END SUBROUTINE assemble_AA_contraction
     335              : 
     336              : ! **************************************************************************************************
     337              : !> \brief Dense MO coefficients of the cyclically owned SCF k points (owner of k: MODULO(k-1, ranks)).
     338              : !> Pack the local BLACS tiles by destination in bounded k-point batches. The common matrix
     339              : !> structure supplies the row and column indices for unpacking each sender's tile.
     340              : !> \param bs_env ...
     341              : !> \param mo_coeff distributed MO coefficients per k point and spin
     342              : !> \param coeff coeff(:, :, k_local, spin) for the owned k points
     343              : ! **************************************************************************************************
     344           42 :    SUBROUTINE owned_mo_coefficients(bs_env, mo_coeff, coeff)
     345              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     346              :       TYPE(cp_cfm_type), DIMENSION(:, :), INTENT(IN)     :: mo_coeff
     347              :       COMPLEX(KIND=dp), ALLOCATABLE, INTENT(OUT)         :: coeff(:, :, :, :)
     348              : 
     349              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'owned_mo_coefficients'
     350              :       INTEGER(KIND=int_8), PARAMETER :: buffer_elements = 64000000_int_8/INT(2*dp_size, int_8)
     351              : 
     352              :       COMPLEX(KIND=dp), ALLOCATABLE                      :: received(:), sent(:)
     353              :       INTEGER :: batch_size, col, first_k, first_owned, first_owned_k, handle, i_col, i_owned, &
     354              :          i_rank, i_row, ikp, ipcol, iprow, ispin, last_k, my_rank, n_ao, n_k, n_mo, n_owned, &
     355              :          n_owned_batch, ncol_local, ncol_src, nrow_local, nrow_src, num_pe, offset
     356              :       INTEGER(KIND=int_8)                                :: matrix_size, max_tile_size
     357           42 :       INTEGER, ALLOCATABLE                               :: cols(:, :), recv_counts(:), &
     358           42 :                                                             recv_displs(:), rows(:, :), &
     359              :                                                             send_counts(:), send_displs(:), &
     360           42 :                                                             tile_sizes(:)
     361           42 :       INTEGER, POINTER                                   :: local_cols(:), local_rows(:)
     362              :       LOGICAL                                            :: same_layout
     363              :       TYPE(cp_blacs_env_type), POINTER                   :: context
     364              :       TYPE(cp_fm_struct_type), POINTER                   :: layout
     365              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     366              : 
     367           42 :       CALL timeset(routineN, handle)
     368              : 
     369           42 :       n_k = SIZE(mo_coeff, 1)
     370           42 :       para_env => bs_env%para_env
     371           42 :       num_pe = para_env%num_pe
     372           42 :       my_rank = para_env%mepos
     373              :       CALL cp_cfm_get_info(mo_coeff(1, 1), nrow_global=n_ao, ncol_global=n_mo, nrow_local=nrow_local, &
     374           42 :                            ncol_local=ncol_local, context=context, matrix_struct=layout)
     375           42 :       CPASSERT(layout%para_env%num_pe == num_pe)
     376           42 :       CPASSERT(layout%para_env%mepos == my_rank)
     377           42 :       CALL cp_fm_struct_get(layout, nrow_locals=local_rows, ncol_locals=local_cols)
     378           42 :       matrix_size = INT(n_ao, int_8)*INT(n_mo, int_8)
     379          168 :       max_tile_size = INT(MAXVAL(local_rows), int_8)*INT(MAXVAL(local_cols), int_8)
     380           42 :       CPASSERT(matrix_size > 0_int_8 .AND. max_tile_size > 0_int_8)
     381           42 :       CPASSERT(matrix_size + max_tile_size <= INT(HUGE(0), int_8))
     382           42 :       n_owned = (n_k + num_pe - 1 - my_rank)/num_pe
     383              :       batch_size = INT(MIN(INT(n_k, int_8), INT(num_pe, int_8)*MAX(1_int_8, buffer_elements/matrix_size), &
     384           42 :                            MAX(1_int_8, buffer_elements/max_tile_size)))
     385            0 :       ALLOCATE (coeff(n_ao, n_mo, n_owned, SIZE(mo_coeff, 2)), &
     386              :                 sent(MAX(1, nrow_local*ncol_local*batch_size)), &
     387          420 :                 received(MAX(1, INT(matrix_size)*MIN(n_owned, (batch_size + num_pe - 1)/num_pe))))
     388              :       ALLOCATE (rows(MAXVAL(local_rows), 0:context%num_pe(1) - 1), &
     389              :                 cols(MAXVAL(local_cols), 0:context%num_pe(2) - 1), &
     390              :                 recv_counts(0:num_pe - 1), recv_displs(0:num_pe - 1), &
     391          672 :                 send_counts(0:num_pe - 1), send_displs(0:num_pe - 1), tile_sizes(0:num_pe - 1))
     392          126 :       DO iprow = 0, context%num_pe(1) - 1
     393          306 :          DO i_row = 1, local_rows(iprow)
     394          264 :             rows(i_row, iprow) = layout%l2g_row(i_row, iprow)
     395              :          END DO
     396              :       END DO
     397           84 :       DO ipcol = 0, context%num_pe(2) - 1
     398          264 :          DO i_col = 1, local_cols(ipcol)
     399          222 :             cols(i_col, ipcol) = layout%l2g_col(i_col, ipcol)
     400              :          END DO
     401              :       END DO
     402          126 :       DO i_rank = 0, num_pe - 1
     403           84 :          iprow = context%mpi2blacs(1, i_rank)
     404           84 :          ipcol = context%mpi2blacs(2, i_rank)
     405          126 :          tile_sizes(i_rank) = local_rows(iprow)*local_cols(ipcol)
     406              :       END DO
     407          126 :       CPASSERT(SUM(tile_sizes) == INT(matrix_size))
     408              : 
     409           84 :       DO ispin = 1, SIZE(mo_coeff, 2)
     410          126 :          DO first_k = 1, n_k, batch_size
     411           42 :             last_k = MIN(first_k + batch_size - 1, n_k)
     412           42 :             first_owned_k = first_k + MODULO(my_rank + 1 - first_k, num_pe)
     413           42 :             first_owned = (first_owned_k - 1)/num_pe + 1
     414           42 :             n_owned_batch = (last_k - first_owned_k + num_pe)/num_pe
     415          126 :             recv_counts(:) = n_owned_batch*tile_sizes
     416           42 :             recv_displs(0) = 0
     417           84 :             DO i_rank = 1, num_pe - 1
     418           84 :                recv_displs(i_rank) = recv_displs(i_rank - 1) + recv_counts(i_rank - 1)
     419              :             END DO
     420              : 
     421              :             offset = 0
     422          126 :             DO i_rank = 0, num_pe - 1
     423           84 :                send_displs(i_rank) = offset
     424          870 :                DO ikp = first_k + MODULO(i_rank + 1 - first_k, num_pe), last_k, num_pe
     425          786 :                   same_layout = ASSOCIATED(mo_coeff(ikp, ispin)%matrix_struct, layout)
     426          786 :                   CPASSERT(same_layout)
     427         5106 :                   DO i_col = 1, ncol_local
     428        16464 :                      sent(offset + 1:offset + nrow_local) = mo_coeff(ikp, ispin)%local_data(:nrow_local, i_col)
     429         5022 :                      offset = offset + nrow_local
     430              :                   END DO
     431              :                END DO
     432          126 :                send_counts(i_rank) = offset - send_displs(i_rank)
     433              :             END DO
     434              : 
     435           42 :             CALL para_env%alltoall(sent, send_counts, send_displs, received, recv_counts, recv_displs)
     436          168 :             DO i_rank = 0, num_pe - 1
     437           84 :                IF (recv_counts(i_rank) == 0) CYCLE
     438           84 :                iprow = context%mpi2blacs(1, i_rank)
     439           84 :                ipcol = context%mpi2blacs(2, i_rank)
     440           84 :                nrow_src = local_rows(iprow)
     441           84 :                ncol_src = local_cols(ipcol)
     442           84 :                offset = recv_displs(i_rank)
     443          912 :                DO i_owned = first_owned, first_owned + n_owned_batch - 1
     444         5106 :                   DO i_col = 1, ncol_src
     445         4236 :                      col = cols(i_col, ipcol)
     446        16464 :                      coeff(rows(:nrow_src, iprow), col, i_owned, ispin) = received(offset + 1:offset + nrow_src)
     447         5022 :                      offset = offset + nrow_src
     448              :                   END DO
     449              :                END DO
     450              :             END DO
     451              :          END DO
     452              :       END DO
     453              : 
     454           42 :       CALL timestop(handle)
     455              : 
     456           84 :    END SUBROUTINE owned_mo_coefficients
     457              : 
     458              : ! **************************************************************************************************
     459              : !> \brief Construct a complete cell grid dual to the uniform SCF k-point mesh.
     460              : !> \param bs_env ...
     461              : !> \param index_to_cell ...
     462              : ! **************************************************************************************************
     463           56 :    SUBROUTINE build_full_cell_grid(bs_env, index_to_cell)
     464              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     465              :       INTEGER, ALLOCATABLE, INTENT(OUT)                  :: index_to_cell(:, :)
     466              : 
     467              :       INTEGER                                            :: cell(3), i1, i2, i3, i_cell, &
     468              :                                                             i_direction, lower(3), upper(3)
     469              : 
     470          224 :       DO i_direction = 1, 3
     471          168 :          lower(i_direction) = -bs_env%kpoints_scf_desymm%nkp_grid(i_direction)/2
     472              :          upper(i_direction) = lower(i_direction) + &
     473          224 :                               bs_env%kpoints_scf_desymm%nkp_grid(i_direction) - 1
     474              :       END DO
     475          336 :       ALLOCATE (index_to_cell(3, PRODUCT(bs_env%kpoints_scf_desymm%nkp_grid)))
     476           56 :       i_cell = 0
     477          200 :       DO i1 = lower(1), upper(1)
     478          600 :          DO i2 = lower(2), upper(2)
     479         1536 :             DO i3 = lower(3), upper(3)
     480          992 :                i_cell = i_cell + 1
     481         3968 :                cell = [i1, i2, i3]
     482         4368 :                index_to_cell(:, i_cell) = cell
     483              :             END DO
     484              :          END DO
     485              :       END DO
     486              : 
     487           56 :    END SUBROUTINE build_full_cell_grid
     488              : 
     489              : ! **************************************************************************************************
     490              : !> \brief Zero-wave-vector Fourier value of the selected RI metric kernel.
     491              : !> \param bs_env ...
     492              : !> \return ...
     493              : ! **************************************************************************************************
     494          332 :    FUNCTION ri_metric_head_zero(bs_env) RESULT(head)
     495              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     496              :       REAL(KIND=dp)                                      :: head
     497              : 
     498          332 :       IF (bs_env%ri_metric%potential_type == do_potential_short) THEN
     499          332 :          IF (bs_env%ri_metric%omega <= 0.0_dp) THEN
     500            0 :             CPABORT('RI attenuation must be positive')
     501              :          END IF
     502          332 :          head = pi/bs_env%ri_metric%omega**2
     503              :       ELSE
     504            0 :          IF (bs_env%ri_metric%potential_type /= do_potential_truncated) THEN
     505            0 :             CPABORT('Unsupported RI metric')
     506              :          END IF
     507            0 :          head = twopi*bs_env%ri_metric%cutoff_radius**2
     508              :       END IF
     509          332 :    END FUNCTION ri_metric_head_zero
     510              : 
     511              : ! **************************************************************************************************
     512              : !> \brief Form distributed I_PQ(R) = (φ_P,0 | v | φ_Q,R) over every screened neighbor cell.
     513              : !>
     514              : !> The finite-range potential v and the Gaussian screening radii determine the cell set.
     515              : !> No cell is dropped because it lies outside the SCF Born-von Karman cell. Each real matrix
     516              : !> remains distributed over the existing RI matrix communicator; callers release fm_R.
     517              : !> The reciprocal interaction is I_PQ(q) = sum_R exp(i q.R) I_PQ(R).
     518              : !> \param fm_R ...
     519              : !> \param cells ...
     520              : !> \param potential ...
     521              : !> \param regularization ...
     522              : !> \param bs_env ...
     523              : !> \param qs_env ...
     524              : !> \param reference_basis ...
     525              : ! **************************************************************************************************
     526           28 :    SUBROUTINE build_ri_2c_lattice(fm_R, cells, potential, regularization, bs_env, qs_env, reference_basis)
     527              :       TYPE(cp_fm_type), ALLOCATABLE, INTENT(OUT)         :: fm_R(:)
     528              :       INTEGER, ALLOCATABLE, INTENT(OUT)                  :: cells(:, :)
     529              :       TYPE(coulomb_operator_type), INTENT(IN)            :: potential
     530              :       REAL(KIND=dp), INTENT(IN)                          :: regularization
     531              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     532              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     533              :       LOGICAL, INTENT(IN), OPTIONAL                      :: reference_basis
     534              : 
     535              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_ri_2c_lattice'
     536              : 
     537              :       INTEGER                                            :: bounds(3), cell_index(3), handle, icell, &
     538              :                                                             ix, iy, iz, ncells
     539           28 :       INTEGER, ALLOCATABLE                               :: occupied(:, :, :), occupied_flat(:), &
     540              :                                                             sizes(:)
     541           56 :       INTEGER, CONTIGUOUS, POINTER                       :: col_sizes(:), row_sizes(:)
     542              :       LOGICAL                                            :: use_reference_basis
     543              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs
     544              :       TYPE(cp_fm_struct_type), POINTER                   :: reference_matrix_struct
     545              :       TYPE(dbcsr_distribution_type)                      :: distribution
     546           28 :       TYPE(dbcsr_type), ALLOCATABLE                      :: matrices(:)
     547              :       TYPE(distribution_2d_type), POINTER                :: dist_2d
     548              :       TYPE(kpoint_type), POINTER                         :: kpoints_ptr
     549          308 :       TYPE(kpoint_type), TARGET                          :: kpoints
     550              :       TYPE(mp_para_env_type), POINTER                    :: para
     551           28 :       TYPE(neighbor_list_iterator_p_type), POINTER       :: iterator(:)
     552           28 :       TYPE(neighbor_list_set_p_type), POINTER            :: neighbors(:)
     553           28 :       TYPE(particle_type), POINTER                       :: particles(:)
     554           28 :       TYPE(qs_kind_type), POINTER                        :: qs_kinds(:)
     555              : 
     556           28 :       CALL timeset(routineN, handle)
     557              : 
     558           28 :       use_reference_basis = .FALSE.
     559           28 :       IF (PRESENT(reference_basis)) use_reference_basis = reference_basis
     560           28 :       NULLIFY (blacs, para, reference_matrix_struct)
     561              :       CALL get_qs_env(qs_env, distribution_2d=dist_2d, particle_set=particles, qs_kind_set=qs_kinds, &
     562           28 :                       blacs_env=blacs, para_env=para)
     563           84 :       ALLOCATE (sizes(bs_env%n_atom))
     564           28 :       CALL get_particle_set(particles, qs_kinds, nsgf=sizes, basis=bs_env%basis_set_RI)
     565           28 :       NULLIFY (neighbors, iterator)
     566              :       CALL build_2c_neighbor_lists(neighbors, bs_env%basis_set_RI, bs_env%basis_set_RI, &
     567           28 :                                    potential, "full_2c_RI", qs_env, sym_ij=.FALSE., dist_2d=dist_2d)
     568           28 :       bounds = 0
     569           28 :       CALL neighbor_list_iterator_create(iterator, neighbors)
     570         9892 :       DO WHILE (neighbor_list_iterate(iterator) == 0)
     571         9864 :          CALL get_iterator_info(iterator, cell=cell_index)
     572        39484 :          bounds = MAX(bounds, ABS(cell_index))
     573              :       END DO
     574           28 :       CALL neighbor_list_iterator_release(iterator)
     575           28 :       CALL bs_env%para_env%max(bounds)
     576          140 :       ALLOCATE (occupied(-bounds(1):bounds(1), -bounds(2):bounds(2), -bounds(3):bounds(3)))
     577           28 :       occupied = 0
     578           28 :       CALL neighbor_list_iterator_create(iterator, neighbors)
     579         9892 :       DO WHILE (neighbor_list_iterate(iterator) == 0)
     580         9864 :          CALL get_iterator_info(iterator, cell=cell_index)
     581         9864 :          occupied(cell_index(1), cell_index(2), cell_index(3)) = 1
     582              :       END DO
     583           28 :       CALL neighbor_list_iterator_release(iterator)
     584          168 :       ALLOCATE (occupied_flat(SIZE(occupied)))
     585          140 :       occupied_flat(:) = RESHAPE(occupied, [SIZE(occupied)])
     586           28 :       CALL bs_env%para_env%max(occupied_flat)
     587          112 :       occupied(:, :, :) = RESHAPE(occupied_flat, SHAPE(occupied))
     588           28 :       DEALLOCATE (occupied_flat)
     589         9576 :       ncells = SUM(occupied)
     590           28 :       CPASSERT(ncells > 0)
     591         5288 :       ALLOCATE (cells(3, ncells), fm_R(ncells))
     592          112 :       ALLOCATE (kpoints%cell_to_index(-bounds(1):bounds(1), -bounds(2):bounds(2), -bounds(3):bounds(3)))
     593         9576 :       kpoints%cell_to_index = 0
     594              :       icell = 0
     595          304 :       DO ix = -bounds(1), bounds(1)
     596         2764 :          DO iy = -bounds(2), bounds(2)
     597        11244 :             DO iz = -bounds(3), bounds(3)
     598         8508 :                IF (occupied(ix, iy, iz) == 0) CYCLE
     599         5148 :                icell = icell + 1
     600        20592 :                cells(:, icell) = [ix, iy, iz]
     601        10968 :                kpoints%cell_to_index(ix, iy, iz) = icell
     602              :             END DO
     603              :          END DO
     604              :       END DO
     605           28 :       DEALLOCATE (occupied)
     606           28 :       kpoints_ptr => kpoints
     607         5232 :       ALLOCATE (matrices(ncells))
     608           28 :       CALL cp_dbcsr_dist2d_to_dist(dist_2d, distribution)
     609          112 :       ALLOCATE (row_sizes(SIZE(sizes)), col_sizes(SIZE(sizes)))
     610           84 :       row_sizes = sizes
     611           84 :       col_sizes = sizes
     612           28 :       CALL dbcsr_create(matrices(1), "full RI two-center", distribution, dbcsr_type_no_symmetry, row_sizes, col_sizes)
     613           28 :       DEALLOCATE (row_sizes, col_sizes)
     614         5148 :       DO icell = 2, ncells
     615         5148 :          CALL dbcsr_create(matrices(icell), template=matrices(1))
     616              :       END DO
     617              :       CALL build_2c_integrals(matrices, 0.0_dp, qs_env, neighbors, bs_env%basis_set_RI, &
     618              :                               bs_env%basis_set_RI, potential, do_kpoints=.TRUE., &
     619           28 :                               ext_kpoints=kpoints_ptr, regularization_RI=regularization)
     620         5176 :       DO icell = 1, ncells
     621         5148 :          IF (use_reference_basis) THEN
     622         2016 :             IF (.NOT. bs_env%auto_ri%enabled) THEN
     623            0 :                CPABORT('Reference RI lattice requires AUTO_RI')
     624              :             END IF
     625         2016 :             IF (.NOT. ASSOCIATED(reference_matrix_struct)) THEN
     626              :                CALL cp_fm_struct_create(reference_matrix_struct, context=blacs, nrow_global=SUM(sizes), &
     627           80 :                                         ncol_global=SUM(sizes), para_env=para)
     628              :             END IF
     629         2016 :             CALL cp_fm_create(fm_R(icell), reference_matrix_struct)
     630              :          ELSE
     631         3132 :             CALL cp_fm_create(fm_R(icell), bs_env%fm_RI_RI%matrix_struct)
     632              :          END IF
     633         5148 :          CALL copy_dbcsr_to_fm(matrices(icell), fm_R(icell))
     634         5176 :          CALL dbcsr_release(matrices(icell))
     635              :       END DO
     636           28 :       CALL dbcsr_distribution_release(distribution)
     637           28 :       CALL release_neighbor_list_sets(neighbors)
     638           28 :       IF (ASSOCIATED(reference_matrix_struct)) CALL cp_fm_struct_release(reference_matrix_struct)
     639           28 :       DEALLOCATE (matrices, sizes, kpoints%cell_to_index)
     640              : 
     641           28 :       CALL timestop(handle)
     642              : 
     643          112 :    END SUBROUTINE build_ri_2c_lattice
     644              : 
     645              : ! **************************************************************************************************
     646              : !> \brief Evaluate I_PQ(q) = sum_R exp(i q.R) I_PQ(R) collectively into an existing dense matrix.
     647              : !>
     648              : !> q is in reciprocal fractional coordinates, so q.R includes 2π. The real-space matrices
     649              : !> stay distributed; no global RI-by-RI-by-cell array is replicated on the ranks.
     650              : !> \param fm_R ...
     651              : !> \param cells ...
     652              : !> \param qpoint ...
     653              : !> \param matrix_q ...
     654              : ! **************************************************************************************************
     655           22 :    SUBROUTINE ri_2c_lattice_to_kp(fm_R, cells, qpoint, matrix_q)
     656              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_R(:)
     657              :       INTEGER, INTENT(IN)                                :: cells(:, :)
     658              :       REAL(KIND=dp), INTENT(IN)                          :: qpoint(3)
     659              :       COMPLEX(KIND=dp), INTENT(OUT)                      :: matrix_q(:, :)
     660              : 
     661              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'ri_2c_lattice_to_kp'
     662              : 
     663              :       COMPLEX(KIND=dp)                                   :: phase
     664              :       INTEGER                                            :: handle, icell, icol, irow, ncols, nrows
     665           22 :       INTEGER, POINTER                                   :: cols(:), rows(:)
     666              : 
     667           22 :       CALL timeset(routineN, handle)
     668              : 
     669           22 :       CPASSERT(SIZE(fm_R) > 0)
     670           22 :       CPASSERT(SIZE(cells, 1) == 3)
     671           22 :       CPASSERT(SIZE(cells, 2) == SIZE(fm_R))
     672           22 :       CALL cp_fm_get_info(fm_R(1), nrow_local=nrows, ncol_local=ncols, row_indices=rows, col_indices=cols)
     673         8098 :       matrix_q = z_zero
     674         4684 :       DO icell = 1, SIZE(fm_R)
     675        18648 :          phase = EXP(CMPLX(0.0_dp, twopi*DOT_PRODUCT(qpoint, REAL(cells(:, icell), dp)), dp))
     676        69376 :          DO icol = 1, ncols
     677       588726 :             DO irow = 1, nrows
     678              :                matrix_q(rows(irow), cols(icol)) = matrix_q(rows(irow), cols(icol)) + &
     679       584064 :                                                   phase*fm_R(icell)%local_data(irow, icol)
     680              :             END DO
     681              :          END DO
     682              :       END DO
     683        16174 :       CALL fm_R(1)%matrix_struct%para_env%sum(matrix_q)
     684              : 
     685           22 :       CALL timestop(handle)
     686              : 
     687           22 :    END SUBROUTINE ri_2c_lattice_to_kp
     688              : 
     689              : ! **************************************************************************************************
     690              : !> \brief Integrate each auxiliary function for the Gamma charge-mode projection.
     691              : !> For a primitive x^(2m) exp(-α x²), I_0=sqrt(π/α), I_2m=(2m-1)I_(2m-2)/(2α).
     692              : !> Odd Cartesian moments vanish; the existing spherical contraction supplies normalization.
     693              : !> \param qs_env Atomic auxiliary bases.
     694              : !> \param charge Integrals of the reference auxiliary functions.
     695              : ! **************************************************************************************************
     696           20 :    SUBROUTINE gamma_auxiliary_charges(qs_env, charge)
     697              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     698              :       COMPLEX(KIND=dp), INTENT(OUT)                      :: charge(:)
     699              : 
     700              :       INTEGER                                            :: first, iatom, ico, il, ipgf, iset, isgf, &
     701              :                                                             lmax, ncart, offset
     702              :       REAL(KIND=dp)                                      :: alpha
     703           20 :       REAL(KIND=dp), ALLOCATABLE                         :: moments(:), primitive(:)
     704              :       TYPE(gto_basis_set_type), POINTER                  :: basis
     705           20 :       TYPE(particle_type), POINTER                       :: particles(:)
     706           20 :       TYPE(qs_kind_type), POINTER                        :: qs_kinds(:)
     707              : 
     708           20 :       CALL get_qs_env(qs_env, particle_set=particles, qs_kind_set=qs_kinds)
     709          476 :       charge = z_zero
     710           20 :       first = 0
     711           60 :       DO iatom = 1, SIZE(particles)
     712              :          CALL get_qs_kind(qs_kinds(particles(iatom)%atomic_kind%kind_number), &
     713           40 :                           basis_set=basis, basis_type='RI_AUX')
     714          104 :          DO iset = 1, basis%nset
     715           64 :             lmax = basis%lmax(iset)
     716           64 :             ncart = ncoset(lmax)
     717          320 :             ALLOCATE (moments(0:lmax), primitive(ncart*basis%npgf(iset)))
     718           64 :             primitive = 0.0_dp
     719          352 :             DO ipgf = 1, basis%npgf(iset)
     720          288 :                alpha = basis%zet(ipgf, iset)
     721          288 :                moments = 0.0_dp
     722          288 :                moments(0) = SQRT(pi/alpha)
     723          288 :                DO il = 2, lmax, 2
     724          288 :                   moments(il) = REAL(il - 1, dp)*moments(il - 2)/(2.0_dp*alpha)
     725              :                END DO
     726          832 :                DO ico = ncoset(basis%lmin(iset) - 1) + 1, ncart
     727         2208 :                   primitive((ipgf - 1)*ncart + ico) = PRODUCT(moments(indco(:, ico)))
     728              :                END DO
     729              :             END DO
     730           64 :             offset = basis%first_sgf(1, iset)
     731          520 :             DO isgf = offset, offset + basis%nsgf_set(iset) - 1
     732         4192 :                charge(first + isgf) = CMPLX(SUM(basis%sphi(1:SIZE(primitive), isgf)*primitive), 0.0_dp, dp)
     733              :             END DO
     734          104 :             DEALLOCATE (moments, primitive)
     735              :          END DO
     736           60 :          first = first + basis%nsgf
     737              :       END DO
     738           20 :       CPASSERT(first == SIZE(charge))
     739              : 
     740           40 :    END SUBROUTINE gamma_auxiliary_charges
     741              : 
     742              : ! **************************************************************************************************
     743              : !> \brief Return the contiguous part of 1..n owned by one rank of a block distribution.
     744              : !> \param n Number of distributed items (grid rows or unordered grid pairs).
     745              : !> \param rank ...
     746              : !> \param n_rank ...
     747              : !> \param first First owned item.
     748              : !> \param n_local Number of owned items.
     749              : ! **************************************************************************************************
     750          932 :    PURE SUBROUTINE block_range(n, rank, n_rank, first, n_local)
     751              :       INTEGER, INTENT(IN)                                :: n, rank, n_rank
     752              :       INTEGER, INTENT(OUT)                               :: first, n_local
     753              : 
     754          932 :       first = INT(INT(n, int_8)*rank/n_rank) + 1
     755          932 :       n_local = INT(INT(n, int_8)*(rank + 1)/n_rank) - first + 1
     756              : 
     757          932 :    END SUBROUTINE block_range
     758              : 
     759              : END MODULE gw_ri_rs_small_cell_full_kp_lattice
        

Generated by: LCOV version 2.0-1