LCOV - code coverage report
Current view: top level - src - kpoint_transform.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 79.4 % 1205 957
Test Date: 2026-11-24 01:22:08 Functions: 67.5 % 40 27

            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 Prepared real-space/reciprocal-space transforms and distributed AO adapters.
      10              : !>        Routes fix geometry and ownership. Captured source rows own numerical
      11              : !>        values; cached evaluation reads them without communication or SCF state.
      12              : ! **************************************************************************************************
      13              : MODULE kpoint_transform
      14              :    USE cp_cfm_types,                    ONLY: cp_cfm_type
      15              :    USE cp_dbcsr_api,                    ONLY: dbcsr_get_block_p,&
      16              :                                               dbcsr_get_info,&
      17              :                                               dbcsr_get_readonly_block_p,&
      18              :                                               dbcsr_p_type,&
      19              :                                               dbcsr_set,&
      20              :                                               dbcsr_type
      21              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_equivalent,&
      22              :                                               cp_fm_struct_release,&
      23              :                                               cp_fm_struct_retain,&
      24              :                                               cp_fm_struct_type
      25              :    USE cp_fm_types,                     ONLY: cp_fm_p_type,&
      26              :                                               cp_fm_type
      27              :    USE cp_log_handling,                 ONLY: cp_logger_get_default_io_unit
      28              :    USE input_constants,                 ONLY: rskp_backend_fft,&
      29              :                                               rskp_backend_gemm
      30              :    USE kinds,                           ONLY: dp,&
      31              :                                               int_8
      32              :    USE kpoint_lattice_fft,              ONLY: cell_to_k_grid_fft,&
      33              :                                               cell_to_k_grid_prepare,&
      34              :                                               cell_to_k_grid_release,&
      35              :                                               cell_to_k_grid_work_type,&
      36              :                                               lattice_fft_profile_type
      37              :    USE local_gemm_api,                  ONLY: local_gemm_ctxt_type
      38              :    USE machine,                         ONLY: m_walltime
      39              :    USE mathconstants,                   ONLY: twopi,&
      40              :                                               z_one,&
      41              :                                               z_zero
      42              :    USE message_passing,                 ONLY: mp_para_env_type
      43              :    USE qs_neighbor_list_types,          ONLY: get_iterator_info,&
      44              :                                               get_neighbor_list_set_p,&
      45              :                                               neighbor_list_iterate,&
      46              :                                               neighbor_list_iterator_create,&
      47              :                                               neighbor_list_iterator_p_type,&
      48              :                                               neighbor_list_iterator_release,&
      49              :                                               neighbor_list_set_p_type
      50              :    USE util,                            ONLY: locate,&
      51              :                                               sort
      52              : 
      53              : !$ USE omp_lib, ONLY: omp_get_max_threads, omp_get_thread_num, omp_get_num_threads
      54              : #include "./base/base_uses.f90"
      55              : 
      56              :    IMPLICIT NONE
      57              :    PRIVATE
      58              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'kpoint_transform'
      59              :    INTEGER(KIND=int_8), PARAMETER :: fft_batch_bytes = 32_int_8*1024_int_8**2
      60              :    INTEGER(KIND=int_8), PARAMETER :: rskp_panel_bytes = 64_int_8*1024_int_8**2
      61              :    CHARACTER(LEN=14), PARAMETER :: fft_profile_stages(9) = [CHARACTER(LEN=14) :: &
      62              :                    'initialize', 'geometry', 'buffers', 'grid-fill', 'FFT-X/plan', 'FFT-Y/plan', 'FFT-Z/plan', 'extract', 'release']
      63              :    INTEGER(KIND=int_8), PARAMETER, PRIVATE :: rskp_gemm_bytes = 1000_int_8*1024_int_8**2, &
      64              :                                               dbcsr_batch_bytes = 1000_int_8*1024_int_8**2
      65              :    PUBLIC :: k_grid_to_cell_phase_type
      66              :    PUBLIC :: kp_transform_plan_type, kp_transform_plan_create, rskp_route_type, rskp_values_type
      67              :    PUBLIC :: rskp_route_create, rskp_route_release, rskp_capture, rskp_compatible, rskp_values_release
      68              :    PUBLIC :: rskp_backend_gemm, rskp_backend_fft, cell_to_k_backend_prepare
      69              :    PUBLIC :: rskp_batch_size, cell_to_k_backend_evaluate_batch
      70              :    PUBLIC :: rskp_dbcsr_transform_batch
      71              :    PUBLIC :: rskp_prepared_transform_type, rskp_transform_prepare
      72              :    PUBLIC :: rskp_transform_evaluate, rskp_transform_release
      73              :    PUBLIC :: rskp_transform
      74              :    PUBLIC :: cell_to_k_sparse_fft, k_grid_to_cell_contract, rskp_phase_factors, rskp_work_matrix
      75              :    PUBLIC :: k_grid_to_cell_phase_prepare
      76              :    PUBLIC :: cell_to_k_transform
      77              : 
      78              :    ! Unweighted one-dimensional phases for one symmetry group's local k domain.
      79              :    TYPE :: k_grid_to_cell_phase_type
      80              :       INTEGER :: first(4) = 1
      81              :       INTEGER, ALLOCATABLE :: coordinate(:)
      82              :       REAL(KIND=dp), ALLOCATABLE :: cosine(:, :), sine(:, :)
      83              :    END TYPE k_grid_to_cell_phase_type
      84              : 
      85              :    TYPE :: kp_transform_plan_type
      86              :       INTEGER :: nentry = 0, ngroup = 0
      87              :       LOGICAL :: symmetric = .FALSE.
      88              :       INTEGER, ALLOCATABLE, DIMENSION(:) :: col, col_offset, group_start, image, row, row_offset
      89              :       INTEGER, ALLOCATABLE, DIMENSION(:, :) :: cell
      90              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:) :: symmetry_sign
      91              :    END TYPE kp_transform_plan_type
      92              : 
      93              :    ! Numerical plans borrow no FM, DBCSR or SCF objects.
      94              :    TYPE rskp_backend_plan_type
      95              :       INTEGER :: backend = rskp_backend_gemm
      96              :       INTEGER, ALLOCATABLE :: packed_first(:), fold_map(:, :)
      97              :       INTEGER, ALLOCATABLE :: phase_index(:), phase_cells(:, :), phase_count(:, :), phase_first(:)
      98              :       INTEGER(KIND=int_8) :: max_per_k = 0_int_8
      99              :       REAL(KIND=dp), ALLOCATABLE :: phases(:, :, :)
     100              :       TYPE(cell_to_k_grid_work_type) :: fft_work = cell_to_k_grid_work_type()
     101              :    END TYPE rskp_backend_plan_type
     102              : 
     103              :    ! Stable canonical AO route and destination mapping, shared by both backends.
     104              :    TYPE rskp_route_type
     105              :       TYPE(cp_fm_struct_type), POINTER :: matrix_struct => NULL()
     106              :       TYPE(mp_para_env_type), POINTER :: world => NULL(), group => NULL(), inter => NULL()
     107              :       TYPE(kp_transform_plan_type) :: traversal = kp_transform_plan_type()
     108              :       TYPE(neighbor_list_set_p_type), POINTER :: source_sab(:) => NULL()
     109              :       TYPE(rskp_backend_plan_type) :: transform = rskp_backend_plan_type()
     110              :       INTEGER :: nrow = 0, ncol = 0, nimage = 0, nvalue = 0
     111              :       LOGICAL :: world_target = .FALSE.
     112              :       INTEGER(KIND=int_8) :: storage = 0_int_8
     113              :       INTEGER, ALLOCATABLE :: entry(:, :), block_first(:), block_order(:), element_first(:)
     114              :       INTEGER(KIND=int_8), ALLOCATABLE :: element_offset(:, :)
     115              :       INTEGER, ALLOCATABLE :: row_size(:), col_size(:), first(:)
     116              :       INTEGER, ALLOCATABLE :: send_entry(:), send_first(:), scount(:, :), rcount(:, :), &
     117              :                               sdisp(:, :), rdisp(:, :), send_element(:)
     118              :       REAL(KIND=dp), ALLOCATABLE :: send_values(:), recv_values(:)
     119              :    END TYPE rskp_route_type
     120              : 
     121              :    ! One source row: backend payload plus the source identity used by adapters.
     122              :    TYPE rskp_values_type
     123              :       REAL(KIND=dp), ALLOCATABLE :: packed(:)
     124              :       LOGICAL, ALLOCATABLE :: active(:, :)
     125              :       ! Unscaled canonical elements by local k; mirrors and FM padding are not stored.
     126              :       COMPLEX(KIND=dp), ALLOCATABLE :: fft_values(:, :)
     127              :       TYPE(dbcsr_p_type), POINTER :: source(:, :) => NULL()
     128              :       INTEGER :: matrix_row = 0, mirror_sign = 1
     129              :       COMPLEX(KIND=dp) :: scale = z_one
     130              :    END TYPE rskp_values_type
     131              : 
     132              :    ! Slot-free owner for captured source rows sharing one target-local R-to-K map.
     133              :    TYPE :: rskp_prepared_transform_type
     134              :       PRIVATE
     135              :       TYPE(rskp_route_type) :: route = rskp_route_type()
     136              :       TYPE(rskp_values_type), ALLOCATABLE :: values(:)
     137              :       INTEGER, ALLOCATABLE :: kp_dist(:, :)
     138              :       REAL(KIND=dp), ALLOCATABLE :: work(:)
     139              :    END TYPE rskp_prepared_transform_type
     140              : 
     141              : CONTAINS
     142              : 
     143              : ! **************************************************************************************************
     144              : !> \brief Transform local real matrix panels with the selected RSKP backend.
     145              : !>        GEMM reuses the prepared parity folding and block contraction. FFT reuses one geometry
     146              : !>        across bounded matrix tiles. Both accept rectangular panels and regular-grid subsets.
     147              : !>        Input and output may be strided; only the internal GEMM panels are contiguous.
     148              : !>        Call outside OpenMP worker regions; this service owns its numerical workspace.
     149              : !> \param values_rs real matrices, with one image per third-dimension column
     150              : !> \param cells lattice translations of the images
     151              : !> \param xkp requested reciprocal coordinates, in output order
     152              : !> \param nkp_grid mesh dimensions for FFT
     153              : !> \param values_k complex transformed matrices
     154              : !> \param backend GEMM or FFT
     155              : !> \param accumulate add this image panel to an existing output
     156              : !> \param profile_fft print local FFT stage times on the logger rank, without MPI collectives
     157              : !> \param profile_label identify the caller operation in the optional FFT profile
     158              : ! **************************************************************************************************
     159          184 :    SUBROUTINE cell_to_k_transform(values_rs, cells, xkp, nkp_grid, values_k, backend, accumulate, &
     160              :                                   profile_fft, profile_label)
     161              :       REAL(KIND=dp), INTENT(IN)                          :: values_rs(:, :, :)
     162              :       INTEGER, INTENT(IN)                                :: cells(:, :)
     163              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
     164              :       INTEGER, INTENT(IN)                                :: nkp_grid(3)
     165              :       COMPLEX(KIND=dp), INTENT(INOUT)                    :: values_k(:, :, :)
     166              :       INTEGER, INTENT(IN)                                :: backend
     167              :       LOGICAL, INTENT(IN), OPTIONAL                      :: accumulate, profile_fft
     168              :       CHARACTER(LEN=*), INTENT(IN), OPTIONAL             :: profile_label
     169              : 
     170              :       INTEGER :: column, count, first_column, first_row, handle, i, image, kfirst, last, &
     171              :          last_column, matrix_rows, nk, nphase, nrow, ntile, nworkers, odd, offset, omp_limit, &
     172              :          panels(4), pos, row, sense, start, unit_nr, width
     173              :       INTEGER(KIND=int_8)                                :: cache_bytes, ifirst, nvalues, &
     174              :                                                             worker_bytes
     175              :       LOGICAL                                            :: active(4), add, measure_fft
     176              :       REAL(KIND=dp)                                      :: profile_started, started
     177          368 :       REAL(KIND=dp), ALLOCATABLE                         :: factors(:, :), packed(:), RESULT(:, :)
     178          184 :       TYPE(lattice_fft_profile_type), ALLOCATABLE        :: fft_profile
     179          736 :       TYPE(rskp_backend_plan_type)                       :: plan
     180              : 
     181          184 :       CALL timeset('cell_to_k_transform', handle)
     182          184 :       measure_fft = .FALSE.
     183          184 :       IF (PRESENT(profile_fft)) measure_fft = profile_fft .AND. backend == rskp_backend_fft
     184              :       IF (measure_fft) THEN
     185            0 :          ALLOCATE (fft_profile)
     186            0 :          profile_started = m_walltime()
     187              :       END IF
     188          184 :       CPASSERT(SIZE(cells, 1) == 3 .AND. SIZE(xkp, 1) == 3)
     189          184 :       CPASSERT(SIZE(cells, 2) == SIZE(values_rs, 3))
     190          184 :       CPASSERT(SIZE(values_k, 1) == SIZE(values_rs, 1))
     191          184 :       CPASSERT(SIZE(values_k, 2) == SIZE(values_rs, 2))
     192          184 :       nk = SIZE(xkp, 2)
     193          184 :       CPASSERT(SIZE(values_k, 3) == nk)
     194          184 :       add = .FALSE.
     195          184 :       IF (PRESENT(accumulate)) add = accumulate
     196              :       ! A nonempty FFT overwrites its output; GEMM and empty image sums need zeros.
     197       125204 :       IF (.NOT. add .AND. (backend /= rskp_backend_fft .OR. SIZE(values_rs, KIND=int_8) == 0)) values_k = z_zero
     198          184 :       IF (measure_fft) fft_profile%seconds(1) = m_walltime() - profile_started
     199          736 :       IF (SIZE(values_rs, KIND=int_8) == 0 .OR. nk == 0) THEN
     200            0 :          CALL timestop(handle)
     201            0 :          RETURN
     202              :       END IF
     203          184 :       SELECT CASE (backend)
     204              :       CASE (rskp_backend_fft)
     205              :          CALL cell_to_k_grid_fft(values_rs, cells, xkp, nkp_grid, values_k, &
     206            0 :                                  require_fft=.TRUE., accumulate=add, profile=fft_profile)
     207              :       CASE (rskp_backend_gemm)
     208          184 :          nvalues = SIZE(values_rs, 1, KIND=int_8)*SIZE(values_rs, 2, KIND=int_8)
     209          184 :          matrix_rows = SIZE(values_rs, 1)
     210          184 :          nworkers = 1
     211          184 : !$       nworkers = omp_get_max_threads()
     212          184 :          worker_bytes = rskp_panel_bytes/(2*nworkers)
     213              :          ntile = INT(MIN(nvalues, 4096_int_8, &
     214          184 :                          MAX(1_int_8, worker_bytes/(16_int_8*(SIZE(cells, 2, KIND=int_8) + 1)))))
     215              :          CALL cell_to_k_phase_prepare(plan, cells, [1, SIZE(cells, 2) + 1], &
     216              :                                       [(image, image=1, SIZE(cells, 2))], [1, ntile + 1], &
     217        71532 :                                       xkp, rskp_panel_bytes/2, 0_int_8)
     218          184 :          cache_bytes = 0_int_8
     219          736 :          IF (ALLOCATED(plan%phases)) cache_bytes = 8_int_8*SIZE(plan%phases, KIND=int_8)
     220              :          worker_bytes = (rskp_panel_bytes - cache_bytes)/nworkers - &
     221          184 :                         8_int_8*(plan%packed_first(2) - 1)
     222          184 :          width = INT(MIN(INT(nk, int_8), MAX(1_int_8, worker_bytes/(16_int_8*plan%max_per_k))))
     223          552 :          nphase = MAXVAL(plan%phase_count(1:2, 1))
     224          920 :          panels = plan%phase_count([1, 1, 2, 3], 1)
     225              : !$OMP PARALLEL DEFAULT(NONE) &
     226              : !$OMP SHARED(values_rs, values_k, matrix_rows, nvalues, xkp, plan, ntile, nphase, panels, nk, width) &
     227              : !$OMP PRIVATE(packed, factors, result, ifirst, last, nrow, image, pos, odd, sense, start, active, i, kfirst) &
     228          184 : !$OMP PRIVATE(first_row, first_column, last_column, column, row, count, offset)
     229              :          ALLOCATE (packed(plan%packed_first(2) - 1), factors(nphase, 2*width), RESULT(ntile, 2*width))
     230              : !$OMP DO SCHEDULE(STATIC)
     231              :          DO ifirst = 1, nvalues, ntile
     232              :             nrow = INT(MIN(INT(ntile, int_8), nvalues - ifirst + 1))
     233              :             first_row = INT(MODULO(ifirst - 1, INT(matrix_rows, int_8))) + 1
     234              :             first_column = INT((ifirst - 1)/INT(matrix_rows, int_8)) + 1
     235              :             last_column = INT((ifirst + INT(nrow, int_8) - 2)/INT(matrix_rows, int_8)) + 1
     236              :             packed(:) = 0.0_dp
     237              :             DO image = 1, SIZE(values_rs, 3)
     238              :                pos = plan%fold_map(1, image)
     239              :                odd = ABS(plan%fold_map(2, image))
     240              :                sense = SIGN(1, plan%fold_map(2, image))
     241              :                ! Split the flattened tile into column-local row spans. Array descriptors
     242              :                ! retain the caller's strides, including a partial first-dimension chunk.
     243              :                offset = 0
     244              :                row = first_row
     245              :                DO column = first_column, last_column
     246              :                   count = MIN(nrow - offset, matrix_rows - row + 1)
     247              :                   packed(pos + offset:pos + offset + count - 1) = &
     248              :                      packed(pos + offset:pos + offset + count - 1) + values_rs(row:row + count - 1, column, image)
     249              :                   IF (odd > 0) THEN
     250              :                      packed(odd + offset:odd + offset + count - 1) = &
     251              :                         packed(odd + offset:odd + offset + count - 1) + &
     252              :                         REAL(sense, dp)*values_rs(row:row + count - 1, column, image)
     253              :                   END IF
     254              :                   offset = offset + count
     255              :                   row = 1
     256              :                END DO
     257              :             END DO
     258              :             active = .FALSE.
     259              :             start = 1
     260              :             DO i = 1, 4
     261              :                IF (panels(i) > 0) active(i) = ANY(packed(start:start + ntile*panels(i) - 1) /= 0.0_dp)
     262              :                start = start + ntile*panels(i)
     263              :             END DO
     264              :             DO kfirst = 1, nk, width
     265              :                last = MIN(kfirst + width - 1, nk)
     266              :                CALL cell_to_k_block_gemm(packed, plan, 1, xkp(:, kfirst:last), kfirst, &
     267              :                                          factors(:, 1:2*(last - kfirst + 1)), &
     268              :                                          RESULT(:, 1:2*(last - kfirst + 1)), active)
     269              :                offset = 0
     270              :                row = first_row
     271              :                DO column = first_column, last_column
     272              :                   count = MIN(nrow - offset, matrix_rows - row + 1)
     273              :                   values_k(row:row + count - 1, column, kfirst:last) = &
     274              :                      values_k(row:row + count - 1, column, kfirst:last) + &
     275              :                      CMPLX(RESULT(offset + 1:offset + count, 1:last - kfirst + 1), &
     276              :                            RESULT(offset + 1:offset + count, last - kfirst + 2:2*(last - kfirst + 1)), KIND=dp)
     277              :                   offset = offset + count
     278              :                   row = 1
     279              :                END DO
     280              :             END DO
     281              :          END DO
     282              : !$OMP END DO
     283              :          DEALLOCATE (packed, factors, RESULT)
     284              : !$OMP END PARALLEL
     285              :       CASE DEFAULT
     286          184 :          CPABORT('Unknown R-to-K backend')
     287              :       END SELECT
     288          184 :       IF (measure_fft) THEN
     289            0 :          started = m_walltime() - profile_started
     290            0 :          unit_nr = cp_logger_get_default_io_unit()
     291              :          omp_limit = 1
     292            0 : !$       omp_limit = omp_get_max_threads()
     293            0 :          IF (unit_nr > 0) THEN
     294            0 :             WRITE (unit_nr, '(T2,A)') 'R2K_FFT_PROFILE| Local panels; logger-rank wall seconds, no MPI reduction'
     295            0 :             IF (PRESENT(profile_label)) WRITE (unit_nr, '(T2,A,A)') 'R2K_FFT_PROFILE| operation: ', TRIM(profile_label)
     296            0 :             WRITE (unit_nr, '(T2,A,3I10)') 'R2K_FFT_PROFILE| source shape: ', SHAPE(values_rs)
     297            0 :             WRITE (unit_nr, '(T2,A,6I8)') 'R2K_FFT_PROFILE| grid / padded: ', nkp_grid, fft_profile%nfft
     298            0 :             WRITE (unit_nr, '(T2,A,2I16,2I8)') 'R2K_FFT_PROFILE| elements/batches/tile min/max: ', &
     299            0 :                fft_profile%elements, fft_profile%batches, fft_profile%tile_min, fft_profile%tile_max
     300            0 :             WRITE (unit_nr, '(T2,A,I8,2L3)') 'R2K_FFT_PROFILE| FFT OpenMP limit / input,output contiguous: ', &
     301            0 :                omp_limit, IS_CONTIGUOUS(values_rs), IS_CONTIGUOUS(values_k)
     302            0 :             IF (fft_profile%pair_major) WRITE (unit_nr, '(T2,A)') &
     303            0 :                'R2K_FFT_PROFILE| FFT-X/plan reports full 3D batched FFT (Y/Z entries zero)'
     304              :             WRITE (unit_nr, '(T2,A)') &
     305            0 :                'R2K_FFT_PROFILE| grid-fill/extract use size-gated OpenMP; FFT axes include one-shot planning'
     306            0 :             DO i = 1, SIZE(fft_profile_stages)
     307            0 :                WRITE (unit_nr, '(T2,A,A14,F14.6)') 'R2K_FFT_PROFILE| ', fft_profile_stages(i), fft_profile%seconds(i)
     308              :             END DO
     309            0 :             WRITE (unit_nr, '(T2,A,F14.6)') 'R2K_FFT_PROFILE| total         ', started
     310              :          END IF
     311              :       END IF
     312          184 :       CALL timestop(handle)
     313          184 :    END SUBROUTINE cell_to_k_transform
     314              : 
     315              : ! **************************************************************************************************
     316              : !> \brief Transformation of real space matrices to a kpoint
     317              : !> \param rmatrix  Real part of kpoint matrix
     318              : !> \param cmatrix  Complex part of kpoint matrix (optional)
     319              : !> \param rsmat    Real space matrices
     320              : !> \param ispin    Spin index
     321              : !> \param xkp      Kpoint coordinates
     322              : !> \param cell_to_index   mapping of cell indices to RS index
     323              : !> \param sab_nl   Defining neighbor list
     324              : !> \param is_complex  Matrix to be transformed is imaginary
     325              : !> \param rs_sign  Matrix to be transformed is csaled by rs_sign
     326              : ! **************************************************************************************************
     327        31052 :    SUBROUTINE rskp_transform(rmatrix, cmatrix, rsmat, ispin, &
     328              :                              xkp, cell_to_index, sab_nl, is_complex, rs_sign)
     329              : 
     330              :       TYPE(dbcsr_type)                                   :: rmatrix
     331              :       TYPE(dbcsr_type), OPTIONAL                         :: cmatrix
     332              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rsmat
     333              :       INTEGER, INTENT(IN)                                :: ispin
     334              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: xkp
     335              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
     336              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     337              :          POINTER                                         :: sab_nl
     338              :       LOGICAL, INTENT(IN), OPTIONAL                      :: is_complex
     339              :       REAL(KIND=dp), INTENT(IN), OPTIONAL                :: rs_sign
     340              : 
     341              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'rskp_transform'
     342              : 
     343              :       INTEGER                                            :: handle, iatom, ic, icol, irow, jatom, &
     344              :                                                             nimg
     345              :       INTEGER, DIMENSION(3)                              :: cell
     346              :       LOGICAL                                            :: do_symmetric, found, my_complex, &
     347              :                                                             wfn_real_only
     348              :       REAL(KIND=dp)                                      :: arg, coskl, fsign, fsym, sinkl
     349        15526 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: cblock, rblock, rsblock
     350              :       TYPE(neighbor_list_iterator_p_type), &
     351        15526 :          DIMENSION(:), POINTER                           :: nl_iterator
     352              : 
     353        15526 :       CALL timeset(routineN, handle)
     354              : 
     355        15526 :       my_complex = .FALSE.
     356        15526 :       IF (PRESENT(is_complex)) my_complex = is_complex
     357              : 
     358        15526 :       fsign = 1.0_dp
     359        15526 :       IF (PRESENT(rs_sign)) fsign = rs_sign
     360              : 
     361        15526 :       wfn_real_only = .TRUE.
     362        15526 :       IF (PRESENT(cmatrix)) wfn_real_only = .FALSE.
     363              : 
     364        15526 :       nimg = SIZE(rsmat, 2)
     365              : 
     366        15526 :       CALL get_neighbor_list_set_p(neighbor_list_sets=sab_nl, symmetric=do_symmetric)
     367              : 
     368        15526 :       CALL neighbor_list_iterator_create(nl_iterator, sab_nl)
     369     13631647 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
     370     13616121 :          CALL get_iterator_info(nl_iterator, iatom=iatom, jatom=jatom, cell=cell)
     371              : 
     372              :          ! fsym = +- 1 is due to real space matrices being non-symmetric (although in a symmtric type)
     373              :          ! with the link S_mu^0,nu^b = S_nu^0,mu^-b, and the KP matrices beeing Hermitian
     374     13616121 :          fsym = 1.0_dp
     375     13616121 :          irow = iatom
     376     13616121 :          icol = jatom
     377     13616121 :          IF (do_symmetric .AND. (iatom > jatom)) THEN
     378      5877441 :             irow = jatom
     379      5877441 :             icol = iatom
     380      5877441 :             fsym = -1.0_dp
     381              :          END IF
     382              : 
     383     13616121 :          ic = cell_to_index(cell(1), cell(2), cell(3))
     384     13616121 :          IF (ic < 1 .OR. ic > nimg) CYCLE
     385              : 
     386     13616121 :          arg = REAL(cell(1), dp)*xkp(1) + REAL(cell(2), dp)*xkp(2) + REAL(cell(3), dp)*xkp(3)
     387     13616121 :          IF (my_complex) THEN
     388            0 :             coskl = fsign*fsym*COS(twopi*arg)
     389            0 :             sinkl = fsign*SIN(twopi*arg)
     390              :          ELSE
     391     13616121 :             coskl = fsign*COS(twopi*arg)
     392     13616121 :             sinkl = fsign*fsym*SIN(twopi*arg)
     393              :          END IF
     394              : 
     395              :          CALL dbcsr_get_block_p(matrix=rsmat(ispin, ic)%matrix, row=irow, col=icol, &
     396     13616121 :                                 block=rsblock, found=found)
     397     13616121 :          IF (.NOT. found) CYCLE
     398              : 
     399     13631647 :          IF (wfn_real_only) THEN
     400              :             CALL dbcsr_get_block_p(matrix=rmatrix, row=irow, col=icol, &
     401         7536 :                                    block=rblock, found=found)
     402         7536 :             IF (.NOT. found) CYCLE
     403      2750640 :             rblock = rblock + coskl*rsblock
     404              :          ELSE
     405              :             CALL dbcsr_get_block_p(matrix=rmatrix, row=irow, col=icol, &
     406     13608585 :                                    block=rblock, found=found)
     407     13608585 :             IF (.NOT. found) CYCLE
     408              :             CALL dbcsr_get_block_p(matrix=cmatrix, row=irow, col=icol, &
     409     13608585 :                                    block=cblock, found=found)
     410     13608585 :             IF (.NOT. found) CYCLE
     411   1494753869 :             rblock = rblock + coskl*rsblock
     412   1494753869 :             cblock = cblock + sinkl*rsblock
     413              :          END IF
     414              : 
     415              :       END DO
     416        15526 :       CALL neighbor_list_iterator_release(nl_iterator)
     417              : 
     418        15526 :       CALL timestop(handle)
     419              : 
     420        15526 :    END SUBROUTINE rskp_transform
     421              : 
     422              : ! **************************************************************************************************
     423              : !> \brief Prepare source rows for a generic group- or world-distributed target.
     424              : !>        GEMM retains sparse snapshots and sizes k tiles against a workspace target.
     425              : !>        Own route, snapshots, singleton scratch and any FFT cache without SCF slots.
     426              : !> \param prepared transform handle to initialize
     427              : !> \param source real-space source rows and images
     428              : !> \param source_rows source rows sharing the route/backend plan
     429              : !> \param source_sab neighbor-list geometry of source
     430              : !> \param cell_to_index translation-to-image map
     431              : !> \param target_struct output matrix layout
     432              : !> \param world source-matrix communicator
     433              : !> \param group optional target-group communicator; omit for a world target
     434              : !> \param inter optional communicator joining equivalent group ranks; omit for a world target
     435              : !> \param backend selected GEMM or FFT backend
     436              : !> \param xkp full global k-point coordinates
     437              : !> \param nkp_grid regular-grid dimensions
     438              : !> \param kp_dist optional global k ranges by inter-group rank; omit for a world target
     439              : !> \param mirror_sign transpose parity (+1 Hermitian, -1 anti-Hermitian)
     440              : !> \param scale complex prefactor applied to direct and mirrored contributions
     441              : ! **************************************************************************************************
     442         1414 :    SUBROUTINE rskp_transform_prepare(prepared, source, source_rows, source_sab, cell_to_index, target_struct, &
     443         1414 :                                      world, group, inter, backend, xkp, nkp_grid, kp_dist, mirror_sign, scale)
     444              : 
     445              :       TYPE(rskp_prepared_transform_type), INTENT(INOUT)  :: prepared
     446              :       TYPE(dbcsr_p_type), POINTER                        :: source(:, :)
     447              :       INTEGER, INTENT(IN)                                :: source_rows(:)
     448              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     449              :          POINTER                                         :: source_sab
     450              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
     451              :       TYPE(cp_fm_struct_type), POINTER                   :: target_struct
     452              :       TYPE(mp_para_env_type), POINTER                    :: world
     453              :       TYPE(mp_para_env_type), OPTIONAL, POINTER          :: group, inter
     454              :       INTEGER, INTENT(IN)                                :: backend
     455              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
     456              :       INTEGER, INTENT(IN)                                :: nkp_grid(3)
     457              :       INTEGER, INTENT(IN), OPTIONAL                      :: kp_dist(:, :), mirror_sign
     458              :       COMPLEX(KIND=dp), INTENT(IN), OPTIONAL             :: scale
     459              : 
     460              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'rskp_transform_prepare'
     461              : 
     462              :       INTEGER                                            :: first, handle, irow, nk_local
     463              :       INTEGER(KIND=int_8)                                :: max_backend_bytes
     464         1414 :       INTEGER, ALLOCATABLE                               :: eval_kp_dist(:, :)
     465              :       LOGICAL                                            :: ready
     466         1414 :       REAL(KIND=dp), ALLOCATABLE                         :: phase_xkp(:, :)
     467              :       TYPE(mp_para_env_type), POINTER                    :: eval_group, eval_inter
     468              : 
     469         1414 :       CALL timeset(routineN, handle)
     470         1414 :       CALL rskp_transform_release(prepared)
     471         1414 :       CPASSERT(SIZE(source_rows) > 0)
     472         4366 :       CPASSERT(ALL(source_rows >= 1) .AND. ALL(source_rows <= SIZE(source, 1)))
     473         1414 :       CPASSERT(SIZE(xkp, 1) == 3 .AND. SIZE(xkp, 2) > 0)
     474         1414 :       CPASSERT(ASSOCIATED(target_struct) .AND. ASSOCIATED(world))
     475         1414 :       IF (PRESENT(group) .EQV. PRESENT(inter)) THEN
     476         1414 :          IF (PRESENT(group)) THEN
     477          810 :             CPASSERT(PRESENT(kp_dist))
     478          810 :             CPASSERT(ASSOCIATED(group) .AND. ASSOCIATED(inter))
     479          810 :             eval_group => group
     480          810 :             eval_inter => inter
     481              :          ELSE
     482          604 :             CPASSERT(.NOT. PRESENT(kp_dist))
     483          604 :             CPASSERT(ASSOCIATED(target_struct%para_env, world))
     484          604 :             eval_group => world
     485          604 :             eval_inter => world
     486              :          END IF
     487              :       ELSE
     488            0 :          CPABORT("R-to-K group and inter communicators must be supplied together")
     489              :       END IF
     490         1414 :       IF (PRESENT(kp_dist)) THEN
     491          810 :          CPASSERT(SIZE(kp_dist, 1) == 2)
     492         7524 :          ALLOCATE (eval_kp_dist, source=kp_dist)
     493              :       ELSE
     494          604 :          ALLOCATE (eval_kp_dist(2, 1))
     495         1812 :          eval_kp_dist(:, 1) = [1, SIZE(xkp, 2)]
     496              :       END IF
     497         1414 :       max_backend_bytes = rskp_gemm_bytes
     498         1414 :       IF (backend == rskp_backend_fft) max_backend_bytes = rskp_panel_bytes
     499        11752 :       ALLOCATE (prepared%kp_dist, source=eval_kp_dist)
     500         5718 :       ALLOCATE (prepared%values(SIZE(source_rows)))
     501              :       CALL rskp_route_create(source, source_sab, cell_to_index, target_struct, world, eval_group, eval_inter, backend, &
     502         1414 :                              prepared%route, ready)
     503         1414 :       IF (.NOT. ready) THEN
     504            0 :          CPABORT("R-to-K route has an incompatible source or target layout")
     505              :       END IF
     506              : 
     507         1414 :       IF (backend == rskp_backend_fft .OR. prepared%route%world_target) THEN
     508          626 :          CALL cell_to_k_backend_prepare(prepared%route, xkp, nkp_grid, max_backend_bytes)
     509              :       ELSE
     510          788 :          first = eval_kp_dist(1, eval_inter%mepos + 1)
     511        19480 :          ALLOCATE (phase_xkp, source=xkp(:, first:eval_kp_dist(2, eval_inter%mepos + 1)))
     512          788 :          CALL cell_to_k_backend_prepare(prepared%route, phase_xkp, nkp_grid, max_backend_bytes)
     513              :       END IF
     514         2890 :       DO irow = 1, SIZE(source_rows)
     515         2890 :          CALL rskp_capture(source, source_rows(irow), prepared%route, prepared%values(irow), mirror_sign, scale)
     516              :       END DO
     517         1414 :       IF (backend == rskp_backend_fft) THEN
     518           10 :          nk_local = SIZE(xkp, 2)
     519           10 :          IF (.NOT. prepared%route%world_target) THEN
     520              :             nk_local = eval_kp_dist(2, eval_inter%mepos + 1) - &
     521           10 :                        eval_kp_dist(1, eval_inter%mepos + 1) + 1
     522              :          END IF
     523           20 :          DO irow = 1, SIZE(source_rows)
     524            0 :             ALLOCATE (prepared%values(irow)%fft_values( &
     525           40 :                       prepared%route%element_first(SIZE(prepared%route%element_first)) - 1, nk_local))
     526              :             CALL cell_to_k_sparse_fft(prepared%values(irow), prepared%route, xkp, nkp_grid, &
     527              :                                       eval_kp_dist, eval_inter, &
     528           10 :                                       max_backend_bytes, cache=prepared%values(irow)%fft_values)
     529           20 :             DEALLOCATE (prepared%values(irow)%packed)
     530              :          END DO
     531           10 :          ALLOCATE (prepared%work(0))
     532              :       ELSE
     533         4212 :          ALLOCATE (prepared%work(2_int_8*prepared%route%transform%max_per_k))
     534              :       END IF
     535         1414 :       CALL timestop(handle)
     536         4242 :    END SUBROUTINE rskp_transform_prepare
     537              : 
     538              : ! **************************************************************************************************
     539              : !> \brief Evaluate one k point directly into an FM, split-FM or CFM target.
     540              : !>        The handle owns mutable scratch; concurrent evaluations need separate handles.
     541              : !>        Evaluation uses the batch backend with width one and no communication.
     542              : !>        Groups that do not own the requested global k point leave outputs unchanged.
     543              : !> \param prepared initialized transform handle
     544              : !> \param source_index one-based source row index supplied at preparation
     545              : !> \param k global k-point index
     546              : !> \param xkp full global k-point coordinates
     547              : !> \param fm_re real output matrix for split-FM storage
     548              : !> \param fm_im optional imaginary output matrix for split-FM storage
     549              : !> \param cfm optional complex full-matrix output
     550              : ! **************************************************************************************************
     551        10196 :    SUBROUTINE rskp_transform_evaluate(prepared, source_index, k, xkp, fm_re, fm_im, cfm)
     552              :       TYPE(rskp_prepared_transform_type), INTENT(INOUT)  :: prepared
     553              :       INTEGER, INTENT(IN)                                :: source_index, k
     554              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
     555              :       TYPE(cp_fm_type), INTENT(INOUT), OPTIONAL, TARGET  :: fm_re, fm_im
     556              :       TYPE(cp_cfm_type), INTENT(INOUT), OPTIONAL, TARGET :: cfm
     557              : 
     558        10196 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: batch(:, :, :)
     559              :       INTEGER                                            :: first_local, ncomp
     560              :       LOGICAL                                            :: target_layout_matches
     561        50980 :       TYPE(cp_fm_p_type)                                 :: output(1, 2)
     562              : 
     563        10196 :       CPASSERT(ALLOCATED(prepared%values))
     564        10196 :       CPASSERT(source_index >= 1 .AND. source_index <= SIZE(prepared%values))
     565        10196 :       CPASSERT(PRESENT(fm_re) .NEQV. PRESENT(cfm))
     566        10196 :       CPASSERT(.NOT. PRESENT(fm_im) .OR. PRESENT(fm_re))
     567        10196 :       CPASSERT(ALLOCATED(prepared%work))
     568        10196 :       CPASSERT(k >= 1 .AND. k <= SIZE(xkp, 2))
     569        10196 :       first_local = k
     570        10196 :       IF (.NOT. prepared%route%world_target) THEN
     571         8400 :          IF (k < prepared%kp_dist(1, prepared%route%inter%mepos + 1) .OR. &
     572         4088 :              k > prepared%kp_dist(2, prepared%route%inter%mepos + 1)) RETURN
     573         4312 :          first_local = k - prepared%kp_dist(1, prepared%route%inter%mepos + 1) + 1
     574              :       END IF
     575         6108 :       IF (PRESENT(cfm)) THEN
     576         1770 :          target_layout_matches = cp_fm_struct_equivalent(cfm%matrix_struct, prepared%route%matrix_struct)
     577         1770 :          CPASSERT(target_layout_matches)
     578         1770 :          batch(1:SIZE(cfm%local_data, 1), 1:SIZE(cfm%local_data, 2), 1:1) => cfm%local_data
     579              :          CALL cell_to_k_backend_evaluate_batch(prepared%values(source_index), prepared%route, &
     580         1770 :                                                xkp(:, k:k), first_local, prepared%work, batch=batch)
     581              :       ELSE
     582         4338 :          output(1, 1)%matrix => fm_re
     583         4338 :          ncomp = 1
     584         4338 :          IF (PRESENT(fm_im)) THEN
     585         4336 :             output(1, 2)%matrix => fm_im
     586         4336 :             ncomp = 2
     587              :          END IF
     588              :          CALL cell_to_k_backend_evaluate_batch(prepared%values(source_index), prepared%route, &
     589         4338 :                                                xkp(:, k:k), first_local, prepared%work, output=output(:, 1:ncomp))
     590              :       END IF
     591              :    END SUBROUTINE rskp_transform_evaluate
     592              : 
     593              : ! **************************************************************************************************
     594              : !> \brief Release the route, snapshot and cached backend state of a prepared transform.
     595              : !> \param prepared transform handle to release
     596              : ! **************************************************************************************************
     597         2828 :    SUBROUTINE rskp_transform_release(prepared)
     598              :       TYPE(rskp_prepared_transform_type), INTENT(INOUT)  :: prepared
     599              : 
     600              :       INTEGER                                            :: irow
     601              : 
     602         2828 :       IF (ALLOCATED(prepared%values)) THEN
     603         2890 :          DO irow = 1, SIZE(prepared%values)
     604         2890 :             CALL rskp_values_release(prepared%values(irow))
     605              :          END DO
     606         2890 :          DEALLOCATE (prepared%values)
     607              :       END IF
     608         2828 :       CALL rskp_route_release(prepared%route)
     609         2828 :       IF (ALLOCATED(prepared%kp_dist)) DEALLOCATE (prepared%kp_dist)
     610         2828 :       IF (ALLOCATED(prepared%work)) DEALLOCATE (prepared%work)
     611         2828 :    END SUBROUTINE rskp_transform_release
     612              : 
     613              : ! **************************************************************************************************
     614              : !> \brief Transform all real-space spin rows to a full k-grid in distributed DBCSR matrices.
     615              : !>        The real and imaginary output blocks retain their caller-provided sparsity and
     616              : !>        distribution. GEMM contracts all images of an AO block together; FFT transforms
     617              : !>        element tiles while reusing one prepared lattice geometry.
     618              : !> \param source real-space image matrices, by spin and image
     619              : !> \param real_k symmetric real output matrices, by spin and k point
     620              : !> \param imag_k antisymmetric imaginary output matrices, by spin and k point
     621              : !> \param xkp full reciprocal grid
     622              : !> \param cell_to_index translation-to-image map
     623              : !> \param sab_nl neighbor-list geometry of source
     624              : !> \param nkp_grid dimensions of the regular reciprocal grid
     625              : !> \param backend selected bulk R-to-K backend
     626              : ! **************************************************************************************************
     627            0 :    SUBROUTINE rskp_dbcsr_transform_batch(source, real_k, imag_k, xkp, cell_to_index, sab_nl, nkp_grid, backend)
     628              : 
     629              :       TYPE(dbcsr_p_type), POINTER                        :: source(:, :), real_k(:, :), imag_k(:, :)
     630              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
     631              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
     632              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     633              :          POINTER                                         :: sab_nl
     634              :       INTEGER, INTENT(IN)                                :: nkp_grid(3), backend
     635              : 
     636              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'rskp_dbcsr_transform_batch'
     637              : 
     638            0 :       COMPLEX(KIND=dp), ALLOCATABLE                      :: fft_output(:, :, :)
     639              :       INTEGER :: col, first, first_k, g, handle, i, ik, ispin, last, max_images, max_nelem, ncol, &
     640              :          nelem, nentry, nfold, ngroup, nimages, nk, nphase, nrow, nspin, odd, offset, panels(4), &
     641              :          pos, row_first, row_last, tile_first, tile_size, tile_width, width
     642              :       INTEGER(KIND=int_8)                                :: available_bytes, fft_tile_budget, &
     643              :                                                             nfactor, panel_bytes, per_k_bytes, &
     644              :                                                             per_tile_bytes
     645            0 :       INTEGER, ALLOCATABLE                               :: element_first(:), group_first(:), &
     646            0 :                                                             order(:), signed_cells(:, :)
     647            0 :       INTEGER, DIMENSION(:), POINTER                     :: col_size, row_size
     648              :       LOGICAL                                            :: active(4), found, found_im, found_re
     649            0 :       REAL(KIND=dp), ALLOCATABLE, TARGET                 :: packed(:), work(:)
     650            0 :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: factors(:, :), fft_input(:, :, :), &
     651            0 :                                                             image_re(:, :), RESULT(:, :)
     652            0 :       REAL(KIND=dp), POINTER                             :: iblock(:, :), rblock(:, :), &
     653            0 :                                                             result_block(:, :), rsblock(:, :)
     654            0 :       TYPE(cell_to_k_grid_work_type)                     :: fft_work
     655            0 :       TYPE(kp_transform_plan_type)                       :: plan
     656            0 :       TYPE(rskp_backend_plan_type)                       :: transform
     657              : 
     658            0 :       CALL timeset(routineN, handle)
     659            0 :       nspin = SIZE(source, 1)
     660            0 :       nk = SIZE(xkp, 2)
     661            0 :       CPASSERT(nk > 0)
     662            0 :       IF (backend /= rskp_backend_gemm .AND. backend /= rskp_backend_fft) THEN
     663            0 :          CPABORT("Unknown R-to-K backend")
     664              :       END IF
     665            0 :       CPASSERT(nspin > 0 .AND. SIZE(real_k, 1) == nspin .AND. SIZE(imag_k, 1) == nspin)
     666            0 :       CPASSERT(SIZE(real_k, 2) == nk .AND. SIZE(imag_k, 2) == nk)
     667            0 :       CPASSERT(SIZE(source, 2) > 0)
     668            0 :       CPASSERT(ASSOCIATED(sab_nl) .AND. ASSOCIATED(cell_to_index))
     669            0 :       DO ik = 1, nk
     670            0 :          DO ispin = 1, nspin
     671            0 :             CALL dbcsr_set(real_k(ispin, ik)%matrix, 0.0_dp)
     672            0 :             CALL dbcsr_set(imag_k(ispin, ik)%matrix, 0.0_dp)
     673              :          END DO
     674              :       END DO
     675              : 
     676            0 :       CALL kp_transform_plan_create(plan, sab_nl, cell_to_index, SIZE(source, 2), group_entries=.TRUE.)
     677            0 :       nentry = plan%nentry
     678            0 :       IF (nentry == 0) THEN
     679            0 :          CALL timestop(handle)
     680            0 :          RETURN
     681              :       END IF
     682            0 :       CALL dbcsr_get_info(source(1, 1)%matrix, row_blk_size=row_size, col_blk_size=col_size)
     683            0 :       ALLOCATE (group_first(nentry + 1), element_first(nentry + 1), order(nentry), signed_cells(3, nentry))
     684            0 :       DO i = 1, nentry
     685            0 :          order(i) = i
     686            0 :          signed_cells(:, i) = NINT(plan%symmetry_sign(i))*plan%cell(:, i)
     687              :       END DO
     688            0 :       max_images = 0
     689            0 :       max_nelem = 0
     690            0 :       ngroup = 0
     691            0 :       element_first(1) = 1
     692            0 :       first = 1
     693            0 :       DO WHILE (first <= nentry)
     694              :          last = first
     695            0 :          DO WHILE (last < nentry)
     696            0 :             IF (plan%row(last + 1) /= plan%row(first) .OR. plan%col(last + 1) /= plan%col(first)) EXIT
     697            0 :             last = last + 1
     698              :          END DO
     699            0 :          ngroup = ngroup + 1
     700            0 :          group_first(ngroup) = first
     701            0 :          panel_bytes = INT(row_size(plan%row(first)), int_8)*col_size(plan%col(first))*nspin
     702            0 :          IF (panel_bytes + element_first(ngroup) > HUGE(nelem)) THEN
     703            0 :             CPABORT("R-to-K DBCSR panel offsets exceed the integer range")
     704              :          END IF
     705            0 :          element_first(ngroup + 1) = element_first(ngroup) + INT(panel_bytes)
     706            0 :          max_nelem = MAX(max_nelem, INT(panel_bytes))
     707            0 :          max_images = MAX(max_images, last - first + 1)
     708            0 :          first = last + 1
     709              :       END DO
     710            0 :       group_first(ngroup + 1) = nentry + 1
     711            0 :       panel_bytes = 8_int_8*max_nelem*max_images
     712            0 :       available_bytes = dbcsr_batch_bytes - panel_bytes
     713            0 :       IF (backend == rskp_backend_gemm) THEN
     714              :          ! The raw image panel is retained; the budget sizes optional phases and k tiles.
     715            0 :          available_bytes = MAX(0_int_8, available_bytes)
     716              :          CALL cell_to_k_phase_prepare(transform, signed_cells, group_first(1:ngroup + 1), order, &
     717            0 :                                       element_first(1:ngroup + 1), xkp, available_bytes, 0_int_8)
     718            0 :          IF (ALLOCATED(transform%phases)) THEN
     719            0 :             available_bytes = available_bytes - 8_int_8*SIZE(transform%phases, KIND=int_8)
     720              :          END IF
     721            0 :          per_k_bytes = 16_int_8*transform%max_per_k
     722            0 :          tile_width = INT(MIN(INT(nk, int_8), MAX(1_int_8, available_bytes/MAX(1_int_8, per_k_bytes))))
     723            0 :          ALLOCATE (work(per_k_bytes/8*tile_width))
     724              :       ELSE
     725            0 :          fft_tile_budget = fft_batch_bytes
     726            0 :          CALL cell_to_k_grid_prepare(fft_work, signed_cells, xkp, nkp_grid)
     727            0 :          IF (.NOT. fft_work%regular) THEN
     728            0 :             CPABORT("Forced lattice FFT needs a supported regular grid or subset")
     729              :          END IF
     730              :       END IF
     731            0 :       ALLOCATE (packed(panel_bytes/8))
     732              : 
     733            0 :       DO g = 1, ngroup
     734            0 :          first = group_first(g)
     735            0 :          last = group_first(g + 1) - 1
     736            0 :          nimages = last - first + 1
     737            0 :          nrow = row_size(plan%row(first))
     738            0 :          ncol = col_size(plan%col(first))
     739            0 :          nelem = nrow*ncol
     740            0 :          IF (backend == rskp_backend_gemm) THEN
     741            0 :             panels = transform%phase_count([1, 1, 2, 3], g)
     742            0 :             nfold = SUM(panels)
     743              :          ELSE
     744              :             nfold = nimages
     745              :          END IF
     746            0 :          image_re(1:nelem*nspin, 1:nfold) => packed(1:INT(nelem, int_8)*INT(nspin, int_8)*INT(nfold, int_8))
     747            0 :          image_re = 0.0_dp
     748            0 :          DO i = first, last
     749            0 :             pos = i - first + 1
     750            0 :             odd = 0
     751            0 :             IF (backend == rskp_backend_gemm) THEN
     752            0 :                pos = (transform%fold_map(1, i) - transform%packed_first(g))/(nelem*nspin) + 1
     753            0 :                IF (transform%fold_map(2, i) /= 0) THEN
     754            0 :                   odd = (ABS(transform%fold_map(2, i)) - transform%packed_first(g))/(nelem*nspin) + 1
     755              :                END IF
     756              :             END IF
     757            0 :             DO ispin = 1, nspin
     758              :                CALL dbcsr_get_readonly_block_p(source(ispin, plan%image(i))%matrix, plan%row(first), plan%col(first), &
     759            0 :                                                rsblock, found)
     760            0 :                IF (.NOT. found) CYCLE
     761            0 :                CPASSERT(SIZE(rsblock, 1) == nrow .AND. SIZE(rsblock, 2) == ncol)
     762              :                image_re((ispin - 1)*nelem + 1:ispin*nelem, pos) = &
     763            0 :                   image_re((ispin - 1)*nelem + 1:ispin*nelem, pos) + RESHAPE(rsblock, [nelem])
     764            0 :                IF (odd == 0) CYCLE
     765              :                image_re((ispin - 1)*nelem + 1:ispin*nelem, odd) = &
     766              :                   image_re((ispin - 1)*nelem + 1:ispin*nelem, odd) + &
     767            0 :                   REAL(SIGN(1, transform%fold_map(2, i)), dp)*RESHAPE(rsblock, [nelem])
     768              :             END DO
     769              :          END DO
     770            0 :          IF (.NOT. ANY(image_re /= 0.0_dp)) CYCLE
     771              : 
     772            0 :          IF (backend == rskp_backend_gemm) THEN
     773              :             pos = 1
     774            0 :             DO i = 1, 4
     775            0 :                active(i) = ANY(image_re(:, pos:pos + panels(i) - 1) /= 0.0_dp)
     776            0 :                pos = pos + panels(i)
     777              :             END DO
     778            0 :             nphase = MAXVAL(transform%phase_count(1:2, g))
     779            0 :             DO first_k = 1, nk, tile_width
     780            0 :                width = MIN(tile_width, nk - first_k + 1)
     781            0 :                nfactor = 2_int_8*nphase*width
     782            0 :                factors(1:nphase, 1:2*width) => work(1:nfactor)
     783            0 :                RESULT(1:nelem*nspin, 1:2*width) => work(nfactor + 1:nfactor + 2_int_8*nelem*nspin*width)
     784              :                CALL cell_to_k_block_gemm(packed(1:nelem*nspin*nfold), transform, g, &
     785            0 :                                          xkp(:, first_k:first_k + width - 1), first_k, factors, RESULT, active)
     786            0 :                DO ik = 1, width
     787            0 :                   DO ispin = 1, nspin
     788              :                      CALL dbcsr_get_block_p(real_k(ispin, first_k + ik - 1)%matrix, plan%row(first), plan%col(first), &
     789            0 :                                             rblock, found)
     790            0 :                      IF (found) THEN
     791            0 :                         CPASSERT(SIZE(rblock, 1) == nrow .AND. SIZE(rblock, 2) == ncol)
     792            0 :                         result_block(1:nrow, 1:ncol) => RESULT((ispin - 1)*nelem + 1:ispin*nelem, ik)
     793            0 :                         rblock = result_block
     794              :                      END IF
     795              :                      CALL dbcsr_get_block_p(imag_k(ispin, first_k + ik - 1)%matrix, plan%row(first), plan%col(first), &
     796            0 :                                             iblock, found)
     797            0 :                      IF (found) THEN
     798            0 :                         CPASSERT(SIZE(iblock, 1) == nrow .AND. SIZE(iblock, 2) == ncol)
     799            0 :                         result_block(1:nrow, 1:ncol) => RESULT((ispin - 1)*nelem + 1:ispin*nelem, width + ik)
     800            0 :                         iblock = result_block
     801              :                      END IF
     802              :                   END DO
     803              :                END DO
     804              :             END DO
     805              :          ELSE
     806            0 :             per_tile_bytes = 16_int_8*nspin*nk
     807            0 :             IF (INT(nspin, int_8)*INT(nk, int_8) > INT(HUGE(0), int_8)) THEN
     808            0 :                CPABORT("R-to-K DBCSR FFT tile exceeds the integer range")
     809              :             END IF
     810              :             tile_width = MIN(nelem, INT(MAX(1_int_8, MIN(fft_tile_budget/per_tile_bytes, &
     811            0 :                                                          INT(HUGE(0), int_8)/(INT(nspin, int_8)*INT(nk, int_8))))))
     812            0 :             fft_input(1:nelem, 1:nspin, 1:nimages) => packed(1:INT(nelem, int_8)*INT(nspin, int_8)*INT(nimages, int_8))
     813            0 :             ALLOCATE (fft_output(tile_width, nspin, nk))
     814            0 :             DO tile_first = 1, nelem, tile_width
     815            0 :                tile_size = MIN(tile_width, nelem - tile_first + 1)
     816              :                CALL cell_to_k_grid_fft(fft_input(tile_first:tile_first + tile_size - 1, :, :), &
     817              :                                        signed_cells(:, first:last), xkp, &
     818              :                                        nkp_grid, fft_output(1:tile_size, :, :), require_fft=.TRUE., work=fft_work, &
     819            0 :                                        cell_first=first)
     820            0 :                DO ik = 1, nk
     821            0 :                   DO ispin = 1, nspin
     822              :                      CALL dbcsr_get_block_p(real_k(ispin, ik)%matrix, plan%row(first), plan%col(first), &
     823            0 :                                             rblock, found_re)
     824            0 :                      IF (found_re) THEN
     825            0 :                         CPASSERT(SIZE(rblock, 1) == nrow .AND. SIZE(rblock, 2) == ncol)
     826              :                      END IF
     827              :                      CALL dbcsr_get_block_p(imag_k(ispin, ik)%matrix, plan%row(first), plan%col(first), &
     828            0 :                                             iblock, found_im)
     829            0 :                      IF (found_im) THEN
     830            0 :                         CPASSERT(SIZE(iblock, 1) == nrow .AND. SIZE(iblock, 2) == ncol)
     831              :                      END IF
     832            0 :                      IF (.NOT. (found_re .OR. found_im)) CYCLE
     833              :                      ! Write each column segment directly; FFT tiles may split a column.
     834            0 :                      DO col = (tile_first - 1)/nrow + 1, (tile_first + tile_size - 2)/nrow + 1
     835            0 :                         offset = (col - 1)*nrow
     836            0 :                         row_first = MAX(1, tile_first - offset)
     837            0 :                         row_last = MIN(nrow, tile_first + tile_size - 1 - offset)
     838            0 :                         pos = offset + row_first - tile_first + 1
     839            0 :                         IF (found_re) rblock(row_first:row_last, col) = &
     840            0 :                            REAL(fft_output(pos:pos + row_last - row_first, ispin, ik), dp)
     841            0 :                         IF (found_im) iblock(row_first:row_last, col) = &
     842            0 :                            AIMAG(fft_output(pos:pos + row_last - row_first, ispin, ik))
     843              :                      END DO
     844              :                   END DO
     845              :                END DO
     846              :             END DO
     847            0 :             DEALLOCATE (fft_output)
     848              :          END IF
     849              :       END DO
     850            0 :       CALL cell_to_k_grid_release(fft_work)
     851            0 :       CALL timestop(handle)
     852            0 :    END SUBROUTINE rskp_dbcsr_transform_batch
     853              : 
     854              : ! **************************************************************************************************
     855              : !> \brief Build the immutable neighbor-list traversal shared by R-to-K and K-to-R transforms.
     856              : !> \param plan ...
     857              : !> \param sab_nl ...
     858              : !> \param cell_to_index ...
     859              : !> \param nimg ...
     860              : !> \param block_template ...
     861              : !> \param group_entries ...
     862              : ! **************************************************************************************************
     863        86132 :    SUBROUTINE kp_transform_plan_create(plan, sab_nl, cell_to_index, nimg, block_template, group_entries)
     864              : 
     865              :       TYPE(kp_transform_plan_type), INTENT(OUT)          :: plan
     866              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     867              :          POINTER                                         :: sab_nl
     868              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
     869              :       INTEGER, INTENT(IN)                                :: nimg
     870              :       TYPE(dbcsr_type), INTENT(IN), OPTIONAL             :: block_template
     871              :       LOGICAL, INTENT(IN), OPTIONAL                      :: group_entries
     872              : 
     873              :       INTEGER                                            :: i, iatom, icell, icol, igroup, irow, &
     874              :                                                             jatom, nblock
     875        86132 :       INTEGER(KIND=int_8), ALLOCATABLE, DIMENSION(:)     :: key
     876        86132 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: order
     877              :       INTEGER, DIMENSION(3)                              :: cell
     878        86132 :       INTEGER, DIMENSION(:), POINTER                     :: col_offsets, row_offsets
     879              :       LOGICAL                                            :: do_grouping, do_symmetric, store_offsets
     880              :       TYPE(neighbor_list_iterator_p_type), &
     881        86132 :          DIMENSION(:), POINTER                           :: iterator
     882              : 
     883        86132 :       CALL get_neighbor_list_set_p(neighbor_list_sets=sab_nl, symmetric=do_symmetric)
     884        86132 :       plan%symmetric = do_symmetric
     885        86132 :       do_grouping = .FALSE.
     886        86132 :       IF (PRESENT(group_entries)) do_grouping = group_entries
     887        86132 :       store_offsets = PRESENT(block_template)
     888        86132 :       IF (store_offsets) THEN
     889        41910 :          CALL dbcsr_get_info(block_template, row_blk_offset=row_offsets, col_blk_offset=col_offsets)
     890              :       END IF
     891        86132 :       CALL neighbor_list_iterator_create(iterator, sab_nl)
     892     18755557 :       DO WHILE (neighbor_list_iterate(iterator) == 0)
     893     18669425 :          CALL get_iterator_info(iterator, cell=cell)
     894     18669425 :          icell = cell_to_index(cell(1), cell(2), cell(3))
     895     18755557 :          IF (icell >= 1 .AND. icell <= nimg) plan%nentry = plan%nentry + 1
     896              :       END DO
     897        86132 :       CALL neighbor_list_iterator_release(iterator)
     898              : 
     899            0 :       ALLOCATE (plan%row(plan%nentry), plan%col(plan%nentry), plan%image(plan%nentry), &
     900       762003 :                 plan%cell(3, plan%nentry), plan%symmetry_sign(plan%nentry))
     901        86132 :       IF (store_offsets) THEN
     902       123600 :          ALLOCATE (plan%row_offset(plan%nentry), plan%col_offset(plan%nentry))
     903              :       END IF
     904              : 
     905        86132 :       i = 0
     906        86132 :       CALL neighbor_list_iterator_create(iterator, sab_nl)
     907     18755557 :       DO WHILE (neighbor_list_iterate(iterator) == 0)
     908     18669425 :          CALL get_iterator_info(iterator, iatom=iatom, jatom=jatom, cell=cell)
     909     18669425 :          icell = cell_to_index(cell(1), cell(2), cell(3))
     910     18669425 :          IF (icell < 1 .OR. icell > nimg) CYCLE
     911     18669209 :          i = i + 1
     912     18669209 :          irow = iatom
     913     18669209 :          icol = jatom
     914     18669209 :          plan%symmetry_sign(i) = 1.0_dp
     915     18669209 :          IF (do_symmetric .AND. iatom > jatom) THEN
     916      7717626 :             irow = jatom
     917      7717626 :             icol = iatom
     918      7717626 :             plan%symmetry_sign(i) = -1.0_dp
     919              :          END IF
     920     18669209 :          plan%row(i) = irow
     921     18669209 :          plan%col(i) = icol
     922     18669209 :          IF (store_offsets) THEN
     923      8705981 :             plan%row_offset(i) = row_offsets(irow)
     924      8705981 :             plan%col_offset(i) = col_offsets(icol)
     925              :          END IF
     926     18669209 :          plan%image(i) = icell
     927     74763184 :          plan%cell(:, i) = cell
     928              :       END DO
     929        86132 :       CALL neighbor_list_iterator_release(iterator)
     930        86132 :       CPASSERT(i == plan%nentry)
     931              : 
     932        86132 :       IF (do_grouping .AND. plan%nentry > 0) THEN
     933     19963786 :          nblock = MAX(MAXVAL(plan%row), MAXVAL(plan%col))
     934       213110 :          ALLOCATE (key(plan%nentry), order(plan%nentry))
     935     10003204 :          DO i = 1, plan%nentry
     936              :             key(i) = INT(plan%image(i), KIND=int_8) + INT(nimg, KIND=int_8)* &
     937              :                      (INT(plan%row(i) - 1, KIND=int_8) + INT(nblock, KIND=int_8)* &
     938     10003204 :                       INT(plan%col(i) - 1, KIND=int_8))
     939              :          END DO
     940        42622 :          CALL sort(key, plan%nentry, order)
     941     20006408 :          plan%row(:) = plan%row(order)
     942     20006408 :          plan%col(:) = plan%col(order)
     943        42622 :          IF (store_offsets) THEN
     944            0 :             plan%row_offset(:) = plan%row_offset(order)
     945            0 :             plan%col_offset(:) = plan%col_offset(order)
     946              :          END IF
     947     20006408 :          plan%image(:) = plan%image(order)
     948     79769900 :          plan%cell(:, :) = plan%cell(:, order)
     949     20006408 :          plan%symmetry_sign(:) = plan%symmetry_sign(order)
     950              : 
     951        42622 :          plan%ngroup = 1
     952      9960582 :          DO i = 2, plan%nentry
     953      9960582 :             IF (key(i) /= key(i - 1)) plan%ngroup = plan%ngroup + 1
     954              :          END DO
     955       127866 :          ALLOCATE (plan%group_start(plan%ngroup + 1))
     956        42622 :          igroup = 1
     957        42622 :          plan%group_start(igroup) = 1
     958      9960582 :          DO i = 2, plan%nentry
     959      9960582 :             IF (key(i) /= key(i - 1)) THEN
     960      9917960 :                igroup = igroup + 1
     961      9917960 :                plan%group_start(igroup) = i
     962              :             END IF
     963              :          END DO
     964        42622 :          plan%group_start(plan%ngroup + 1) = plan%nentry + 1
     965        42622 :          DEALLOCATE (key, order)
     966              :       END IF
     967              : 
     968       172264 :    END SUBROUTINE kp_transform_plan_create
     969              : 
     970              : ! **************************************************************************************************
     971              : !> \brief Contract one real image panel with real phase factors.
     972              : !> \param nrow number of AO elements in the panel
     973              : !> \param nimages number of real-space images in the panel
     974              : !> \param nk number of k-point columns
     975              : !> \param values_re image values contributing to the real output
     976              : !> \param phase_re real phase factors
     977              : !> \param result_re real output panel
     978              : !> \param beta output accumulation factor
     979              : ! **************************************************************************************************
     980      2407612 :    SUBROUTINE rskp_gemm_contract(nrow, nimages, nk, values_re, phase_re, result_re, beta)
     981              :       INTEGER, INTENT(IN)                                :: nrow, nimages, nk
     982              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: values_re(:, :), phase_re(:, :)
     983              :       REAL(KIND=dp), CONTIGUOUS, INTENT(INOUT)           :: result_re(:, :)
     984              :       REAL(KIND=dp), INTENT(IN)                          :: beta
     985              : 
     986      2407612 :       CPASSERT(nrow > 0 .AND. nimages > 0 .AND. nk > 0)
     987      2407612 :       CPASSERT(SIZE(values_re, 1) >= nrow .AND. SIZE(values_re, 2) >= nimages)
     988      2407612 :       CPASSERT(SIZE(phase_re, 1) >= nimages .AND. SIZE(phase_re, 2) >= nk)
     989      2407612 :       CPASSERT(SIZE(result_re, 1) >= nrow .AND. SIZE(result_re, 2) >= nk)
     990              : 
     991              :       CALL dgemm('N', 'N', nrow, nk, nimages, 1.0_dp, values_re, SIZE(values_re, 1), &
     992      2407612 :                  phase_re, SIZE(phase_re, 1), beta, result_re, SIZE(result_re, 1))
     993      2407612 :    END SUBROUTINE rskp_gemm_contract
     994              : 
     995              : ! **************************************************************************************************
     996              : !> \brief Cache routing to the FM tiles of one representative group.
     997              : !>        Equivalent ranks in the other groups receive only their tile's blocks.
     998              : !>        Both backends receive the union of locally owned direct/mirrored AO elements.
     999              : !>        Missing source blocks are packed as zero on a fixed geometry.
    1000              : !> \param source operator layout template
    1001              : !> \param source_sab neighbor lists belonging to source
    1002              : !> \param cell_to_index map from lattice translations to source image indices
    1003              : !> \param matrix_struct target group or world FM layout
    1004              : !> \param world communicator distributing the source DBCSR matrices
    1005              : !> \param group communicator of group-local FM targets
    1006              : !> \param inter communicator joining equivalent FM ranks across groups
    1007              : !> \param backend GEMM or FFT
    1008              : !> \param route context-owned structural route
    1009              : !> \param ready false collectively if source or target layout is incompatible
    1010              : ! **************************************************************************************************
    1011       209550 :    SUBROUTINE rskp_route_create(source, source_sab, cell_to_index, matrix_struct, world, group, inter, &
    1012              :                                 backend, route, ready)
    1013              : 
    1014              :       TYPE(dbcsr_p_type), POINTER                        :: source(:, :)
    1015              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1016              :          POINTER                                         :: source_sab
    1017              :       INTEGER, POINTER                                   :: cell_to_index(:, :, :)
    1018              :       TYPE(cp_fm_struct_type), POINTER                   :: matrix_struct
    1019              :       TYPE(mp_para_env_type), POINTER                    :: world, group, inter
    1020              :       INTEGER, INTENT(IN)                                :: backend
    1021              :       TYPE(rskp_route_type), INTENT(OUT)                 :: route
    1022              :       LOGICAL, INTENT(OUT)                               :: ready
    1023              : 
    1024              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'rskp_route_create'
    1025              : 
    1026              :       INTEGER                                            :: compatible, dest, handle, i, iblock, &
    1027              :                                                             layout(11), layout_max(11), &
    1028              :                                                             layout_min(11), nblock, ncol, nowner, &
    1029              :                                                             nrow, p, pos, rank
    1030              :       INTEGER(KIND=int_8)                                :: nr(2), ns(2), storage
    1031        41910 :       INTEGER(KIND=int_8), ALLOCATABLE                   :: recv_size(:, :), send_size(:, :)
    1032        41910 :       INTEGER, ALLOCATABLE                               :: identities(:, :), owner(:), &
    1033        41910 :                                                             position(:, :), send_metadata(:, :), &
    1034        41910 :                                                             value_count(:), value_start(:)
    1035        41910 :       INTEGER, POINTER                                   :: col_size(:), row_size(:)
    1036        41910 :       LOGICAL, ALLOCATABLE                               :: needed(:)
    1037              : 
    1038        41910 :       CALL timeset(routineN, handle)
    1039        41910 :       ready = .FALSE.
    1040        41910 :       route%world => world
    1041        41910 :       route%group => group
    1042        41910 :       route%inter => inter
    1043        41910 :       CALL dbcsr_get_info(source(1, 1)%matrix, row_blk_size=row_size, col_blk_size=col_size)
    1044              :       CALL kp_transform_plan_create(route%traversal, source_sab, cell_to_index, &
    1045        41910 :                                     SIZE(source, 2), block_template=source(1, 1)%matrix)
    1046        41910 :       route%source_sab => source_sab
    1047        41910 :       route%transform%backend = backend
    1048        41910 :       route%world_target = ASSOCIATED(matrix_struct%para_env, world)
    1049        41910 :       nowner = group%num_pe
    1050        41910 :       IF (route%world_target) nowner = world%num_pe
    1051              :       compatible = MERGE(1, 0, route%world_target .OR. &
    1052        41910 :                          ASSOCIATED(matrix_struct%para_env, group))
    1053        41910 :       IF (.NOT. route%world_target) THEN
    1054              :          layout = [matrix_struct%nrow_global, matrix_struct%ncol_global, &
    1055              :                    matrix_struct%nrow_block, matrix_struct%ncol_block, matrix_struct%first_p_pos, &
    1056       743292 :                    matrix_struct%context%num_pe, matrix_struct%context%mepos, matrix_struct%local_leading_dimension]
    1057        41294 :          layout_min = layout
    1058        41294 :          layout_max = layout
    1059        41294 :          CALL inter%min(layout_min)
    1060        41294 :          CALL inter%max(layout_max)
    1061       495528 :          IF (ANY(layout_min /= layout_max)) compatible = 0
    1062              :       END IF
    1063       380242 :       IF (SUM(row_size) /= matrix_struct%nrow_global .OR. &
    1064            0 :           SUM(col_size) /= matrix_struct%ncol_global) compatible = 0
    1065        41910 :       IF (route%traversal%symmetric) THEN
    1066        41854 :          IF (matrix_struct%nrow_global /= matrix_struct%ncol_global .OR. SIZE(row_size) /= SIZE(col_size)) THEN
    1067            0 :             compatible = 0
    1068       210908 :          ELSE IF (ANY(row_size /= col_size)) THEN
    1069            0 :             compatible = 0
    1070              :          END IF
    1071              :       END IF
    1072        41910 :       CALL world%min(compatible)
    1073        41910 :       IF (compatible == 0) THEN
    1074              :          CALL cp_warn(__LOCATION__, &
    1075            0 :                       "Prepared R-to-K transform has an incompatible source or target layout")
    1076            0 :          CALL timestop(handle)
    1077            0 :          RETURN
    1078              :       END IF
    1079        41910 :       route%nimage = SIZE(source, 2)
    1080       209550 :       ALLOCATE (route%row_size(SIZE(row_size)), route%col_size(SIZE(col_size)))
    1081       211076 :       route%row_size(:) = row_size
    1082       211076 :       route%col_size(:) = col_size
    1083              :       ALLOCATE (identities(2, 0:world%num_pe - 1), owner(0:nowner - 1), &
    1084       335280 :                 needed(0:nowner - 1), value_count(0:nowner - 1), value_start(0:nowner - 1))
    1085       125730 :       CALL world%allgather([group%mepos, inter%mepos], identities)
    1086        96644 :       owner(:) = -1
    1087        41910 :       IF (route%world_target) THEN
    1088         1848 :          DO rank = 0, world%num_pe - 1
    1089         1848 :             owner(rank) = rank
    1090              :          END DO
    1091              :       ELSE
    1092       123882 :          DO rank = 0, world%num_pe - 1
    1093       123882 :             IF (identities(2, rank) == 0) owner(identities(1, rank)) = rank
    1094              :          END DO
    1095              :       END IF
    1096        96644 :       CPASSERT(ALL(owner >= 0))
    1097       167640 :       ALLOCATE (send_size(2, 0:world%num_pe - 1), recv_size(2, 0:world%num_pe - 1))
    1098        41910 :       send_size(:, :) = 0_int_8
    1099      8747891 :       DO i = 1, route%traversal%nentry
    1100      8705981 :          nrow = row_size(route%traversal%row(i))
    1101      8705981 :          ncol = col_size(route%traversal%col(i))
    1102      8705981 :          CALL rskp_owners(route, matrix_struct, i, needed, value_count)
    1103     21431130 :          DO p = 0, SIZE(owner) - 1
    1104     12683239 :             IF (.NOT. needed(p)) CYCLE
    1105     10580492 :             dest = owner(p)
    1106     10580492 :             send_size(1, dest) = send_size(1, dest) + 1_int_8
    1107     21389220 :             send_size(2, dest) = send_size(2, dest) + INT(value_count(p), int_8)
    1108              :          END DO
    1109              :       END DO
    1110        41910 :       CALL world%alltoall(send_size, recv_size, 2)
    1111              :       ! Only inter-rank zero receives from the world. The other groups hold
    1112              :       ! equivalent FM tiles, as required by kpoint_env_initialize.
    1113       293370 :       ns = SUM(send_size, DIM=2)
    1114       293370 :       nr = SUM(recv_size, DIM=2)
    1115        41910 :       IF (.NOT. route%world_target) CALL inter%bcast(nr, 0)
    1116              :       ! Conservative routing/capture allocation estimate for diagnostics.
    1117              :       storage = 40_int_8*route%traversal%nentry + &
    1118              :                 4_int_8*(SIZE(row_size) + SIZE(col_size) + matrix_struct%nrow_global + matrix_struct%ncol_global) + &
    1119              :                 48_int_8*ns(1) + MERGE(0_int_8, 8_int_8*ns(2), world%num_pe == 1) + 68_int_8*nr(1) + &
    1120        41910 :                 128_int_8*world%num_pe + 16_int_8*SIZE(owner) + 8_int_8
    1121              :       ! Singleton groups also retain the AO-block group boundaries.
    1122        41910 :       IF (SIZE(owner) == 1) storage = storage + 4_int_8*(nr(1) + 1_int_8)
    1123              :       ! Group permutations, packed offsets, direct/mirror element maps and
    1124              :       ! sorting scratch. The cropped receive buffer is shared by all slots.
    1125        41910 :       storage = storage + 52_int_8*(nr(1) + 1_int_8) + 16_int_8*nr(2)
    1126        41910 :       IF (world%num_pe > 1) storage = storage + 8_int_8*nr(2)
    1127        41910 :       IF (SIZE(owner) > 1) storage = storage + 4_int_8*ns(2)
    1128        41910 :       route%storage = storage
    1129              :       ! Values, offsets and eight-integer metadata records use default INTEGER MPI counts.
    1130       209550 :       IF (MAXVAL(ns) >= INT(HUGE(0), int_8) .OR. MAXVAL(nr) >= INT(HUGE(0), int_8) .OR. &
    1131              :           MAX(ns(1), nr(1)) > INT(HUGE(0), int_8)/8_int_8) THEN
    1132            0 :          CALL cp_abort(__LOCATION__, "R-to-K route counts exceed the integer range")
    1133              :       END IF
    1134              :       ! Route counts are checked explicitly before conversion to default INTEGER.
    1135        41910 :       nblock = INT(nr(1))
    1136        41910 :       route%nvalue = INT(nr(2))
    1137            0 :       ALLOCATE (route%scount(2, 0:world%num_pe - 1), route%rcount(2, 0:world%num_pe - 1), &
    1138       251460 :                 route%sdisp(2, 0:world%num_pe - 1), route%rdisp(2, 0:world%num_pe - 1))
    1139       293370 :       route%scount(:, :) = INT(send_size)
    1140       293370 :       route%rcount(:, :) = INT(recv_size)
    1141        41910 :       IF (SIZE(owner) == 1 .AND. .NOT. route%world_target) CALL inter%bcast(route%rcount, 0)
    1142       125730 :       route%sdisp(:, 0) = 0
    1143       125730 :       route%rdisp(:, 0) = 0
    1144        83820 :       DO rank = 1, world%num_pe - 1
    1145       125730 :          route%sdisp(:, rank) = route%sdisp(:, rank - 1) + route%scount(:, rank - 1)
    1146       167640 :          route%rdisp(:, rank) = route%rdisp(:, rank - 1) + route%rcount(:, rank - 1)
    1147              :       END DO
    1148            0 :       ALLOCATE (route%send_entry(INT(ns(1))), route%send_first(INT(ns(1)) + 1), &
    1149            0 :                 route%send_values(MERGE(0, INT(ns(2)), world%num_pe == 1)), send_metadata(8, INT(ns(1))), &
    1150            0 :                 position(2, 0:world%num_pe - 1), route%entry(8, nblock), &
    1151       667365 :                 route%first(nblock + 1))
    1152        67196 :       IF (SIZE(owner) > 1) ALLOCATE (route%send_element(INT(ns(2))))
    1153       125730 :       IF (world%num_pe > 1) ALLOCATE (route%recv_values(route%nvalue))
    1154       293370 :       position(:, :) = route%sdisp
    1155      8747891 :       DO i = 1, route%traversal%nentry
    1156      8705981 :          nrow = row_size(route%traversal%row(i))
    1157      8705981 :          ncol = col_size(route%traversal%col(i))
    1158      8705981 :          IF (ALLOCATED(route%send_element)) THEN
    1159     11931774 :             value_start(:) = position(2, owner)
    1160              :             CALL rskp_owners(route, matrix_struct, i, needed, value_count, &
    1161      3977258 :                              value_start, route%send_element)
    1162              :          ELSE
    1163      4728723 :             CALL rskp_owners(route, matrix_struct, i, needed, value_count)
    1164              :          END IF
    1165     21431130 :          DO p = 0, SIZE(owner) - 1
    1166     12683239 :             IF (.NOT. needed(p)) CYCLE
    1167     10580492 :             dest = owner(p)
    1168     10580492 :             iblock = position(1, dest) + 1
    1169     10580492 :             pos = position(2, dest) + 1
    1170     10580492 :             route%send_entry(iblock) = i
    1171     10580492 :             route%send_first(iblock) = pos
    1172     52902460 :             send_metadata(1:4, iblock) = [route%traversal%row_offset(i), route%traversal%col_offset(i), nrow, ncol]
    1173     42321968 :             send_metadata(5:7, iblock) = NINT(route%traversal%symmetry_sign(i))*route%traversal%cell(:, i)
    1174              :             send_metadata(8, iblock) = MERGE(1, 0, route%traversal%symmetric .AND. &
    1175     10580492 :                                              route%traversal%row(i) /= route%traversal%col(i))
    1176     42550204 :             position(:, dest) = position(:, dest) + [1, value_count(p)]
    1177              :          END DO
    1178              :       END DO
    1179        41910 :       route%send_first(INT(ns(1)) + 1) = INT(ns(2)) + 1
    1180        41910 :       IF (SIZE(owner) == 1 .AND. world%num_pe == 1) THEN
    1181            0 :          CALL world%allgatherv(send_metadata, route%entry, 8*route%rcount(1, :), 8*route%rdisp(1, :))
    1182        41910 :       ELSE IF (.NOT. route%world_target .AND. SIZE(owner) == 1) THEN
    1183       145430 :          CALL world%allgatherv(send_metadata, route%entry, 8*route%rcount(1, :), 8*route%rdisp(1, :))
    1184              :       ELSE
    1185              :          CALL world%alltoall(send_metadata, 8*route%scount(1, :), 8*route%sdisp(1, :), &
    1186       115416 :                              route%entry, 8*route%rcount(1, :), 8*route%rdisp(1, :))
    1187        12824 :          IF (.NOT. route%world_target) CALL inter%bcast(route%entry, 0)
    1188              :       END IF
    1189        41910 :       route%matrix_struct => matrix_struct
    1190        41910 :       CALL cp_fm_struct_retain(route%matrix_struct)
    1191        41910 :       CALL rskp_tile_map(route)
    1192        41910 :       ready = .TRUE.
    1193        41910 :       CALL timestop(handle)
    1194              : 
    1195       125730 :    END SUBROUTINE rskp_route_create
    1196              : 
    1197              : ! **************************************************************************************************
    1198              : !> \brief Map routed blocks to local FM ownership and stable atom-pair groups.
    1199              : !>        FM indices are ordered globally; dummy indices on empty tiles lie outside the matrix.
    1200              : !> \param route fixed routing and target distribution
    1201              : ! **************************************************************************************************
    1202        41910 :    SUBROUTINE rskp_tile_map(route)
    1203              :       TYPE(rskp_route_type), INTENT(INOUT)               :: route
    1204              : 
    1205              :       INTEGER                                            :: c0, col, element, first, g, i, image, m, &
    1206              :                                                             nc, ngroup, nr, overlap, pos, r0, row
    1207        41910 :       INTEGER(KIND=int_8), ALLOCATABLE                   :: key(:)
    1208        41910 :       INTEGER, ALLOCATABLE                               :: element_count(:)
    1209              :       LOGICAL                                            :: direct, mirror
    1210        41910 :       INTEGER :: rows(0:route%matrix_struct%nrow_global), cols(0:route%matrix_struct%ncol_global)
    1211              : 
    1212      1040598 :       rows(:) = 0
    1213      1040994 :       cols(:) = 0
    1214       874638 :       DO i = 1, SIZE(route%matrix_struct%row_indices)
    1215       832728 :          r0 = route%matrix_struct%row_indices(i)
    1216       874638 :          IF (r0 >= 1 .AND. r0 <= UBOUND(rows, 1)) rows(r0) = 1
    1217              :       END DO
    1218       999084 :       DO i = 1, SIZE(route%matrix_struct%col_indices)
    1219       957174 :          c0 = route%matrix_struct%col_indices(i)
    1220       999084 :          IF (c0 >= 1 .AND. c0 <= UBOUND(cols, 1)) cols(c0) = 1
    1221              :       END DO
    1222       998688 :       DO i = 1, UBOUND(rows, 1)
    1223       998688 :          rows(i) = rows(i) + rows(i - 1)
    1224              :       END DO
    1225       999084 :       DO i = 1, UBOUND(cols, 1)
    1226       999084 :          cols(i) = cols(i) + cols(i - 1)
    1227              :       END DO
    1228        41910 :       route%nrow = rows(UBOUND(rows, 1))
    1229        41910 :       route%ncol = cols(UBOUND(cols, 1))
    1230       167640 :       ALLOCATE (route%block_order(SIZE(route%entry, 2)), element_count(SIZE(route%entry, 2)))
    1231              :       BLOCK
    1232              :          ! Source-rank reception need not keep a pair contiguous on distributed FM layouts.
    1233       125730 :          ALLOCATE (key(SIZE(route%entry, 2)))
    1234     15351125 :          DO i = 1, SIZE(key)
    1235              :             key(i) = INT(route%entry(1, i), int_8) + &
    1236     15351125 :                      INT(route%matrix_struct%nrow_global, int_8)*(route%entry(2, i) - 1)
    1237              :          END DO
    1238        41910 :          IF (SIZE(key) > 0) CALL sort(key, SIZE(key), route%block_order)
    1239        41910 :          ngroup = 0
    1240     15351125 :          IF (SIZE(key) > 0) ngroup = 1 + COUNT(key(2:) /= key(:SIZE(key) - 1))
    1241       125730 :          ALLOCATE (route%block_first(ngroup + 1))
    1242        41910 :          route%block_first(1) = 1
    1243        41910 :          g = 1
    1244     15309215 :          DO i = 2, SIZE(key)
    1245     15267305 :             IF (key(i) == key(i - 1)) CYCLE
    1246       550614 :             g = g + 1
    1247     15309215 :             route%block_first(g) = i
    1248              :          END DO
    1249        41910 :          route%block_first(ngroup + 1) = SIZE(key) + 1
    1250              :       END BLOCK
    1251        83820 :       ALLOCATE (route%element_first(ngroup + 1))
    1252        41910 :       route%element_first(1) = 1
    1253        41910 :       pos = 1
    1254       634434 :       DO g = 1, ngroup
    1255       592524 :          first = route%block_order(route%block_first(g))
    1256       592524 :          r0 = route%entry(1, first)
    1257       592524 :          c0 = route%entry(2, first)
    1258       592524 :          nr = route%entry(3, first)
    1259       592524 :          nc = route%entry(4, first)
    1260       592524 :          m = (rows(r0 + nr - 1) - rows(r0 - 1))*(cols(c0 + nc - 1) - cols(c0 - 1))
    1261       592524 :          IF (route%entry(8, first) /= 0) THEN
    1262              :             ! Subtract the intersection: a rank owning both orientations
    1263              :             ! needs one input value and one GEMM row for that element.
    1264              :             overlap = COUNT(rows(r0:r0 + nr - 1) > rows(r0 - 1:r0 + nr - 2) .AND. &
    1265              :                             cols(r0:r0 + nr - 1) > cols(r0 - 1:r0 + nr - 2))* &
    1266              :                       COUNT(rows(c0:c0 + nc - 1) > rows(c0 - 1:c0 + nc - 2) .AND. &
    1267      4970064 :                             cols(c0:c0 + nc - 1) > cols(c0 - 1:c0 + nc - 2))
    1268       444660 :             m = m + (rows(c0 + nc - 1) - rows(c0 - 1))*(cols(r0 + nr - 1) - cols(r0 - 1)) - overlap
    1269              :          END IF
    1270       592524 :          route%element_first(g + 1) = route%element_first(g) + m
    1271     15943649 :          DO i = route%block_first(g), route%block_first(g + 1) - 1
    1272     15309215 :             image = route%block_order(i)
    1273     15309215 :             element_count(image) = m
    1274     15901739 :             pos = pos + m
    1275              :          END DO
    1276              :       END DO
    1277        41910 :       route%first(1) = 1
    1278     15351125 :       DO i = 1, SIZE(element_count)
    1279     15351125 :          route%first(i + 1) = route%first(i) + element_count(i)
    1280              :       END DO
    1281        41910 :       CPASSERT(pos == route%nvalue + 1)
    1282        41910 :       CPASSERT(route%first(SIZE(element_count) + 1) == pos)
    1283       125730 :       ALLOCATE (route%element_offset(2, route%element_first(ngroup + 1) - 1))
    1284     70106589 :       route%element_offset(:, :) = 0_int_8
    1285       634434 :       DO g = 1, ngroup
    1286       592524 :          first = route%block_order(route%block_first(g))
    1287       592524 :          r0 = route%entry(1, first)
    1288       592524 :          c0 = route%entry(2, first)
    1289       592524 :          nr = route%entry(3, first)
    1290       592524 :          nc = route%entry(4, first)
    1291       592524 :          element = route%element_first(g)
    1292      3670945 :          DO col = c0, c0 + nc - 1
    1293     27742504 :             DO row = r0, r0 + nr - 1
    1294     24071559 :                direct = rows(row) > rows(row - 1) .AND. cols(col) > cols(col - 1)
    1295     24071559 :                mirror = .FALSE.
    1296     24071559 :                IF (route%entry(8, first) /= 0) THEN
    1297     16739836 :                   mirror = rows(col) > rows(col - 1) .AND. cols(row) > cols(row - 1)
    1298              :                END IF
    1299      9172752 :                IF (.NOT. (direct .OR. mirror)) CYCLE
    1300     23354893 :                IF (direct) route%element_offset(1, element) = &
    1301              :                   INT(rows(row), int_8) + &
    1302     21765565 :                   INT(cols(col) - 1, int_8)*route%matrix_struct%local_leading_dimension
    1303     23354893 :                IF (mirror) route%element_offset(2, element) = &
    1304              :                   INT(rows(col), int_8) + &
    1305     14898807 :                   INT(cols(row) - 1, int_8)*route%matrix_struct%local_leading_dimension
    1306     27149980 :                element = element + 1
    1307              :             END DO
    1308              :          END DO
    1309       634434 :          CPASSERT(element == route%element_first(g + 1))
    1310              :       END DO
    1311        41910 :       IF (route%transform%backend == rskp_backend_fft) THEN
    1312        11342 :          ALLOCATE (route%transform%packed_first(ngroup + 1), route%transform%fold_map(2, SIZE(route%entry, 2)), source=0)
    1313              :          pos = 1
    1314          214 :          DO g = 1, ngroup
    1315          180 :             route%transform%packed_first(g) = pos
    1316          180 :             m = route%element_first(g + 1) - route%element_first(g)
    1317         3878 :             DO i = route%block_first(g), route%block_first(g + 1) - 1
    1318         3664 :                route%transform%fold_map(1, route%block_order(i)) = pos
    1319         3844 :                pos = pos + m
    1320              :             END DO
    1321              :          END DO
    1322           34 :          route%transform%packed_first(ngroup + 1) = pos
    1323              :       END IF
    1324        41910 :    END SUBROUTINE rskp_tile_map
    1325              : 
    1326              : ! **************************************************************************************************
    1327              : !> \brief Find group-local FM owners and optionally pack their cropped source indices.
    1328              : !> \param route source AO block layout and neighbor traversal
    1329              : !> \param fms target FM layout within each group
    1330              : !> \param i traversal entry
    1331              : !> \param needed recipient group-local ranks, without duplicate mirror sends
    1332              : !> \param value_count cropped value counts by target rank
    1333              : !> \param value_start optional offsets into the value-index buffer
    1334              : !> \param value_index optional column-major source indices, packed by recipient
    1335              : ! **************************************************************************************************
    1336     17411962 :    SUBROUTINE rskp_owners(route, fms, i, needed, value_count, value_start, value_index)
    1337              : 
    1338              :       TYPE(rskp_route_type), INTENT(IN)                  :: route
    1339              :       TYPE(cp_fm_struct_type), INTENT(IN)                :: fms
    1340              :       INTEGER, INTENT(IN)                                :: i
    1341              :       LOGICAL, INTENT(OUT)                               :: needed(0:)
    1342              :       INTEGER, INTENT(OUT)                               :: value_count(0:)
    1343              :       INTEGER, INTENT(IN), OPTIONAL                      :: value_start(0:)
    1344              :       INTEGER, INTENT(INOUT), OPTIONAL                   :: value_index(:)
    1345              : 
    1346              :       INTEGER                                            :: c0, col, direct, mirror, nc, nr, r0, row
    1347              :       LOGICAL                                            :: mirror_block
    1348              : 
    1349     17411962 :       r0 = route%traversal%row_offset(i)
    1350     17411962 :       c0 = route%traversal%col_offset(i)
    1351     17411962 :       nr = route%row_size(route%traversal%row(i))
    1352     17411962 :       nc = route%col_size(route%traversal%col(i))
    1353              :       mirror_block = route%traversal%symmetric .AND. &
    1354     17411962 :                      route%traversal%row(i) /= route%traversal%col(i)
    1355     17411962 :       CPASSERT(PRESENT(value_start) .EQV. PRESENT(value_index))
    1356     42778440 :       value_count(:) = 0
    1357     17411962 :       IF (SIZE(needed) == 1) THEN
    1358     18914892 :          needed(:) = .TRUE.
    1359      9457446 :          value_count(0) = nr*nc
    1360              :          RETURN
    1361              :       END IF
    1362              :       ! Send each canonical source element at most once to a recipient,
    1363              :       ! even when that rank owns both its direct and mirrored destinations.
    1364     55106728 :       DO col = 0, nc - 1
    1365    501499192 :          DO row = 0, nr - 1
    1366    446392464 :             direct = fms%context%blacs2mpi(fms%g2p_row(r0 + row), fms%g2p_col(c0 + col))
    1367    446392464 :             mirror = direct
    1368    446392464 :             IF (mirror_block) THEN
    1369    322404826 :                mirror = fms%context%blacs2mpi(fms%g2p_row(c0 + col), fms%g2p_col(r0 + row))
    1370              :             END IF
    1371    446392464 :             value_count(direct) = value_count(direct) + 1
    1372    446392464 :             IF (PRESENT(value_index)) THEN
    1373    223196232 :                value_index(value_start(direct) + value_count(direct)) = row + col*nr + 1
    1374              :             END IF
    1375    446392464 :             IF (mirror == direct) CYCLE
    1376    180747716 :             value_count(mirror) = value_count(mirror) + 1
    1377    227899928 :             IF (PRESENT(value_index)) THEN
    1378     90373858 :                value_index(value_start(mirror) + value_count(mirror)) = row + col*nr + 1
    1379              :             END IF
    1380              :          END DO
    1381              :       END DO
    1382     23863548 :       needed(:) = value_count > 0
    1383              :    END SUBROUTINE rskp_owners
    1384              : 
    1385              : ! **************************************************************************************************
    1386              : !> \brief Check the source AO layout, not its values or sparse block presence.
    1387              : !> \param route fixed context route
    1388              : !> \param source current operator images
    1389              : !> \param matrix_row row to capture
    1390              : !> \param source_sab source neighbor list, required to match the route's geometry
    1391              : !> \return whether the row has the route's image count and AO layout
    1392              : ! **************************************************************************************************
    1393        51344 :    FUNCTION rskp_compatible(route, source, matrix_row, source_sab) RESULT(compatible)
    1394              : 
    1395              :       TYPE(rskp_route_type), INTENT(IN)                  :: route
    1396              :       TYPE(dbcsr_p_type), POINTER                        :: source(:, :)
    1397              :       INTEGER, INTENT(IN)                                :: matrix_row
    1398              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1399              :          POINTER                                         :: source_sab
    1400              :       LOGICAL                                            :: compatible
    1401              : 
    1402              :       INTEGER                                            :: image
    1403        51344 :       INTEGER, POINTER                                   :: col_size(:), row_size(:)
    1404              : 
    1405        51344 :       compatible = .FALSE.
    1406        51344 :       IF (.NOT. ASSOCIATED(route%source_sab, source_sab)) RETURN
    1407        51344 :       IF (SIZE(source, 2) /= route%nimage) RETURN
    1408        51344 :       IF (matrix_row < 1 .OR. matrix_row > SIZE(source, 1)) RETURN
    1409      3317066 :       DO image = 1, SIZE(source, 2)
    1410      3265722 :          CALL dbcsr_get_info(source(matrix_row, image)%matrix, row_blk_size=row_size, col_blk_size=col_size)
    1411      3265722 :          IF (SIZE(row_size) /= SIZE(route%row_size) .OR. SIZE(col_size) /= SIZE(route%col_size)) RETURN
    1412     29770546 :          IF (ANY(row_size /= route%row_size) .OR. ANY(col_size /= route%col_size)) RETURN
    1413              :       END DO
    1414        51344 :       compatible = .TRUE.
    1415              : 
    1416        51344 :    END FUNCTION rskp_compatible
    1417              : 
    1418              : ! **************************************************************************************************
    1419              : !> \brief Capture current values using cached routing, with no per-k communication.
    1420              : !>        GEMM/FFT snapshots own packed local AO-element/image matrices. A shared
    1421              : !>        cropped receive buffer is reused across slots and operator refreshes.
    1422              : !> \param source current real-space operator images
    1423              : !> \param matrix_row row to snapshot
    1424              : !> \param route context-owned metadata, counts and reusable packing buffer
    1425              : !> \param snapshot immutable tile-local values
    1426              : !> \param mirror_sign transpose parity of the unscaled operator (+1 or -1)
    1427              : !> \param scale complex prefactor, applied after forming direct and mirrored values
    1428              : ! **************************************************************************************************
    1429        52820 :    SUBROUTINE rskp_capture(source, matrix_row, route, snapshot, mirror_sign, scale)
    1430              : 
    1431              :       TYPE(dbcsr_p_type), POINTER                        :: source(:, :)
    1432              :       INTEGER, INTENT(IN)                                :: matrix_row
    1433              :       TYPE(rskp_route_type), INTENT(INOUT), TARGET       :: route
    1434              :       TYPE(rskp_values_type), INTENT(OUT), TARGET        :: snapshot
    1435              :       INTEGER, INTENT(IN), OPTIONAL                      :: mirror_sign
    1436              :       COMPLEX(KIND=dp), INTENT(IN), OPTIONAL             :: scale
    1437              : 
    1438              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'rskp_capture'
    1439              : 
    1440              :       INTEGER                                            :: col, element, g, handle, i, iblock, m, &
    1441              :                                                             ncol, nrow, odd, panels(4), pos, row
    1442              :       LOGICAL                                            :: found
    1443              :       REAL(KIND=dp)                                      :: sense
    1444              :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: received(:)
    1445        52820 :       REAL(KIND=dp), POINTER                             :: block(:, :)
    1446              :       TYPE(mp_para_env_type), POINTER                    :: inter, world
    1447              : 
    1448        52820 :       CALL timeset(routineN, handle)
    1449        52820 :       world => route%world
    1450        52820 :       inter => route%inter
    1451        52820 :       m = route%transform%packed_first(SIZE(route%transform%packed_first)) - 1
    1452        52820 :       CPASSERT(m <= route%nvalue)
    1453   1177100673 :       ALLOCATE (snapshot%packed(m), source=0.0_dp)
    1454        52820 :       snapshot%source => source
    1455        52820 :       snapshot%matrix_row = matrix_row
    1456        52820 :       IF (PRESENT(mirror_sign)) snapshot%mirror_sign = mirror_sign
    1457        52820 :       CPASSERT(ABS(snapshot%mirror_sign) == 1)
    1458        52820 :       IF (PRESENT(scale)) snapshot%scale = scale
    1459        52820 :       IF (world%num_pe == 1) THEN
    1460              :          ! Add each image to its fixed raw-FFT or parity-GEMM panels.
    1461            0 :          DO iblock = 1, SIZE(route%entry, 2)
    1462            0 :             i = route%send_entry(iblock)
    1463              :             CALL dbcsr_get_readonly_block_p(source(matrix_row, route%traversal%image(i))%matrix, &
    1464            0 :                                             route%traversal%row(i), route%traversal%col(i), block, found)
    1465            0 :             IF (.NOT. found) CYCLE
    1466            0 :             pos = route%transform%fold_map(1, iblock)
    1467            0 :             odd = ABS(route%transform%fold_map(2, iblock))
    1468            0 :             sense = REAL(SIGN(1, route%transform%fold_map(2, iblock)), dp)
    1469            0 :             DO col = 1, SIZE(block, 2)
    1470            0 :                DO row = 1, SIZE(block, 1)
    1471            0 :                   snapshot%packed(pos) = snapshot%packed(pos) + block(row, col)
    1472            0 :                   IF (odd > 0) THEN
    1473            0 :                      snapshot%packed(odd) = snapshot%packed(odd) + sense*block(row, col)
    1474            0 :                      odd = odd + 1
    1475              :                   END IF
    1476            0 :                   pos = pos + 1
    1477              :                END DO
    1478              :             END DO
    1479              :          END DO
    1480              :       ELSE
    1481        52820 :          received => route%recv_values
    1482    834165753 :          route%send_values(:) = 0.0_dp
    1483              : !$OMP PARALLEL DO DEFAULT(NONE) SHARED(source, matrix_row, route) &
    1484        52820 : !$OMP PRIVATE(iblock, i, block, found, nrow, ncol, pos, row, col, element) SCHEDULE(STATIC)
    1485              :          DO iblock = 1, SIZE(route%send_entry)
    1486              :             i = route%send_entry(iblock)
    1487              :             CALL dbcsr_get_readonly_block_p(source(matrix_row, route%traversal%image(i))%matrix, &
    1488              :                                             route%traversal%row(i), route%traversal%col(i), block, found)
    1489              :             IF (.NOT. found) CYCLE
    1490              :             nrow = route%row_size(route%traversal%row(i))
    1491              :             ncol = route%col_size(route%traversal%col(i))
    1492              :             CPASSERT(SIZE(block, 1) == nrow .AND. SIZE(block, 2) == ncol)
    1493              :             pos = route%send_first(iblock)
    1494              :             IF (ALLOCATED(route%send_element)) THEN
    1495              :                DO element = pos, route%send_first(iblock + 1) - 1
    1496              :                   row = MODULO(route%send_element(element) - 1, nrow) + 1
    1497              :                   col = (route%send_element(element) - 1)/nrow + 1
    1498              :                   route%send_values(element) = block(row, col)
    1499              :                END DO
    1500              :                CYCLE
    1501              :             END IF
    1502              :             DO col = 1, ncol
    1503              :                DO row = 1, nrow
    1504              :                   route%send_values(pos) = block(row, col)
    1505              :                   pos = pos + 1
    1506              :                END DO
    1507              :             END DO
    1508              :          END DO
    1509              : !$OMP END PARALLEL DO
    1510        52820 :          IF (world%num_pe == 1 .OR. &
    1511              :              (.NOT. route%world_target .AND. route%group%num_pe == 1)) THEN
    1512       177100 :             CALL world%allgatherv(route%send_values, received, route%rcount(2, :), route%rdisp(2, :))
    1513              :          ELSE
    1514              :             CALL world%alltoall(route%send_values, route%scount(2, :), route%sdisp(2, :), &
    1515       156600 :                                 received, route%rcount(2, :), route%rdisp(2, :))
    1516        17400 :             IF (.NOT. route%world_target) CALL inter%bcast(received, 0)
    1517              :          END IF
    1518              :          BLOCK
    1519     20493638 :             DO iblock = 1, SIZE(route%entry, 2)
    1520     20440818 :                pos = route%transform%fold_map(1, iblock)
    1521     20440818 :                odd = ABS(route%transform%fold_map(2, iblock))
    1522     20440818 :                m = route%first(iblock + 1) - route%first(iblock)
    1523              :                snapshot%packed(pos:pos + m - 1) = snapshot%packed(pos:pos + m - 1) + &
    1524   2394766062 :                                                   received(route%first(iblock):route%first(iblock + 1) - 1)
    1525     20440818 :                IF (odd == 0) CYCLE
    1526     13701996 :                sense = REAL(SIGN(1, route%transform%fold_map(2, iblock)), dp)
    1527              :                snapshot%packed(odd:odd + m - 1) = snapshot%packed(odd:odd + m - 1) + &
    1528   1680309370 :                                                   sense*received(route%first(iblock):route%first(iblock + 1) - 1)
    1529              :             END DO
    1530              :          END BLOCK
    1531              :       END IF
    1532        52820 :       IF (route%transform%backend == rskp_backend_gemm) THEN
    1533       158274 :          ALLOCATE (snapshot%active(4, SIZE(route%transform%phase_count, 2)))
    1534       759570 :          DO g = 1, SIZE(snapshot%active, 2)
    1535       706812 :             m = route%element_first(g + 1) - route%element_first(g)
    1536      3534060 :             panels = route%transform%phase_count([1, 1, 2, 3], g)
    1537       706812 :             pos = route%transform%packed_first(g)
    1538      3586818 :             DO i = 1, 4
    1539      7774838 :                snapshot%active(i, g) = ANY(snapshot%packed(pos:pos + m*panels(i) - 1) /= 0.0_dp)
    1540      3534060 :                pos = pos + m*panels(i)
    1541              :             END DO
    1542              :          END DO
    1543              :       END IF
    1544        52820 :       CALL timestop(handle)
    1545              : 
    1546       105640 :    END SUBROUTINE rskp_capture
    1547              : 
    1548              : ! **************************************************************************************************
    1549              : !> \brief Release one captured row without invalidating other slots or routing.
    1550              : !> \param snapshot row to clear
    1551              : ! **************************************************************************************************
    1552       185288 :    SUBROUTINE rskp_values_release(snapshot)
    1553              : 
    1554              :       TYPE(rskp_values_type), INTENT(INOUT)              :: snapshot
    1555              : 
    1556       185288 :       IF (ALLOCATED(snapshot%packed)) DEALLOCATE (snapshot%packed)
    1557       185288 :       IF (ALLOCATED(snapshot%active)) DEALLOCATE (snapshot%active)
    1558       185288 :       IF (ALLOCATED(snapshot%fft_values)) DEALLOCATE (snapshot%fft_values)
    1559       185288 :       NULLIFY (snapshot%source)
    1560       185288 :       snapshot%matrix_row = 0
    1561       185288 :       snapshot%mirror_sign = 1
    1562       185288 :       snapshot%scale = z_one
    1563              : 
    1564       185288 :    END SUBROUTINE rskp_values_release
    1565              : 
    1566              : ! **************************************************************************************************
    1567              : !> \brief Release backend-owned geometry and FFT work buffers from a route.
    1568              : !> \param route route whose backend plan is no longer needed
    1569              : ! **************************************************************************************************
    1570        43324 :    SUBROUTINE rskp_route_release(route)
    1571              :       TYPE(rskp_route_type), INTENT(INOUT)               :: route
    1572              : 
    1573        43324 :       CALL cell_to_k_grid_release(route%transform%fft_work)
    1574        43324 :       IF (ASSOCIATED(route%matrix_struct)) CALL cp_fm_struct_release(route%matrix_struct)
    1575       173296 :       route = rskp_route_type()
    1576        43324 :    END SUBROUTINE rskp_route_release
    1577              : 
    1578              : ! **************************************************************************************************
    1579              : !> \brief FFT captured raw-element panels and retain the destination group's k points.
    1580              : !>        Reuse the sparse route and the dense layout consumed by the batched solvers.
    1581              : !> \param snapshot immutable packed raw-image panels
    1582              : !> \param route fixed element/image layout and equivalent target tiles across groups
    1583              : !> \param xkp full reciprocal grid
    1584              : !> \param nkp_grid reciprocal-grid dimensions
    1585              : !> \param kp_dist global k-point range of each group
    1586              : !> \param inter communicator joining equivalent FM ranks across groups
    1587              : !> \param max_bytes soft workspace target, excluding retained inputs and destinations
    1588              : !> \param cache optional unscaled canonical elements by local k point
    1589              : !> \param output optional existing split-FM destinations, instead of cache
    1590              : ! **************************************************************************************************
    1591           62 :    SUBROUTINE cell_to_k_sparse_fft(snapshot, route, xkp, nkp_grid, kp_dist, inter, max_bytes, cache, output)
    1592              :       TYPE(rskp_values_type), INTENT(IN), TARGET         :: snapshot
    1593              :       TYPE(rskp_route_type), INTENT(INOUT)               :: route
    1594              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    1595              :       INTEGER, INTENT(IN)                                :: nkp_grid(3), kp_dist(:, :)
    1596              :       TYPE(mp_para_env_type), INTENT(IN)                 :: inter
    1597              :       INTEGER(KIND=int_8), INTENT(IN)                    :: max_bytes
    1598              :       COMPLEX(KIND=dp), CONTIGUOUS, INTENT(OUT), &
    1599              :          OPTIONAL                                        :: cache(:, :)
    1600              :       TYPE(cp_fm_p_type), INTENT(IN), OPTIONAL           :: output(:, :)
    1601              : 
    1602           62 :       COMPLEX(KIND=dp), ALLOCATABLE, TARGET              :: received(:), transformed(:, :, :)
    1603           62 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: canonical(:, :), send(:)
    1604              :       INTEGER                                            :: element, first, group, i, igroup, ik, &
    1605              :                                                             last, my_peer, nelem, nimages, nk, &
    1606              :                                                             nlocal, npeers, ntile, nwave, offset, &
    1607              :                                                             start, width
    1608              :       INTEGER(KIND=int_8)                                :: available, fixed_bytes, ngrid, &
    1609              :                                                             per_element, workspace_bytes
    1610           62 :       INTEGER, ALLOCATABLE                               :: ranges(:, :), rcount(:), rdisp(:), &
    1611              :                                                             scount(:), sdisp(:)
    1612           62 :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: values(:, :, :)
    1613              : 
    1614            0 :       CPASSERT(route%transform%backend == rskp_backend_fft)
    1615           62 :       CPASSERT(PRESENT(cache) .NEQV. PRESENT(output))
    1616           62 :       CPASSERT(route%transform%fft_work%regular)
    1617          248 :       ngrid = PRODUCT(INT(route%transform%fft_work%nfft, int_8))
    1618           62 :       nk = SIZE(xkp, 2)
    1619           62 :       IF (PRESENT(cache)) THEN
    1620           62 :          CPASSERT(SIZE(cache, 1) == route%element_first(SIZE(route%element_first)) - 1)
    1621           62 :          nlocal = SIZE(cache, 2)
    1622       153042 :          cache = z_zero
    1623              :       ELSE
    1624            0 :          nlocal = SIZE(output, 1)
    1625            0 :          DO ik = 1, nlocal
    1626            0 :             DO i = 1, SIZE(output, 2)
    1627            0 :                output(ik, i)%matrix%local_data(:, :) = 0.0_dp
    1628              :             END DO
    1629              :          END DO
    1630              :       END IF
    1631           62 :       npeers = 1
    1632           62 :       my_peer = 0
    1633           62 :       IF (.NOT. route%world_target) THEN
    1634           62 :          npeers = inter%num_pe
    1635           62 :          my_peer = inter%mepos
    1636              :       END IF
    1637          186 :       ALLOCATE (ranges(2, npeers))
    1638          186 :       ranges(:, 1) = [1, nk]
    1639          376 :       IF (.NOT. route%world_target) ranges(:, :) = kp_dist
    1640           62 :       CPASSERT(nlocal == ranges(2, my_peer + 1) - ranges(1, my_peer + 1) + 1)
    1641           62 :       available = max_bytes
    1642           62 :       IF (.NOT. route%world_target) CALL inter%min(available)
    1643          372 :       ALLOCATE (scount(npeers), sdisp(npeers), rcount(npeers), rdisp(npeers))
    1644          394 :       DO igroup = 1, SIZE(route%block_first) - 1
    1645          332 :          first = route%block_first(igroup)
    1646          332 :          last = route%block_first(igroup + 1) - 1
    1647          332 :          nelem = route%element_first(igroup + 1) - route%element_first(igroup)
    1648          332 :          nimages = last - first + 1
    1649              :          values(1:nelem, 1:1, 1:nimages) => &
    1650          332 :             snapshot%packed(route%transform%packed_first(igroup):route%transform%packed_first(igroup + 1) - 1)
    1651          620 :          IF (.NOT. ANY(values /= 0.0_dp)) CYCLE
    1652              :          ! Each group transforms different AO elements; exchange only the owned k ranges.
    1653          332 :          fixed_bytes = 16_int_8*nk + 28_int_8*SIZE(route%entry, 2) + 16_int_8*npeers
    1654              :          per_element = 16_int_8*nk + 48_int_8*ngrid + &
    1655          796 :                        16_int_8*npeers*MAXVAL(ranges(2, :) - ranges(1, :) + 1)
    1656              :          width = INT(MAX(0_int_8, MIN((INT(nelem, int_8) + INT(npeers, int_8) - 1_int_8)/INT(npeers, int_8), &
    1657              :                                       MAX(1_int_8, fft_batch_bytes/(48_int_8*ngrid)), &
    1658              :                                       MAX(1_int_8, (available - fixed_bytes)/per_element), INT(HUGE(0), int_8)/nk, &
    1659              :                                       INT(HUGE(0), int_8)/(INT(npeers, int_8)* &
    1660          796 :                                                            MAXVAL(ranges(2, :) - ranges(1, :) + 1)))))
    1661          332 :          IF (width == 0) THEN
    1662            0 :             CPABORT("Lattice FFT tile exceeds the integer MPI count range")
    1663              :          END IF
    1664          394 :          DO element = 1, nelem, width*npeers
    1665          332 :             start = element + my_peer*width
    1666          332 :             ntile = MAX(0, MIN(width, nelem - start + 1))
    1667          332 :             nwave = MIN(width*npeers, nelem - element + 1)
    1668         1992 :             ALLOCATE (transformed(ntile, 1, nk), received(nwave*nlocal))
    1669          332 :             IF (ntile > 0) THEN
    1670              :                workspace_bytes = available - fixed_bytes - 16_int_8*(SIZE(transformed, KIND=int_8) + &
    1671         1328 :                                                                      SIZE(received, KIND=int_8))
    1672              :                CALL cell_to_k_grid_fft(values(start:start + ntile - 1, :, :), &
    1673              :                                        route%entry(5:7, route%block_order(first:last)), &
    1674              :                                        xkp, nkp_grid, transformed, &
    1675              :                                        require_fft=.TRUE., work=route%transform%fft_work, cell_first=first, &
    1676        34172 :                                        max_workspace_bytes=workspace_bytes)
    1677              :             END IF
    1678         1328 :             send(1:SIZE(transformed)) => transformed
    1679          796 :             scount(:) = ntile*(ranges(2, :) - ranges(1, :) + 1)
    1680          796 :             sdisp(:) = ntile*(ranges(1, :) - 1)
    1681              :             offset = 0
    1682          796 :             DO group = 1, npeers
    1683          464 :                rcount(group) = MAX(0, MIN(width, nelem - element - (group - 1)*width + 1))*nlocal
    1684          464 :                rdisp(group) = offset
    1685          796 :                offset = offset + rcount(group)
    1686              :             END DO
    1687          332 :             IF (npeers > 1) THEN
    1688          132 :                CALL inter%alltoall(send, scount, sdisp, received, rcount, rdisp)
    1689              :             ELSE
    1690       216720 :                received(:) = send
    1691              :             END IF
    1692          796 :             DO group = 1, npeers
    1693          464 :                ntile = rcount(group)/MAX(1, nlocal)
    1694          464 :                IF (ntile == 0) CYCLE
    1695          464 :                start = route%element_first(igroup) + element + (group - 1)*width - 1
    1696          464 :                canonical(1:ntile, 1:nlocal) => received(rdisp(group) + 1:rdisp(group) + rcount(group))
    1697          796 :                IF (PRESENT(cache)) THEN
    1698       154568 :                   cache(start:start + ntile - 1, :) = canonical
    1699              :                ELSE
    1700            0 :                   CALL cell_to_k_scatter(canonical, start, route, snapshot%mirror_sign, snapshot%scale, output=output)
    1701              :                END IF
    1702              :             END DO
    1703          332 :             DEALLOCATE (transformed, received)
    1704              :          END DO
    1705              :       END DO
    1706          124 :    END SUBROUTINE cell_to_k_sparse_fft
    1707              : 
    1708              : ! **************************************************************************************************
    1709              : !> \brief Scatter unscaled canonical element tiles into caller-owned dense destinations.
    1710              : !>        The caller clears the destinations once. Mirror parity applies before complex scaling.
    1711              : !> \param values canonical elements by local k point
    1712              : !> \param first_element first canonical element in the route
    1713              : !> \param route immutable destination offsets
    1714              : !> \param mirror_sign transpose parity
    1715              : !> \param scale complex output prefactor
    1716              : !> \param batch optional complex matrix batch
    1717              : !> \param output optional split-FM destinations instead of batch
    1718              : ! **************************************************************************************************
    1719          204 :    SUBROUTINE cell_to_k_scatter(values, first_element, route, mirror_sign, scale, batch, output)
    1720              :       COMPLEX(KIND=dp), INTENT(IN)                       :: values(:, :)
    1721              :       INTEGER, INTENT(IN)                                :: first_element
    1722              :       TYPE(rskp_route_type), INTENT(IN)                  :: route
    1723              :       INTEGER, INTENT(IN)                                :: mirror_sign
    1724              :       COMPLEX(KIND=dp), INTENT(IN)                       :: scale
    1725              :       COMPLEX(KIND=dp), CONTIGUOUS, INTENT(INOUT), &
    1726              :          OPTIONAL, TARGET                                :: batch(:, :, :)
    1727              :       TYPE(cp_fm_p_type), INTENT(IN), OPTIONAL           :: output(:, :)
    1728              : 
    1729              :       COMPLEX(KIND=dp)                                   :: value
    1730          204 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: dense(:, :)
    1731              :       INTEGER                                            :: element, i, ic, k
    1732              :       INTEGER(KIND=int_8)                                :: dest
    1733          204 :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: real_values(:)
    1734              : 
    1735            0 :       CPASSERT(PRESENT(batch) .NEQV. PRESENT(output))
    1736          204 :       IF (PRESENT(batch)) THEN
    1737          204 :          CPASSERT(SIZE(batch, 3) == SIZE(values, 2))
    1738          204 :          dense(1:SIZE(batch, 1, KIND=int_8)*SIZE(batch, 2, KIND=int_8), 1:SIZE(batch, 3)) => batch
    1739          408 :          DO k = 1, SIZE(values, 2)
    1740          612 : !$OMP SIMD PRIVATE(element,dest,value)
    1741              :             DO i = 1, SIZE(values, 1)
    1742       152776 :                element = first_element + i - 1
    1743       152776 :                dest = route%element_offset(1, element)
    1744       152776 :                IF (dest > 0) dense(dest, k) = scale*values(i, k)
    1745       152776 :                dest = route%element_offset(2, element)
    1746       152776 :                value = REAL(mirror_sign, dp)*CONJG(values(i, k))
    1747       152776 :                IF (dest > 0) dense(dest, k) = scale*value
    1748              :             END DO
    1749              :          END DO
    1750              :       ELSE
    1751            0 :          CPASSERT(SIZE(output, 1) == SIZE(values, 2))
    1752            0 :          CPASSERT(SIZE(output, 2) >= 1 .AND. SIZE(output, 2) <= 2)
    1753            0 :          DO k = 1, SIZE(values, 2)
    1754            0 :             DO ic = 1, SIZE(output, 2)
    1755            0 :                real_values(1:SIZE(output(k, ic)%matrix%local_data, KIND=int_8)) => output(k, ic)%matrix%local_data
    1756            0 : !$OMP SIMD PRIVATE(element,dest,value)
    1757              :                DO i = 1, SIZE(values, 1)
    1758            0 :                   element = first_element + i - 1
    1759            0 :                   dest = route%element_offset(1, element)
    1760            0 :                   value = scale*values(i, k)
    1761            0 :                   IF (dest > 0) real_values(dest) = MERGE(REAL(value, dp), AIMAG(value), ic == 1)
    1762            0 :                   dest = route%element_offset(2, element)
    1763            0 :                   value = scale*(REAL(mirror_sign, dp)*CONJG(values(i, k)))
    1764            0 :                   IF (dest > 0) real_values(dest) = MERGE(REAL(value, dp), AIMAG(value), ic == 1)
    1765              :                END DO
    1766              :             END DO
    1767              :          END DO
    1768              :       END IF
    1769          204 :    END SUBROUTINE cell_to_k_scatter
    1770              : 
    1771              : ! **************************************************************************************************
    1772              : !> \brief Fix parity panels per canonical atom pair and cache their shared phases.
    1773              : !>        Reserve one complex worker and caller-specified retained output storage.
    1774              : !>        Oversized tables use the same contraction kernel with tile-local phases.
    1775              : !> \param plan geometry-only dictionary and optional immutable phase table
    1776              : !> \param translations signed image translations
    1777              : !> \param group_first boundaries of canonical AO groups in order
    1778              : !> \param order image permutation grouped by canonical AO pair
    1779              : !> \param element_first cumulative row counts of the packed group panels
    1780              : !> \param xkp fixed group-local reciprocal coordinates
    1781              : !> \param max_bytes shared-phase and worker/output-workspace budget
    1782              : !> \param output_bytes workspace reserved for retained output tiles
    1783              : ! **************************************************************************************************
    1784        42060 :    SUBROUTINE cell_to_k_phase_prepare(plan, translations, group_first, order, element_first, xkp, max_bytes, output_bytes)
    1785              :       TYPE(rskp_backend_plan_type), INTENT(INOUT)        :: plan
    1786              :       INTEGER, INTENT(IN)                                :: translations(:, :), group_first(:), &
    1787              :                                                             order(:), element_first(:)
    1788              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    1789              :       INTEGER(KIND=int_8), INTENT(IN)                    :: max_bytes, output_bytes
    1790              : 
    1791              :       COMPLEX(KIND=dp)                                   :: phase
    1792              :       INTEGER                                            :: c, first, g, i, iblock, ik, j, m, n, &
    1793              :                                                             nfold, nk, npair, nr, nsingle, pos
    1794              :       INTEGER(KIND=int_8)                                :: cache_bytes, minimum_bytes
    1795        42060 :       INTEGER, ALLOCATABLE                               :: cells(:, :), classes(:), &
    1796        42060 :                                                             global_class(:), local_class(:), &
    1797        42060 :                                                             slots(:)
    1798        42060 :       LOGICAL, ALLOCATABLE                               :: members(:, :)
    1799              :       REAL(KIND=dp)                                      :: arg
    1800              : 
    1801        42060 :       CALL rskp_image_classes(translations, classes, plan%phase_cells)
    1802        42060 :       n = SIZE(group_first) - 1
    1803            0 :       ALLOCATE (plan%phase_count(3, n), plan%phase_first(n + 1), plan%packed_first(n + 1), &
    1804       462660 :                 plan%phase_index(SIZE(classes)), plan%fold_map(2, SIZE(classes)))
    1805     46064631 :       plan%fold_map = 0
    1806        42060 :       plan%phase_first(1) = 1
    1807        42060 :       plan%packed_first(1) = 1
    1808        42060 :       plan%max_per_k = 0_int_8
    1809       634588 :       DO g = 1, n
    1810       592528 :          first = group_first(g)
    1811              :          CALL rskp_image_classes(translations(:, order(first:group_first(g + 1) - 1)), &
    1812     61955956 :                                  local_class, cells)
    1813      3485949 :          ALLOCATE (members(2, SIZE(cells, 2)), slots(SIZE(cells, 2)), global_class(SIZE(cells, 2)))
    1814       592528 :          members = .FALSE.
    1815     15933385 :          DO i = 1, SIZE(local_class)
    1816     15340857 :             c = local_class(i)
    1817     15340857 :             IF (c == 0) CYCLE
    1818     14759961 :             members(MERGE(1, 2, c > 0), ABS(c)) = .TRUE.
    1819     14759961 :             iblock = order(first + i - 1)
    1820     15933385 :             global_class(ABS(c)) = ABS(classes(iblock))
    1821              :          END DO
    1822     10396111 :          npair = COUNT(ALL(members, DIM=1))
    1823       592528 :          nsingle = SIZE(cells, 2) - npair
    1824      9846091 :          plan%phase_count(:, g) = [npair, nsingle, MERGE(1, 0, ANY(local_class == 0))]
    1825       592528 :          i = 0
    1826       592528 :          j = 0
    1827     10396111 :          DO c = 1, SIZE(cells, 2)
    1828     22655520 :             IF (ALL(members(:, c))) THEN
    1829      4956378 :                i = i + 1
    1830      4956378 :                slots(c) = i
    1831      4956378 :                plan%phase_index(plan%phase_first(g) + i - 1) = global_class(c)
    1832              :             ELSE
    1833      4847205 :                j = j + 1
    1834      4847205 :                slots(c) = 2*npair + j
    1835      7347757 :                plan%phase_index(plan%phase_first(g) + npair + j - 1) = MERGE(1, -1, members(1, c))*global_class(c)
    1836              :             END IF
    1837              :          END DO
    1838       592528 :          m = element_first(g + 1) - element_first(g)
    1839       592528 :          nfold = 2*npair + nsingle + plan%phase_count(3, g)
    1840       592528 :          plan%phase_first(g + 1) = plan%phase_first(g) + npair + nsingle
    1841       592528 :          IF (INT(plan%packed_first(g), int_8) + INT(m, int_8)*nfold > HUGE(m)) THEN
    1842            0 :             CPABORT("R-to-K folded panel offsets exceed the integer range")
    1843              :          END IF
    1844       592528 :          plan%packed_first(g + 1) = plan%packed_first(g) + m*nfold
    1845       592528 :          plan%max_per_k = MAX(plan%max_per_k, INT(m, int_8) + MAX(npair, nsingle))
    1846     15933385 :          DO i = 1, SIZE(local_class)
    1847     15340857 :             iblock = order(first + i - 1)
    1848     15340857 :             c = local_class(i)
    1849     15340857 :             pos = nfold
    1850     15340857 :             IF (c /= 0) pos = slots(ABS(c))
    1851     15340857 :             plan%fold_map(1, iblock) = plan%packed_first(g) + (pos - 1)*m
    1852     15340857 :             IF (c == 0) CYCLE
    1853     37524654 :             IF (ALL(members(:, ABS(c)))) THEN
    1854      9912756 :                plan%fold_map(2, iblock) = SIGN(plan%packed_first(g) + (npair + pos - 1)*m, c)
    1855              :             END IF
    1856              :          END DO
    1857       634588 :          DEALLOCATE (members, slots, global_class)
    1858              :       END DO
    1859              : 
    1860        42060 :       nr = SIZE(plan%phase_cells, 2)
    1861        42060 :       nk = SIZE(xkp, 2)
    1862        42060 :       cache_bytes = 16_int_8*nr*nk
    1863        42060 :       minimum_bytes = 16_int_8*plan%max_per_k + output_bytes
    1864        42060 :       IF (cache_bytes + minimum_bytes > max_bytes) RETURN
    1865       210234 :       ALLOCATE (plan%phases(nr, nk, 2))
    1866       140804 :       DO ik = 1, nk
    1867       140804 : !$OMP SIMD PRIVATE(arg,phase)
    1868              :          DO i = 1, nr
    1869     14231640 :             arg = twopi*DOT_PRODUCT(REAL(plan%phase_cells(:, i), dp), xkp(:, ik))
    1870      3557910 :             phase = EXP(CMPLX(0.0_dp, arg, KIND=dp))
    1871      3557910 :             plan%phases(i, ik, 1) = REAL(phase, dp)
    1872      3557910 :             plan%phases(i, ik, 2) = AIMAG(phase)
    1873              :          END DO
    1874              :       END DO
    1875        42060 :    END SUBROUTINE cell_to_k_phase_prepare
    1876              : 
    1877              : ! **************************************************************************************************
    1878              : !> \brief Prepare the selected R-to-K backend plan once for a fixed route.
    1879              : !>        Both backends retain their geometry with the route; the snapshots then
    1880              : !>        provide only values and use the common evaluate interface.
    1881              : !> \param route fixed sparse AO route and backend workspace
    1882              : !> \param xkp reciprocal coordinates for the route's k-point domain
    1883              : !> \param nkp_grid regular-grid dimensions required by the FFT backend
    1884              : !> \param max_bytes phase-cache budget for the GEMM backend
    1885              : ! **************************************************************************************************
    1886        41910 :    SUBROUTINE cell_to_k_backend_prepare(route, xkp, nkp_grid, max_bytes)
    1887              :       TYPE(rskp_route_type), INTENT(INOUT)               :: route
    1888              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    1889              :       INTEGER, INTENT(IN)                                :: nkp_grid(3)
    1890              :       INTEGER(KIND=int_8), INTENT(IN)                    :: max_bytes
    1891              : 
    1892        83786 :       SELECT CASE (route%transform%backend)
    1893              :       CASE (rskp_backend_gemm)
    1894              :          CALL cell_to_k_phase_prepare(route%transform, route%entry(5:7, :), route%block_first, route%block_order, &
    1895              :                                       route%element_first, xkp, max_bytes, &
    1896        41876 :                                       32_int_8*route%matrix_struct%local_leading_dimension*MAX(1, route%ncol))
    1897              :       CASE (rskp_backend_fft)
    1898        18354 :          CALL cell_to_k_grid_prepare(route%transform%fft_work, route%entry(5:7, route%block_order), xkp, nkp_grid)
    1899           34 :          IF (.NOT. route%transform%fft_work%regular) THEN
    1900            0 :             CPABORT("Forced lattice FFT needs a supported regular grid or subset")
    1901              :          END IF
    1902              :       CASE DEFAULT
    1903        41910 :          CPABORT("Unknown R-to-K backend")
    1904              :       END SELECT
    1905        41910 :    END SUBROUTINE cell_to_k_backend_prepare
    1906              : 
    1907              : ! **************************************************************************************************
    1908              : !> \brief Contract parity-folded pairs and concatenate phases for unpaired translations.
    1909              : !> \param packed immutable parity panels of one AO group
    1910              : !> \param plan phase dictionary shared by the FM and DBCSR adapters
    1911              : !> \param igroup canonical atom-pair group
    1912              : !> \param xkp k coordinates for this tile
    1913              : !> \param first_k first index in the route-local phase table
    1914              : !> \param factors cosine columns followed by optional sine columns
    1915              : !> \param RESULT real columns followed by optional imaginary columns
    1916              : !> \param active nonzero even, odd, single and origin panels, determined at capture
    1917              : ! **************************************************************************************************
    1918      1038800 :    SUBROUTINE cell_to_k_block_gemm(packed, plan, igroup, xkp, first_k, factors, RESULT, active)
    1919              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN), TARGET      :: packed(:)
    1920              :       TYPE(rskp_backend_plan_type), INTENT(IN)           :: plan
    1921              :       INTEGER, INTENT(IN)                                :: igroup
    1922              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    1923              :       INTEGER, INTENT(IN)                                :: first_k
    1924              :       REAL(KIND=dp), CONTIGUOUS, INTENT(OUT)             :: factors(:, :), RESULT(:, :)
    1925              :       LOGICAL, INTENT(IN)                                :: active(4)
    1926              : 
    1927              :       INTEGER                                            :: first, i, ik, nactive, nelem, nk, npair, &
    1928              :                                                             nsingle, pass, phase, start
    1929              :       LOGICAL                                            :: use_cosine, use_sine
    1930              :       REAL(KIND=dp)                                      :: arg, beta(2)
    1931      1038800 :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: values(:, :), values_im(:, :)
    1932              : 
    1933      1038800 :       nelem = SIZE(RESULT, 1)
    1934      1038800 :       nk = SIZE(xkp, 2)
    1935      1032630 :       CPASSERT(SIZE(RESULT, 2) == nk .OR. SIZE(RESULT, 2) == 2*nk)
    1936      1038800 :       npair = plan%phase_count(1, igroup)
    1937      1038800 :       nsingle = plan%phase_count(2, igroup)
    1938      1038800 :       first = plan%phase_first(igroup)
    1939      1038800 :       start = 1
    1940      1038800 :       IF (ALLOCATED(plan%phases)) THEN
    1941      1038800 :          CPASSERT(first_k >= 1 .AND. first_k + nk - 1 <= SIZE(plan%phases, 2))
    1942              :       END IF
    1943      1038800 :       beta = 0.0_dp
    1944      3116400 :       DO pass = 1, 2
    1945      2077600 :          nactive = MERGE(npair, nsingle, pass == 1)
    1946      2077600 :          IF (nactive == 0) CYCLE
    1947      1599205 :          use_cosine = MERGE(active(1), active(3), pass == 1)
    1948      1599205 :          use_sine = SIZE(RESULT, 2) == 2*nk .AND. MERGE(active(2), active(3), pass == 1)
    1949        22250 :          IF (.NOT. (use_cosine .OR. use_sine)) THEN
    1950         4817 :             start = start + nelem*nactive*MERGE(2, 1, pass == 1)
    1951         4817 :             first = first + nactive
    1952         4817 :             CYCLE
    1953              :          END IF
    1954      4058410 :          DO ik = 1, nk
    1955     39748792 :             DO i = 1, nactive
    1956     35690382 :                phase = plan%phase_index(first + i - 1)
    1957     38154404 :                IF (ALLOCATED(plan%phases)) THEN
    1958     35690382 :                   IF (use_cosine) factors(i, ik) = plan%phases(ABS(phase), first_k + ik - 1, 1)
    1959     35690382 :                   IF (use_sine) THEN
    1960     35077798 :                      factors(i, nk + ik) = REAL(SIGN(1, phase), dp)*plan%phases(ABS(phase), first_k + ik - 1, 2)
    1961              :                   END IF
    1962              :                ELSE
    1963            0 :                   arg = twopi*DOT_PRODUCT(REAL(plan%phase_cells(:, ABS(phase)), dp), xkp(:, ik))
    1964            0 :                   IF (use_cosine) factors(i, ik) = COS(arg)
    1965            0 :                   IF (use_sine) factors(i, nk + ik) = REAL(SIGN(1, phase), dp)*SIN(arg)
    1966              :                END IF
    1967              :             END DO
    1968              :          END DO
    1969      1594388 :          values(1:nelem, 1:nactive) => packed(start:start + nelem*nactive - 1)
    1970      1594388 :          IF (pass == 1) THEN
    1971       825662 :             start = start + nelem*npair
    1972       825662 :             IF (active(1)) THEN
    1973       825662 :                CALL rskp_gemm_contract(nelem, npair, nk, values, factors(:, 1:nk), RESULT(:, 1:nk), 0.0_dp)
    1974       825662 :                beta(1) = 1.0_dp
    1975              :             END IF
    1976       825662 :             IF (SIZE(RESULT, 2) == 2*nk .AND. active(2)) THEN
    1977       813061 :                values_im(1:nelem, 1:npair) => packed(start:start + nelem*npair - 1)
    1978              :                CALL rskp_gemm_contract(nelem, npair, nk, values_im, factors(:, nk + 1:2*nk), &
    1979       813061 :                                        RESULT(:, nk + 1:2*nk), 0.0_dp)
    1980       813061 :                beta(2) = 1.0_dp
    1981              :             END IF
    1982       825662 :             start = start + nelem*npair
    1983              :          ELSE
    1984       768726 :             IF (SIZE(RESULT, 2) == 2*nk .AND. beta(1) == beta(2)) THEN
    1985       763731 :                CALL rskp_gemm_contract(nelem, nsingle, 2*nk, values, factors, RESULT, beta(1))
    1986              :             ELSE
    1987         4995 :                CALL rskp_gemm_contract(nelem, nsingle, nk, values, factors(:, 1:nk), RESULT(:, 1:nk), beta(1))
    1988         4995 :                IF (SIZE(RESULT, 2) == 2*nk) THEN
    1989              :                   CALL rskp_gemm_contract(nelem, nsingle, nk, values, factors(:, nk + 1:2*nk), &
    1990          163 :                                           RESULT(:, nk + 1:2*nk), beta(2))
    1991              :                END IF
    1992              :             END IF
    1993      2306178 :             beta = 1.0_dp
    1994       768726 :             start = start + nelem*nsingle
    1995              :          END IF
    1996      3111583 :          first = first + nactive
    1997              :       END DO
    1998      1530029 :       IF (beta(1) == 0.0_dp) RESULT(:, 1:nk) = 0.0_dp
    1999      1584956 :       IF (SIZE(RESULT, 2) == 2*nk .AND. beta(2) == 0.0_dp) RESULT(:, nk + 1:2*nk) = 0.0_dp
    2000      1038800 :       IF (active(4)) THEN
    2001      2595022 :          DO ik = 1, nk
    2002     73666619 :             RESULT(:, ik) = RESULT(:, ik) + packed(start:start + nelem - 1)
    2003              :          END DO
    2004              :       END IF
    2005      1038800 :    END SUBROUTINE cell_to_k_block_gemm
    2006              : 
    2007              : ! **************************************************************************************************
    2008              : !> \brief Bound worker scratch and output tiles for either prepared backend.
    2009              : !>        Packed input belongs to the snapshot and is shared by every k tile.
    2010              : !> \param route borrowed local AO-element layout
    2011              : !> \param nk local k-point count
    2012              : !> \param ncomp contraction components for split-FM outputs (two for a complex source scale)
    2013              : !> \param nworkers requested workers, reduced to fit the workspace
    2014              : !> \param nmatrices retained complex operator tiles; zero writes existing split-FM outputs
    2015              : !> \param max_bytes shared-phase, worker-scratch and output-tile budget
    2016              : !> \param width k points per worker
    2017              : !> \param work_size real scratch elements per worker
    2018              : ! **************************************************************************************************
    2019        29660 :    SUBROUTINE rskp_batch_size(route, nk, ncomp, nworkers, nmatrices, max_bytes, width, work_size)
    2020              :       TYPE(rskp_route_type), INTENT(IN)                  :: route
    2021              :       INTEGER, INTENT(IN)                                :: nk, ncomp
    2022              :       INTEGER, INTENT(INOUT)                             :: nworkers
    2023              :       INTEGER, INTENT(IN)                                :: nmatrices
    2024              :       INTEGER(KIND=int_8), INTENT(IN)                    :: max_bytes
    2025              :       INTEGER, INTENT(OUT)                               :: width
    2026              :       INTEGER(KIND=int_8), INTENT(OUT)                   :: work_size
    2027              : 
    2028              :       INTEGER                                            :: nc
    2029              :       INTEGER(KIND=int_8)                                :: available_bytes, output_bytes, &
    2030              :                                                             per_k_bytes
    2031              : 
    2032        29660 :       CPASSERT(nworkers > 0 .AND. nk > 0 .AND. nmatrices >= 0)
    2033        29660 :       available_bytes = max_bytes
    2034        29660 :       IF (ALLOCATED(route%transform%phases)) THEN
    2035       118640 :          available_bytes = available_bytes - 8_int_8*SIZE(route%transform%phases, KIND=int_8)
    2036              :       END IF
    2037        29660 :       output_bytes = 16_int_8*nmatrices*route%matrix_struct%local_leading_dimension*MAX(1, route%ncol)
    2038        29660 :       nc = 2
    2039        29660 :       IF (nmatrices == 0) nc = ncomp
    2040        29660 :       per_k_bytes = MAX(1_int_8, 8_int_8*nc*route%transform%max_per_k + output_bytes)
    2041        29660 :       nworkers = MIN(nworkers, nk)
    2042        29660 :       nworkers = MIN(nworkers, INT(MAX(1_int_8, available_bytes/per_k_bytes)))
    2043        29660 :       width = INT(MIN(INT(nk, int_8), MAX(1_int_8, available_bytes/(nworkers*per_k_bytes))))
    2044        29660 :       width = MIN(width, (nk + nworkers - 1)/nworkers)
    2045        29660 :       work_size = INT(nc, int_8)*width*route%transform%max_per_k
    2046        29660 :    END SUBROUTINE rskp_batch_size
    2047              : 
    2048              : ! **************************************************************************************************
    2049              : !> \brief Assemble a local complex operator tile directly from packed sparse inputs.
    2050              : !> \param snapshot immutable BLAS-layout input values
    2051              : !> \param route borrowed local AO-element layout
    2052              : !> \param xkp coordinates for this k tile
    2053              : !> \param first_k first index in the route-local phase table
    2054              : !> \param work caller-owned real phase and result scratch
    2055              : !> \param batch optional complex output (row, column, k point), including padding
    2056              : !> \param output optional existing split-FM destinations (k point, component)
    2057              : ! **************************************************************************************************
    2058        79088 :    SUBROUTINE cell_to_k_gemm_batch(snapshot, route, xkp, first_k, work, batch, output)
    2059              :       TYPE(rskp_values_type), INTENT(IN), TARGET         :: snapshot
    2060              :       TYPE(rskp_route_type), INTENT(IN)                  :: route
    2061              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    2062              :       INTEGER, INTENT(IN)                                :: first_k
    2063              :       REAL(KIND=dp), CONTIGUOUS, INTENT(INOUT), TARGET   :: work(:)
    2064              :       COMPLEX(KIND=dp), CONTIGUOUS, INTENT(OUT), &
    2065              :          OPTIONAL, TARGET                                :: batch(:, :, :)
    2066              :       TYPE(cp_fm_p_type), INTENT(IN), OPTIONAL           :: output(:, :)
    2067              : 
    2068              :       COMPLEX(KIND=dp)                                   :: value
    2069        79088 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: complex_values(:, :)
    2070              :       INTEGER                                            :: element, first, ic, igroup, j, ld, nc, &
    2071              :                                                             nelem, nphase, width
    2072              :       INTEGER(KIND=int_8)                                :: dest, nfactor
    2073        79088 :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: factors(:, :), real_values(:), &
    2074        79088 :                                                             RESULT(:, :)
    2075              : 
    2076            0 :       CPASSERT(route%transform%backend == rskp_backend_gemm)
    2077        79088 :       CPASSERT(PRESENT(batch) .NEQV. PRESENT(output))
    2078        79088 :       width = SIZE(xkp, 2)
    2079        79088 :       ld = route%matrix_struct%local_leading_dimension
    2080        79088 :       nc = 2
    2081        79088 :       IF (PRESENT(batch)) THEN
    2082        70839 :          CPASSERT(SIZE(batch, 1) == route%matrix_struct%local_leading_dimension)
    2083        70839 :          CPASSERT(SIZE(batch, 2) >= route%ncol .AND. SIZE(batch, 3) == width)
    2084    102353013 :          batch = z_zero
    2085        70839 :          complex_values(1:SIZE(batch, 1, KIND=int_8)*SIZE(batch, 2), 1:width) => batch
    2086              :       ELSE
    2087         8249 :          nc = SIZE(output, 2)
    2088         8249 :          CPASSERT(SIZE(output, 1) == width .AND. (nc == 1 .OR. nc == 2))
    2089        18869 :          DO j = 1, width
    2090        39795 :             DO ic = 1, nc
    2091        20926 :                CPASSERT(SIZE(output(j, ic)%matrix%local_data, 1) == ld)
    2092     12609522 :                output(j, ic)%matrix%local_data = 0.0_dp
    2093              :             END DO
    2094              :          END DO
    2095         8249 :          IF (AIMAG(snapshot%scale) /= 0.0_dp) nc = 2
    2096              :       END IF
    2097      1117842 :       DO igroup = 1, SIZE(route%transform%phase_count, 2)
    2098      1038754 :          first = route%element_first(igroup)
    2099      1038754 :          nelem = route%element_first(igroup + 1) - first
    2100      1038754 :          IF (nelem == 0) CYCLE
    2101      1492119 :          IF (.NOT. ANY(snapshot%active(:, igroup))) CYCLE
    2102      3115848 :          nphase = MAXVAL(route%transform%phase_count(1:2, igroup))
    2103      1038616 :          nfactor = INT(nc, int_8)*nphase*width
    2104      1038616 :          CPASSERT(SIZE(work, KIND=int_8) >= nfactor + INT(nc, int_8)*nelem*width)
    2105      1038616 :          factors(1:nphase, 1:nc*width) => work(1:nfactor)
    2106      1038616 :          RESULT(1:nelem, 1:nc*width) => work(nfactor + 1:nfactor + INT(nc, int_8)*nelem*width)
    2107              :          CALL cell_to_k_block_gemm(snapshot%packed(route%transform%packed_first(igroup): &
    2108              :                                                    route%transform%packed_first(igroup + 1) - 1), &
    2109      1038616 :                                    route%transform, igroup, xkp, first_k, factors, RESULT, snapshot%active(:, igroup))
    2110      2715246 :          DO j = 1, width
    2111      2636296 :             IF (PRESENT(batch)) THEN
    2112      3132895 : !$OMP SIMD PRIVATE(dest,value)
    2113              :                DO element = first, route%element_first(igroup + 1) - 1
    2114     66504347 :                   value = CMPLX(RESULT(element - first + 1, j), RESULT(element - first + 1, width + j), KIND=dp)
    2115     66504347 :                   dest = route%element_offset(1, element)
    2116     66504347 :                   IF (dest > 0) complex_values(dest, j) = snapshot%scale*value
    2117     66504347 :                   dest = route%element_offset(2, element)
    2118     66504347 :                   IF (dest > 0) complex_values(dest, j) = snapshot%scale*REAL(snapshot%mirror_sign, dp)*CONJG(value)
    2119              :                END DO
    2120              :             ELSE
    2121       180397 :                DO ic = 1, SIZE(output, 2)
    2122       354624 :                   real_values(1:SIZE(output(j, ic)%matrix%local_data, KIND=int_8)) => output(j, ic)%matrix%local_data
    2123       298605 : !$OMP SIMD PRIVATE(dest,value)
    2124              :                   DO element = first, route%element_first(igroup + 1) - 1
    2125      8282728 :                      dest = route%element_offset(1, element)
    2126      8282728 :                      IF (AIMAG(snapshot%scale) == 0.0_dp) THEN
    2127      8282728 :                         IF (dest > 0) real_values(dest) = REAL(snapshot%scale, dp)* &
    2128      7760106 :                                                           RESULT(element - first + 1, j + (ic - 1)*width)
    2129              :                      ELSE
    2130              :                         value = snapshot%scale*CMPLX(RESULT(element - first + 1, j), &
    2131            0 :                                                      RESULT(element - first + 1, width + j), dp)
    2132            0 :                         IF (dest > 0) real_values(dest) = MERGE(REAL(value, dp), AIMAG(value), ic == 1)
    2133              :                      END IF
    2134      8282728 :                      dest = route%element_offset(2, element)
    2135      8282728 :                      IF (AIMAG(snapshot%scale) == 0.0_dp) THEN
    2136      8282728 :                         IF (dest > 0) real_values(dest) = REAL(snapshot%scale, dp)*REAL(snapshot%mirror_sign, dp)* &
    2137              :                                                           MERGE(1.0_dp, -1.0_dp, ic == 1)* &
    2138      6367101 :                                                           RESULT(element - first + 1, j + (ic - 1)*width)
    2139              :                      ELSE
    2140              :                         value = snapshot%scale*REAL(snapshot%mirror_sign, dp)* &
    2141            0 :                                 CMPLX(RESULT(element - first + 1, j), -RESULT(element - first + 1, width + j), dp)
    2142            0 :                         IF (dest > 0) real_values(dest) = MERGE(REAL(value, dp), AIMAG(value), ic == 1)
    2143              :                      END IF
    2144              :                   END DO
    2145              :                END DO
    2146              :             END IF
    2147              :          END DO
    2148              :       END DO
    2149        79088 :    END SUBROUTINE cell_to_k_gemm_batch
    2150              : 
    2151              : ! **************************************************************************************************
    2152              : !> \brief Evaluate a k-point tile through the selected prepared R-to-K backend.
    2153              : !>        GEMM contracts the retained real-space panel; FFT returns a slice of
    2154              : !>        the canonical reciprocal-space snapshot materialized during capture.
    2155              : !> \param snapshot backend input or prepared reciprocal-space values
    2156              : !> \param route fixed sparse layout and backend plan
    2157              : !> \param xkp reciprocal coordinates for this k tile
    2158              : !> \param first_local first k index in the route-local domain
    2159              : !> \param work caller-owned GEMM scratch; unused by the FFT backend
    2160              : !> \param batch complex output tile (row, column, k point)
    2161              : !> \param output optional split-FM output tile (k point, component), instead of batch
    2162              : ! **************************************************************************************************
    2163        79292 :    SUBROUTINE cell_to_k_backend_evaluate_batch(snapshot, route, xkp, first_local, work, batch, output)
    2164              :       TYPE(rskp_values_type), INTENT(IN), TARGET         :: snapshot
    2165              :       TYPE(rskp_route_type), INTENT(IN)                  :: route
    2166              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    2167              :       INTEGER, INTENT(IN)                                :: first_local
    2168              :       REAL(KIND=dp), CONTIGUOUS, INTENT(INOUT), TARGET   :: work(:)
    2169              :       COMPLEX(KIND=dp), CONTIGUOUS, INTENT(OUT), &
    2170              :          OPTIONAL                                        :: batch(:, :, :)
    2171              :       TYPE(cp_fm_p_type), INTENT(IN), OPTIONAL           :: output(:, :)
    2172              : 
    2173              :       INTEGER                                            :: ic, j, width
    2174              :       LOGICAL                                            :: compatible
    2175              : 
    2176        79292 :       CPASSERT(PRESENT(batch) .NEQV. PRESENT(output))
    2177        79292 :       width = SIZE(xkp, 2)
    2178        79292 :       IF (PRESENT(output)) THEN
    2179         8249 :          CPASSERT(SIZE(output, 1) == width)
    2180         8249 :          CPASSERT(SIZE(output, 2) >= 1 .AND. SIZE(output, 2) <= 2)
    2181        18869 :          DO j = 1, width
    2182        39795 :             DO ic = 1, SIZE(output, 2)
    2183        20926 :                compatible = cp_fm_struct_equivalent(output(j, ic)%matrix%matrix_struct, route%matrix_struct)
    2184        31546 :                CPASSERT(compatible)
    2185              :             END DO
    2186              :          END DO
    2187              :       END IF
    2188       158380 :       SELECT CASE (route%transform%backend)
    2189              :       CASE (rskp_backend_gemm)
    2190       158176 :          CALL cell_to_k_gemm_batch(snapshot, route, xkp, first_local, work, batch=batch, output=output)
    2191              :       CASE (rskp_backend_fft)
    2192          204 :          CPASSERT(ALLOCATED(snapshot%fft_values))
    2193          204 :          CPASSERT(first_local >= 1)
    2194          204 :          CPASSERT(first_local + width - 1 <= SIZE(snapshot%fft_values, 2))
    2195          204 :          IF (PRESENT(batch)) THEN
    2196          204 :             CPASSERT(SIZE(batch, 1) == route%matrix_struct%local_leading_dimension)
    2197          204 :             CPASSERT(SIZE(batch, 2) >= route%ncol)
    2198          204 :             CPASSERT(SIZE(batch, 3) == width)
    2199       196968 :             batch = z_zero
    2200              :          ELSE
    2201            0 :             DO j = 1, width
    2202            0 :                DO ic = 1, SIZE(output, 2)
    2203            0 :                   output(j, ic)%matrix%local_data(:, :) = 0.0_dp
    2204              :                END DO
    2205              :             END DO
    2206              :          END IF
    2207              :          CALL cell_to_k_scatter(snapshot%fft_values(:, first_local:first_local + width - 1), 1, route, &
    2208          408 :                                 snapshot%mirror_sign, snapshot%scale, batch=batch, output=output)
    2209              :       CASE DEFAULT
    2210        79292 :          CPABORT("Unknown R-to-K backend")
    2211              :       END SELECT
    2212        79292 :    END SUBROUTINE cell_to_k_backend_evaluate_batch
    2213              : 
    2214              : ! **************************************************************************************************
    2215              : !> \brief Tabulate distinct absolute translation coordinates for a group's local k points.
    2216              : !>        All AO pairs share these unweighted phases. Zero coordinates are exact;
    2217              : !>        negative coordinates use the same cosine and the opposite sine.
    2218              : !> \param table owned axis-coordinate dictionary and phases
    2219              : !> \param cells globally available image translations
    2220              : !> \param xkp this symmetry group's local contribution coordinates
    2221              : !> \param nworkers maximum number of OpenMP workers
    2222              : ! **************************************************************************************************
    2223       722484 :    SUBROUTINE k_grid_to_cell_phase_prepare(table, cells, xkp, nworkers)
    2224              :       TYPE(k_grid_to_cell_phase_type), INTENT(OUT)       :: table
    2225              :       INTEGER, INTENT(IN)                                :: cells(:, :)
    2226              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
    2227              :       INTEGER, INTENT(IN)                                :: nworkers
    2228              : 
    2229              :       COMPLEX(KIND=dp)                                   :: phase
    2230              :       INTEGER                                            :: axis, i, k, n, nk, pos
    2231       103212 :       INTEGER, ALLOCATABLE                               :: coordinates(:, :), COUNT(:), &
    2232       103212 :                                                             direction(:), order(:), values(:)
    2233              :       REAL(KIND=dp)                                      :: arg
    2234              : 
    2235       103212 :       CPASSERT(SIZE(cells, 1) == 3 .AND. SIZE(xkp, 1) == 3)
    2236       103212 :       CPASSERT(nworkers > 0)
    2237       103212 :       n = SIZE(cells, 2) + 1
    2238       103212 :       nk = SIZE(xkp, 2)
    2239       619272 :       ALLOCATE (coordinates(3, n), COUNT(3), values(n), order(n))
    2240       412848 :       DO axis = 1, 3
    2241       309636 :          values(1) = 0
    2242     26177595 :          values(2:n) = ABS(cells(axis, :))
    2243       309636 :          CALL sort(values, n, order)
    2244       309636 :          COUNT(axis) = 0
    2245     26487231 :          DO i = 1, n
    2246     26177595 :             IF (i > 1) THEN
    2247     25867959 :                IF (values(i) == values(i - 1)) CYCLE
    2248              :             END IF
    2249       886607 :             COUNT(axis) = COUNT(axis) + 1
    2250     26487231 :             coordinates(axis, COUNT(axis)) = values(i)
    2251              :          END DO
    2252       412848 :          table%first(axis + 1) = table%first(axis) + COUNT(axis)
    2253              :       END DO
    2254       412848 :       n = SUM(count)
    2255       928908 :       ALLOCATE (table%coordinate(n), direction(n), table%cosine(nk, n), table%sine(nk, n))
    2256       412848 :       DO axis = 1, 3
    2257       309636 :          pos = table%first(axis)
    2258      1196243 :          table%coordinate(pos:pos + COUNT(axis) - 1) = coordinates(axis, 1:COUNT(axis))
    2259      1299455 :          direction(pos:pos + COUNT(axis) - 1) = axis
    2260              :       END DO
    2261              : !$OMP PARALLEL DEFAULT(NONE) NUM_THREADS(MIN(nworkers,MAX(1,nk))) IF(MIN(nworkers,MAX(1,nk)) > 1) &
    2262       103212 : !$OMP SHARED(table,xkp,direction,n,nk) PRIVATE(i,k,arg,phase)
    2263       103212 : !$OMP DO COLLAPSE(2) SCHEDULE(STATIC)
    2264              :       DO i = 1, n
    2265              :          DO k = 1, nk
    2266              :             IF (table%coordinate(i) == 0) THEN
    2267              :                table%cosine(k, i) = 1.0_dp
    2268              :                table%sine(k, i) = 0.0_dp
    2269              :             ELSE
    2270              :                arg = twopi*REAL(table%coordinate(i), dp)*xkp(direction(i), k)
    2271              :                phase = EXP(CMPLX(0.0_dp, arg, KIND=dp))
    2272              :                table%cosine(k, i) = REAL(phase, dp)
    2273              :                table%sine(k, i) = AIMAG(phase)
    2274              :             END IF
    2275              :          END DO
    2276              :       END DO
    2277              : !$OMP END DO NOWAIT
    2278              : !$OMP END PARALLEL
    2279       103212 :    END SUBROUTINE k_grid_to_cell_phase_prepare
    2280              : 
    2281              : ! **************************************************************************************************
    2282              : !> \brief Weighted K-to-R contraction of one AO block, before spatial rotations and MPI.
    2283              : !>        The caller supplies the atom mapping and image multiplicities. Phases include
    2284              : !>        the gauge shift, time reversal and conjugation of a transposed source block.
    2285              : !> \param source borrowed local matrices by k point, real/imaginary component and spin
    2286              : !> \param tiles local FM intervals (first/last row and column) by atom, k, component and spin
    2287              : !> \param ikp_index local source indices for this symmetry contribution
    2288              : !> \param xkp reciprocal coordinates for these contributions
    2289              : !> \param weight original k-point weights, including symmetry multiplicity
    2290              : !> \param images translations, real multiplicities and imaginary sign sums
    2291              : !> \param source_pair source AO atom pair
    2292              : !> \param block_shape source AO row and column sizes
    2293              : !> \param block_offset global first row and column of the source block
    2294              : !> \param shift column-minus-row gauge shift
    2295              : !> \param time_reversal conjugate the source before applying its gauge phase
    2296              : !> \param trans conjugate the imaginary contribution on transposition
    2297              : !> \param phase_table group-local unweighted one-dimensional phases
    2298              : !> \param sums allocated flattened source blocks by image and spin
    2299              : !> \param gemm_ctx worker-owned host GEMM contexts
    2300              : ! **************************************************************************************************
    2301      1851234 :    SUBROUTINE k_grid_to_cell_contract(source, tiles, ikp_index, xkp, weight, images, source_pair, &
    2302              :                                       block_shape, block_offset, shift, time_reversal, trans, &
    2303      1851234 :                                       phase_table, sums, gemm_ctx)
    2304              :       TYPE(cp_fm_p_type), INTENT(IN)                     :: source(:, :, :)
    2305              :       INTEGER, INTENT(IN)                                :: tiles(:, :, :, :, :), ikp_index(:)
    2306              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :), weight(:)
    2307              :       INTEGER, INTENT(IN)                                :: images(:, :), source_pair(2), &
    2308              :                                                             block_shape(2), block_offset(2), &
    2309              :                                                             shift(3)
    2310              :       LOGICAL, INTENT(IN)                                :: time_reversal, trans
    2311              :       TYPE(k_grid_to_cell_phase_type), INTENT(IN)        :: phase_table
    2312              :       REAL(KIND=dp), ALLOCATABLE, INTENT(INOUT)          :: sums(:, :, :)
    2313              :       TYPE(local_gemm_ctxt_type), INTENT(INOUT)          :: gemm_ctx(:)
    2314              : 
    2315              :       INTEGER(KIND=int_8), PARAMETER                     :: max_elements = 1048576_int_8
    2316              : 
    2317              :       INTEGER :: a, actual_workers, axis, b, batch, column, first, i, ic, ifirst, ii, ikp, ilast, &
    2318              :          image, ispin, ix, iy, iz, j, jj, k, last, nc, nclass, nelement, nimage, nrow, nsine, &
    2319              :          nspin, nworkers, pos, thread
    2320      1851234 :       INTEGER, ALLOCATABLE                               :: cells(:, :), image_class(:), &
    2321      1851234 :                                                             phase_index(:, :), sine_index(:)
    2322              :       LOGICAL                                            :: contributes, has_zero, identity_gauge, &
    2323              :                                                             real_only, zero_shift
    2324              :       REAL(KIND=dp)                                      :: cosine_xy, sine, sine_xy, sx, sy, sz
    2325      1851234 :       REAL(KIND=dp), ALLOCATABLE :: beta(:), gauge(:), gauge_factors(:, :, :), packed(:, :), &
    2326      1851234 :          phases(:, :), reduced(:, :, :, :), zero_sum(:, :, :)
    2327              :       TYPE(cp_fm_type), POINTER                          :: matrix
    2328              : 
    2329      1851234 :       CPASSERT(SIZE(gemm_ctx) > 0)
    2330      1851234 :       nc = SIZE(source, 2)
    2331      1851234 :       nspin = SIZE(source, 3)
    2332      1851234 :       real_only = nc == 1
    2333      1851234 :       CPASSERT(nc == 1 .OR. nc == 2)
    2334      1851234 :       CPASSERT(SIZE(xkp, 2) == SIZE(ikp_index) .AND. SIZE(weight) == SIZE(ikp_index))
    2335      1851234 :       CPASSERT(SIZE(phase_table%cosine, 1) == SIZE(ikp_index))
    2336      1851234 :       a = source_pair(1)
    2337      1851234 :       b = source_pair(2)
    2338      1851234 :       nelement = block_shape(1)*block_shape(2)
    2339      1851234 :       nimage = SIZE(images, 2)
    2340      1851234 :       IF (ALLOCATED(sums)) THEN
    2341      6155174 :          IF (ANY(SHAPE(sums) /= [nelement, nimage, nspin])) DEALLOCATE (sums)
    2342              :       END IF
    2343      3904418 :       IF (.NOT. ALLOCATED(sums)) ALLOCATE (sums(nelement, nimage, nspin))
    2344      1851234 :       IF (nelement == 0 .OR. nimage == 0 .OR. SIZE(ikp_index) == 0) THEN
    2345            0 :          sums = 0.0_dp
    2346              :          RETURN
    2347              :       END IF
    2348      1851234 :       CALL rskp_image_classes(images(1:3, :), image_class, cells)
    2349      1851234 :       nclass = SIZE(cells, 2)
    2350      1952741 :       has_zero = ANY(image_class == 0)
    2351              :       ! Only classes whose output multiplicities use the imaginary source need sine.
    2352      5514822 :       ALLOCATE (sine_index(nclass), source=0)
    2353      1851234 :       IF (.NOT. real_only) THEN
    2354     72266509 :          DO image = 1, nimage
    2355     70418815 :             i = ABS(image_class(image))
    2356     72266509 :             IF (i > 0 .AND. images(5, image) /= 0) sine_index(i) = 1
    2357              :          END DO
    2358              :       END IF
    2359      1851234 :       nsine = 0
    2360     47363164 :       DO i = 1, nclass
    2361     45511930 :          IF (sine_index(i) == 0) CYCLE
    2362     45230114 :          nsine = nsine + 1
    2363     47363164 :          sine_index(i) = nsine
    2364              :       END DO
    2365      5514822 :       ALLOCATE (phase_index(3, nclass))
    2366     47363164 :       DO image = 1, nclass
    2367    183898954 :          DO axis = 1, 3
    2368    136535790 :             first = phase_table%first(axis)
    2369    136535790 :             last = phase_table%first(axis + 1) - 1
    2370    136535790 :             pos = locate(phase_table%coordinate(first:last), ABS(cells(axis, image)))
    2371    136535790 :             CPASSERT(pos > 0)
    2372    136535790 :             pos = pos + first - 1
    2373    136535790 :             CPASSERT(phase_table%coordinate(pos) == ABS(cells(axis, image)))
    2374    182047720 :             phase_index(axis, image) = pos
    2375              :          END DO
    2376              :       END DO
    2377      6576224 :       zero_shift = ALL(shift == 0)
    2378      1851234 :       identity_gauge = zero_shift .AND. .NOT. time_reversal
    2379      1851234 :       nworkers = MIN(SIZE(gemm_ctx), SIZE(ikp_index))
    2380              :       ! Split K for parallelism and an 8 MiB packed/phase scratch target per worker.
    2381              :       ! N retains the complete canonical image set; no image-based task limit applies.
    2382      1851234 :       batch = MIN(512, 1 + (SIZE(ikp_index) - 1)/nworkers)
    2383              :       batch = MAX(1, MIN(batch, INT(max_elements/(INT(nc, int_8)*INT(nelement, int_8) + &
    2384      1851234 :                                                   INT(nclass + nsine, int_8)))))
    2385      1851234 :       nworkers = MIN(nworkers, 1 + (SIZE(ikp_index) - 1)/batch)
    2386      1851234 :       actual_workers = 1
    2387     11068524 :       ALLOCATE (reduced(nelement, nclass + nsine, nspin, nworkers))
    2388      9172342 :       IF (has_zero) ALLOCATE (zero_sum(nelement, nspin, nworkers), source=0.0_dp)
    2389              : !$OMP PARALLEL DEFAULT(NONE) NUM_THREADS(nworkers) IF(nworkers > 1) &
    2390              : !$OMP SHARED(source,tiles,ikp_index,xkp,weight,A,b,block_shape,block_offset,shift,time_reversal, &
    2391              : !$OMP        nelement,nspin,nclass,nsine,nc,batch,cells,sine_index,identity_gauge,real_only,has_zero, &
    2392              : !$OMP        phase_table,phase_index,zero_shift, &
    2393              : !$OMP        reduced,zero_sum,gemm_ctx,actual_workers) &
    2394              : !$OMP PRIVATE(thread,packed,phases,beta,gauge,gauge_factors,first,last,image,k,ispin, &
    2395              : !$OMP         contributes,ikp,ic,ifirst,ilast,column,matrix,nrow,j,jj,ii,i, &
    2396              : !$OMP         ix,iy,iz,sx,sy,sz,cosine_xy,sine_xy)
    2397              :       thread = 1
    2398              : !$    thread = omp_get_thread_num() + 1
    2399              : !$OMP MASTER
    2400              : !$    actual_workers = omp_get_num_threads()
    2401              : !$OMP END MASTER
    2402              :       ALLOCATE (beta(nspin), source=0.0_dp)
    2403              :       CALL rskp_work_matrix(packed, nelement, nc*batch)
    2404              :       CALL rskp_work_matrix(phases, batch, nclass + nsine)
    2405              :       IF (.NOT. identity_gauge .AND. nc == 2) ALLOCATE (gauge(nelement))
    2406              :       IF (.NOT. identity_gauge) ALLOCATE (gauge_factors(2, 2, batch))
    2407              : !$OMP DO SCHEDULE(STATIC)
    2408              :       DO first = 1, SIZE(ikp_index), batch
    2409              :          last = MIN(first + batch - 1, SIZE(ikp_index))
    2410              :          DO image = 1, nclass
    2411              :             ix = phase_index(1, image)
    2412              :             iy = phase_index(2, image)
    2413              :             iz = phase_index(3, image)
    2414              :             sx = REAL(SIGN(1, cells(1, image)), dp)
    2415              :             sy = REAL(SIGN(1, cells(2, image)), dp)
    2416              :             sz = REAL(SIGN(1, cells(3, image)), dp)
    2417              : !$OMP SIMD PRIVATE(cosine_xy,sine_xy)
    2418              :             DO k = first, last
    2419              :                cosine_xy = phase_table%cosine(k, ix)*phase_table%cosine(k, iy) - &
    2420              :                            sx*sy*phase_table%sine(k, ix)*phase_table%sine(k, iy)
    2421              :                sine_xy = sx*phase_table%sine(k, ix)*phase_table%cosine(k, iy) + &
    2422              :                          sy*phase_table%cosine(k, ix)*phase_table%sine(k, iy)
    2423              :                phases(k - first + 1, image) = weight(k)*( &
    2424              :                                               cosine_xy*phase_table%cosine(k, iz) - sine_xy*sz*phase_table%sine(k, iz))
    2425              :                IF (sine_index(image) > 0) THEN
    2426              :                   phases(k - first + 1, nclass + sine_index(image)) = weight(k)*( &
    2427              :                                                            sine_xy*phase_table%cosine(k, iz) + cosine_xy*sz*phase_table%sine(k, iz))
    2428              :                END IF
    2429              :             END DO
    2430              :          END DO
    2431              :          IF (.NOT. identity_gauge) THEN
    2432              :             DO k = first, last
    2433              :                IF (zero_shift) THEN
    2434              :                   gauge_factors(:, :, k - first + 1) = 0.0_dp
    2435              :                   gauge_factors(1, 1, k - first + 1) = 1.0_dp
    2436              :                   gauge_factors(2, 2, k - first + 1) = MERGE(-1.0_dp, 1.0_dp, time_reversal)
    2437              :                ELSE
    2438              :                   CALL rskp_phase_factors(shift, xkp(:, k), time_reversal, real_only, &
    2439              :                                           gauge_factors(:, :, k - first + 1))
    2440              :                END IF
    2441              :             END DO
    2442              :          END IF
    2443              :          DO ispin = 1, nspin
    2444              :             packed = 0.0_dp
    2445              :             contributes = .FALSE.
    2446              :             DO k = first, last
    2447              :                ikp = ikp_index(k)
    2448              :                DO ic = 1, nc
    2449              :                   ifirst = tiles(1, a, ikp, ic, ispin)
    2450              :                   ilast = tiles(2, a, ikp, ic, ispin)
    2451              :                   IF (ifirst > ilast .OR. tiles(3, b, ikp, ic, ispin) > tiles(4, b, ikp, ic, ispin)) CYCLE
    2452              :                   contributes = .TRUE.
    2453              :                   column = k - first + 1 + (ic - 1)*batch
    2454              :                   matrix => source(ikp, ic, ispin)%matrix
    2455              :                   nrow = ilast - ifirst + 1
    2456              :                   DO j = tiles(3, b, ikp, ic, ispin), tiles(4, b, ikp, ic, ispin)
    2457              :                      jj = matrix%matrix_struct%col_indices(j) - block_offset(2)
    2458              :                      ii = matrix%matrix_struct%row_indices(ifirst) - block_offset(1) + 1 + jj*block_shape(1)
    2459              :                      IF (matrix%matrix_struct%row_indices(ilast) - &
    2460              :                          matrix%matrix_struct%row_indices(ifirst) == nrow - 1) THEN
    2461              :                         packed(ii:ii + nrow - 1, column) = matrix%local_data(ifirst:ilast, j)
    2462              :                      ELSE
    2463              :                         DO i = ifirst, ilast
    2464              :                            ii = matrix%matrix_struct%row_indices(i) - block_offset(1) + 1 + jj*block_shape(1)
    2465              :                            packed(ii, column) = matrix%local_data(i, j)
    2466              :                         END DO
    2467              :                      END IF
    2468              :                   END DO
    2469              :                END DO
    2470              :                column = k - first + 1
    2471              :                IF (.NOT. identity_gauge) THEN
    2472              :                   IF (nc == 1) THEN
    2473              :                      packed(:, column) = gauge_factors(1, 1, column)*packed(:, column)
    2474              :                   ELSE
    2475              :                      gauge(:) = gauge_factors(1, 1, column)*packed(:, column) + &
    2476              :                                 gauge_factors(1, 2, column)*packed(:, batch + column)
    2477              :                      packed(:, batch + column) = gauge_factors(2, 1, column)*packed(:, column) + &
    2478              :                                                  gauge_factors(2, 2, column)*packed(:, batch + column)
    2479              :                      packed(:, column) = gauge
    2480              :                   END IF
    2481              :                END IF
    2482              :                IF (has_zero) zero_sum(:, ispin, thread) = zero_sum(:, ispin, thread) + weight(k)*packed(:, column)
    2483              :             END DO
    2484              :             IF (.NOT. contributes .OR. nclass == 0) CYCLE
    2485              :             CALL gemm_ctx(thread)%gemm('N', 'N', nelement, nclass, last - first + 1, 1.0_dp, &
    2486              :                                        packed, nelement, phases, batch, beta(ispin), reduced(:, :, ispin, thread), nelement)
    2487              :             IF (nsine > 0) THEN
    2488              :                CALL gemm_ctx(thread)%gemm('N', 'N', nelement, nsine, last - first + 1, 1.0_dp, &
    2489              :                                           packed(:, batch + 1:), nelement, phases(:, nclass + 1:), batch, &
    2490              :                                           beta(ispin), reduced(:, nclass + 1:, ispin, thread), nelement)
    2491              :             END IF
    2492              :             beta(ispin) = 1.0_dp
    2493              :          END DO
    2494              :       END DO
    2495              : !$OMP END DO
    2496              :       ! An idle worker, or a spin with no locally owned source elements, contributes zero.
    2497              :       DO ispin = 1, nspin
    2498              :          IF (beta(ispin) == 0.0_dp) reduced(:, :, ispin, thread) = 0.0_dp
    2499              :       END DO
    2500              :       DEALLOCATE (beta, packed, phases)
    2501              :       IF (ALLOCATED(gauge)) DEALLOCATE (gauge)
    2502      1851234 :       IF (ALLOCATED(gauge_factors)) DEALLOCATE (gauge_factors)
    2503              : !$OMP END PARALLEL
    2504              :       ! Merge local k contributions before expanding multiplicities and rotating AO blocks.
    2505      1851234 :       DO thread = 2, actual_workers
    2506            0 :          reduced(:, :, :, 1) = reduced(:, :, :, 1) + reduced(:, :, :, thread)
    2507      1851234 :          IF (has_zero) zero_sum(:, :, 1) = zero_sum(:, :, 1) + zero_sum(:, :, thread)
    2508              :       END DO
    2509      3725340 :       DO ispin = 1, nspin
    2510     75999257 :          DO image = 1, nimage
    2511     72273917 :             i = ABS(image_class(image))
    2512     74148023 :             IF (i == 0) THEN
    2513     81648354 :                sums(:, image, ispin) = REAL(images(4, image), dp)*zero_sum(:, ispin, 1)
    2514              :             ELSE
    2515   4480775703 :                sums(:, image, ispin) = REAL(images(4, image), dp)*reduced(:, i, ispin, 1)
    2516     70420768 :                IF (sine_index(i) == 0) CYCLE
    2517     69837090 :                sine = REAL(images(5, image)*SIGN(1, image_class(image)), dp)*MERGE(-1.0_dp, 1.0_dp, trans)
    2518   4347491893 :                sums(:, image, ispin) = sums(:, image, ispin) + sine*reduced(:, nclass + sine_index(i), ispin, 1)
    2519              :             END IF
    2520              :          END DO
    2521              :       END DO
    2522      1851234 :    END SUBROUTINE k_grid_to_cell_contract
    2523              : 
    2524              : ! **************************************************************************************************
    2525              : !> \brief Classify translations by +/-R, without assuming operator or k-point symmetry.
    2526              : !> \param cells integer translations
    2527              : !> \param classes signed class for each input; zero denotes the origin
    2528              : !> \param representatives canonical nonzero translations, one per class
    2529              : ! **************************************************************************************************
    2530      2485822 :    SUBROUTINE rskp_image_classes(cells, classes, representatives)
    2531              :       INTEGER, INTENT(IN)                                :: cells(:, :)
    2532              :       INTEGER, ALLOCATABLE, INTENT(OUT)                  :: classes(:), representatives(:, :)
    2533              : 
    2534              :       INTEGER                                            :: d, i, n, nclass
    2535      2485822 :       INTEGER, ALLOCATABLE                               :: first(:), keys(:, :), order(:), sense(:)
    2536              : 
    2537      2485822 :       n = SIZE(cells, 2)
    2538     19886576 :       ALLOCATE (keys(3, n), order(n), sense(n), first(n), classes(n))
    2539    104041353 :       DO i = 1, n
    2540    101555531 :          sense(i) = 1
    2541    147403197 :          DO d = 1, 3
    2542    144411128 :             IF (cells(d, i) == 0) CYCLE
    2543     98563462 :             sense(i) = SIGN(1, cells(d, i))
    2544    147403197 :             EXIT
    2545              :          END DO
    2546    408707946 :          keys(:, i) = sense(i)*cells(:, i)
    2547              :       END DO
    2548      2485822 :       IF (n > 0) CALL sort(keys, 1, n, 1, 3, order)
    2549              :       nclass = 0
    2550    104041353 :       DO i = 1, n
    2551    147403197 :          IF (ALL(keys(:, i) == 0)) THEN
    2552      2992069 :             classes(order(i)) = 0
    2553      2992069 :             CYCLE
    2554              :          END IF
    2555     98563462 :          IF (nclass == 0) THEN
    2556      2423803 :             nclass = 1
    2557      2423803 :             first(nclass) = i
    2558    310222297 :          ELSE IF (ANY(keys(:, i) /= keys(:, first(nclass)))) THEN
    2559     54033844 :             nclass = nclass + 1
    2560     54033844 :             first(nclass) = i
    2561              :          END IF
    2562    101049284 :          classes(order(i)) = sense(order(i))*nclass
    2563              :       END DO
    2564      7395447 :       ALLOCATE (representatives(3, nclass))
    2565    228316410 :       representatives(:, :) = keys(:, first(1:nclass))
    2566      2485822 :    END SUBROUTINE rskp_image_classes
    2567              : 
    2568              : ! **************************************************************************************************
    2569              : !> \brief Real two-component representation of the Bloch phase and time reversal.
    2570              : !> \param shift column-minus-row cell shift with the selected phase direction
    2571              : !> \param xkp target k-point coordinates
    2572              : !> \param time_reversal conjugate the source before applying the phase
    2573              : !> \param real_only reject phases not representable by real wavefunctions
    2574              : !> \param phase coefficients mapping source [Re,Im] to transformed [Re,Im]
    2575              : ! **************************************************************************************************
    2576       770282 :    SUBROUTINE rskp_phase_factors(shift, xkp, time_reversal, real_only, phase)
    2577              :       INTEGER, INTENT(IN)                                :: shift(3)
    2578              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(3)
    2579              :       LOGICAL, INTENT(IN)                                :: time_reversal, real_only
    2580              :       REAL(KIND=dp), INTENT(OUT)                         :: phase(2, 2)
    2581              : 
    2582              :       REAL(KIND=dp)                                      :: arg, cosine, sine
    2583              : 
    2584       770282 :       arg = twopi*(REAL(shift(1), dp)*xkp(1) + REAL(shift(2), dp)*xkp(2) + REAL(shift(3), dp)*xkp(3))
    2585       770282 :       cosine = COS(arg)
    2586       770282 :       sine = SIN(arg)
    2587       770282 :       IF (real_only .AND. ABS(sine) > 1.e-12_dp) THEN
    2588            0 :          CALL cp_abort(__LOCATION__, "Real k-point wavefunctions cannot represent symmetry phases")
    2589              :       END IF
    2590      2310846 :       phase(:, 1) = [cosine, -sine]
    2591      2310846 :       phase(:, 2) = MERGE(-1.0_dp, 1.0_dp, time_reversal)*[sine, cosine]
    2592       770282 :    END SUBROUTINE rskp_phase_factors
    2593              : 
    2594              : ! **************************************************************************************************
    2595              : !> \brief Allocate a dense work matrix with the requested shape
    2596              : !> \param work dense work matrix
    2597              : !> \param nrow number of rows
    2598              : !> \param ncol number of columns
    2599              : ! **************************************************************************************************
    2600     53828866 :    SUBROUTINE rskp_work_matrix(work, nrow, ncol)
    2601              : 
    2602              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    2603              :          INTENT(INOUT)                                   :: work
    2604              :       INTEGER, INTENT(IN)                                :: nrow, ncol
    2605              : 
    2606     53828866 :       IF (ALLOCATED(work)) THEN
    2607     50097110 :          IF (SIZE(work, 1) == nrow .AND. SIZE(work, 2) == ncol) RETURN
    2608        27978 :          DEALLOCATE (work)
    2609              :       END IF
    2610     15000056 :       ALLOCATE (work(nrow, ncol))
    2611              : 
    2612              :    END SUBROUTINE rskp_work_matrix
    2613              : 
    2614            0 : END MODULE kpoint_transform
        

Generated by: LCOV version 2.0-1