LCOV - code coverage report
Current view: top level - src - qs_kpoint_operators.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 91.2 % 377 344
Test Date: 2026-11-24 01:22:08 Functions: 90.0 % 20 18

            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 Assembly of real and complex k-point operators from real-space DBCSR matrices.
      10              : !>        SCF slots and spin rows adapt the generic kpoint_transform machinery.
      11              : !>        Prepare captures values collectively; evaluation reads immutable snapshots
      12              : !>        into group-local or explicitly prepared world-distributed destinations.
      13              : !>        Start/finish retain the round bookkeeping used by SCF drivers.
      14              : !>        Serialize context mutation and collective preparation. Parallel evaluation
      15              : !>        requires private destinations and scratch. Release before the host environment.
      16              : ! **************************************************************************************************
      17              : MODULE qs_kpoint_operators
      18              :    USE cp_cfm_types,                    ONLY: cp_cfm_type
      19              :    USE cp_dbcsr_api,                    ONLY: dbcsr_init_p,&
      20              :                                               dbcsr_p_type,&
      21              :                                               dbcsr_type
      22              :    USE cp_dbcsr_operations,             ONLY: copy_fm_to_dbcsr_bc
      23              :    USE cp_fm_pool_types,                ONLY: cp_fm_pool_type,&
      24              :                                               fm_pool_create_fm,&
      25              :                                               fm_pool_give_back_fm
      26              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_equivalent,&
      27              :                                               cp_fm_struct_type
      28              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      29              :                                               cp_fm_p_type,&
      30              :                                               cp_fm_release,&
      31              :                                               cp_fm_type
      32              :    USE kinds,                           ONLY: dp,&
      33              :                                               int_8
      34              :    USE kpoint_transform,                ONLY: &
      35              :         cell_to_k_backend_evaluate_batch, cell_to_k_backend_prepare, cell_to_k_sparse_fft, &
      36              :         rskp_backend_fft, rskp_batch_size, rskp_capture, rskp_compatible, rskp_route_create, &
      37              :         rskp_route_release, rskp_route_type, rskp_values_release, rskp_values_type
      38              :    USE kpoint_types,                    ONLY: kpoint_env_type,&
      39              :                                               kpoint_type
      40              :    USE message_passing,                 ONLY: mp_para_env_type
      41              :    USE qs_matrix_pools,                 ONLY: mpools_get
      42              :    USE qs_neighbor_list_types,          ONLY: neighbor_list_set_p_type
      43              : 
      44              : !$ USE omp_lib, ONLY: omp_get_max_threads
      45              : #include "./base/base_uses.f90"
      46              : 
      47              :    IMPLICIT NONE
      48              : 
      49              :    PRIVATE
      50              : 
      51              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_kpoint_operators'
      52              : 
      53              :    PUBLIC :: kpoint_operator_context_create, kpoint_operator_context_release
      54              :    PUBLIC :: kpoint_operator_start, kpoint_operator_finish
      55              :    PUBLIC :: kpoint_operator_get, kpoint_operator_prepare
      56              :    PUBLIC :: kpoint_operator_evaluate
      57              :    PUBLIC :: kpoint_operator_batch_size, kpoint_operator_evaluate_batch
      58              :    PUBLIC :: kpoint_operator_store, kpoint_operator_get_local, kpoint_operator_get_all
      59              : 
      60              :    INTEGER, PARAMETER, PUBLIC :: kpoint_slot_ks = 1, &
      61              :                                  kpoint_slot_s = 2, &
      62              :                                  kpoint_slot_t = 3
      63              : 
      64              :    !> Row of rsmat that carries the spin-free operator image. S and T carry
      65              :    !> no spin copies: drivers launch one instance per spin of their loop and
      66              :    !> read this same row in every instance.
      67              :    INTEGER, PARAMETER, PUBLIC :: kpoint_spin_free = 1
      68              : 
      69              :    !> Number of defined slots; grows only inside this module.
      70              :    INTEGER, PARAMETER, PRIVATE :: kpoint_num_slots = kpoint_slot_t - kpoint_slot_ks + 1
      71              : 
      72              :    !> Instance states of one (k point, spin, slot) round.
      73              :    !> State transitions happen only inside the service routines.
      74              :    INTEGER, PARAMETER, PRIVATE :: kpoint_slot_idle = 0, &
      75              :                                   kpoint_slot_local = 1
      76              : 
      77              :    ! Structural element/image route shared by captured GEMM/FFT rows. The
      78              :    ! borrowed source neighbor lists must remain alive and unchanged with it.
      79              :    ! Immutable captured values; FFT slots also own the local reciprocal matrices.
      80              :    ! Shared metadata belong to the route; source identifies explicitly prepared starts.
      81              :    ! Shared phases, worker scratch and output tiles; at least one k point is evaluated.
      82              :    INTEGER(KIND=int_8), PARAMETER :: rs_batch_bytes = 64_int_8*1024_int_8**2
      83              : 
      84              : ! **************************************************************************************************
      85              : !> \brief Caller-owned assembly context for a fixed geometry and parallel layout.
      86              : !>        OT retains it for one inner SCF loop; other drivers use one call.
      87              : !>        Release before changing the neighbor lists, matrix pools or k-point groups.
      88              : !>        Components are private and touched only by this module.
      89              : ! **************************************************************************************************
      90              :    TYPE, PUBLIC :: kpoint_operator_context_type
      91              :       PRIVATE
      92              :       INTEGER :: nspin = 0
      93              :       LOGICAL :: overlap_stored = .FALSE.
      94              :       TYPE(kpoint_type), POINTER :: kpoints => NULL()
      95              :       TYPE(cp_fm_pool_type), POINTER :: group_fm_pool => NULL()
      96              :       TYPE(cp_fm_type), ALLOCATABLE :: fmlocal, fmimag
      97              :       TYPE(rskp_values_type), ALLOCATABLE :: rs(:, :)
      98              :       TYPE(rskp_route_type), ALLOCATABLE :: rs_route
      99              :       INTEGER, ALLOCATABLE :: status(:, :, :)
     100              :    END TYPE kpoint_operator_context_type
     101              : 
     102              : CONTAINS
     103              : 
     104              : ! **************************************************************************************************
     105              : !> \brief Create an empty operator context.
     106              : !>        The context owns no buffers after this call; they are created on first
     107              : !>        use and released with the context.
     108              : !> \param ctx context to initialize
     109              : !> \param kpoints host k-point environment, referenced, not copied
     110              : !> \param ao_ao_fm optional legacy context template, checked for communicator compatibility only
     111              : !> \param nspin instance spin space of the owning driver call: the bound of
     112              : !>        the spin loop its start and finish calls iterate. Fixed for the
     113              : !>        lifetime of the context
     114              : ! **************************************************************************************************
     115        40496 :    SUBROUTINE kpoint_operator_context_create(ctx, kpoints, ao_ao_fm, nspin)
     116              : 
     117              :       TYPE(kpoint_operator_context_type), INTENT(OUT)    :: ctx
     118              :       TYPE(kpoint_type), POINTER                         :: kpoints
     119              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: ao_ao_fm
     120              :       INTEGER, INTENT(IN)                                :: nspin
     121              : 
     122              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_context_create'
     123              : 
     124              :       INTEGER                                            :: handle
     125              : 
     126        40496 :       CALL timeset(routineN, handle)
     127              : 
     128        40496 :       CPASSERT(nspin >= 1)
     129        40496 :       ctx%nspin = nspin
     130        40496 :       CPASSERT(ASSOCIATED(kpoints))
     131        40496 :       ctx%kpoints => kpoints
     132        40496 :       IF (PRESENT(ao_ao_fm)) THEN
     133        40496 :          IF (.NOT. ASSOCIATED(ao_ao_fm%matrix_struct%para_env, kpoints%blacs_env_all%para_env)) THEN
     134            0 :             CPABORT("R-to-K template must use the k-point host communicator")
     135              :          END IF
     136              :       END IF
     137              : 
     138        40496 :       CALL timestop(handle)
     139              : 
     140        40496 :    END SUBROUTINE kpoint_operator_context_create
     141              : 
     142              : ! **************************************************************************************************
     143              : !> \brief Release the context together with every buffer it created.
     144              : !>        Call once, at the end of the fixed-layout scope that created the context.
     145              : !>        Every started instance must have been finished.
     146              : !> \param ctx context to release
     147              : ! **************************************************************************************************
     148        40496 :    SUBROUTINE kpoint_operator_context_release(ctx)
     149              : 
     150              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     151              : 
     152              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_context_release'
     153              : 
     154              :       INTEGER                                            :: handle, ispin, slot
     155              : 
     156        40496 :       CALL timeset(routineN, handle)
     157              : 
     158        40496 :       IF (ALLOCATED(ctx%status)) THEN
     159       161280 :          CPASSERT(ALL(ctx%status == kpoint_slot_idle))
     160              :       END IF
     161              : 
     162        40496 :       IF (ALLOCATED(ctx%rs)) THEN
     163       161984 :          DO slot = 1, kpoint_num_slots
     164       290654 :             DO ispin = 1, ctx%nspin
     165       250158 :                CALL rskp_values_release(ctx%rs(ispin, slot))
     166              :             END DO
     167              :          END DO
     168       169166 :          DEALLOCATE (ctx%rs)
     169              :       END IF
     170        40496 :       IF (ALLOCATED(ctx%rs_route)) THEN
     171        40496 :          CALL rskp_route_release(ctx%rs_route)
     172        40496 :          DEALLOCATE (ctx%rs_route)
     173              :       END IF
     174        40496 :       IF (ALLOCATED(ctx%fmimag)) THEN
     175           58 :          CALL cp_fm_release(ctx%fmimag)
     176           58 :          DEALLOCATE (ctx%fmimag)
     177              :       END IF
     178        40496 :       IF (ALLOCATED(ctx%fmlocal)) THEN
     179        40394 :          CALL fm_pool_give_back_fm(ctx%group_fm_pool, ctx%fmlocal)
     180        40394 :          DEALLOCATE (ctx%fmlocal)
     181              :       END IF
     182        40496 :       IF (ALLOCATED(ctx%status)) DEALLOCATE (ctx%status)
     183        40496 :       NULLIFY (ctx%kpoints, ctx%group_fm_pool)
     184        40496 :       ctx%overlap_stored = .FALSE.
     185              : 
     186        40496 :       CALL timestop(handle)
     187              : 
     188        40496 :    END SUBROUTINE kpoint_operator_context_release
     189              : 
     190              : ! **************************************************************************************************
     191              : !> \brief Acquire only the group-local output workspace; both backends share it.
     192              : !> \param ctx operator context
     193              : ! **************************************************************************************************
     194        50636 :    SUBROUTINE kpoint_operator_ensure_group(ctx)
     195              : 
     196              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     197              : 
     198        50636 :       IF (.NOT. ALLOCATED(ctx%fmlocal)) THEN
     199        40394 :          CALL mpools_get(ctx%kpoints%mpools, ao_ao_fm_pool=ctx%group_fm_pool)
     200        40394 :          ALLOCATE (ctx%fmlocal)
     201        40394 :          CALL fm_pool_create_fm(ctx%group_fm_pool, ctx%fmlocal)
     202              :       END IF
     203              : 
     204        50636 :    END SUBROUTINE kpoint_operator_ensure_group
     205              : 
     206              : ! **************************************************************************************************
     207              : !> \brief Prepare an immutable operator slot for group-local assembly.
     208              : !>        Refresh after the source values change, with every instance idle.
     209              : !>        Other prepared slots and structural routing remain valid. Without
     210              : !>        matrix_row, capture one row per instance spin; with matrix_row, store
     211              : !>        one row shared by all instance spins. mirror_sign controls the
     212              : !>        transpose relation of the transformed operator.
     213              : !> \param ctx context spanning the current initialized k-point environment
     214              : !> \param rsmat current real-space operator images
     215              : !> \param slot slot to replace (KS, S or T)
     216              : !> \param matrix_row optional explicit spin-free operator row
     217              : !> \param TARGET optional FM object defining the prepared-output layout
     218              : !> \param target_struct optional FM structure defining the prepared-output
     219              : !>        layout, as an alternative to TARGET
     220              : !> \param sab_nl optional source neighbor lists; defaults to the host AO lists
     221              : !> \param mirror_sign optional transpose sign (+1 Hermitian, -1 anti-Hermitian)
     222              : !> \param output optional final split-FM destinations for FFT, without an intermediate cache
     223              : ! **************************************************************************************************
     224        97068 :    SUBROUTINE kpoint_operator_prepare(ctx, rsmat, slot, matrix_row, TARGET, target_struct, sab_nl, &
     225        48534 :                                       mirror_sign, output)
     226              : 
     227              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     228              :       TYPE(dbcsr_p_type), POINTER                        :: rsmat(:, :)
     229              :       INTEGER, INTENT(IN)                                :: slot
     230              :       INTEGER, INTENT(IN), OPTIONAL                      :: matrix_row
     231              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: target
     232              :       TYPE(cp_fm_struct_type), OPTIONAL, POINTER         :: target_struct
     233              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     234              :          OPTIONAL, POINTER                               :: sab_nl
     235              :       INTEGER, INTENT(IN), OPTIONAL                      :: mirror_sign
     236              :       TYPE(cp_fm_p_type), INTENT(IN), OPTIONAL           :: output(:, :, :)
     237              : 
     238              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_prepare'
     239              : 
     240              :       INTEGER                                            :: compatible, handle, ic, ikp, ispin, nk, &
     241              :                                                             nrow, output_mirror_sign, row
     242              :       INTEGER(KIND=int_8)                                :: workspace_bytes
     243              :       LOGICAL                                            :: ready, world_target
     244              :       TYPE(cp_fm_struct_type), POINTER                   :: fms
     245              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     246              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     247        48534 :          POINTER                                         :: source_sab
     248              : 
     249        48534 :       CALL timeset(routineN, handle)
     250        48534 :       CPASSERT(ASSOCIATED(ctx%kpoints))
     251        48534 :       CPASSERT(.NOT. (PRESENT(TARGET) .AND. PRESENT(target_struct)))
     252        48534 :       output_mirror_sign = 1
     253        48534 :       IF (PRESENT(mirror_sign)) output_mirror_sign = mirror_sign
     254        48534 :       CPASSERT(ABS(output_mirror_sign) == 1)
     255        48534 :       IF (PRESENT(sab_nl)) THEN
     256            0 :          CPASSERT(ASSOCIATED(sab_nl))
     257            0 :          source_sab => sab_nl
     258              :       ELSE
     259        48534 :          source_sab => ctx%kpoints%sab_nl
     260              :       END IF
     261        48534 :       CPASSERT(ASSOCIATED(source_sab))
     262        48534 :       CPASSERT(slot >= kpoint_slot_ks .AND. slot <= kpoint_slot_t)
     263        48534 :       IF (ALLOCATED(ctx%status)) THEN
     264            0 :          CPASSERT(ALL(ctx%status == kpoint_slot_idle))
     265              :       END IF
     266        48534 :       IF (.NOT. ALLOCATED(ctx%rs)) THEN
     267       371646 :          ALLOCATE (ctx%rs(ctx%nspin, kpoint_num_slots))
     268              :       END IF
     269       100496 :       DO ispin = 1, ctx%nspin
     270       100496 :          CALL rskp_values_release(ctx%rs(ispin, slot))
     271              :       END DO
     272        48534 :       nrow = ctx%nspin
     273        48534 :       IF (PRESENT(matrix_row)) THEN
     274         7650 :          CPASSERT(matrix_row >= 1 .AND. matrix_row <= SIZE(rsmat, 1))
     275              :          nrow = 1
     276              :       ELSE
     277        40884 :          CPASSERT(SIZE(rsmat, 1) == ctx%nspin)
     278              :       END IF
     279        48534 :       para_env => ctx%kpoints%blacs_env_all%para_env
     280        48534 :       IF (PRESENT(target_struct)) THEN
     281            0 :          CPASSERT(ASSOCIATED(target_struct))
     282            0 :          fms => target_struct
     283        48534 :       ELSE IF (PRESENT(TARGET)) THEN
     284          176 :          fms => target%matrix_struct
     285              :       ELSE
     286        48358 :          CALL kpoint_operator_ensure_group(ctx)
     287        48358 :          fms => ctx%fmlocal%matrix_struct
     288              :       END IF
     289        48534 :       CPASSERT(ASSOCIATED(fms))
     290              :       ! Group-local targets are routed through group leaders and broadcast
     291              :       ! within each group; world targets are routed directly to world ranks.
     292        48534 :       world_target = ASSOCIATED(fms%para_env, para_env)
     293              :       compatible = MERGE(1, 0, world_target .OR. &
     294        48534 :                          ASSOCIATED(fms%para_env, ctx%kpoints%para_env_kp))
     295        48534 :       CALL para_env%min(compatible)
     296        48534 :       IF (compatible == 0) THEN
     297            0 :          CPABORT("R-to-K output must use the host group or world communicator")
     298              :       END IF
     299        48534 :       IF (.NOT. ALLOCATED(ctx%rs_route)) THEN
     300       202480 :          ALLOCATE (ctx%rs_route)
     301              :          CALL rskp_route_create(rsmat, source_sab, ctx%kpoints%cell_to_index, fms, &
     302              :                                 ctx%kpoints%blacs_env_all%para_env, ctx%kpoints%para_env_kp, &
     303              :                                 ctx%kpoints%para_env_inter_kp, ctx%kpoints%rskp_transform, &
     304        40496 :                                 ctx%rs_route, ready)
     305        40496 :          IF (.NOT. ready) THEN
     306            0 :             CPABORT("R-to-K route has an incompatible source or target layout")
     307              :          END IF
     308        40496 :          IF (ctx%rs_route%transform%backend == rskp_backend_fft .OR. ctx%rs_route%world_target) THEN
     309           24 :             CALL cell_to_k_backend_prepare(ctx%rs_route, ctx%kpoints%xkp, ctx%kpoints%nkp_grid, rs_batch_bytes)
     310              :          ELSE
     311              :             CALL cell_to_k_backend_prepare(ctx%rs_route, &
     312              :                                            ctx%kpoints%xkp(:, ctx%kpoints%kp_range(1):ctx%kpoints%kp_range(2)), &
     313        40472 :                                            ctx%kpoints%nkp_grid, rs_batch_bytes)
     314              :          END IF
     315              :       END IF
     316        48534 :       compatible = MERGE(1, 0, cp_fm_struct_equivalent(fms, ctx%rs_route%matrix_struct))
     317        48534 :       IF (world_target .NEQV. ctx%rs_route%world_target) compatible = 0
     318        99878 :       DO ispin = 1, nrow
     319        51344 :          row = ispin
     320        51344 :          IF (PRESENT(matrix_row)) row = matrix_row
     321        99878 :          IF (.NOT. rskp_compatible(ctx%rs_route, rsmat, row, source_sab)) compatible = 0
     322              :       END DO
     323        48534 :       CALL para_env%min(compatible)
     324        48534 :       IF (compatible == 0) THEN
     325            0 :          CPABORT("R-to-K snapshot has an incompatible layout")
     326              :       END IF
     327        48534 :       IF (PRESENT(output)) THEN
     328            0 :          CPASSERT(ctx%rs_route%transform%backend == rskp_backend_fft)
     329              :          compatible = MERGE(1, 0, SIZE(output, 2) == nrow .AND. &
     330            0 :                             SIZE(output, 3) >= 1 .AND. SIZE(output, 3) <= 2)
     331            0 :          DO ispin = 1, SIZE(output, 2)
     332            0 :             DO ikp = 1, SIZE(output, 1)
     333            0 :                DO ic = 1, SIZE(output, 3)
     334            0 :                   IF (.NOT. cp_fm_struct_equivalent(fms, output(ikp, ispin, ic)%matrix%matrix_struct)) compatible = 0
     335              :                END DO
     336              :             END DO
     337              :          END DO
     338            0 :          CALL para_env%min(compatible)
     339            0 :          CPASSERT(compatible == 1)
     340              :       END IF
     341        48534 :       IF (ctx%rs_route%transform%backend == rskp_backend_fft) THEN
     342           38 :          nk = SIZE(ctx%kpoints%xkp, 2)
     343           38 :          IF (.NOT. world_target) nk = SIZE(ctx%kpoints%kp_env)
     344              :          ! Retained inputs and outputs do not limit the temporary element tile.
     345           38 :          workspace_bytes = rs_batch_bytes
     346              :       END IF
     347        99878 :       DO ispin = 1, nrow
     348        51344 :          row = ispin
     349        51344 :          IF (PRESENT(matrix_row)) row = matrix_row
     350        51344 :          CALL rskp_capture(rsmat, row, ctx%rs_route, ctx%rs(ispin, slot), mirror_sign=output_mirror_sign)
     351        99878 :          IF (ctx%rs_route%transform%backend == rskp_backend_fft) THEN
     352           52 :             IF (PRESENT(output)) THEN
     353            0 :                CPASSERT(SIZE(output, 1) == nk .AND. SIZE(output, 2) == nrow)
     354              :                CALL cell_to_k_sparse_fft(ctx%rs(ispin, slot), ctx%rs_route, ctx%kpoints%xkp, &
     355              :                                          ctx%kpoints%nkp_grid, ctx%kpoints%kp_dist, ctx%kpoints%para_env_inter_kp, &
     356            0 :                                          workspace_bytes, output=output(:, ispin, :))
     357              :             ELSE
     358            0 :                ALLOCATE (ctx%rs(ispin, slot)%fft_values( &
     359          208 :                          ctx%rs_route%element_first(SIZE(ctx%rs_route%element_first)) - 1, nk))
     360              :                CALL cell_to_k_sparse_fft(ctx%rs(ispin, slot), ctx%rs_route, ctx%kpoints%xkp, &
     361              :                                          ctx%kpoints%nkp_grid, ctx%kpoints%kp_dist, ctx%kpoints%para_env_inter_kp, &
     362           52 :                                          workspace_bytes, cache=ctx%rs(ispin, slot)%fft_values)
     363              :             END IF
     364           52 :             DEALLOCATE (ctx%rs(ispin, slot)%packed)
     365              :          END IF
     366              :       END DO
     367        48534 :       CALL timestop(handle)
     368              : 
     369        48534 :    END SUBROUTINE kpoint_operator_prepare
     370              : 
     371              : ! **************************************************************************************************
     372              : !> \brief Match an explicitly prepared row, sharing spin-free rows across spins.
     373              : !> \param ctx operator context
     374              : !> \param source live array identity identifying the prepared operation
     375              : !> \param ispin instance spin
     376              : !> \param slot prepared slot
     377              : !> \param matrix_row operator row
     378              : !> \return snapshot spin index, or zero when the prepared source does not match
     379              : ! **************************************************************************************************
     380        37046 :    FUNCTION kpoint_operator_rs_match(ctx, source, ispin, slot, matrix_row) RESULT(irs)
     381              : 
     382              :       TYPE(kpoint_operator_context_type), INTENT(IN)     :: ctx
     383              :       TYPE(dbcsr_p_type), POINTER                        :: source(:, :)
     384              :       INTEGER, INTENT(IN)                                :: ispin, slot, matrix_row
     385              :       INTEGER                                            :: irs
     386              : 
     387              :       INTEGER                                            :: i
     388              : 
     389        37046 :       irs = 0
     390        37046 :       IF (.NOT. ALLOCATED(ctx%rs)) RETURN
     391        37046 :       i = ispin
     392        37046 :       IF (.NOT. ASSOCIATED(ctx%rs(i, slot)%source)) i = 1
     393        37046 :       IF (ASSOCIATED(ctx%rs(i, slot)%source, source) .AND. ctx%rs(i, slot)%matrix_row == matrix_row) irs = i
     394              : 
     395              :    END FUNCTION kpoint_operator_rs_match
     396              : 
     397              : ! **************************************************************************************************
     398              : !> \brief Evaluate an immutable prepared operator with exclusively caller-owned output and scratch.
     399              : !>        Slots support independent worker evaluation through width-one batches.
     400              : !>        Source blocks must stay unchanged until the next collective refresh.
     401              : !> \param ctx prepared read-only context
     402              : !> \param ispin instance spin
     403              : !> \param slot operator slot
     404              : !> \param ik global k index owned by this group
     405              : !> \param TARGET optional private complex singleton output
     406              : !> \param fm_re optional private real output instead of TARGET
     407              : !> \param fm_im optional private imaginary output, accompanying fm_re for a complex operator
     408              : ! **************************************************************************************************
     409        40642 :    SUBROUTINE kpoint_operator_evaluate(ctx, ispin, slot, ik, TARGET, fm_re, fm_im)
     410              :       TYPE(kpoint_operator_context_type), INTENT(IN)     :: ctx
     411              :       INTEGER, INTENT(IN)                                :: ispin, slot, ik
     412              :       TYPE(cp_cfm_type), INTENT(INOUT), OPTIONAL         :: target
     413              :       TYPE(cp_fm_type), INTENT(INOUT), OPTIONAL, TARGET  :: fm_re, fm_im
     414              : 
     415        40642 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: batch(:, :, :)
     416              :       INTEGER                                            :: first, nc, row
     417              :       LOGICAL                                            :: target_layout_matches
     418        40642 :       REAL(KIND=dp), ALLOCATABLE                         :: work(:)
     419       203210 :       TYPE(cp_fm_p_type)                                 :: output(1, 2)
     420              : 
     421        40642 :       CPASSERT(PRESENT(TARGET) .NEQV. PRESENT(fm_re))
     422        40642 :       CPASSERT(.NOT. PRESENT(fm_im) .OR. PRESENT(fm_re))
     423        40642 :       IF (ctx%rs_route%world_target) THEN
     424            0 :          CPASSERT(ik >= 1 .AND. ik <= ctx%kpoints%nkp)
     425              :       ELSE
     426        40642 :          CPASSERT(ik >= ctx%kpoints%kp_range(1))
     427        40642 :          CPASSERT(ik <= ctx%kpoints%kp_range(2))
     428              :       END IF
     429        40642 :       row = ispin
     430        40642 :       IF (.NOT. ASSOCIATED(ctx%rs(row, slot)%source)) row = 1
     431        40642 :       CPASSERT(ASSOCIATED(ctx%rs(row, slot)%source))
     432        40642 :       first = ik
     433        40642 :       IF (.NOT. ctx%rs_route%world_target) first = ik - ctx%kpoints%kp_range(1) + 1
     434        40642 :       nc = 2
     435        40642 :       IF (PRESENT(TARGET)) THEN
     436        39815 :          target_layout_matches = cp_fm_struct_equivalent(target%matrix_struct, ctx%rs_route%matrix_struct)
     437        39815 :          CPASSERT(target_layout_matches)
     438          827 :       ELSE IF (.NOT. PRESENT(fm_im) .AND. AIMAG(ctx%rs(row, slot)%scale) == 0.0_dp) THEN
     439          312 :          nc = 1
     440              :       END IF
     441              :       ! Caller-owned output needs only width-one contraction scratch.
     442       121758 :       ALLOCATE (work(INT(nc, int_8)*ctx%rs_route%transform%max_per_k))
     443        40642 :       IF (PRESENT(TARGET)) THEN
     444        39815 :          batch(1:SIZE(target%local_data, 1), 1:SIZE(target%local_data, 2), 1:1) => target%local_data
     445        39815 :          CALL kpoint_operator_evaluate_batch(ctx, row, slot, ik, batch, work)
     446              :       ELSE
     447          827 :          output(1, 1)%matrix => fm_re
     448          827 :          nc = 1
     449          827 :          IF (PRESENT(fm_im)) THEN
     450          515 :             output(1, 2)%matrix => fm_im
     451          515 :             nc = 2
     452              :          END IF
     453              :          CALL cell_to_k_backend_evaluate_batch(ctx%rs(row, slot), ctx%rs_route, &
     454          827 :                                                ctx%kpoints%xkp(:, ik:ik), first, work, output=output(:, :nc))
     455              :       END IF
     456        40642 :       IF (ctx%kpoints%use_real_wfn .AND. AIMAG(ctx%rs(row, slot)%scale) == 0.0_dp) THEN
     457          312 :          IF (PRESENT(TARGET)) target%local_data(:, :) = CMPLX(REAL(target%local_data, dp), 0.0_dp, dp)
     458          312 :          IF (PRESENT(fm_im)) fm_im%local_data(:, :) = 0.0_dp
     459              :       END IF
     460        40642 :    END SUBROUTINE kpoint_operator_evaluate
     461              : 
     462              : ! **************************************************************************************************
     463              : !> \brief Mark a prepared operator for a round, including inactive groups.
     464              : !>        Finish every started instance before preparing another snapshot.
     465              : !> \param ctx context created by kpoint_operator_context_create
     466              : !> \param ikp global round, up to the maximum k-point count across groups
     467              : !> \param ispin instance spin: keys the bookkeeping
     468              : !> \param rsmat source identity of the immutable snapshot captured by prepare
     469              : !> \param slot prepared instance slot
     470              : !> \param matrix_row row of rsmat to transform. Spin-free operators such
     471              : !>        as S and T must pass kpoint_spin_free: their first matrix
     472              : !>        dimension counts derivatives, not spins. A spin index is out of
     473              : !>        bounds in plain SCF, but with derivatives stored it reads another
     474              : !>        valid row silently
     475              : ! **************************************************************************************************
     476        30018 :    SUBROUTINE kpoint_operator_start(ctx, ikp, ispin, rsmat, slot, matrix_row)
     477              : 
     478              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     479              :       INTEGER, INTENT(IN)                                :: ikp, ispin
     480              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rsmat
     481              :       INTEGER, INTENT(IN)                                :: slot, matrix_row
     482              : 
     483              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_start'
     484              : 
     485              :       INTEGER                                            :: handle, irs, kpmax
     486              : 
     487        30018 :       CALL timeset(routineN, handle)
     488              : 
     489        30018 :       CPASSERT(ASSOCIATED(ctx%kpoints))
     490        30018 :       CPASSERT(ASSOCIATED(ctx%kpoints%sab_nl))
     491              :       ! The instance spin is bounded by the spin space declared at creation;
     492              :       ! the matrix row by this operator's own rows. The two bounds differ for
     493              :       ! spin-free operators such as S, whose first dimension counts
     494              :       ! real-space blocks.
     495        30018 :       CPASSERT(ispin >= 1 .AND. ispin <= ctx%nspin)
     496        30018 :       CPASSERT(matrix_row >= 1 .AND. matrix_row <= SIZE(rsmat, 1))
     497        60298 :       kpmax = MAXVAL(ctx%kpoints%kp_dist(2, :) - ctx%kpoints%kp_dist(1, :) + 1)
     498        30018 :       CPASSERT(ikp >= 1 .AND. ikp <= kpmax)
     499        30018 :       CPASSERT(slot >= kpoint_slot_ks .AND. slot <= kpoint_slot_t)
     500              :       ! State is per round; no communication is deferred to finish.
     501        30018 :       IF (.NOT. ALLOCATED(ctx%status)) THEN
     502        56100 :          ALLOCATE (ctx%status(kpmax, ctx%nspin, kpoint_num_slots))
     503       161280 :          ctx%status(:, :, :) = kpoint_slot_idle
     504              :       END IF
     505        30018 :       CPASSERT(ctx%status(ikp, ispin, slot) == kpoint_slot_idle)
     506        30018 :       irs = kpoint_operator_rs_match(ctx, rsmat, ispin, slot, matrix_row)
     507        30018 :       IF (irs == 0) THEN
     508            0 :          CPABORT("Operator start requires a matching prepared source row")
     509              :       END IF
     510        30018 :       ctx%status(ikp, ispin, slot) = kpoint_slot_local
     511              : 
     512        30018 :       CALL timestop(handle)
     513              : 
     514        30018 :    END SUBROUTINE kpoint_operator_start
     515              : 
     516              : ! **************************************************************************************************
     517              : !> \brief Evaluate a started instance on its owning group and return the slot to idle.
     518              : !> \param ctx context that started the instance
     519              : !> \param ikp global round of the start call
     520              : !> \param ispin spin component of the start call
     521              : !> \param slot slot of the start call
     522              : !> \param cmat caller-allocated complex matrix that receives the operator.
     523              : !>        It must share the distribution of the k-point group. Unchanged on
     524              : !>        groups without a k point in this round
     525              : !> \param fm_re optional real FM output instead of cmat for real wavefunctions, on the group layout
     526              : ! **************************************************************************************************
     527        30018 :    SUBROUTINE kpoint_operator_finish(ctx, ikp, ispin, slot, cmat, fm_re)
     528              : 
     529              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     530              :       INTEGER, INTENT(IN)                                :: ikp, ispin, slot
     531              :       TYPE(cp_cfm_type), OPTIONAL                        :: cmat
     532              :       TYPE(cp_fm_type), OPTIONAL                         :: fm_re
     533              : 
     534              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_finish'
     535              : 
     536              :       INTEGER                                            :: handle, ik, irs, kpmax
     537              :       INTEGER, DIMENSION(2)                              :: kp_range
     538              : 
     539        30018 :       CALL timeset(routineN, handle)
     540              : 
     541        30018 :       CPASSERT(ASSOCIATED(ctx%kpoints))
     542        30018 :       CPASSERT(ALLOCATED(ctx%status))
     543        30018 :       kpmax = SIZE(ctx%status, 1)
     544        30018 :       CPASSERT(ikp >= 1 .AND. ikp <= kpmax)
     545        30018 :       CPASSERT(ispin >= 1 .AND. ispin <= ctx%nspin)
     546        30018 :       CPASSERT(slot >= kpoint_slot_ks .AND. slot <= kpoint_slot_t)
     547        30018 :       CPASSERT(ctx%status(ikp, ispin, slot) /= kpoint_slot_idle)
     548        30018 :       CPASSERT(PRESENT(cmat) .NEQV. PRESENT(fm_re))
     549        30018 :       CPASSERT(.NOT. PRESENT(fm_re) .OR. ctx%kpoints%use_real_wfn)
     550        90054 :       kp_range = ctx%kpoints%kp_range
     551        30018 :       CPASSERT(ctx%status(ikp, ispin, slot) == kpoint_slot_local)
     552        30018 :       irs = ispin
     553        30018 :       IF (.NOT. ASSOCIATED(ctx%rs(irs, slot)%source)) irs = 1
     554        30018 :       ik = kp_range(1) + ikp - 1
     555        30018 :       IF (ik <= kp_range(2)) THEN
     556        30016 :          CALL kpoint_operator_evaluate(ctx, irs, slot, ik, cmat, fm_re=fm_re)
     557              :       END IF
     558        30018 :       ctx%status(ikp, ispin, slot) = kpoint_slot_idle
     559              : 
     560        30018 :       CALL timestop(handle)
     561              : 
     562        30018 :    END SUBROUTINE kpoint_operator_finish
     563              : 
     564              : ! **************************************************************************************************
     565              : !> \brief Evaluate one operator round into CFM, split FM or block-cyclic DBCSR.
     566              : !>        Destinations must match the prepared layout. DBCSR matrices must be
     567              : !>        freshly initialized with dbcsr_init_p. Inactive groups leave outputs unchanged.
     568              : !>        Without a slot, get collectively refreshes the source before evaluation.
     569              : !> \param ctx context created by kpoint_operator_context_create
     570              : !> \param ikp global round, up to the maximum k-point count across groups
     571              : !> \param ispin instance spin: bounds-checked against the context spin space
     572              : !> \param rsmat real-space image matrices of the operator
     573              : !> \param cmat complex matrix output
     574              : !> \param fm_re real-part matrix output
     575              : !> \param fm_im imaginary-part output; may be omitted for real wavefunctions
     576              : !> \param mat_re real-part block-cyclic dbcsr output
     577              : !> \param mat_im imaginary-part block-cyclic dbcsr output
     578              : !> \param matrix_row row of rsmat to transform. Spin-free operators such
     579              : !>        as S and T must pass kpoint_spin_free: their first matrix
     580              : !>        dimension counts derivatives, not spins. A spin index is out of
     581              : !>        bounds in plain SCF, but with derivatives stored it reads another
     582              : !>        valid row silently
     583              : !> \param slot optional prepared slot; a missing or mismatched snapshot aborts
     584              : ! **************************************************************************************************
     585         7028 :    SUBROUTINE kpoint_operator_get(ctx, ikp, ispin, rsmat, cmat, fm_re, fm_im, &
     586              :                                   mat_re, mat_im, matrix_row, slot)
     587              : 
     588              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     589              :       INTEGER, INTENT(IN)                                :: ikp, ispin
     590              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rsmat
     591              :       TYPE(cp_cfm_type), OPTIONAL                        :: cmat
     592              :       TYPE(cp_fm_type), OPTIONAL                         :: fm_re, fm_im
     593              :       TYPE(dbcsr_type), INTENT(INOUT), OPTIONAL          :: mat_re, mat_im
     594              :       INTEGER, INTENT(IN)                                :: matrix_row
     595              :       INTEGER, INTENT(IN), OPTIONAL                      :: slot
     596              : 
     597              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_get'
     598              : 
     599              :       INTEGER                                            :: handle, ik, irs, kpmax, selected_slot
     600              : 
     601         7028 :       CALL timeset(routineN, handle)
     602              : 
     603        28112 :       CPASSERT(COUNT([PRESENT(cmat), PRESENT(fm_re), PRESENT(mat_re)]) == 1)
     604         7028 :       IF (PRESENT(fm_re) .OR. PRESENT(fm_im)) THEN
     605          308 :          CPASSERT(PRESENT(fm_re))
     606          308 :          CPASSERT(PRESENT(fm_im) .OR. ctx%kpoints%use_real_wfn)
     607              :       END IF
     608         7028 :       IF (PRESENT(mat_re) .OR. PRESENT(mat_im)) THEN
     609          236 :          CPASSERT(PRESENT(mat_re) .AND. PRESENT(mat_im))
     610              :       END IF
     611              : 
     612         7028 :       CPASSERT(ASSOCIATED(ctx%kpoints))
     613         7028 :       CPASSERT(ASSOCIATED(ctx%kpoints%sab_nl))
     614         7028 :       CPASSERT(ispin >= 1 .AND. ispin <= ctx%nspin)
     615         7028 :       CPASSERT(matrix_row >= 1 .AND. matrix_row <= SIZE(rsmat, 1))
     616        16590 :       kpmax = MAXVAL(ctx%kpoints%kp_dist(2, :) - ctx%kpoints%kp_dist(1, :) + 1)
     617         7028 :       CPASSERT(ikp >= 1 .AND. ikp <= kpmax)
     618         7028 :       selected_slot = kpoint_slot_ks
     619         7028 :       IF (PRESENT(slot)) THEN
     620         7000 :          selected_slot = slot
     621              :       ELSE
     622           28 :          CALL kpoint_operator_prepare(ctx, rsmat, selected_slot, matrix_row=matrix_row)
     623              :       END IF
     624         7028 :       CPASSERT(selected_slot >= kpoint_slot_ks .AND. selected_slot <= kpoint_slot_t)
     625         7028 :       irs = kpoint_operator_rs_match(ctx, rsmat, ispin, selected_slot, matrix_row)
     626         7028 :       IF (irs == 0) THEN
     627            0 :          CPABORT("Operator get requires a matching prepared source row")
     628              :       END IF
     629         7028 :       ik = ctx%kpoints%kp_range(1) + ikp - 1
     630         7028 :       IF (ik <= ctx%kpoints%kp_range(2)) THEN
     631         6996 :          IF (PRESENT(mat_re)) THEN
     632          236 :             CALL kpoint_operator_ensure_group(ctx)
     633          236 :             IF (.NOT. ALLOCATED(ctx%fmimag)) THEN
     634           58 :                ALLOCATE (ctx%fmimag)
     635           58 :                CALL cp_fm_create(ctx%fmimag, ctx%fmlocal%matrix_struct)
     636              :             END IF
     637          236 :             CALL kpoint_operator_evaluate(ctx, irs, selected_slot, ik, fm_re=ctx%fmlocal, fm_im=ctx%fmimag)
     638          236 :             CALL copy_fm_to_dbcsr_bc(ctx%fmlocal, mat_re)
     639          236 :             CALL copy_fm_to_dbcsr_bc(ctx%fmimag, mat_im)
     640              :          ELSE
     641         6760 :             CALL kpoint_operator_evaluate(ctx, irs, selected_slot, ik, TARGET=cmat, fm_re=fm_re, fm_im=fm_im)
     642              :          END IF
     643              :       END IF
     644              : 
     645         7028 :       CALL timestop(handle)
     646              : 
     647         7028 :    END SUBROUTINE kpoint_operator_get
     648              : 
     649              : ! **************************************************************************************************
     650              : !> \brief Read a cached operator inside a group-local OT loop.
     651              : !>        Every group layout requires collective cache preparation before entering the loop.
     652              : !>        This routine copies the prepared cache, without recomputing the real-space transform.
     653              : !> \param matrix_rs current real-space operator
     654              : !> \param kpoints host environment
     655              : !> \param kp local k-point state
     656              : !> \param ispin source row (one for spin-free S/T)
     657              : !> \param cache_re prepared real part on the k-point group
     658              : !> \param cache_im prepared imaginary part on the k-point group
     659              : !> \param matrix_re newly initialized sparse real output
     660              : !> \param matrix_im newly initialized sparse imaginary output
     661              : ! **************************************************************************************************
     662         6661 :    SUBROUTINE kpoint_operator_get_local(matrix_rs, kpoints, kp, ispin, cache_re, cache_im, &
     663              :                                         matrix_re, matrix_im)
     664              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_rs
     665              :       TYPE(kpoint_type), POINTER                         :: kpoints
     666              :       TYPE(kpoint_env_type), POINTER                     :: kp
     667              :       INTEGER, INTENT(IN)                                :: ispin
     668              :       TYPE(cp_fm_type), INTENT(IN)                       :: cache_re, cache_im
     669              :       TYPE(dbcsr_type), POINTER                          :: matrix_re, matrix_im
     670              : 
     671         6661 :       CPASSERT(ASSOCIATED(matrix_rs))
     672         6661 :       CPASSERT(ispin >= 1 .AND. ispin <= SIZE(matrix_rs, 1))
     673         6661 :       CPASSERT(ASSOCIATED(kpoints))
     674         6661 :       CPASSERT(ASSOCIATED(kp))
     675              : 
     676         6661 :       CALL dbcsr_init_p(matrix_re)
     677         6661 :       CALL dbcsr_init_p(matrix_im)
     678         6661 :       CALL copy_fm_to_dbcsr_bc(cache_re, matrix_re)
     679         6661 :       CALL copy_fm_to_dbcsr_bc(cache_im, matrix_im)
     680         6661 :    END SUBROUTINE kpoint_operator_get_local
     681              : 
     682              : ! **************************************************************************************************
     683              : !> \brief Fill caller-owned matrices for one operator row, including independent history snapshots.
     684              : !>        Preparation is collective. One-rank groups evaluate k points
     685              : !>        concurrently, with no MPI or matrix allocation/refcounts inside the worker loop.
     686              : !> \param kpoints host environment
     687              : !> \param ao_ao_fm global-layout template
     688              : !> \param rsmat current real-space images
     689              : !> \param slot operator slot
     690              : !> \param cmat allocated group-local outputs, one per locally owned k point
     691              : !> \param matrix_row source row; S/T use kpoint_spin_free
     692              : ! **************************************************************************************************
     693         1212 :    SUBROUTINE kpoint_operator_get_all(kpoints, ao_ao_fm, rsmat, slot, cmat, matrix_row)
     694              :       TYPE(kpoint_type), POINTER                         :: kpoints
     695              :       TYPE(cp_fm_type), INTENT(IN)                       :: ao_ao_fm
     696              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rsmat
     697              :       INTEGER, INTENT(IN)                                :: slot
     698              :       TYPE(cp_cfm_type), DIMENSION(:), INTENT(INOUT)     :: cmat
     699              :       INTEGER, INTENT(IN)                                :: matrix_row
     700              : 
     701              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_get_all'
     702              : 
     703              :       INTEGER                                            :: handle, ik, ikp, kplocal, kpmax, &
     704              :                                                             nworkers, width
     705              :       INTEGER(KIND=int_8)                                :: work_size
     706         1212 :       TYPE(kpoint_operator_context_type)                 :: ctx
     707              : 
     708         1212 :       CALL timeset(routineN, handle)
     709         1212 :       kplocal = SIZE(kpoints%kp_env)
     710         1212 :       CPASSERT(SIZE(cmat) == kplocal .AND. kplocal > 0)
     711         1212 :       CALL kpoint_operator_context_create(ctx, kpoints, ao_ao_fm, 1)
     712         1212 :       CALL kpoint_operator_prepare(ctx, rsmat, slot, matrix_row=matrix_row)
     713         1212 :       IF (kpoints%para_env_kp%num_pe == 1) THEN
     714              :          nworkers = 1
     715         1058 : !$       nworkers = MIN(omp_get_max_threads(), kplocal)
     716         1058 :          CALL kpoint_operator_batch_size(ctx, nworkers, 1, width, work_size)
     717              : !$OMP PARALLEL DEFAULT(NONE) NUM_THREADS(nworkers) SHARED(ctx,kpoints,cmat,slot,kplocal) &
     718         1058 : !$OMP PRIVATE(ikp,ik)
     719         1058 : !$OMP DO SCHEDULE(DYNAMIC, 1)
     720              :          DO ikp = 1, kplocal
     721              :             ik = kpoints%kp_range(1) + ikp - 1
     722              :             CALL kpoint_operator_evaluate(ctx, 1, slot, ik, cmat(ikp))
     723              :          END DO
     724              : !$OMP END DO
     725              : !$OMP END PARALLEL
     726              :       ELSE
     727          308 :          kpmax = MAXVAL(kpoints%kp_dist(2, :) - kpoints%kp_dist(1, :) + 1)
     728          398 :          DO ikp = 1, kpmax
     729              :             CALL kpoint_operator_get(ctx, ikp, 1, rsmat, cmat=cmat(MIN(ikp, kplocal)), &
     730          398 :                                      matrix_row=matrix_row, slot=slot)
     731              :          END DO
     732              :       END IF
     733         1212 :       CALL kpoint_operator_context_release(ctx)
     734         1212 :       CALL timestop(handle)
     735         1212 :    END SUBROUTINE kpoint_operator_get_all
     736              : 
     737              : ! **************************************************************************************************
     738              : !> \brief Borrow the group-local OT cache for one operator slot.
     739              : !> \param kp owning k-point environment
     740              : !> \param slot KS, overlap or kinetic operator slot
     741              : !> \param ispin spin index, used only for the KS slot
     742              : !> \return non-owning real/imaginary FM array
     743              : ! **************************************************************************************************
     744         5455 :    FUNCTION kpoint_operator_cache(kp, slot, ispin) RESULT(cache)
     745              :       TYPE(kpoint_env_type), INTENT(IN)                  :: kp
     746              :       INTEGER, INTENT(IN)                                :: slot, ispin
     747              :       TYPE(cp_fm_type), POINTER                          :: cache(:)
     748              : 
     749         9853 :       SELECT CASE (slot)
     750              :       CASE (kpoint_slot_ks)
     751         4398 :          cache => kp%ot_hmat(:, ispin)
     752              :       CASE (kpoint_slot_s)
     753          712 :          cache => kp%ot_smat
     754              :       CASE (kpoint_slot_t)
     755         5455 :          cache => kp%ot_tmat
     756              :       END SELECT
     757         5455 :    END FUNCTION kpoint_operator_cache
     758              : 
     759              : ! **************************************************************************************************
     760              : !> \brief Fill existing split-FM caches through the common prepared batch evaluator.
     761              : !>        Each worker owns a k tile and spin. Direct/mirrored destinations
     762              : !>        share contractions; packed input is immutable and reused across k tiles.
     763              : !> \param ctx prepared group-local context and owned output caches
     764              : !> \param slot operator slot
     765              : !> \param nrows number of captured spin rows
     766              : ! **************************************************************************************************
     767         2610 :    SUBROUTINE kpoint_operator_store_prepared(ctx, slot, nrows)
     768              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     769              :       INTEGER, INTENT(IN)                                :: slot, nrows
     770              : 
     771              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_store_prepared'
     772              : 
     773              :       INTEGER                                            :: first, handle, ic, ikp, ispin, last, nc, &
     774              :                                                             nk, nworkers, width
     775              :       INTEGER(KIND=int_8)                                :: work_size
     776         2610 :       REAL(KIND=dp), ALLOCATABLE                         :: work(:)
     777         2610 :       TYPE(cp_fm_p_type), ALLOCATABLE                    :: output(:, :, :)
     778         2610 :       TYPE(cp_fm_type), POINTER                          :: cache(:)
     779              : 
     780         2610 :       CALL timeset(routineN, handle)
     781         2610 :       nk = SIZE(ctx%kpoints%kp_env)
     782         2610 :       IF (nk == 0) THEN
     783            0 :          CALL timestop(handle)
     784            0 :          RETURN
     785              :       END IF
     786         2610 :       nc = MERGE(1, 2, ctx%kpoints%use_real_wfn)
     787        35348 :       ALLOCATE (output(nk, nrows, nc))
     788         7341 :       DO ikp = 1, nk
     789        12796 :          DO ispin = 1, nrows
     790         5455 :             cache => kpoint_operator_cache(ctx%kpoints%kp_env(ikp)%kpoint_env, slot, ispin)
     791        21096 :             DO ic = 1, nc
     792        16365 :                output(ikp, ispin, ic)%matrix => cache(ic)
     793              :             END DO
     794              :          END DO
     795              :       END DO
     796              :       nworkers = 1
     797         2610 : !$    nworkers = omp_get_max_threads()
     798         2610 :       CALL rskp_batch_size(ctx%rs_route, nk, nc, nworkers, 0, rs_batch_bytes, width, work_size)
     799              : !$OMP PARALLEL DEFAULT(NONE) NUM_THREADS(nworkers) &
     800         2610 : !$OMP SHARED(ctx,slot,output,nk,nrows,width,work_size) PRIVATE(work,first,last,ispin)
     801              :       ALLOCATE (work(work_size))
     802              : !$OMP DO COLLAPSE(2) SCHEDULE(DYNAMIC, 1)
     803              :       DO first = 1, nk, width
     804              :          DO ispin = 1, nrows
     805              :             last = MIN(nk, first + width - 1)
     806              :             CALL cell_to_k_backend_evaluate_batch(ctx%rs(ispin, slot), ctx%rs_route, &
     807              :                                                   ctx%kpoints%xkp(:, ctx%kpoints%kp_range(1) + first - 1: &
     808              :                                                                   ctx%kpoints%kp_range(1) + last - 1), &
     809              :                                                   first, work, output=output(first:last, ispin, :))
     810              :          END DO
     811              :       END DO
     812              : !$OMP END DO
     813         2610 :       DEALLOCATE (work)
     814              : !$OMP END PARALLEL
     815         2610 :       CALL timestop(handle)
     816         5220 :    END SUBROUTINE kpoint_operator_store_prepared
     817              : 
     818              : ! **************************************************************************************************
     819              : !> \brief Size local k tiles, budgeting operator outputs and block scratch over all workers.
     820              : !>        A block exceeding the budget is processed by one worker with one k point.
     821              : !>        OT writes existing caches and distributes block/spin jobs; dense callers distribute k tiles.
     822              : !> \param ctx prepared group-local context
     823              : !> \param nworkers requested workers, reduced to fit the minimum working set
     824              : !> \param nmatrices simultaneously retained complex operator tiles; zero writes existing split-FM caches
     825              : !> \param width number of k points per worker
     826              : !> \param work_size real block scratch elements per worker
     827              : ! **************************************************************************************************
     828        27050 :    SUBROUTINE kpoint_operator_batch_size(ctx, nworkers, nmatrices, width, work_size)
     829              :       TYPE(kpoint_operator_context_type), INTENT(IN)     :: ctx
     830              :       INTEGER, INTENT(INOUT)                             :: nworkers
     831              :       INTEGER, INTENT(IN)                                :: nmatrices
     832              :       INTEGER, INTENT(OUT)                               :: width
     833              :       INTEGER(KIND=int_8), INTENT(OUT)                   :: work_size
     834              : 
     835              :       INTEGER                                            :: nc, nk
     836              : 
     837        27050 :       CPASSERT(nmatrices >= 0 .AND. nworkers > 0)
     838        27050 :       nk = SIZE(ctx%kpoints%kp_env)
     839        27050 :       IF (ctx%rs_route%world_target) nk = ctx%kpoints%nkp
     840        27050 :       nc = MERGE(1, 2, ctx%kpoints%use_real_wfn)
     841        27050 :       CALL rskp_batch_size(ctx%rs_route, nk, nc, nworkers, nmatrices, rs_batch_bytes, width, work_size)
     842        27050 :    END SUBROUTINE kpoint_operator_batch_size
     843              : 
     844              : ! **************************************************************************************************
     845              : !> \brief Deliver a complex k tile using real block/image contractions or the prepared FFT cache.
     846              : !>        The prepared route and snapshots are immutable; workers share no output or scratch.
     847              : !> \param ctx prepared group-local context
     848              : !> \param ispin operator spin
     849              : !> \param slot prepared operator slot
     850              : !> \param first_k first global k index
     851              : !> \param batch complex output (local row, local column, k point), including padding
     852              : !> \param work private real scratch sized by kpoint_operator_batch_size
     853              : ! **************************************************************************************************
     854        69273 :    SUBROUTINE kpoint_operator_evaluate_batch(ctx, ispin, slot, first_k, batch, work)
     855              :       TYPE(kpoint_operator_context_type), INTENT(IN)     :: ctx
     856              :       INTEGER, INTENT(IN)                                :: ispin, slot, first_k
     857              :       COMPLEX(KIND=dp), CONTIGUOUS, INTENT(OUT)          :: batch(:, :, :)
     858              :       REAL(KIND=dp), CONTIGUOUS, INTENT(INOUT), TARGET   :: work(:)
     859              : 
     860              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_evaluate_batch'
     861              : 
     862              :       INTEGER                                            :: first, handle, spin, width
     863              : 
     864        69273 :       CALL timeset(routineN, handle)
     865        69273 :       CPASSERT(SIZE(batch, 1) >= ctx%rs_route%nrow)
     866        69273 :       CPASSERT(SIZE(batch, 2) >= ctx%rs_route%ncol)
     867        69273 :       width = SIZE(batch, 3)
     868        69273 :       IF (ctx%rs_route%world_target) THEN
     869            0 :          CPASSERT(first_k >= 1 .AND. first_k + width - 1 <= ctx%kpoints%nkp)
     870              :       ELSE
     871        69273 :          CPASSERT(first_k >= ctx%kpoints%kp_range(1))
     872        69273 :          CPASSERT(first_k + width - 1 <= ctx%kpoints%kp_range(2))
     873              :       END IF
     874        69273 :       spin = ispin
     875        69273 :       IF (.NOT. ASSOCIATED(ctx%rs(spin, slot)%source)) spin = 1
     876        69273 :       CPASSERT(ASSOCIATED(ctx%rs(spin, slot)%source))
     877        69273 :       first = first_k
     878        69273 :       IF (.NOT. ctx%rs_route%world_target) first = first_k - ctx%kpoints%kp_range(1) + 1
     879              :       CALL cell_to_k_backend_evaluate_batch(ctx%rs(spin, slot), ctx%rs_route, &
     880              :                                             ctx%kpoints%xkp(:, first_k:first_k + width - 1), &
     881        69273 :                                             first, work, batch)
     882        69273 :       CALL timestop(handle)
     883        69273 :    END SUBROUTINE kpoint_operator_evaluate_batch
     884              : 
     885              : ! **************************************************************************************************
     886              : !> \brief Prepare owned split-FM operators for OT without entering an SCF eigensolver.
     887              : !>        H (or the initialization density) retains all source spins and is refreshed on each call.
     888              : !>        S is stored once per context; the caller controls when to prepare T.
     889              : !>        Outputs survive the context. Only routing and scratch persist between calls.
     890              : !> \param ctx context with fixed geometry, AO layout and spin capacity
     891              : !> \param matrix_ks Hamiltonian or initialization density
     892              : !> \param matrix_s spin-free overlap
     893              : !> \param matrix_t optional spin-free kinetic operator; absent leaves the existing kinetic cache alone
     894              : ! **************************************************************************************************
     895         2042 :    SUBROUTINE kpoint_operator_store(ctx, matrix_ks, matrix_s, matrix_t)
     896              :       TYPE(kpoint_operator_context_type), INTENT(INOUT)  :: ctx
     897              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks, matrix_s
     898              :       TYPE(dbcsr_p_type), DIMENSION(:, :), OPTIONAL, &
     899              :          POINTER                                         :: matrix_t
     900              : 
     901              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'kpoint_operator_store'
     902              :       INTEGER                                            :: handle, ic, ikp, ispin, ncomp, nspin
     903              :       LOGICAL                                            :: kinetic, reuse
     904              :       TYPE(cp_fm_struct_type), POINTER                   :: matrix_struct
     905              :       TYPE(kpoint_env_type), POINTER                     :: kp
     906              :       TYPE(kpoint_type), POINTER                         :: kpoints
     907              : 
     908         2042 :       CALL timeset(routineN, handle)
     909         2042 :       kpoints => ctx%kpoints
     910         2042 :       nspin = SIZE(matrix_ks, 1)
     911         2042 :       CPASSERT(nspin == 1 .OR. nspin == ctx%nspin)
     912         2042 :       ncomp = MERGE(1, 2, kpoints%use_real_wfn)
     913         2042 :       kinetic = PRESENT(matrix_t)
     914         2042 :       IF (kinetic) kinetic = ASSOCIATED(matrix_t)
     915         2042 :       CALL kpoint_operator_ensure_group(ctx)
     916         2042 :       matrix_struct => ctx%fmlocal%matrix_struct
     917         5716 :       DO ikp = 1, SIZE(kpoints%kp_env)
     918         3674 :          kp => kpoints%kp_env(ikp)%kpoint_env
     919         3674 :          reuse = .FALSE.
     920         3674 :          IF (ASSOCIATED(kp%ot_hmat)) THEN
     921        10350 :             IF (ALL(SHAPE(kp%ot_hmat) == [ncomp, nspin])) THEN
     922         3450 :                reuse = cp_fm_struct_equivalent(kp%ot_hmat(1, 1)%matrix_struct, matrix_struct)
     923              :             END IF
     924              :          END IF
     925         3450 :          IF (.NOT. reuse) THEN
     926          224 :             CALL cp_fm_release(kp%ot_hmat)
     927         1703 :             ALLOCATE (kp%ot_hmat(ncomp, nspin))
     928          493 :             DO ispin = 1, nspin
     929         1031 :                DO ic = 1, ncomp
     930          807 :                   CALL cp_fm_create(kp%ot_hmat(ic, ispin), matrix_struct)
     931              :                END DO
     932              :             END DO
     933              :          END IF
     934         3674 :          CALL allocate_spin_free(kp%ot_smat)
     935         5716 :          IF (kinetic) CALL allocate_spin_free(kp%ot_tmat)
     936              :       END DO
     937         2042 :       CALL store_slot(matrix_ks, kpoint_slot_ks, nspin)
     938         2042 :       IF (.NOT. ctx%overlap_stored) THEN
     939          384 :          CALL store_slot(matrix_s, kpoint_slot_s, 1)
     940          384 :          ctx%overlap_stored = .TRUE.
     941              :       END IF
     942         2042 :       IF (kinetic) CALL store_slot(matrix_t, kpoint_slot_t, 1)
     943         2042 :       CALL timestop(handle)
     944              : 
     945              :    CONTAINS
     946              : 
     947              : ! **************************************************************************************************
     948              : !> \brief ...
     949              : !> \param cache ...
     950              : ! **************************************************************************************************
     951         4019 :       SUBROUTINE allocate_spin_free(cache)
     952              :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: cache
     953              : 
     954              :       INTEGER                                            :: ic
     955              :       LOGICAL                                            :: reuse
     956              : 
     957         4019 :          reuse = .FALSE.
     958         4019 :          IF (ASSOCIATED(cache)) THEN
     959         3720 :             IF (SIZE(cache) == ncomp) reuse = cp_fm_struct_equivalent(cache(1)%matrix_struct, matrix_struct)
     960              :          END IF
     961         3720 :          IF (reuse) RETURN
     962          299 :          CALL cp_fm_release(cache)
     963         1495 :          ALLOCATE (cache(ncomp))
     964          897 :          DO ic = 1, ncomp
     965          897 :             CALL cp_fm_create(cache(ic), matrix_struct)
     966              :          END DO
     967              :       END SUBROUTINE allocate_spin_free
     968              : 
     969              : ! **************************************************************************************************
     970              : !> \brief ...
     971              : !> \param rsmat ...
     972              : !> \param slot ...
     973              : !> \param nrows ...
     974              : ! **************************************************************************************************
     975         2610 :       SUBROUTINE store_slot(rsmat, slot, nrows)
     976              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rsmat
     977              :       INTEGER, INTENT(IN)                                :: slot, nrows
     978              : 
     979              :       INTEGER                                            :: component, ik, ispin
     980         2610 :       TYPE(cp_fm_p_type), ALLOCATABLE                    :: destinations(:, :, :)
     981         2610 :       TYPE(cp_fm_type), POINTER                          :: cache(:)
     982              : 
     983         2610 :          IF (kpoints%rskp_transform == rskp_backend_fft) THEN
     984            0 :             ALLOCATE (destinations(SIZE(kpoints%kp_env), nrows, ncomp))
     985            0 :             DO ik = 1, SIZE(kpoints%kp_env)
     986            0 :                DO ispin = 1, nrows
     987            0 :                   cache => kpoint_operator_cache(kpoints%kp_env(ik)%kpoint_env, slot, ispin)
     988            0 :                   DO component = 1, ncomp
     989            0 :                      destinations(ik, ispin, component)%matrix => cache(component)
     990              :                   END DO
     991              :                END DO
     992              :             END DO
     993              :          END IF
     994         2610 :          IF (slot == kpoint_slot_ks .AND. nrows == ctx%nspin) THEN
     995         2042 :             CALL kpoint_operator_prepare(ctx, rsmat, slot, output=destinations)
     996              :          ELSE
     997          568 :             CALL kpoint_operator_prepare(ctx, rsmat, slot, matrix_row=kpoint_spin_free, output=destinations)
     998              :          END IF
     999         2610 :          IF (.NOT. ALLOCATED(destinations)) CALL kpoint_operator_store_prepared(ctx, slot, nrows)
    1000              :          ! The split-FM caches now own the results. Do not retain source block
    1001              :          ! pointers or duplicate snapshots across Hamiltonian rebuilds.
    1002         2610 :          IF (ALLOCATED(ctx%rs)) THEN
    1003         5790 :             DO ispin = 1, ctx%nspin
    1004         5790 :                CALL rskp_values_release(ctx%rs(ispin, slot))
    1005              :             END DO
    1006              :          END IF
    1007         5220 :       END SUBROUTINE store_slot
    1008              : 
    1009              :    END SUBROUTINE kpoint_operator_store
    1010              : 
    1011            0 : END MODULE qs_kpoint_operators
        

Generated by: LCOV version 2.0-1