LCOV - code coverage report
Current view: top level - src - kpoint_lattice_fft.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 82.9 % 369 306
Test Date: 2026-11-24 01:22:08 Functions: 70.0 % 20 14

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief Sparse direct and regular-grid lattice Fourier transforms.
      10              : !>
      11              : !>        Image cells are folded modulo the reciprocal grid; shifted meshes use a phase twist.
      12              : !>        Forward transforms can embed a regular-grid subset. The inverse transform can also
      13              : !>        embed an explicitly allowed subset with its supplied weights and zero missing points.
      14              : !>        Generic low-level wrappers retain a direct phase-sum fallback for non-RSKP
      15              : !>        callers. The selected RSKP FFT backend requires successful FFT execution.
      16              : ! **************************************************************************************************
      17              : MODULE kpoint_lattice_fft
      18              :    USE fft_api,                         ONLY: fft_3d_local
      19              :    USE fft_tools,                       ONLY: BWFFT,&
      20              :                                               FFT_RADIX_NEXT,&
      21              :                                               FWFFT,&
      22              :                                               fft_allocate,&
      23              :                                               fft_deallocate,&
      24              :                                               fft_radix_operations
      25              :    USE kinds,                           ONLY: dp,&
      26              :                                               int_8
      27              :    USE machine,                         ONLY: m_walltime
      28              :    USE mathconstants,                   ONLY: gaussi,&
      29              :                                               twopi,&
      30              :                                               z_zero
      31              : #include "./base/base_uses.f90"
      32              : 
      33              :    IMPLICIT NONE
      34              : 
      35              :    PRIVATE
      36              : 
      37              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'kpoint_lattice_fft'
      38              : 
      39              :    PUBLIC :: cell_to_k_grid_fft, cell_to_k_grid_prepare, cell_to_k_grid_release, cell_to_k_grid_work_type
      40              :    PUBLIC :: k_grid_to_cell_fft, k_grid_to_cell_prepare, k_grid_to_cell_execute, k_grid_to_cell_release
      41              :    PUBLIC :: k_grid_to_cell_work_type, lattice_fft_shape, regular_kpoint_grid
      42              :    PUBLIC :: k_grid_to_cell_panel_width
      43              :    PUBLIC :: lattice_fft_profile_type, lattice_fft_execute_pair_major, lattice_fft_prepare_geometry
      44              : 
      45              :    ! Optional local FFT diagnostics; enable explicitly for profiling builds.
      46              :    LOGICAL, PARAMETER, PUBLIC :: fft_profile_enabled = .FALSE.
      47              :    PUBLIC :: lattice_fft_real_sink_type
      48              : 
      49              :    ! Keep pair-major grid filling in cache-sized strips of AO elements and images.
      50              :    INTEGER, PARAMETER :: fft_pack_rows = 8, fft_pack_cells = 32
      51              :    ! Avoid OpenMP launch overhead unless a packing/extraction stage has enough values.
      52              :    INTEGER(KIND=int_8), PARAMETER :: fft_parallel_values = 32768_int_8
      53              :    ! Keep the default pair-major workspace bounded, as in the master lattice FFT.
      54              :    INTEGER(KIND=int_8), PARAMETER :: fft_workspace_bytes = 64_int_8*1024_int_8**2
      55              :    INTEGER(KIND=int_8), PARAMETER :: fft_panel_element_bytes = 48_int_8
      56              : 
      57              :    ! Optional local-panel diagnostics. Axis times include any plan creation.
      58              :    TYPE lattice_fft_profile_type
      59              :       REAL(KIND=dp) :: seconds(9) = 0.0_dp
      60              :       INTEGER(KIND=int_8) :: batches = 0_int_8, elements = 0_int_8
      61              :       INTEGER(KIND=int_8) :: transforms = 0_int_8
      62              :       INTEGER :: nfft(3) = 0, tile_min = HUGE(0), tile_max = 0
      63              :       LOGICAL :: pair_major = .FALSE., two_real = .FALSE.
      64              :    END TYPE lattice_fft_profile_type
      65              : 
      66              :    ! Reusable forward lattice geometry and bounded numerical FFT workspace.
      67              :    TYPE cell_to_k_grid_work_type
      68              :       LOGICAL :: regular = .FALSE.
      69              :       INTEGER :: nfft(3) = 0
      70              :       INTEGER, ALLOCATABLE, PRIVATE :: k_slot(:), cell_slot(:)
      71              :       COMPLEX(KIND=dp), ALLOCATABLE, PRIVATE :: cell_factor(:)
      72              :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER, PRIVATE :: fft_in(:) => NULL(), fft_out(:) => NULL()
      73              :    END TYPE cell_to_k_grid_work_type
      74              : 
      75              :    ! Reusable inverse lattice maps, buffers and plans; the caller releases them after use.
      76              :    TYPE k_grid_to_cell_work_type
      77              :       LOGICAL, PRIVATE :: regular = .FALSE., uniform_weights = .FALSE.
      78              :       INTEGER :: nfft(3) = 0
      79              :       INTEGER, ALLOCATABLE :: k_slot(:), cell_slot(:), k_partner(:)
      80              :       INTEGER, ALLOCATABLE, PRIVATE :: cells(:, :)
      81              :       REAL(KIND=dp), ALLOCATABLE, PRIVATE :: xkp(:, :), weight(:)
      82              :       COMPLEX(KIND=dp), ALLOCATABLE, PRIVATE :: cell_phase(:)
      83              :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER, PRIVATE :: fft_in(:) => NULL(), fft_out(:) => NULL()
      84              :    END TYPE k_grid_to_cell_work_type
      85              : 
      86              :    ! A real-output consumer may finish extraction directly in its next operator's layout.
      87              :    ! The FFT algorithm and its bounded panels remain shared with the array-output interface.
      88              :    TYPE, ABSTRACT :: lattice_fft_real_sink_type
      89              :       ! Whether each complex transform in the supplied panel packs two real fields.
      90              :       LOGICAL :: two_real = .FALSE.
      91              :    CONTAINS
      92              :       PROCEDURE(lattice_fft_consume_real), DEFERRED :: consume
      93              :    END TYPE lattice_fft_real_sink_type
      94              : 
      95              :    ABSTRACT INTERFACE
      96              : ! **************************************************************************************************
      97              : !> \brief Consume one inverse FFT panel for real output.
      98              : !> \param sink consumer storing the output or fusing a subsequent operation
      99              : !> \param first first flattened field index in the panel
     100              : !> \param nbatch number of physical fields in the panel
     101              : !> \param spectrum pair-major complex FFT output
     102              : !> \param cell_slot FFT slot of each requested cell
     103              : !> \param cell_phase inverse Bloch phase with any common weight
     104              : ! **************************************************************************************************
     105              :       SUBROUTINE lattice_fft_consume_real(sink, first, nbatch, spectrum, cell_slot, cell_phase)
     106              :          IMPORT :: dp, int_8, lattice_fft_real_sink_type
     107              :          CLASS(lattice_fft_real_sink_type), INTENT(INOUT) :: sink
     108              :          INTEGER(KIND=int_8), INTENT(IN)                  :: first
     109              :          INTEGER, INTENT(IN)                              :: nbatch, cell_slot(:)
     110              :          COMPLEX(KIND=dp), INTENT(IN)                     :: spectrum(:, :), cell_phase(:)
     111              :       END SUBROUTINE lattice_fft_consume_real
     112              :    END INTERFACE
     113              : 
     114              : CONTAINS
     115              : 
     116              : ! **************************************************************************************************
     117              : !> \brief Test and map a uniformly shifted reciprocal grid or an explicitly allowed subset.
     118              : !> \param xkp reciprocal coordinates, in units of reciprocal lattice vectors
     119              : !> \param nkp_grid regular-grid dimensions
     120              : !> \param grid_index FFT-grid index for every k point
     121              : !> \param k_offset common reciprocal-coordinate offset
     122              : !> \param allow_incomplete accept a subset of a regular grid (missing points are zero)
     123              : !> \return true for a regular grid, complete unless allow_incomplete is set
     124              : ! **************************************************************************************************
     125          228 :    LOGICAL FUNCTION regular_kpoint_grid(xkp, nkp_grid, grid_index, k_offset, allow_incomplete) RESULT(regular)
     126              : 
     127              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: xkp
     128              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: nkp_grid
     129              :       INTEGER, DIMENSION(:, :), INTENT(OUT), OPTIONAL    :: grid_index
     130              :       REAL(KIND=dp), DIMENSION(3), INTENT(OUT), OPTIONAL :: k_offset
     131              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_incomplete
     132              : 
     133              :       REAL(KIND=dp), PARAMETER                           :: map_tolerance = 2.0E-10_dp
     134              : 
     135              :       INTEGER                                            :: d, ik, m, nkp
     136              :       INTEGER, DIMENSION(3)                              :: index
     137              :       LOGICAL                                            :: require_complete
     138          228 :       LOGICAL, ALLOCATABLE, DIMENSION(:, :, :)           :: occupied
     139              :       REAL(KIND=dp)                                      :: offset(3), scaled
     140              : 
     141          228 :       regular = .FALSE.
     142          912 :       IF (SIZE(xkp, 1) < 3 .OR. ANY(nkp_grid <= 0)) RETURN
     143          228 :       nkp = SIZE(xkp, 2)
     144          228 :       require_complete = .TRUE.
     145          228 :       IF (PRESENT(allow_incomplete)) require_complete = .NOT. allow_incomplete
     146          912 :       IF (nkp < 1 .OR. nkp > PRODUCT(nkp_grid)) RETURN
     147          912 :       IF (require_complete .AND. PRODUCT(nkp_grid) /= nkp) RETURN
     148          228 :       IF (PRESENT(grid_index)) THEN
     149          200 :          IF (SIZE(grid_index, 1) < 3 .OR. SIZE(grid_index, 2) < nkp) RETURN
     150              :       END IF
     151              : 
     152          912 :       DO d = 1, 3
     153          684 :          scaled = MODULO(REAL(nkp_grid(d), KIND=dp)*xkp(d, 1), 1.0_dp)
     154          684 :          IF (ABS(scaled) < map_tolerance .OR. ABS(scaled - 1.0_dp) < map_tolerance) scaled = 0.0_dp
     155          912 :          offset(d) = scaled/REAL(nkp_grid(d), KIND=dp)
     156              :       END DO
     157              : 
     158         1140 :       ALLOCATE (occupied(nkp_grid(1), nkp_grid(2), nkp_grid(3)), source=.FALSE.)
     159         2752 :       DO ik = 1, nkp
     160        10098 :          DO d = 1, 3
     161         7574 :             scaled = REAL(nkp_grid(d), KIND=dp)*(xkp(d, ik) - offset(d))
     162         7574 :             m = NINT(scaled)
     163         7574 :             IF (ABS(scaled - REAL(m, KIND=dp)) > map_tolerance) RETURN
     164        10096 :             INDEX(d) = MODULO(m, nkp_grid(d)) + 1
     165              :          END DO
     166         2524 :          IF (occupied(INDEX(1), INDEX(2), INDEX(3))) RETURN
     167         2524 :          occupied(INDEX(1), INDEX(2), INDEX(3)) = .TRUE.
     168         9986 :          IF (PRESENT(grid_index)) grid_index(1:3, ik) = index
     169              :       END DO
     170          226 :       regular = .TRUE.
     171              : 
     172          226 :       IF (regular .AND. PRESENT(k_offset)) k_offset = offset
     173              : 
     174          228 :    END FUNCTION regular_kpoint_grid
     175              : 
     176              : ! **************************************************************************************************
     177              : !> \brief Find backend-supported FFT dimensions that preserve the original lattice grid.
     178              : !>        Sample the padded transform at integer multiples of the original cell indices.
     179              : !> \param n original grid dimensions
     180              : !> \param nfft supported integer multiples, if available
     181              : !> \param allow_arbitrary use exact dimensions when supported by the active FFT backend
     182              : !> \return whether all dimensions have a supported multiple
     183              : ! **************************************************************************************************
     184          226 :    LOGICAL FUNCTION lattice_fft_shape(n, nfft, allow_arbitrary) RESULT(compatible)
     185              : 
     186              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: n
     187              :       INTEGER, DIMENSION(3), INTENT(OUT)                 :: nfft
     188              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_arbitrary
     189              : 
     190              :       INTEGER                                            :: attempt, d, radix_length
     191              : 
     192          226 :       compatible = .FALSE.
     193          226 :       nfft = n
     194          904 :       IF (ANY(n <= 0)) RETURN
     195          226 :       IF (PRESENT(allow_arbitrary)) THEN
     196          226 :          IF (allow_arbitrary) THEN
     197              :             ! The PW grid radix list is a cost heuristic, not a capability limit.
     198          226 :             compatible = .TRUE.
     199              :             RETURN
     200              :          END IF
     201              :       END IF
     202            0 :       DO d = 1, 3
     203            0 :          DO attempt = 0, 15
     204            0 :             IF (nfft(d) == 1) EXIT
     205            0 :             IF (nfft(d) >= 2) THEN
     206            0 :                CALL fft_radix_operations(nfft(d), radix_length, FFT_RADIX_NEXT)
     207            0 :                IF (radix_length == nfft(d)) EXIT
     208              :             END IF
     209            0 :             nfft(d) = nfft(d) + n(d)
     210              :          END DO
     211            0 :          IF (attempt > 15) RETURN
     212              :       END DO
     213          226 :       compatible = .TRUE.
     214              : 
     215              :    END FUNCTION lattice_fft_shape
     216              : 
     217              : ! **************************************************************************************************
     218              : !> \brief Prepare shared lattice FFT geometry in internal z,y,x storage order.
     219              : !>        An optional translated origin maps R to R-cell_origin. The output phase
     220              : !>        restores exp(2*pi*i*m*cell_origin/nkp_grid) for a forward transform;
     221              : !>        the physical k offset is returned separately for caller-specific factors.
     222              : !> \param xkp ...
     223              : !> \param nkp_grid ...
     224              : !> \param cells ...
     225              : !> \param grid_index ...
     226              : !> \param nfft ...
     227              : !> \param k_offset ...
     228              : !> \param cell_index ...
     229              : !> \param cell_linear ...
     230              : !> \param cell_origin ...
     231              : !> \param origin_phase ...
     232              : !> \param allow_incomplete ...
     233              : !> \param grid_linear ...
     234              : !> \return ...
     235              : ! **************************************************************************************************
     236          200 :    LOGICAL FUNCTION lattice_fft_prepare_geometry(xkp, nkp_grid, cells, grid_index, nfft, k_offset, &
     237          200 :                                                  cell_index, cell_linear, cell_origin, origin_phase, &
     238              :                                                  allow_incomplete, grid_linear) RESULT(compatible)
     239              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
     240              :       INTEGER, INTENT(IN)                                :: nkp_grid(3), cells(:, :)
     241              :       INTEGER, INTENT(OUT)                               :: grid_index(:, :), nfft(3)
     242              :       REAL(KIND=dp), INTENT(OUT)                         :: k_offset(3)
     243              :       INTEGER, ALLOCATABLE, INTENT(OUT), OPTIONAL        :: cell_index(:, :), cell_linear(:)
     244              :       INTEGER, INTENT(IN), OPTIONAL                      :: cell_origin(3)
     245              :       COMPLEX(KIND=dp), INTENT(OUT), OPTIONAL            :: origin_phase(:)
     246              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_incomplete
     247              :       INTEGER, ALLOCATABLE, INTENT(OUT), OPTIONAL        :: grid_linear(:)
     248              : 
     249              :       INTEGER                                            :: d, icell, ik, INDEX(3), origin(3), &
     250              :                                                             physical_axis, SHAPE(3)
     251              :       REAL(KIND=dp)                                      :: arg
     252              : 
     253          200 :       compatible = regular_kpoint_grid(xkp, nkp_grid, grid_index, k_offset, allow_incomplete)
     254          200 :       IF (.NOT. compatible) RETURN
     255          198 :       compatible = lattice_fft_shape(nkp_grid, shape, allow_arbitrary=.TRUE.)
     256          198 :       IF (.NOT. compatible) RETURN
     257              : 
     258          792 :       nfft = SHAPE([3, 2, 1])
     259        18486 :       grid_index = grid_index([3, 2, 1], :)
     260          198 :       IF (PRESENT(grid_linear)) THEN
     261          594 :          ALLOCATE (grid_linear(SIZE(xkp, 2)))
     262         2484 :          DO ik = 1, SIZE(xkp, 2)
     263              :             grid_linear(ik) = grid_index(1, ik) + nfft(1)* &
     264         2484 :                               (grid_index(2, ik) - 1 + nfft(2)*(grid_index(3, ik) - 1))
     265              :          END DO
     266              :       END IF
     267          198 :       origin = 0
     268          198 :       IF (PRESENT(cell_origin)) origin = cell_origin
     269          198 :       IF (PRESENT(cell_index)) ALLOCATE (cell_index(3, SIZE(cells, 2)))
     270          594 :       IF (PRESENT(cell_linear)) ALLOCATE (cell_linear(SIZE(cells, 2)))
     271         8060 :       DO icell = 1, SIZE(cells, 2)
     272        31448 :          DO d = 1, 3
     273        23586 :             physical_axis = 4 - d
     274              :             INDEX(d) = 1 + MODULO(cells(physical_axis, icell) - origin(physical_axis), &
     275        31448 :                                   nkp_grid(physical_axis))*(nfft(d)/nkp_grid(physical_axis))
     276              :          END DO
     277         7862 :          IF (PRESENT(cell_index)) cell_index(:, icell) = index
     278         7862 :          IF (PRESENT(cell_linear)) cell_linear(icell) = &
     279         8060 :             INDEX(1) + nfft(1)*(INDEX(2) - 1 + nfft(2)*(INDEX(3) - 1))
     280              :       END DO
     281          198 :       IF (PRESENT(origin_phase)) THEN
     282            0 :          CPASSERT(SIZE(origin_phase) == SIZE(xkp, 2))
     283            0 :          DO ik = 1, SIZE(xkp, 2)
     284            0 :             arg = SUM(REAL(grid_index([3, 2, 1], ik) - 1, dp)*REAL(origin, dp)/REAL(nkp_grid, dp))
     285            0 :             origin_phase(ik) = EXP(gaussi*twopi*arg)
     286              :          END DO
     287              :       END IF
     288              : 
     289              :    END FUNCTION lattice_fft_prepare_geometry
     290              : 
     291              : ! **************************************************************************************************
     292              : !> \brief Transform pair-major FFT input directly to pair-major output.
     293              : !>        Report the complete 3D transform under the first FFT stage in the profile.
     294              : !> \param dir ...
     295              : !> \param n ...
     296              : !> \param nbatch ...
     297              : !> \param buffer ...
     298              : !> \param scratch ...
     299              : !> \param profile ...
     300              : ! **************************************************************************************************
     301         2639 :    SUBROUTINE lattice_fft_execute_pair_major(dir, n, nbatch, buffer, scratch, profile)
     302              :       LOGICAL, INTENT(IN)                                :: dir
     303              :       INTEGER, INTENT(IN)                                :: n(3), nbatch
     304              :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: buffer(:), scratch(:)
     305              :       TYPE(lattice_fft_profile_type), INTENT(INOUT), &
     306              :          OPTIONAL                                        :: profile
     307              : 
     308         2639 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: swap(:)
     309              :       REAL(KIND=dp)                                      :: started
     310              : 
     311            8 :       IF (PRESENT(profile)) started = m_walltime()
     312         2639 :       CALL fft_3d_local(dir, n, nbatch, .TRUE., .TRUE., buffer, scratch)
     313         2639 :       IF (PRESENT(profile)) profile%seconds(5) = profile%seconds(5) + m_walltime() - started
     314         2639 :       swap => buffer
     315         2639 :       buffer => scratch
     316         2639 :       scratch => swap
     317         2639 :    END SUBROUTINE lattice_fft_execute_pair_major
     318              : 
     319              : ! **************************************************************************************************
     320              : !> \brief Transform a batch of real matrices from image cells to every supplied k point.
     321              : !> \param values_rs real-space matrices; the last dimension enumerates image cells
     322              : !> \param index_to_cell integer lattice vector for every image cell
     323              : !> \param xkp reciprocal coordinates of all requested k points
     324              : !> \param nkp_grid dimensions of the candidate regular reciprocal grid
     325              : !> \param values_k complex matrices at every k point
     326              : !> \param used_fft reports whether the regular-grid FFT path was used
     327              : !> \param deriv_direction optional Cartesian k derivative (1, 2, or 3)
     328              : !> \param hmat direct-lattice cell matrix, required for a derivative
     329              : !> \param selected_kpoints optional indices of k points to retain in values_k
     330              : !> \param require_fft abort if FFT cannot be used; never execute a direct phase sum
     331              : !> \param work optional prepared geometry, unchanged throughout repeated calls
     332              : !> \param cell_first first prepared image-map column for this batch
     333              : !> \param max_workspace_bytes optional soft FFT workspace target; one element always fits the policy
     334              : !> \param accumulate add to values_k; abort on FFT execution failure to avoid partial accumulation
     335              : !> \param profile optional local-panel stage timings and batch counts
     336              : ! **************************************************************************************************
     337          704 :    SUBROUTINE cell_to_k_grid_fft(values_rs, index_to_cell, xkp, nkp_grid, values_k, &
     338          352 :                                  used_fft, deriv_direction, hmat, selected_kpoints, require_fft, work, cell_first, &
     339              :                                  max_workspace_bytes, accumulate, profile)
     340              : 
     341              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: values_rs
     342              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: index_to_cell
     343              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: xkp
     344              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: nkp_grid
     345              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), &
     346              :          INTENT(INOUT)                                   :: values_k
     347              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: used_fft
     348              :       INTEGER, INTENT(IN), OPTIONAL                      :: deriv_direction
     349              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN), &
     350              :          OPTIONAL                                        :: hmat
     351              :       INTEGER, DIMENSION(:), INTENT(IN), OPTIONAL        :: selected_kpoints
     352              :       LOGICAL, INTENT(IN), OPTIONAL                      :: require_fft
     353              :       TYPE(cell_to_k_grid_work_type), INTENT(INOUT), &
     354              :          OPTIONAL, TARGET                                :: work
     355              :       INTEGER, INTENT(IN), OPTIONAL                      :: cell_first
     356              :       INTEGER(KIND=int_8), INTENT(IN), OPTIONAL          :: max_workspace_bytes
     357              :       LOGICAL, INTENT(IN), OPTIONAL                      :: accumulate
     358              :       TYPE(lattice_fft_profile_type), INTENT(INOUT), &
     359              :          OPTIONAL                                        :: profile
     360              : 
     361          704 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: input(:, :), output(:, :)
     362              :       INTEGER                                            :: handle, i, icell, ik, ik_out, image, &
     363              :                                                             image_first, matrix_column, &
     364              :                                                             matrix_row, nbatch, nout, row_first, &
     365              :                                                             slot, start, width
     366              :       INTEGER(KIND=int_8)                                :: budget, first, matrix_index, needed, &
     367              :                                                             ngrid, nvalues
     368              :       LOGICAL                                            :: add, success
     369              :       REAL(KIND=dp)                                      :: started
     370              :       TYPE(cell_to_k_grid_work_type), POINTER            :: plan
     371         1408 :       TYPE(cell_to_k_grid_work_type), TARGET             :: local_work
     372              : 
     373          352 :       CALL timeset("cell_to_k_grid_fft", handle)
     374          352 :       add = .FALSE.
     375          352 :       IF (PRESENT(accumulate)) add = accumulate
     376              : 
     377          352 :       IF (SIZE(index_to_cell, 1) < 3 .OR. &
     378              :           SIZE(index_to_cell, 2) /= SIZE(values_rs, 3)) THEN
     379            0 :          CPABORT("Inconsistent real-space image-cell mapping in lattice FFT")
     380              :       END IF
     381          352 :       nout = SIZE(xkp, 2)
     382          352 :       IF (PRESENT(selected_kpoints)) THEN
     383            4 :          nout = SIZE(selected_kpoints)
     384           24 :          IF (ANY(selected_kpoints < 1) .OR. ANY(selected_kpoints > SIZE(xkp, 2))) THEN
     385            0 :             CPABORT("Selected lattice-FFT k-point index is out of range")
     386              :          END IF
     387              :       END IF
     388              :       IF (SIZE(values_k, 1) /= SIZE(values_rs, 1) .OR. &
     389          352 :           SIZE(values_k, 2) /= SIZE(values_rs, 2) .OR. &
     390              :           SIZE(values_k, 3) /= nout) THEN
     391            0 :          CPABORT("Inconsistent input and output matrix batches in lattice FFT")
     392              :       END IF
     393          352 :       IF (PRESENT(deriv_direction)) THEN
     394            4 :          IF (.NOT. PRESENT(hmat)) THEN
     395            0 :             CALL cp_abort(__LOCATION__, "Lattice-FFT derivative requested without a cell matrix")
     396              :          END IF
     397            4 :          IF (deriv_direction < 1 .OR. deriv_direction > 3) THEN
     398            0 :             CPABORT("Lattice-FFT derivative direction must be 1, 2, or 3")
     399              :          END IF
     400              :       END IF
     401              : 
     402          352 :       IF (PRESENT(work)) THEN
     403              :          plan => work
     404              :       ELSE
     405           20 :          plan => local_work
     406           20 :          IF (PRESENT(profile)) started = m_walltime()
     407           20 :          CALL cell_to_k_grid_prepare(plan, index_to_cell, xkp, nkp_grid, deriv_direction, hmat)
     408           20 :          IF (PRESENT(profile)) profile%seconds(2) = profile%seconds(2) + m_walltime() - started
     409              :       END IF
     410          352 :       IF (.NOT. plan%regular .AND. PRESENT(require_fft)) THEN
     411            0 :          IF (require_fft) THEN
     412            0 :             CPABORT("Forced lattice FFT needs a supported regular grid or subset")
     413              :          END IF
     414              :       END IF
     415          352 :       success = .FALSE.
     416          352 :       IF (plan%regular) THEN
     417          350 :          start = 1
     418          350 :          IF (PRESENT(cell_first)) start = cell_first
     419          332 :          CPASSERT(start >= 1)
     420          350 :          IF (SIZE(values_rs, 3) > SIZE(plan%cell_factor) - start + 1) THEN
     421            0 :             CPABORT("Lattice FFT image range exceeds the prepared geometry")
     422              :          END IF
     423         1400 :          ngrid = PRODUCT(INT(plan%nfft, int_8))
     424              :          ! A single pair may exceed this soft limit; otherwise keep workspaces bounded.
     425          350 :          budget = fft_workspace_bytes
     426          350 :          IF (PRESENT(max_workspace_bytes)) budget = MAX(48_int_8*ngrid, max_workspace_bytes)
     427          350 :          nvalues = SIZE(values_rs, 1, KIND=int_8)*SIZE(values_rs, 2, KIND=int_8)
     428              :          ! The FFT wrappers and allocated buffer sizes use default INTEGER.
     429          350 :          CPASSERT(ngrid <= HUGE(0))
     430              :          width = INT(MIN(nvalues, MAX(1_int_8, budget/(48_int_8*ngrid)), &
     431          350 :                          INT(HUGE(0), int_8)/ngrid))
     432          350 :          IF (width == 0) THEN
     433              :             success = .TRUE.
     434              :          ELSE
     435          350 :             needed = ngrid*width
     436          350 :             CPASSERT(needed <= HUGE(0))
     437          350 :             IF (PRESENT(profile)) THEN
     438            0 :                profile%nfft = plan%nfft
     439            0 :                started = m_walltime()
     440              :             END IF
     441          350 :             IF (ASSOCIATED(plan%fft_in)) THEN
     442              :                ! Reuse capacity while also allowing a smaller caller budget.
     443          286 :                IF (SIZE(plan%fft_in, KIND=int_8) < needed .OR. &
     444          298 :                    32_int_8*SIZE(plan%fft_in, KIND=int_8) + 16_int_8*needed > budget) THEN
     445           12 :                   CALL fft_deallocate(plan%fft_in)
     446           12 :                   CALL fft_deallocate(plan%fft_out)
     447              :                END IF
     448              :             END IF
     449          350 :             IF (.NOT. ASSOCIATED(plan%fft_in)) THEN
     450          128 :                CALL fft_allocate(plan%fft_in, [INT(needed)])
     451          128 :                CALL fft_allocate(plan%fft_out, [INT(needed)])
     452              :             END IF
     453          350 :             IF (PRESENT(profile)) THEN
     454            0 :                profile%pair_major = .TRUE.
     455            0 :                profile%seconds(3) = profile%seconds(3) + m_walltime() - started
     456              :             END IF
     457              :             ! Flatten both matrix dimensions so each FFT batch spans whole columns.
     458          700 :             DO first = 1_int_8, nvalues, INT(width, int_8)
     459          350 :                nbatch = INT(MIN(INT(width, int_8), nvalues - first + 1_int_8))
     460          350 :                IF (PRESENT(profile)) THEN
     461            0 :                   profile%batches = profile%batches + 1_int_8
     462            0 :                   profile%elements = profile%elements + INT(nbatch, int_8)
     463            0 :                   profile%tile_min = MIN(profile%tile_min, nbatch)
     464            0 :                   profile%tile_max = MAX(profile%tile_max, nbatch)
     465            0 :                   started = m_walltime()
     466              :                END IF
     467          350 :                input(1:nbatch, 1:INT(ngrid)) => plan%fft_in(1:INT(ngrid)*nbatch)
     468          350 :                input = z_zero
     469              :                ! Read adjacent AO elements together while retaining each element's image order.
     470              : !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) &
     471              : !$OMP IF(INT(nbatch, int_8)*SIZE(values_rs, 3, KIND=int_8) >= fft_parallel_values) &
     472              : !$OMP SHARED(input, plan, values_rs, first, nbatch, start) &
     473          350 : !$OMP PRIVATE(image_first, icell, image, slot, i, matrix_index, matrix_row, matrix_column)
     474              :                DO row_first = 1, nbatch, fft_pack_rows
     475              :                   DO image_first = 1, SIZE(values_rs, 3), fft_pack_cells
     476              :                      DO icell = image_first, MIN(image_first + fft_pack_cells - 1, SIZE(values_rs, 3))
     477              :                         image = start + icell - 1
     478              :                         slot = plan%cell_slot(image)
     479              :                         IF (SIZE(values_rs, 2) == 1) THEN
     480              : !$OMP SIMD
     481              :                            DO i = row_first, MIN(row_first + fft_pack_rows - 1, nbatch)
     482              :                               input(i, slot) = input(i, slot) + &
     483              :                                                plan%cell_factor(image)*values_rs(INT(first) + i - 1, 1, icell)
     484              :                            END DO
     485              :                         ELSE
     486              : !$OMP SIMD PRIVATE(matrix_index, matrix_row, matrix_column)
     487              :                            DO i = row_first, MIN(row_first + fft_pack_rows - 1, nbatch)
     488              :                               matrix_index = first + INT(i - 2, int_8)
     489              :                               matrix_row = INT(MODULO(matrix_index, INT(SIZE(values_rs, 1), int_8))) + 1
     490              :                               matrix_column = INT(matrix_index/INT(SIZE(values_rs, 1), int_8)) + 1
     491              :                               input(i, slot) = input(i, slot) + &
     492              :                                                plan%cell_factor(image)*values_rs(matrix_row, matrix_column, icell)
     493              :                            END DO
     494              :                         END IF
     495              :                      END DO
     496              :                   END DO
     497              :                END DO
     498              : !$OMP END PARALLEL DO
     499          350 :                IF (PRESENT(profile)) profile%seconds(4) = profile%seconds(4) + m_walltime() - started
     500          350 :                CALL lattice_fft_execute_pair_major(BWFFT, plan%nfft, nbatch, plan%fft_in, plan%fft_out, profile)
     501          350 :                IF (PRESENT(profile)) started = m_walltime()
     502          350 :                output(1:nbatch, 1:INT(ngrid)) => plan%fft_in(1:INT(ngrid)*nbatch)
     503              : !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) &
     504              : !$OMP IF(INT(nbatch, int_8)*SIZE(values_k, 3, KIND=int_8) >= fft_parallel_values) &
     505              : !$OMP SHARED(output, plan, values_k, selected_kpoints, first, nbatch, add) &
     506          350 : !$OMP PRIVATE(ik, i, matrix_index, matrix_row, matrix_column)
     507              :                DO ik_out = 1, SIZE(values_k, 3)
     508              :                   ik = ik_out
     509              :                   IF (PRESENT(selected_kpoints)) ik = selected_kpoints(ik_out)
     510              :                   IF (SIZE(values_k, 2) == 1) THEN
     511              :                      IF (add) THEN
     512              :                         values_k(INT(first):INT(first) + nbatch - 1, 1, ik_out) = &
     513              :                            values_k(INT(first):INT(first) + nbatch - 1, 1, ik_out) + &
     514              :                            output(:, plan%k_slot(ik))
     515              :                      ELSE
     516              :                         values_k(INT(first):INT(first) + nbatch - 1, 1, ik_out) = &
     517              :                            output(:, plan%k_slot(ik))
     518              :                      END IF
     519              :                   ELSE
     520              :                      DO i = 1, nbatch
     521              :                         matrix_index = first + INT(i - 2, int_8)
     522              :                         matrix_row = INT(MODULO(matrix_index, INT(SIZE(values_k, 1), int_8))) + 1
     523              :                         matrix_column = INT(matrix_index/INT(SIZE(values_k, 1), int_8)) + 1
     524              :                         IF (add) THEN
     525              :                            values_k(matrix_row, matrix_column, ik_out) = &
     526              :                               values_k(matrix_row, matrix_column, ik_out) + &
     527              :                               output(i, plan%k_slot(ik))
     528              :                         ELSE
     529              :                            values_k(matrix_row, matrix_column, ik_out) = &
     530              :                               output(i, plan%k_slot(ik))
     531              :                         END IF
     532              :                      END DO
     533              :                   END IF
     534              :                END DO
     535              : !$OMP END PARALLEL DO
     536          700 :                IF (PRESENT(profile)) profile%seconds(8) = profile%seconds(8) + m_walltime() - started
     537              :             END DO
     538              :             success = .TRUE.
     539              :          END IF
     540              :       END IF
     541              :       IF (.NOT. success) THEN
     542            2 :          IF (PRESENT(require_fft)) THEN
     543            0 :             IF (require_fft) THEN
     544            0 :                CPABORT("Forced lattice FFT execution failed")
     545              :             END IF
     546              :          END IF
     547            4 :          CALL direct_cell_to_k(values_rs, index_to_cell, xkp, values_k, deriv_direction, hmat, selected_kpoints, add)
     548              :       END IF
     549          352 :       IF (PRESENT(used_fft)) used_fft = success
     550          352 :       IF (.NOT. PRESENT(work)) THEN
     551           20 :          IF (PRESENT(profile)) started = m_walltime()
     552           20 :          CALL cell_to_k_grid_release(local_work)
     553           20 :          IF (PRESENT(profile)) profile%seconds(9) = profile%seconds(9) + m_walltime() - started
     554              :       END IF
     555          352 :       CALL timestop(handle)
     556         1056 :    END SUBROUTINE cell_to_k_grid_fft
     557              : 
     558              : ! **************************************************************************************************
     559              : !> \brief Prepare fixed forward lattice maps; the caller keeps geometry and k points unchanged.
     560              : !> \param work owned image/grid maps and reusable FFT buffers
     561              : !> \param index_to_cell image translations, including repeated cells from different atom pairs
     562              : !> \param xkp full reciprocal grid
     563              : !> \param nkp_grid reciprocal-grid dimensions
     564              : !> \param deriv_direction optional Cartesian derivative direction
     565              : !> \param hmat direct-lattice cell matrix for a derivative
     566              : ! **************************************************************************************************
     567           54 :    SUBROUTINE cell_to_k_grid_prepare(work, index_to_cell, xkp, nkp_grid, deriv_direction, hmat)
     568              :       TYPE(cell_to_k_grid_work_type), INTENT(INOUT)      :: work
     569              :       INTEGER, INTENT(IN)                                :: index_to_cell(:, :)
     570              :       REAL(KIND=dp), INTENT(IN)                          :: xkp(:, :)
     571              :       INTEGER, INTENT(IN)                                :: nkp_grid(3)
     572              :       INTEGER, INTENT(IN), OPTIONAL                      :: deriv_direction
     573              :       REAL(KIND=dp), INTENT(IN), OPTIONAL                :: hmat(3, 3)
     574              : 
     575              :       INTEGER                                            :: icell
     576           54 :       INTEGER, ALLOCATABLE                               :: grid_index(:, :)
     577              :       REAL(KIND=dp)                                      :: arg, cell_vector(3), k_offset(3)
     578              : 
     579           54 :       CALL cell_to_k_grid_release(work)
     580          162 :       ALLOCATE (grid_index(3, SIZE(xkp, 2)))
     581              :       work%regular = lattice_fft_prepare_geometry(xkp, nkp_grid, index_to_cell, grid_index, &
     582              :                                                   work%nfft, k_offset, cell_linear=work%cell_slot, &
     583           54 :                                                   grid_linear=work%k_slot, allow_incomplete=.TRUE.)
     584           54 :       IF (.NOT. work%regular) RETURN
     585           52 :       IF (PRESENT(deriv_direction)) THEN
     586            4 :          CPASSERT(PRESENT(hmat))
     587            4 :          CPASSERT(deriv_direction >= 1 .AND. deriv_direction <= 3)
     588              :       END IF
     589          156 :       ALLOCATE (work%cell_factor(SIZE(index_to_cell, 2)))
     590         4124 :       DO icell = 1, SIZE(index_to_cell, 2)
     591        16288 :          arg = SUM(k_offset*REAL(index_to_cell(1:3, icell), dp))
     592         4072 :          work%cell_factor(icell) = EXP(gaussi*twopi*arg)
     593         4124 :          IF (PRESENT(deriv_direction)) THEN
     594         1984 :             cell_vector = MATMUL(hmat, REAL(index_to_cell(1:3, icell), dp))
     595          124 :             work%cell_factor(icell) = work%cell_factor(icell)*gaussi*cell_vector(deriv_direction)
     596              :          END IF
     597              :       END DO
     598           54 :    END SUBROUTINE cell_to_k_grid_prepare
     599              : 
     600              : ! **************************************************************************************************
     601              : !> \brief Release forward lattice maps and numerical buffers.
     602              : !> \param work caller-owned prepared transform
     603              : ! **************************************************************************************************
     604        43398 :    SUBROUTINE cell_to_k_grid_release(work)
     605              :       TYPE(cell_to_k_grid_work_type), INTENT(INOUT)      :: work
     606              : 
     607        43398 :       IF (ASSOCIATED(work%fft_in)) CALL fft_deallocate(work%fft_in)
     608        43398 :       IF (ASSOCIATED(work%fft_out)) CALL fft_deallocate(work%fft_out)
     609        43398 :       IF (ALLOCATED(work%k_slot)) DEALLOCATE (work%k_slot)
     610        43398 :       IF (ALLOCATED(work%cell_slot)) DEALLOCATE (work%cell_slot, work%cell_factor)
     611        43398 :       work%regular = .FALSE.
     612        43398 :    END SUBROUTINE cell_to_k_grid_release
     613              : 
     614              : ! **************************************************************************************************
     615              : !> \brief Transform reciprocal-grid data back to image-cell values.
     616              : !> \param values_k complex matrices on the supplied reciprocal points
     617              : !> \param xkp reciprocal coordinates, in units of reciprocal lattice vectors
     618              : !> \param nkp_grid dimensions of the reciprocal grid
     619              : !> \param index_to_cell integer lattice vector for every requested image cell
     620              : !> \param values_rs reconstructed complex matrices in the requested image cells
     621              : !> \param used_fft reports whether the regular-grid FFT path was used
     622              : !> \param weights optional k weights; otherwise use the existing 1/number-of-points normalization
     623              : !> \param allow_incomplete embed a unique regular-grid subset, zero-filling missing points
     624              : ! **************************************************************************************************
     625          116 :    SUBROUTINE k_grid_to_cell_fft(values_k, xkp, nkp_grid, index_to_cell, values_rs, used_fft, &
     626           58 :                                  weights, allow_incomplete)
     627              : 
     628              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), INTENT(IN)   :: values_k
     629              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: xkp
     630              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: nkp_grid
     631              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: index_to_cell
     632              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), INTENT(OUT)  :: values_rs
     633              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: used_fft
     634              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN), OPTIONAL  :: weights
     635              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_incomplete
     636              : 
     637          232 :       TYPE(k_grid_to_cell_work_type)                     :: work
     638              : 
     639           96 :       CALL k_grid_to_cell_prepare(work, xkp, nkp_grid, index_to_cell, weights, allow_incomplete)
     640           58 :       CALL k_grid_to_cell_execute(work, values_k, values_rs, used_fft)
     641           58 :       CALL k_grid_to_cell_release(work)
     642              : 
     643           58 :    END SUBROUTINE k_grid_to_cell_fft
     644              : 
     645              : ! **************************************************************************************************
     646              : !> \brief Prepare one inverse lattice transform for repeated matrix batches.
     647              : !> \param work reusable maps, weights, buffers and backend plans
     648              : !> \param xkp reciprocal coordinates
     649              : !> \param nkp_grid candidate reciprocal-grid dimensions
     650              : !> \param index_to_cell requested lattice translations
     651              : !> \param weights final k weights, otherwise 1/number-of-points
     652              : !> \param allow_incomplete allow missing grid points, with zero values
     653              : !> \param cell_phase_forward unweighted forward Bloch phases, returned for a regular grid
     654              : ! **************************************************************************************************
     655          146 :    SUBROUTINE k_grid_to_cell_prepare(work, xkp, nkp_grid, index_to_cell, weights, allow_incomplete, cell_phase_forward)
     656              : 
     657              :       TYPE(k_grid_to_cell_work_type), INTENT(INOUT)      :: work
     658              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: xkp
     659              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: nkp_grid
     660              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: index_to_cell
     661              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN), OPTIONAL  :: weights
     662              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_incomplete
     663              :       COMPLEX(KIND=dp), INTENT(OUT), OPTIONAL            :: cell_phase_forward(:)
     664              : 
     665              :       INTEGER                                            :: half_shift(3), icell, ik, ncell, nkp, &
     666              :                                                             partner_index(3), partner_slot
     667          146 :       INTEGER, ALLOCATABLE                               :: grid_index(:, :), slot_to_k(:)
     668              :       REAL(KIND=dp), DIMENSION(3)                        :: k_offset
     669              : 
     670          146 :       CALL k_grid_to_cell_release(work)
     671          146 :       nkp = SIZE(xkp, 2)
     672          146 :       ncell = SIZE(index_to_cell, 2)
     673          146 :       IF (SIZE(xkp, 1) < 3 .OR. SIZE(index_to_cell, 1) < 3 .OR. nkp == 0) THEN
     674            0 :          CALL cp_abort(__LOCATION__, "Inconsistent reciprocal-grid mapping in inverse lattice FFT")
     675              :       END IF
     676         1314 :       ALLOCATE (work%xkp(3, nkp), work%cells(3, ncell), work%weight(nkp), grid_index(3, nkp))
     677         7498 :       work%xkp(:, :) = xkp(1:3, :)
     678        15306 :       work%cells(:, :) = index_to_cell(1:3, :)
     679         1984 :       work%weight(:) = 1.0_dp/REAL(nkp, dp)
     680          146 :       IF (PRESENT(weights)) THEN
     681           58 :          CPASSERT(SIZE(weights) == nkp)
     682          446 :          work%weight(:) = weights
     683              :       END IF
     684              :       work%regular = lattice_fft_prepare_geometry(xkp, nkp_grid, index_to_cell, grid_index, &
     685              :                                                   work%nfft, k_offset, cell_linear=work%cell_slot, &
     686          146 :                                                   grid_linear=work%k_slot, allow_incomplete=allow_incomplete)
     687          146 :       IF (.NOT. work%regular) RETURN
     688              :       ! For uniform k weights, apply the common scale once at extraction.
     689         1814 :       work%uniform_weights = ALL(work%weight == work%weight(1))
     690              : 
     691              :       ! Real output depends only on S(k)=[w(k)A(k)+conjg(w(-k)A(-k))]/2.
     692              :       ! A complete inversion-closed mesh permits two such fields in one complex FFT.
     693          584 :       half_shift = NINT(2.0_dp*k_offset*REAL(nkp_grid, dp))
     694         1592 :       IF (ALL(work%nfft == nkp_grid([3, 2, 1])) .AND. nkp == PRODUCT(nkp_grid) .AND. &
     695              :           ALL(ABS(2.0_dp*k_offset*REAL(nkp_grid, dp) - REAL(half_shift, dp)) <= 64.0_dp*EPSILON(1.0_dp))) THEN
     696          448 :          ALLOCATE (work%k_partner(nkp), slot_to_k(nkp))
     697         1724 :          DO ik = 1, nkp
     698         1724 :             slot_to_k(work%k_slot(ik)) = ik
     699              :          END DO
     700         1724 :          DO ik = 1, nkp
     701         6448 :             partner_index = 1 + MODULO(1 - grid_index(:, ik) - half_shift([3, 2, 1]), nkp_grid([3, 2, 1]))
     702              :             partner_slot = partner_index(1) + work%nfft(1)* &
     703         1612 :                            (partner_index(2) - 1 + work%nfft(2)*(partner_index(3) - 1))
     704         1724 :             work%k_partner(ik) = slot_to_k(partner_slot)
     705              :          END DO
     706              :       END IF
     707              : 
     708          438 :       ALLOCATE (work%cell_phase(ncell))
     709          146 :       IF (PRESENT(cell_phase_forward)) THEN
     710           42 :          CPASSERT(SIZE(cell_phase_forward) == ncell)
     711              :       END IF
     712         3936 :       DO icell = 1, ncell
     713        15160 :          work%cell_phase(icell) = EXP(-gaussi*twopi*SUM(k_offset*REAL(index_to_cell(1:3, icell), dp)))
     714         3790 :          IF (PRESENT(cell_phase_forward)) cell_phase_forward(icell) = CONJG(work%cell_phase(icell))
     715         3936 :          IF (work%uniform_weights) work%cell_phase(icell) = work%weight(1)*work%cell_phase(icell)
     716              :       END DO
     717              : 
     718          146 :    END SUBROUTINE k_grid_to_cell_prepare
     719              : 
     720              : ! **************************************************************************************************
     721              : !> \brief Physical fields per inverse FFT panel, including two-real alignment.
     722              : !> \param work prepared inverse FFT geometry
     723              : !> \param nvalues number of physical fields
     724              : !> \param budget workspace limit in bytes
     725              : !> \param real_output whether the inverse uses the real-output path
     726              : !> \return panel width, zero for an empty input
     727              : ! **************************************************************************************************
     728         1610 :    FUNCTION k_grid_to_cell_panel_width(work, nvalues, budget, real_output) RESULT(width)
     729              :       TYPE(k_grid_to_cell_work_type), INTENT(IN)         :: work
     730              :       INTEGER(KIND=int_8), INTENT(IN)                    :: nvalues, budget
     731              :       LOGICAL, INTENT(IN)                                :: real_output
     732              :       INTEGER                                            :: width
     733              : 
     734              :       INTEGER(KIND=int_8)                                :: ngrid
     735              : 
     736         6440 :       ngrid = PRODUCT(INT(work%nfft, int_8))
     737         1610 :       CPASSERT(ngrid > 0 .AND. ngrid <= HUGE(0))
     738         1610 :       width = INT(MIN(nvalues, MAX(1_int_8, budget/(fft_panel_element_bytes*ngrid)), INT(HUGE(0), int_8)/ngrid))
     739         1610 :       IF (real_output .AND. ALLOCATED(work%k_partner) .AND. width > 1) width = 2*(width/2)
     740         1610 :    END FUNCTION k_grid_to_cell_panel_width
     741              : 
     742              : ! **************************************************************************************************
     743              : !> \brief Execute a matrix batch using the prepared inverse lattice transform.
     744              : !>        Call outside OpenMP worker regions: fft_tools owns its shared pool and planner.
     745              : !> \param work prepared transform; scratch is reused, never shared between concurrent callers
     746              : !> \param values_k matrices at the prepared reciprocal points
     747              : !> \param values_rs complex matrices at the prepared lattice translations; omit for values_real
     748              : !> \param used_fft whether this batch used FFT; false denotes a direct fallback or no result
     749              : !> \param require_fft abort on an unsupported mapping or FFT failure, without a direct fallback
     750              : !> \param allow_direct_fallback execute the generic direct sum when FFT is unavailable; defaults to true
     751              : !> \param values_real real part of the inverse transform, instead of values_rs
     752              : !> \param profile optional local-panel stage timings and batch counts
     753              : !> \param max_workspace_bytes optional soft FFT workspace target (default 64 MiB)
     754              : !> \param real_sink consume a real FFT panel directly, instead of materializing an output array
     755              : ! **************************************************************************************************
     756         1568 :    SUBROUTINE k_grid_to_cell_execute(work, values_k, values_rs, used_fft, require_fft, allow_direct_fallback, values_real, &
     757              :                                      profile, max_workspace_bytes, real_sink)
     758              : 
     759              :       TYPE(k_grid_to_cell_work_type), INTENT(INOUT)      :: work
     760              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), INTENT(IN)   :: values_k
     761              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), &
     762              :          INTENT(OUT), OPTIONAL                           :: values_rs
     763              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: used_fft
     764              :       LOGICAL, INTENT(IN), OPTIONAL                      :: require_fft, allow_direct_fallback
     765              :       REAL(KIND=dp), INTENT(OUT), OPTIONAL               :: values_real(:, :, :)
     766              :       TYPE(lattice_fft_profile_type), INTENT(INOUT), &
     767              :          OPTIONAL                                        :: profile
     768              :       INTEGER(KIND=int_8), INTENT(IN), OPTIONAL          :: max_workspace_bytes
     769              : 
     770              :       CLASS(lattice_fft_real_sink_type), INTENT(INOUT), &
     771              :          OPTIONAL                                        :: real_sink
     772              : 
     773              :       INTEGER                                            :: fft_count, fft_width, handle, nbatch, n_output, &
     774              :                                                             output_shape(3), width
     775              :       INTEGER(KIND=int_8)                                :: budget, first, ngrid, nvalues
     776              :       LOGICAL                                            :: pack_real, real_output
     777              :       REAL(KIND=dp)                                      :: started
     778              : 
     779         1568 :       CALL timeset("k_grid_to_cell_fft", handle)
     780         1568 :       CPASSERT(ALLOCATED(work%xkp))
     781         4704 :       n_output = MERGE(1, 0, PRESENT(values_rs)) + MERGE(1, 0, PRESENT(values_real)) + MERGE(1, 0, PRESENT(real_sink))
     782         1568 :       CPASSERT(n_output == 1)
     783         3818 :       IF (PRESENT(values_rs)) output_shape = SHAPE(values_rs)
     784         1658 :       IF (PRESENT(values_real)) output_shape = SHAPE(values_real)
     785         1568 :       IF (PRESENT(real_sink)) THEN
     786         3152 :          output_shape = [SIZE(values_k, 1), SIZE(values_k, 2), SIZE(work%cells, 2)]
     787              :       END IF
     788         6272 :       IF (SIZE(values_k, 3) /= SIZE(work%xkp, 2) .OR. &
     789              :           ANY(output_shape /= [SIZE(values_k, 1), SIZE(values_k, 2), SIZE(work%cells, 2)])) THEN
     790            0 :          CALL cp_abort(__LOCATION__, "Inconsistent matrix batches in inverse lattice FFT")
     791              :       END IF
     792              : 
     793         1568 :       IF (PRESENT(require_fft)) THEN
     794         1468 :          IF (require_fft .AND. .NOT. work%regular) THEN
     795            0 :             CPABORT("Forced inverse lattice FFT needs a supported regular grid")
     796              :          END IF
     797              :       END IF
     798         1568 :       IF (work%regular) THEN
     799         6272 :          ngrid = PRODUCT(INT(work%nfft, int_8))
     800         1568 :          nvalues = SIZE(values_k, 1, KIND=int_8)*SIZE(values_k, 2, KIND=int_8)
     801         1568 :          budget = fft_workspace_bytes
     802         1568 :          IF (PRESENT(max_workspace_bytes)) budget = max_workspace_bytes
     803         1568 :          real_output = PRESENT(values_real) .OR. PRESENT(real_sink)
     804         1568 :          width = k_grid_to_cell_panel_width(work, nvalues, budget, real_output)
     805         1568 :          budget = MAX(fft_panel_element_bytes*ngrid, budget)
     806         1568 :          IF (width == 0) THEN
     807            2 :             IF (PRESENT(used_fft)) used_fft = .TRUE.
     808            2 :             CALL timestop(handle)
     809            2 :             RETURN
     810              :          END IF
     811         1566 :          pack_real = real_output .AND. ALLOCATED(work%k_partner) .AND. width > 1
     812         1566 :          fft_width = width
     813         1566 :          IF (pack_real) fft_width = width/2
     814         1566 :          CPASSERT(ngrid*width <= HUGE(0))
     815         1566 :          IF (PRESENT(profile)) profile%pair_major = .TRUE.
     816              :          IF (PRESENT(profile)) THEN
     817            8 :             profile%two_real = pack_real
     818           32 :             profile%nfft = work%nfft
     819            8 :             started = m_walltime()
     820              :          END IF
     821         1566 :          IF (ASSOCIATED(work%fft_in)) THEN
     822         1414 :             IF (SIZE(work%fft_in, KIND=int_8) < ngrid*fft_width .OR. &
     823         1420 :                 32_int_8*SIZE(work%fft_in, KIND=int_8) + 16_int_8*ngrid*fft_width > budget) THEN
     824           16 :                CALL fft_deallocate(work%fft_in)
     825           16 :                CALL fft_deallocate(work%fft_out)
     826              :             END IF
     827              :          END IF
     828         1566 :          IF (.NOT. ASSOCIATED(work%fft_in)) THEN
     829          324 :             CALL fft_allocate(work%fft_in, [INT(ngrid)*fft_width])
     830          324 :             CALL fft_allocate(work%fft_out, [INT(ngrid)*fft_width])
     831              :          END IF
     832         1566 :          IF (PRESENT(profile)) profile%seconds(3) = profile%seconds(3) + m_walltime() - started
     833              :          ! Flatten both matrix dimensions so each FFT batch spans whole columns.
     834         3302 :          DO first = 1_int_8, nvalues, INT(width, int_8)
     835         1736 :             nbatch = INT(MIN(INT(width, int_8), nvalues - first + 1_int_8))
     836         1736 :             fft_count = nbatch
     837         1736 :             IF (pack_real) fft_count = (nbatch + 1)/2
     838         1736 :             IF (PRESENT(profile)) THEN
     839            8 :                profile%batches = profile%batches + 1_int_8
     840            8 :                profile%elements = profile%elements + INT(nbatch, int_8)
     841            8 :                profile%transforms = profile%transforms + INT(fft_count, int_8)
     842            8 :                profile%tile_min = MIN(profile%tile_min, nbatch)
     843            8 :                profile%tile_max = MAX(profile%tile_max, nbatch)
     844            8 :                started = m_walltime()
     845              :             END IF
     846              :             CALL k_grid_to_cell_pair_major_batch(work, values_k, first, nbatch, values_rs, values_real, &
     847         5968 :                                                  profile, pack_real, real_sink)
     848              :          END DO
     849              :       END IF
     850         1566 :       IF (.NOT. work%regular) THEN
     851            0 :          IF (PRESENT(real_sink)) THEN
     852            0 :             CPABORT('A lattice FFT consumer requires successful FFT execution')
     853              :          END IF
     854            0 :          IF (PRESENT(require_fft)) THEN
     855            0 :             IF (require_fft) THEN
     856            0 :                CPABORT("Forced inverse lattice FFT execution failed")
     857              :             END IF
     858              :          END IF
     859            0 :          IF (PRESENT(allow_direct_fallback)) THEN
     860            0 :             IF (.NOT. allow_direct_fallback) THEN
     861            0 :                IF (PRESENT(values_rs)) values_rs = z_zero
     862            0 :                IF (PRESENT(values_real)) values_real = 0.0_dp
     863            0 :                IF (PRESENT(used_fft)) used_fft = .FALSE.
     864            0 :                CALL timestop(handle)
     865            0 :                RETURN
     866              :             END IF
     867              :          END IF
     868            0 :          CALL direct_k_to_cell(values_k, work%xkp, work%cells, values_rs, work%weight, values_real)
     869              :       END IF
     870         1566 :       IF (PRESENT(used_fft)) used_fft = work%regular
     871         1566 :       CALL timestop(handle)
     872              : 
     873              :    END SUBROUTINE k_grid_to_cell_execute
     874              : 
     875              : ! **************************************************************************************************
     876              : !> \brief One K2R FFT panel with pair-major buffers at both ends.
     877              : !>        Mapping from k-point order to FFT slot is performed by contiguous pair strips.
     878              : !> \param work ...
     879              : !> \param values_k ...
     880              : !> \param first ...
     881              : !> \param nbatch ...
     882              : !> \param values_rs ...
     883              : !> \param values_real ...
     884              : !> \param profile ...
     885              : !> \param pack_real pack two independently symmetrized real-output transforms
     886              : !> \param real_sink real-output consumer
     887              : ! **************************************************************************************************
     888         1736 :    SUBROUTINE k_grid_to_cell_pair_major_batch(work, values_k, first, nbatch, values_rs, values_real, profile, &
     889              :                                               pack_real, real_sink)
     890              :       TYPE(k_grid_to_cell_work_type), INTENT(INOUT)      :: work
     891              :       COMPLEX(KIND=dp), INTENT(IN)                       :: values_k(:, :, :)
     892              :       INTEGER(KIND=int_8), INTENT(IN)                    :: first
     893              :       INTEGER, INTENT(IN)                                :: nbatch
     894              :       COMPLEX(KIND=dp), INTENT(INOUT), OPTIONAL          :: values_rs(:, :, :)
     895              :       REAL(KIND=dp), INTENT(INOUT), OPTIONAL             :: values_real(:, :, :)
     896              :       TYPE(lattice_fft_profile_type), INTENT(INOUT), &
     897              :          OPTIONAL                                        :: profile
     898              :       LOGICAL, INTENT(IN)                                :: pack_real
     899              : 
     900              :       CLASS(lattice_fft_real_sink_type), INTENT(INOUT), &
     901              :          OPTIONAL                                        :: real_sink
     902              : 
     903              :       COMPLEX(KIND=dp)                                   :: field_a, field_b, phase, spectrum
     904         1736 :       COMPLEX(KIND=dp), CONTIGUOUS, POINTER              :: input(:, :), output(:, :)
     905              :       INTEGER                                            :: fft_count, i, icell, ik, ipartner, &
     906              :                                                             matrix_column, matrix_row, &
     907              :                                                             other_column, other_row, partner_slot, &
     908              :                                                             slot
     909              :       INTEGER(KIND=int_8)                                :: matrix_index, ngrid
     910              :       REAL(KIND=dp)                                      :: started
     911              : 
     912         6944 :       ngrid = PRODUCT(INT(work%nfft, int_8))
     913         1736 :       fft_count = nbatch
     914         1736 :       IF (pack_real) fft_count = (nbatch + 1)/2
     915         1736 :       input(1:fft_count, 1:INT(ngrid)) => work%fft_in(1:fft_count*INT(ngrid))
     916         1736 :       IF (PRESENT(profile)) started = m_walltime()
     917              :       ! Missing k points and FFT padding must be zero-filled.
     918         1736 :       IF (SIZE(values_k, 3, KIND=int_8) /= ngrid) input = z_zero
     919              : !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) &
     920              : !$OMP IF(INT(nbatch, int_8)*SIZE(values_k, 3, KIND=int_8) >= fft_parallel_values) &
     921              : !$OMP SHARED(input, work, values_k, first, nbatch, fft_count, pack_real) &
     922              : !$OMP PRIVATE(ik, slot, i, matrix_index, matrix_row, matrix_column, ipartner, partner_slot) &
     923         1736 : !$OMP PRIVATE(other_row, other_column, field_a, field_b)
     924              :       DO ik = 1, SIZE(values_k, 3)
     925              :          slot = work%k_slot(ik)
     926              :          IF (pack_real) THEN
     927              :             ipartner = work%k_partner(ik)
     928              :             IF (ipartner < ik) CYCLE
     929              :             partner_slot = work%k_slot(ipartner)
     930              :             ! Visit each +/-k pair once, so every original input is read once.
     931              :             ! Keep the factor 1/2 in extraction, alongside the common Bloch phase.
     932              :             IF (SIZE(values_k, 2) == 1) THEN
     933              :                !$OMP SIMD PRIVATE(matrix_row, field_a, field_b)
     934              :                DO i = 1, fft_count
     935              :                   matrix_row = INT(first) + 2*i - 2
     936              :                   IF (work%uniform_weights) THEN
     937              :                      field_a = values_k(matrix_row, 1, ik) + CONJG(values_k(matrix_row, 1, ipartner))
     938              :                   ELSE
     939              :                      field_a = work%weight(ik)*values_k(matrix_row, 1, ik) + &
     940              :                                CONJG(work%weight(ipartner)*values_k(matrix_row, 1, ipartner))
     941              :                   END IF
     942              :                   field_b = z_zero
     943              :                   IF (2*i <= nbatch) THEN
     944              :                      IF (work%uniform_weights) THEN
     945              :                         field_b = values_k(matrix_row + 1, 1, ik) + CONJG(values_k(matrix_row + 1, 1, ipartner))
     946              :                      ELSE
     947              :                         field_b = work%weight(ik)*values_k(matrix_row + 1, 1, ik) + &
     948              :                                   CONJG(work%weight(ipartner)*values_k(matrix_row + 1, 1, ipartner))
     949              :                      END IF
     950              :                   END IF
     951              :                   input(i, slot) = field_a + gaussi*field_b
     952              :                   IF (ipartner /= ik) input(i, partner_slot) = CONJG(field_a) + gaussi*CONJG(field_b)
     953              :                END DO
     954              :             ELSE
     955              :                DO i = 1, fft_count
     956              :                   matrix_index = first + INT(2*i - 3, int_8)
     957              :                   matrix_row = INT(MODULO(matrix_index, INT(SIZE(values_k, 1), int_8))) + 1
     958              :                   matrix_column = INT(matrix_index/INT(SIZE(values_k, 1), int_8)) + 1
     959              :                   IF (work%uniform_weights) THEN
     960              :                      field_a = values_k(matrix_row, matrix_column, ik) + &
     961              :                                CONJG(values_k(matrix_row, matrix_column, ipartner))
     962              :                   ELSE
     963              :                      field_a = work%weight(ik)*values_k(matrix_row, matrix_column, ik) + &
     964              :                                CONJG(work%weight(ipartner)*values_k(matrix_row, matrix_column, ipartner))
     965              :                   END IF
     966              :                   field_b = z_zero
     967              :                   IF (2*i <= nbatch) THEN
     968              :                      matrix_index = matrix_index + 1_int_8
     969              :                      other_row = INT(MODULO(matrix_index, INT(SIZE(values_k, 1), int_8))) + 1
     970              :                      other_column = INT(matrix_index/INT(SIZE(values_k, 1), int_8)) + 1
     971              :                      IF (work%uniform_weights) THEN
     972              :                         field_b = values_k(other_row, other_column, ik) + &
     973              :                                   CONJG(values_k(other_row, other_column, ipartner))
     974              :                      ELSE
     975              :                         field_b = work%weight(ik)*values_k(other_row, other_column, ik) + &
     976              :                                   CONJG(work%weight(ipartner)*values_k(other_row, other_column, ipartner))
     977              :                      END IF
     978              :                   END IF
     979              :                   input(i, slot) = field_a + gaussi*field_b
     980              :                   IF (ipartner /= ik) input(i, partner_slot) = CONJG(field_a) + gaussi*CONJG(field_b)
     981              :                END DO
     982              :             END IF
     983              :          ELSE IF (SIZE(values_k, 2) == 1) THEN
     984              :             IF (work%uniform_weights) THEN
     985              :                input(:, slot) = values_k(INT(first):INT(first) + nbatch - 1, 1, ik)
     986              :             ELSE
     987              :                input(:, slot) = work%weight(ik)*values_k(INT(first):INT(first) + nbatch - 1, 1, ik)
     988              :             END IF
     989              :          ELSE
     990              :             DO i = 1, nbatch
     991              :                matrix_index = first + INT(i - 2, int_8)
     992              :                matrix_row = INT(MODULO(matrix_index, INT(SIZE(values_k, 1), int_8))) + 1
     993              :                matrix_column = INT(matrix_index/INT(SIZE(values_k, 1), int_8)) + 1
     994              :                IF (work%uniform_weights) THEN
     995              :                   input(i, slot) = values_k(matrix_row, matrix_column, ik)
     996              :                ELSE
     997              :                   input(i, slot) = work%weight(ik)*values_k(matrix_row, matrix_column, ik)
     998              :                END IF
     999              :             END DO
    1000              :          END IF
    1001              :       END DO
    1002              : !$OMP END PARALLEL DO
    1003         1736 :       IF (PRESENT(profile)) profile%seconds(4) = profile%seconds(4) + m_walltime() - started
    1004         1736 :       CALL lattice_fft_execute_pair_major(FWFFT, work%nfft, fft_count, work%fft_in, work%fft_out, profile)
    1005         1736 :       output(1:fft_count, 1:INT(ngrid)) => work%fft_in(1:fft_count*INT(ngrid))
    1006         1736 :       IF (PRESENT(profile)) started = m_walltime()
    1007         1736 :       IF (PRESENT(real_sink)) THEN
    1008          930 :          real_sink%two_real = pack_real
    1009          930 :          CALL real_sink%consume(first, nbatch, output, work%cell_slot, work%cell_phase)
    1010          930 :          IF (PRESENT(profile)) profile%seconds(8) = profile%seconds(8) + m_walltime() - started
    1011          930 :          RETURN
    1012              :       END IF
    1013              : !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) &
    1014              : !$OMP IF(INT(nbatch, int_8)*SIZE(work%cells, 2, KIND=int_8) >= fft_parallel_values) &
    1015              : !$OMP SHARED(output, work, values_rs, values_real, values_k, first, nbatch, fft_count, pack_real) &
    1016          806 : !$OMP PRIVATE(icell, slot, i, matrix_index, matrix_row, matrix_column, phase, spectrum)
    1017              :       DO icell = 1, SIZE(work%cells, 2)
    1018              :          slot = work%cell_slot(icell)
    1019              :          IF (pack_real) THEN
    1020              :             phase = 0.5_dp*work%cell_phase(icell)
    1021              :             IF (SIZE(values_k, 2) == 1) THEN
    1022              :                !$OMP SIMD PRIVATE(matrix_row, spectrum)
    1023              :                DO i = 1, fft_count
    1024              :                   matrix_row = INT(first) + 2*i - 2
    1025              :                   spectrum = phase*output(i, slot)
    1026              :                   values_real(matrix_row, 1, icell) = REAL(spectrum, dp)
    1027              :                   IF (2*i <= nbatch) values_real(matrix_row + 1, 1, icell) = AIMAG(spectrum)
    1028              :                END DO
    1029              :             ELSE
    1030              :                DO i = 1, nbatch
    1031              :                   matrix_index = first + INT(i - 2, int_8)
    1032              :                   matrix_row = INT(MODULO(matrix_index, INT(SIZE(values_k, 1), int_8))) + 1
    1033              :                   matrix_column = INT(matrix_index/INT(SIZE(values_k, 1), int_8)) + 1
    1034              :                   spectrum = phase*output((i + 1)/2, slot)
    1035              :                   values_real(matrix_row, matrix_column, icell) = &
    1036              :                      MERGE(REAL(spectrum, dp), AIMAG(spectrum), MODULO(i, 2) == 1)
    1037              :                END DO
    1038              :             END IF
    1039              :             CYCLE
    1040              :          END IF
    1041              :          IF (SIZE(values_k, 2) == 1) THEN
    1042              :             IF (PRESENT(values_rs)) THEN
    1043              :                values_rs(INT(first):INT(first) + nbatch - 1, 1, icell) = &
    1044              :                   work%cell_phase(icell)*output(:, slot)
    1045              :             ELSE
    1046              :                values_real(INT(first):INT(first) + nbatch - 1, 1, icell) = &
    1047              :                   REAL(work%cell_phase(icell)*output(:, slot), dp)
    1048              :             END IF
    1049              :          ELSE
    1050              :             DO i = 1, nbatch
    1051              :                matrix_index = first + INT(i - 2, int_8)
    1052              :                matrix_row = INT(MODULO(matrix_index, INT(SIZE(values_k, 1), int_8))) + 1
    1053              :                matrix_column = INT(matrix_index/INT(SIZE(values_k, 1), int_8)) + 1
    1054              :                IF (PRESENT(values_rs)) THEN
    1055              :                   values_rs(matrix_row, matrix_column, icell) = work%cell_phase(icell)*output(i, slot)
    1056              :                ELSE
    1057              :                   values_real(matrix_row, matrix_column, icell) = REAL(work%cell_phase(icell)*output(i, slot), dp)
    1058              :                END IF
    1059              :             END DO
    1060              :          END IF
    1061              :       END DO
    1062              : !$OMP END PARALLEL DO
    1063          806 :       IF (PRESENT(profile)) profile%seconds(8) = profile%seconds(8) + m_walltime() - started
    1064         1736 :    END SUBROUTINE k_grid_to_cell_pair_major_batch
    1065              : 
    1066              : ! **************************************************************************************************
    1067              : !> \brief Release inverse lattice plans before their buffers and shared geometry.
    1068              : !> \param work ...
    1069              : ! **************************************************************************************************
    1070          292 :    SUBROUTINE k_grid_to_cell_release(work)
    1071              : 
    1072              :       TYPE(k_grid_to_cell_work_type), INTENT(INOUT)      :: work
    1073              : 
    1074          292 :       IF (ASSOCIATED(work%fft_in)) CALL fft_deallocate(work%fft_in)
    1075          292 :       IF (ASSOCIATED(work%fft_out)) CALL fft_deallocate(work%fft_out)
    1076          292 :       IF (ALLOCATED(work%xkp)) DEALLOCATE (work%xkp, work%cells, work%weight)
    1077          292 :       IF (ALLOCATED(work%k_slot)) DEALLOCATE (work%k_slot)
    1078          292 :       IF (ALLOCATED(work%k_partner)) DEALLOCATE (work%k_partner)
    1079          292 :       IF (ALLOCATED(work%cell_slot)) DEALLOCATE (work%cell_slot, work%cell_phase)
    1080          292 :       work%regular = .FALSE.
    1081          292 :       work%uniform_weights = .FALSE.
    1082              : 
    1083          292 :    END SUBROUTINE k_grid_to_cell_release
    1084              : 
    1085              : ! **************************************************************************************************
    1086              : !> \brief Direct inverse phase sum for arbitrary reciprocal-point lists.
    1087              : !> \param values_k ...
    1088              : !> \param xkp ...
    1089              : !> \param index_to_cell ...
    1090              : !> \param values_rs ...
    1091              : !> \param weights optional k weights, otherwise 1/number-of-points
    1092              : !> \param values_real real part of the inverse transform, instead of values_rs
    1093              : ! **************************************************************************************************
    1094            0 :    SUBROUTINE direct_k_to_cell(values_k, xkp, index_to_cell, values_rs, weights, values_real)
    1095              : 
    1096              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), INTENT(IN)   :: values_k
    1097              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: xkp
    1098              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: index_to_cell
    1099              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), &
    1100              :          INTENT(OUT), OPTIONAL                           :: values_rs
    1101              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN), OPTIONAL  :: weights
    1102              :       REAL(KIND=dp), INTENT(OUT), OPTIONAL               :: values_real(:, :, :)
    1103              : 
    1104              :       COMPLEX(KIND=dp)                                   :: factor
    1105              :       INTEGER                                            :: icell, ik
    1106              :       REAL(KIND=dp)                                      :: arg, normalization
    1107              : 
    1108            0 :       IF (PRESENT(values_rs)) values_rs = z_zero
    1109            0 :       IF (PRESENT(values_real)) values_real = 0.0_dp
    1110            0 :       normalization = 1.0_dp/REAL(SIZE(xkp, 2), KIND=dp)
    1111            0 :       DO icell = 1, SIZE(index_to_cell, 2)
    1112            0 :          DO ik = 1, SIZE(xkp, 2)
    1113            0 :             IF (PRESENT(weights)) normalization = weights(ik)
    1114            0 :             arg = SUM(xkp(1:3, ik)*REAL(index_to_cell(1:3, icell), KIND=dp))
    1115            0 :             factor = normalization*EXP(-gaussi*twopi*arg)
    1116            0 :             IF (PRESENT(values_rs)) THEN
    1117            0 :                values_rs(:, :, icell) = values_rs(:, :, icell) + factor*values_k(:, :, ik)
    1118              :             ELSE
    1119            0 :                values_real(:, :, icell) = values_real(:, :, icell) + REAL(factor*values_k(:, :, ik), dp)
    1120              :             END IF
    1121              :          END DO
    1122              :       END DO
    1123              : 
    1124            0 :    END SUBROUTINE direct_k_to_cell
    1125              : 
    1126              : ! **************************************************************************************************
    1127              : !> \brief Direct phase-sum fallback for arbitrary reciprocal-point lists.
    1128              : !> \param values_rs ...
    1129              : !> \param index_to_cell ...
    1130              : !> \param xkp ...
    1131              : !> \param values_k ...
    1132              : !> \param deriv_direction ...
    1133              : !> \param hmat ...
    1134              : !> \param selected_kpoints ...
    1135              : !> \param accumulate add to the existing output
    1136              : ! **************************************************************************************************
    1137            4 :    SUBROUTINE direct_cell_to_k(values_rs, index_to_cell, xkp, values_k, &
    1138            2 :                                deriv_direction, hmat, selected_kpoints, accumulate)
    1139              : 
    1140              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: values_rs
    1141              :       INTEGER, DIMENSION(:, :), INTENT(IN)               :: index_to_cell
    1142              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: xkp
    1143              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), &
    1144              :          INTENT(INOUT)                                   :: values_k
    1145              :       INTEGER, INTENT(IN), OPTIONAL                      :: deriv_direction
    1146              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN), &
    1147              :          OPTIONAL                                        :: hmat
    1148              :       INTEGER, DIMENSION(:), INTENT(IN), OPTIONAL        :: selected_kpoints
    1149              :       LOGICAL, INTENT(IN)                                :: accumulate
    1150              : 
    1151              :       COMPLEX(KIND=dp)                                   :: factor
    1152              :       INTEGER                                            :: icell, ik, ik_out
    1153              :       REAL(KIND=dp)                                      :: arg
    1154              :       REAL(KIND=dp), DIMENSION(3)                        :: cell_vector
    1155              : 
    1156         1282 :       IF (.NOT. accumulate) values_k = z_zero
    1157          130 :       DO ik_out = 1, SIZE(values_k, 3)
    1158          128 :          ik = ik_out
    1159          128 :          IF (PRESENT(selected_kpoints)) ik = selected_kpoints(ik_out)
    1160         4098 :          DO icell = 1, SIZE(values_rs, 3)
    1161        15872 :             arg = SUM(xkp(1:3, ik)*REAL(index_to_cell(1:3, icell), KIND=dp))
    1162         3968 :             factor = EXP(gaussi*twopi*arg)
    1163         3968 :             IF (PRESENT(deriv_direction)) THEN
    1164            0 :                cell_vector = MATMUL(hmat, REAL(index_to_cell(1:3, icell), KIND=dp))
    1165            0 :                factor = factor*gaussi*cell_vector(deriv_direction)
    1166              :             END IF
    1167        39808 :             values_k(:, :, ik_out) = values_k(:, :, ik_out) + factor*values_rs(:, :, icell)
    1168              :          END DO
    1169              :       END DO
    1170              : 
    1171            2 :    END SUBROUTINE direct_cell_to_k
    1172              : 
    1173            0 : END MODULE kpoint_lattice_fft
        

Generated by: LCOV version 2.0-1