diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 59bb4967..091e0706 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,7 +11,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest] + os: [ubuntu-24.04] build: [meson, cmake, fpm] build-type: [debug] compiler: [gnu] @@ -24,7 +24,7 @@ jobs: compiler: gnu version: 12 - - os: ubuntu-latest + - os: ubuntu-24.04 build: meson build-type: coverage compiler: gnu @@ -263,7 +263,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest] + os: [ubuntu-24.04] build: [meson, cmake] gcc_v: [10] python_v: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13', '3.14'] diff --git a/config/cmake/Findmctc-lib.cmake b/config/cmake/Findmctc-lib.cmake index f72b75da..a319c568 100644 --- a/config/cmake/Findmctc-lib.cmake +++ b/config/cmake/Findmctc-lib.cmake @@ -17,7 +17,7 @@ set(_lib "mctc-lib") set(_pkg "MCTCLIB") set(_url "https://github.com/grimme-lab/mctc-lib") -set(_rev "06db4d8") +set(_rev "v0.7.0") if(NOT DEFINED "${_pkg}_FIND_METHOD") if(DEFINED "${PROJECT_NAME}-dependency-method") diff --git a/config/cmake/Findmstore.cmake b/config/cmake/Findmstore.cmake index 3a834a28..0bd2e0f6 100644 --- a/config/cmake/Findmstore.cmake +++ b/config/cmake/Findmstore.cmake @@ -17,7 +17,7 @@ set(_lib "mstore") set(_pkg "MSTORE") set(_url "https://github.com/grimme-lab/mstore") -set(_rev "v0.3.0") +set(_rev "v0.4.0") if(NOT DEFINED "${_pkg}_FIND_METHOD") if(DEFINED "${PROJECT_NAME}-dependency-method") diff --git a/doc/api/c.rst b/doc/api/c.rst index bcb07995..77d424fa 100644 --- a/doc/api/c.rst +++ b/doc/api/c.rst @@ -197,7 +197,7 @@ Recreating a structure object requires to recreate the dispersion model as well. Zero derives a particle mesh from the reciprocal cutoff, which scales as :math:`O(N \log N)` and is the default. A positive value interpolates the structure factors on a mesh of that many - points per direction, rounded up to a power of two. + points per direction, rounded up to a product of powers of two and three. A negative value sums over the reciprocal lattice directly, which is exact but scales quadratically with the number of atoms. diff --git a/doc/guide/accuracy.rst b/doc/guide/accuracy.rst index 6b54ce85..57d0e8e7 100644 --- a/doc/guide/accuracy.rst +++ b/doc/guide/accuracy.rst @@ -145,6 +145,8 @@ Particle mesh evaluation The direct reciprocal space sum visits every atom at every wave vector, so its cost grows quadratically with the number of atoms. Setting ``mesh`` interpolates the structure factors on an equispaced mesh with cardinal B-splines and evaluates the sum with a fast Fourier transform instead, which scales as :math:`O(N \log N)`. This is the default; a negative ``mesh`` falls back to the direct summation. +Each requested mesh length is rounded up to the smallest product of powers of two and three. +For example, 271 points become 288 rather than 512, reducing the size of a cubic mesh by a factor of about 5.6. The discretisation error is governed by the mesh spacing, not by the number of mesh points, so the mesh has to grow with the cell. The table lists the deviation from the direct summation for cubic carbon monoxide supercells, in Hartree per atom, against the resulting spacing in a₀: diff --git a/doc/guide/pbc.rst b/doc/guide/pbc.rst index 22c8879b..47732f94 100644 --- a/doc/guide/pbc.rst +++ b/doc/guide/pbc.rst @@ -122,7 +122,7 @@ The mesh is derived from the reciprocal cutoff unless it is given explicitly: .. code-block:: fortran - ! explicit mesh, rounded up to a power of two + ! explicit mesh, rounded up to a product of powers of two and three call new_d3_model(disp, mol, lowrank=d3_lowrank_config(mesh=32)) ! sum over the reciprocal lattice directly @@ -133,7 +133,7 @@ The mesh is derived from the reciprocal cutoff unless it is given explicitly: .. code-block:: c - /* explicit mesh, rounded up to a power of two */ + /* explicit mesh, rounded up to a product of powers of two and three */ dftd3_set_model_ewald(error, d3, 0, 0.0, 0.0, 32); /* sum over the reciprocal lattice directly */ @@ -144,7 +144,7 @@ The mesh is derived from the reciprocal cutoff unless it is given explicitly: .. code-block:: python - # explicit mesh, rounded up to a power of two + # explicit mesh, rounded up to a product of powers of two and three model.set_ewald_summation(mesh=32) # sum over the reciprocal lattice directly diff --git a/fpm.toml b/fpm.toml index f722a0bf..05d9ec8f 100644 --- a/fpm.toml +++ b/fpm.toml @@ -9,11 +9,11 @@ keywords = ["dispersion-correction", "quantum-chemistry"] [dependencies] mctc-lib.git = "https://github.com/grimme-lab/mctc-lib" -mctc-lib.tag = "v0.5.2" +mctc-lib.tag = "v0.7.0" [dev-dependencies] mstore.git = "https://github.com/grimme-lab/mstore" -mstore.tag = "v0.3.0" +mstore.tag = "v0.4.0" [build] external-modules = ["mpi_f08"] diff --git a/src/dftd3/disp.f90 b/src/dftd3/disp.f90 index 31e36086..b7d0d0ac 100644 --- a/src/dftd3/disp.f90 +++ b/src/dftd3/disp.f90 @@ -89,7 +89,7 @@ subroutine get_dispersion_atomic_v2(error, mol, disp, param, cutoff, energies, & !> Communication backend, enables partitioning the coordination number class(work_reducer), intent(in), optional :: reducer - logical :: grad, hess, ewald + logical :: grad, hess, ewald, threebody integer :: mref real(wp), allocatable :: cn(:) real(wp), allocatable :: gwvec(:, :), gwdcn(:, :) @@ -101,6 +101,7 @@ subroutine get_dispersion_atomic_v2(error, mol, disp, param, cutoff, energies, & mref = maxval(disp%ref) grad = present(gradient) .or. present(sigma) hess = present(hessian) + threebody = param%has_threebody() ! a low-rank model under three-dimensional boundary conditions asks for the ! reciprocal space summation, which the damping function has to support @@ -132,13 +133,15 @@ subroutine get_dispersion_atomic_v2(error, mol, disp, param, cutoff, energies, & if (grad) allocate(gwdcn(mref, mol%nat)) call disp%weight_references(mol, cn, gwvec, gwdcn) - allocate(c6(mol%nat, mol%nat)) - if (grad) allocate(dc6dcn(mol%nat, mol%nat)) - if (param%has_threebody()) then - ! the three-body term reads coefficients of pairs this part does not own - call disp%get_atomic_c6(mol, gwvec, gwdcn, c6, dc6dcn) - else - call disp%get_atomic_c6(mol, gwvec, gwdcn, c6, dc6dcn, partition=partition) + if (.not.ewald .or. threebody) then + allocate(c6(mol%nat, mol%nat)) + if (grad) allocate(dc6dcn(mol%nat, mol%nat)) + if (threebody) then + ! the three-body term reads coefficients of pairs this part does not own + call disp%get_atomic_c6(mol, gwvec, gwdcn, c6, dc6dcn) + else + call disp%get_atomic_c6(mol, gwvec, gwdcn, c6, dc6dcn, partition=partition) + end if end if energies(:) = 0.0_wp @@ -160,10 +163,12 @@ subroutine get_dispersion_atomic_v2(error, mol, disp, param, cutoff, energies, & & disp%rvdw, disp%r4r2, c6, dc6dcn, energies, dEdcn, gradient_local, & & sigma_local, partition) end if - call get_lattice_points(mol%periodic, mol%lattice, cutoff%disp3, lattr) - call param%get_dispersion3(mol, lattr, cutoff%disp3, cutoff%width3, & - & disp%rvdw, disp%r4r2, c6, dc6dcn, energies, dEdcn, gradient_local, & - & sigma_local, partition) + if (threebody) then + call get_lattice_points(mol%periodic, mol%lattice, cutoff%disp3, lattr) + call param%get_dispersion3(mol, lattr, cutoff%disp3, cutoff%width3, & + & disp%rvdw, disp%r4r2, c6, dc6dcn, energies, dEdcn, gradient_local, & + & sigma_local, partition) + end if if (grad) then call get_lattice_points(mol%periodic, mol%lattice, cutoff%cn, lattr) if (present(reducer)) then diff --git a/src/dftd3/fourier/ewald.f90 b/src/dftd3/fourier/ewald.f90 index 3cf876b4..4b6ababd 100644 --- a/src/dftd3/fourier/ewald.f90 +++ b/src/dftd3/fourier/ewald.f90 @@ -27,8 +27,8 @@ module dftd3_fourier_ewald use dftd3_cutoff, only : get_lattice_points use dftd3_fourier_decomposition, only : d3_lowrank_c6 - use dftd3_fourier_kernel, only : fourier_term, get_fourier_transform, & - & get_potential_zero + use dftd3_fourier_kernel, only : fourier_term, fourier_kernel, new_fourier_kernel, & + & get_fourier_transform, get_potential_zero use dftd3_partition, only : work_partition, owns_index use mctc_env, only : wp use mctc_io, only : structure_type @@ -87,7 +87,7 @@ subroutine get_dispersion_ewald(mol, lowrank, ghost, terms, nterm, kcut, gwvec, type(work_partition), intent(in), optional :: partition logical :: grad - type(work_partition) :: part + type(fourier_kernel), allocatable :: kernel(:, :, :) integer :: nat, nid, rank, nk, ik, iat, izp, jzp, il, it, ic real(wp) :: vol, rec(3, 3), kvec(3), knorm, kr, erecip, phi, dphi, pval, dpval real(wp) :: qq, zre, zim @@ -110,6 +110,7 @@ subroutine get_dispersion_ewald(mol, lowrank, ghost, terms, nterm, kcut, gwvec, vol = abs(matdet_3x3(mol%lattice)) call get_lattice_points([.true., .true., .true.], rec, kcut, kpoints) nk = size(kpoints, 2) + kernel = new_fourier_kernel(terms) allocate(c6l(rank, nat)) allocate(dc6ldcn(rank, nat), source=0.0_wp) @@ -144,7 +145,7 @@ subroutine get_dispersion_ewald(mol, lowrank, ghost, terms, nterm, kcut, gwvec, erecip = -sum(esum) !$omp parallel default(none) & - !$omp shared(mol, lowrank, terms, nterm, kcut, kpoints, nk, nat, nid, rank, & + !$omp shared(mol, lowrank, kernel, nterm, kcut, kpoints, nk, nat, nid, rank, & !$omp& c6l, dc6ldcn, vol, grad, partition, esum, dsum, gsum, ssum) & !$omp private(ik, iat, izp, jzp, il, it, ic, kvec, knorm, kr, phi, dphi, & !$omp& pval, dpval, qq, zval, zre, zim, phihat, dphihat, phase, sf, fvec, & @@ -168,7 +169,7 @@ subroutine get_dispersion_ewald(mol, lowrank, ghost, terms, nterm, kcut, gwvec, phi = 0.0_wp dphi = 0.0_wp do it = 1, nterm(jzp, izp) - call get_fourier_transform(terms(it, jzp, izp), knorm, pval, dpval) + call get_fourier_transform(kernel(it, jzp, izp), knorm, pval, dpval, grad) phi = phi + pval dphi = dphi + dpval end do diff --git a/src/dftd3/fourier/fft.f90 b/src/dftd3/fourier/fft.f90 index b811a152..be5b031d 100644 --- a/src/dftd3/fourier/fft.f90 +++ b/src/dftd3/fourier/fft.f90 @@ -16,10 +16,8 @@ !> Complex fast Fourier transform on a three-dimensional mesh. !> -!> Self-contained radix-2 implementation, sufficient for the particle mesh -!> evaluation of the dispersion energy which is free to choose its mesh size. -!> Supports powers of two only, a mixed-radix backend would lift the mesh -!> quantisation but only matters once the transform dominates the runtime. +!> Self-contained radix-2/3 Stockham transform. Allowing products of powers of +!> two and three avoids padding the particle mesh to the next power of two. module dftd3_fourier_fft use mctc_env, only : wp use mctc_io_constants, only : pi @@ -29,17 +27,14 @@ module dftd3_fourier_fft public :: fft_mesh, new_fft_mesh, fft_3d, valid_mesh_size - !> Twiddle factors shared by the transforms along all three mesh directions + !> Twiddle factors for the transforms along the three mesh directions type :: fft_mesh !> Number of points along each direction integer :: mesh(3) = 0 - !> Length of the twiddle table, the largest mesh dimension - integer :: nmax = 0 - - !> Roots of unity exp(-2*pi*i*k/nmax) for k = 0 .. nmax/2 - 1 - complex(wp), allocatable :: tw(:) + !> Roots of unity for each direction, whose lengths need not divide each other + complex(wp), allocatable :: tw(:, :) end type fft_mesh @@ -55,12 +50,23 @@ pure function valid_mesh_size(npoint) result(nmesh) !> Supported number of mesh points integer :: nmesh + integer :: pow3, candidate nmesh = 1 do while (nmesh < npoint) nmesh = 2 * nmesh end do + pow3 = 3 + do while (pow3 < nmesh) + candidate = pow3 + do while (candidate < npoint) + candidate = 2 * candidate + end do + nmesh = min(nmesh, candidate) + pow3 = 3 * pow3 + end do + end function valid_mesh_size @@ -73,14 +79,14 @@ subroutine new_fft_mesh(self, mesh) !> Number of points along each direction integer, intent(in) :: mesh(3) - integer :: ik + integer :: ik, idir self%mesh(:) = mesh - self%nmax = maxval(mesh) - - allocate(self%tw(0:self%nmax/2 - 1)) - do ik = 0, self%nmax/2 - 1 - self%tw(ik) = cmplx(cos(2*pi*ik/self%nmax), -sin(2*pi*ik/self%nmax), wp) + allocate(self%tw(0:maxval(mesh) - 1, 3)) + do idir = 1, 3 + do ik = 0, mesh(idir) - 1 + self%tw(ik, idir) = cmplx(cos(2*pi*ik/mesh(idir)), -sin(2*pi*ik/mesh(idir)), wp) + end do end do end subroutine new_fft_mesh @@ -99,13 +105,15 @@ subroutine fft_3d(self, grid, isign) integer, intent(in) :: isign integer :: i1, i2, i3 + complex(wp), allocatable :: work(:, :) - !$omp parallel default(none) shared(self, grid, isign) private(i1, i2, i3) + !$omp parallel default(none) shared(self, grid, isign) private(i1, i2, i3, work) + allocate(work(size(self%tw, 1), 2)) !$omp do schedule(runtime) collapse(2) do i3 = 1, self%mesh(3) do i2 = 1, self%mesh(2) - call fft_1d(grid(:, i2, i3), self%tw, self%nmax, isign) + call fft_1d(grid(:, i2, i3), self%tw(:, 1), work, isign) end do end do !$omp end do @@ -113,7 +121,7 @@ subroutine fft_3d(self, grid, isign) !$omp do schedule(runtime) collapse(2) do i3 = 1, self%mesh(3) do i1 = 1, self%mesh(1) - call fft_1d(grid(i1, :, i3), self%tw, self%nmax, isign) + call fft_1d(grid(i1, :, i3), self%tw(:, 2), work, isign) end do end do !$omp end do @@ -121,68 +129,73 @@ subroutine fft_3d(self, grid, isign) !$omp do schedule(runtime) collapse(2) do i2 = 1, self%mesh(2) do i1 = 1, self%mesh(1) - call fft_1d(grid(i1, i2, :), self%tw, self%nmax, isign) + call fft_1d(grid(i1, i2, :), self%tw(:, 3), work, isign) end do end do !$omp end do + deallocate(work) !$omp end parallel end subroutine fft_3d -!> In-place radix-2 decimation in time transform of a single sequence -pure subroutine fft_1d(zvec, tw, nmax, isign) +!> Autosorting transform using two contiguous work vectors shared across stages +pure subroutine fft_1d(zvec, tw, work, isign) !> Sequence to transform complex(wp), intent(inout) :: zvec(:) - !> Roots of unity for the largest mesh dimension + !> Roots of unity for this direction complex(wp), intent(in) :: tw(0:) - !> Length of the twiddle table - integer, intent(in) :: nmax + !> Per-thread scratch space, reused for every mesh line + complex(wp), intent(inout) :: work(:, :) !> Sign of the exponent integer, intent(in) :: isign - integer :: nn, ii, jj, kk, mm, istep, itw - complex(wp) :: wval, temp + integer :: nn, stride, radix, blocks, jj, kk, ii, io, src, dst + complex(wp) :: wval, wval2, aa, bb, cc, dd, omega nn = size(zvec) if (nn <= 1) return - jj = 1 - do ii = 1, nn - if (jj > ii) then - temp = zvec(jj) - zvec(jj) = zvec(ii) - zvec(ii) = temp - end if - kk = nn / 2 - do while (kk >= 2 .and. jj > kk) - jj = jj - kk - kk = kk / 2 - end do - jj = jj + kk - end do - - mm = 1 - do while (mm < nn) - istep = 2 * mm - do kk = 1, mm - ! every supported length divides nmax, so the table is shared - itw = (kk - 1) * (nmax / istep) - wval = tw(itw) + work(:nn, 1) = zvec + omega = cmplx(0.0_wp, isign * sqrt(3.0_wp) / 2, wp) + src = 1 + stride = 1 + do while (stride < nn) + radix = 3 + if (mod(nn / stride, 2) == 0) radix = 2 + blocks = nn / (radix * stride) + dst = 3 - src + do jj = 0, stride - 1 + wval = tw(jj * blocks) if (isign > 0) wval = conjg(wval) - do ii = kk, nn, istep - temp = wval * zvec(ii + mm) - zvec(ii + mm) = zvec(ii) - temp - zvec(ii) = zvec(ii) + temp + if (radix == 3) wval2 = wval * wval + do kk = 0, blocks - 1 + ii = jj + kk * stride + 1 + io = jj + kk * radix * stride + 1 + aa = work(ii, src) + bb = wval * work(ii + nn/radix, src) + if (radix == 2) then + work(io, dst) = aa + bb + work(io + stride, dst) = aa - bb + else + cc = wval2 * work(ii + 2*nn/radix, src) + dd = omega * (bb - cc) + work(io, dst) = aa + bb + cc + aa = aa - 0.5_wp * (bb + cc) + work(io + stride, dst) = aa + dd + work(io + 2*stride, dst) = aa - dd + end if end do end do - mm = istep + src = dst + stride = radix * stride end do + zvec = work(:nn, src) end subroutine fft_1d diff --git a/src/dftd3/fourier/kernel.f90 b/src/dftd3/fourier/kernel.f90 index 342e173f..e92111d7 100644 --- a/src/dftd3/fourier/kernel.f90 +++ b/src/dftd3/fourier/kernel.f90 @@ -35,6 +35,7 @@ module dftd3_fourier_kernel private public :: fourier_term, max_fourier_terms + public :: fourier_kernel, new_fourier_kernel public :: is_supported_term, get_fourier_transform, get_potential_zero public :: get_reciprocal_cutoff @@ -60,6 +61,14 @@ module dftd3_fourier_kernel end type fourier_term + !> Wave-number-independent coefficients of the Fourier transform + type :: fourier_kernel + private + integer :: npair = 0 + real(wp) :: prefactor = 0.0_wp, radius = 0.0_wp, zero = 0.0_wp + real(wp), allocatable :: angle(:), cosine(:), sine(:), phase(:) + end type fourier_kernel + contains @@ -79,11 +88,35 @@ pure function is_supported_term(term) result(supported) end function is_supported_term -!> Fourier transform of a single term and its derivative w.r.t. the wave number -pure subroutine get_fourier_transform(term, kval, phi, dphi) +!> Prepare a term once before evaluating it at many wave numbers +pure elemental function new_fourier_kernel(term) result(kernel) - !> Term of the damped pair potential type(fourier_term), intent(in) :: term + type(fourier_kernel) :: kernel + integer :: ipole, nexp + + if (abs(term%prefactor) <= 0.0_wp) return + + nexp = term%m - term%alpha + 2 + kernel%prefactor = 4.0_wp*pi*pi / term%alpha * term%prefactor * term%radius**nexp + kernel%radius = term%radius + kernel%zero = kernel%prefactor * term%radius / sin(pi*(term%m + 3)/real(term%alpha, wp)) + ! Reflected poles give equal contributions for even m and alpha. Retain one + ! pole per pair and the unpaired imaginary pole, if present. + kernel%npair = term%alpha / 4 + kernel%angle = [(pi * (2*ipole + 1) / real(term%alpha, wp), ipole=0, (term%alpha-2)/4)] + kernel%cosine = cos(kernel%angle) + kernel%sine = sin(kernel%angle) + kernel%phase = 0.5_wp*pi + nexp*kernel%angle + +end function new_fourier_kernel + + +!> Fourier transform and its derivative w.r.t. the wave number +pure subroutine get_fourier_transform(kernel, kval, phi, dphi, grad) + + !> Prepared coefficients of the damped pair potential + type(fourier_kernel), intent(in) :: kernel !> Wave number real(wp), intent(in) :: kval @@ -94,37 +127,34 @@ pure subroutine get_fourier_transform(term, kval, phi, dphi) !> Derivative of the Fourier transform w.r.t. the wave number real(wp), intent(out) :: dphi - integer :: ipole, npole, nexp - real(wp) :: pre, theta, ct, st, arg, damp, acc, dacc, krad + !> Whether the derivative is required + logical, intent(in) :: grad + + integer :: ipole + real(wp) :: arg, damp, acc, dacc, krad phi = 0.0_wp dphi = 0.0_wp - if (abs(term%prefactor) <= 0.0_wp) return - - nexp = term%m - term%alpha + 2 - pre = 4.0_wp*pi*pi / term%alpha * term%prefactor * term%radius**nexp + if (abs(kernel%prefactor) <= 0.0_wp) return if (kval <= 0.0_wp) then - phi = pre * term%radius / sin(pi*(term%m + 3)/real(term%alpha, wp)) + phi = kernel%zero return end if - npole = term%alpha / 2 - krad = kval * term%radius + krad = kval * kernel%radius acc = 0.0_wp dacc = 0.0_wp - do ipole = 0, npole - 1 - theta = pi * (2*ipole + 1) / real(term%alpha, wp) - ct = cos(theta) - st = sin(theta) - arg = 0.5_wp*pi + nexp*theta + krad*ct - damp = exp(-krad*st) + do ipole = 1, size(kernel%angle) + arg = kernel%phase(ipole) + krad*kernel%cosine(ipole) + damp = exp(-krad*kernel%sine(ipole)) + if (ipole <= kernel%npair) damp = 2.0_wp * damp acc = acc + sin(arg) * damp - dacc = dacc + cos(arg + theta) * damp + if (grad) dacc = dacc + cos(arg + kernel%angle(ipole)) * damp end do - phi = pre * acc / kval - dphi = (pre * term%radius * dacc - phi) / kval + phi = kernel%prefactor * acc / kval + if (grad) dphi = (kernel%prefactor * kernel%radius * dacc - phi) / kval end subroutine get_fourier_transform diff --git a/src/dftd3/fourier/spme.f90 b/src/dftd3/fourier/spme.f90 index c72162c2..6b34deec 100644 --- a/src/dftd3/fourier/spme.f90 +++ b/src/dftd3/fourier/spme.f90 @@ -28,8 +28,8 @@ module dftd3_fourier_spme use dftd3_fourier_decomposition, only : d3_lowrank_c6 use dftd3_fourier_fft, only : fft_mesh, new_fft_mesh, fft_3d, valid_mesh_size - use dftd3_fourier_kernel, only : fourier_term, get_fourier_transform, & - & get_potential_zero + use dftd3_fourier_kernel, only : fourier_term, fourier_kernel, new_fourier_kernel, & + & get_fourier_transform, get_potential_zero use dftd3_partition, only : work_partition, owns_index use mctc_env, only : wp use mctc_io, only : structure_type @@ -122,13 +122,14 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & integer :: nat, nid, rank, iat, izp, jzp, il, it, ic, jc integer :: i1, i2, i3, j1, j2, j3, g1, g2, g3 real(wp) :: vol, rec(3, 3), invlat(3, 3), kvec(3), knorm, erecip - real(wp) :: pval, dpval, phi, dphi, wgt, dwgt(3), sfac, qq, escale + real(wp) :: pval, wgt, dwgt(3), sfac, qq, escale real(wp) :: dudr(3, 3), tvec(3), dtvec(3) + complex(wp) :: potential integer, allocatable :: base(:, :) real(wp), allocatable :: theta(:, :, :), dtheta(:, :, :) real(wp), allocatable :: bfac(:, :), c6l(:, :), dc6ldcn(:, :) real(wp), allocatable :: phik(:, :, :, :), dphik(:, :, :, :) - real(wp), allocatable :: pot(:, :), esum(:), dsum(:), gsum(:, :), ssum(:, :) + real(wp), allocatable :: esum(:), dsum(:), gsum(:, :), ssum(:, :) complex(wp), allocatable :: qgrid(:, :, :, :), tgrid(:, :, :) grad = present(gwdcn) .and. present(dEdcn) .and. present(gradient) & @@ -187,9 +188,8 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & allocate(qgrid(mesh(1), mesh(2), mesh(3), nid)) allocate(tgrid(mesh(1), mesh(2), mesh(3))) - allocate(pot(nat, nid)) - erecip = 0.0_wp + erecip = -sum(esum) escale = -0.5_wp / vol ! the terms of the expansion decouple, so only one set of meshes is live and @@ -197,7 +197,13 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & do il = 1, rank if (.not.owns_index(partition, il)) cycle - qgrid(:, :, :, :) = cmplx(0.0_wp, 0.0_wp, wp) + !$omp parallel do schedule(static) default(none) collapse(2) & + !$omp shared(mesh, nid, qgrid) private(izp, i3) + do izp = 1, nid + do i3 = 1, mesh(3) + qgrid(:, :, i3, izp) = cmplx(0.0_wp, 0.0_wp, wp) + end do + end do do iat = 1, nat if (ghost(iat)) cycle izp = mol%id(iat) @@ -222,19 +228,20 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & ! contract the structure factors with the kernel to obtain the potential ! each species experiences, and accumulate energy and virial on the way do izp = 1, nid - tgrid(:, :, :) = cmplx(0.0_wp, 0.0_wp, wp) !$omp parallel do schedule(runtime) default(none) collapse(2) & !$omp shared(mesh, nid, izp, phik, bfac, qgrid, tgrid) & - !$omp private(i1, i2, i3, jzp, sfac) + !$omp private(i1, i2, i3, jzp, sfac, potential) do i3 = 1, mesh(3) do i2 = 1, mesh(2) do i1 = 1, mesh(1) sfac = bfac(i1, 1) * bfac(i2, 2) * bfac(i3, 3) + potential = cmplx(0.0_wp, 0.0_wp, wp) do jzp = 1, nid - tgrid(i1, i2, i3) = tgrid(i1, i2, i3) + sfac & + potential = potential + sfac & & * phik(pair_index(izp, jzp), i1, i2, i3) & & * qgrid(i1, i2, i3, jzp) end do + tgrid(i1, i2, i3) = potential end do end do end do @@ -242,9 +249,6 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & call fft_3d(fmesh, tgrid, -1) ! gather the potential back onto the atoms of this species - do iat = 1, nat - pot(iat, izp) = 0.0_wp - end do do iat = 1, nat if (ghost(iat) .or. mol%id(iat) /= izp) cycle wgt = 0.0_wp @@ -264,19 +268,17 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & dtvec(1) = dtheta(j1, 1, iat) * tvec(2) * tvec(3) dtvec(2) = tvec(1) * dtheta(j2, 2, iat) * tvec(3) dtvec(3) = tvec(1) * tvec(2) * dtheta(j3, 3, iat) - dwgt(:) = dwgt(:) + matmul(dudr, dtvec) * sfac + dwgt(:) = dwgt(:) + dtvec * sfac end if end do end do end do - pot(iat, izp) = wgt esum(iat) = esum(iat) + escale * lowrank%lambda(il) * c6l(il, iat) * wgt - erecip = erecip + escale * lowrank%lambda(il) * c6l(il, iat) * wgt if (grad) then dsum(iat) = dsum(iat) & & + 2.0_wp * escale * lowrank%lambda(il) * dc6ldcn(il, iat) * wgt gsum(:, iat) = gsum(:, iat) & - & + 2.0_wp * escale * lowrank%lambda(il) * c6l(il, iat) * dwgt(:) + & + 2.0_wp * escale * lowrank%lambda(il) * c6l(il, iat) * matmul(dudr, dwgt) end if end do end do @@ -317,6 +319,7 @@ subroutine get_dispersion_spme(mol, lowrank, ghost, terms, nterm, mesh, gwvec, & energies(:) = energies(:) + esum(:) if (grad) then + erecip = erecip + sum(esum) do ic = 1, 3 ssum(ic, ic) = ssum(ic, ic) - erecip end do @@ -370,8 +373,12 @@ subroutine get_mesh_kernel(mesh, rec, terms, nterm, nid, grad, phik, dphik) real(wp), allocatable, intent(out) :: dphik(:, :, :, :) integer :: i1, i2, i3, j1, j2, j3, izp, jzp, it, npair + integer :: m1, m2, m3 + logical :: mirror real(wp) :: kvec(3), knorm, phi, dphi, pval, dpval + type(fourier_kernel), allocatable :: kernel(:, :, :) + kernel = new_fourier_kernel(terms) npair = nid * (nid + 1) / 2 allocate(phik(npair, mesh(1), mesh(2), mesh(3))) if (grad) then @@ -381,8 +388,8 @@ subroutine get_mesh_kernel(mesh, rec, terms, nterm, nid, grad, phik, dphik) end if !$omp parallel do schedule(runtime) default(none) collapse(2) & - !$omp shared(mesh, rec, terms, nterm, nid, grad, phik, dphik) & - !$omp private(i1, i2, i3, j1, j2, j3, izp, jzp, it, kvec, knorm, phi, dphi, & + !$omp shared(mesh, rec, kernel, nterm, nid, grad, phik, dphik) & + !$omp private(i1, i2, i3, j1, j2, j3, m1, m2, m3, mirror, izp, jzp, it, kvec, knorm, phi, dphi, & !$omp& pval, dpval) do i3 = 1, mesh(3) do i2 = 1, mesh(2) @@ -391,6 +398,18 @@ subroutine get_mesh_kernel(mesh, rec, terms, nterm, nid, grad, phik, dphik) j1 = i1 - 1 - mesh(1) * ((2*(i1 - 1)) / mesh(1)) j2 = i2 - 1 - mesh(2) * ((2*(i2 - 1)) / mesh(2)) j3 = i3 - 1 - mesh(3) * ((2*(i3 - 1)) / mesh(3)) + ! Opposite wave vectors have the same radial kernel. On a Nyquist + ! plane the opposite index is aliased, so a skew cell need not have + ! the same norm there; evaluate those points independently. + mirror = all(2*abs([j1, j2, j3]) /= mesh) + if (mirror) then + m1 = modulo(1 - i1, mesh(1)) + 1 + m2 = modulo(1 - i2, mesh(2)) + 1 + m3 = modulo(1 - i3, mesh(3)) + 1 + if (i3 > m3) cycle + if (i3 == m3 .and. i2 > m2) cycle + if (i3 == m3 .and. i2 == m2 .and. i1 > m1) cycle + end if kvec(:) = rec(:, 1)*j1 + rec(:, 2)*j2 + rec(:, 3)*j3 knorm = norm2(kvec) do izp = 1, nid @@ -398,7 +417,7 @@ subroutine get_mesh_kernel(mesh, rec, terms, nterm, nid, grad, phik, dphik) phi = 0.0_wp dphi = 0.0_wp do it = 1, nterm(jzp, izp) - call get_fourier_transform(terms(it, jzp, izp), knorm, pval, dpval) + call get_fourier_transform(kernel(it, jzp, izp), knorm, pval, dpval, grad) phi = phi + pval dphi = dphi + dpval end do @@ -406,6 +425,10 @@ subroutine get_mesh_kernel(mesh, rec, terms, nterm, nid, grad, phik, dphik) if (grad) dphik(pair_index(izp, jzp), i1, i2, i3) = dphi end do end do + if (mirror) then + phik(:, m1, m2, m3) = phik(:, i1, i2, i3) + if (grad) dphik(:, m1, m2, m3) = dphik(:, i1, i2, i3) + end if end do end do end do diff --git a/subprojects/mctc-lib.wrap b/subprojects/mctc-lib.wrap index d1cd475a..14a257af 100644 --- a/subprojects/mctc-lib.wrap +++ b/subprojects/mctc-lib.wrap @@ -1,4 +1,4 @@ [wrap-git] directory = mctc-lib url = https://github.com/grimme-lab/mctc-lib -revision = 06db4d8 +revision = v0.7.0 diff --git a/subprojects/mstore.wrap b/subprojects/mstore.wrap index 0dfe716c..fec3916b 100644 --- a/subprojects/mstore.wrap +++ b/subprojects/mstore.wrap @@ -1,4 +1,4 @@ [wrap-git] directory = mstore url = https://github.com/grimme-lab/mstore -revision = v0.3.0 +revision = v0.4.0 diff --git a/test/unit/test_fourier.f90 b/test/unit/test_fourier.f90 index 28467d90..a91019a4 100644 --- a/test/unit/test_fourier.f90 +++ b/test/unit/test_fourier.f90 @@ -21,13 +21,15 @@ module test_fourier & new_zero_damping, mzero_damping_param, new_mzero_damping, d3_model, & & new_d3_model, d3_lowrank_config, get_pairwise_dispersion use dftd3_citation, only : citation_type, is_citation_present, doi_fourier_d3 + use dftd3_fourier_fft, only : fft_mesh, new_fft_mesh, fft_3d, valid_mesh_size use dftd3_fourier_jacobi, only : symmetric_eigendecomposition - use dftd3_fourier_kernel, only : fourier_term, get_fourier_transform, & - & get_potential_zero + use dftd3_fourier_kernel, only : fourier_term, fourier_kernel, new_fourier_kernel, & + & get_fourier_transform, get_potential_zero use mctc_env, only : wp use mctc_env_testing, only : new_unittest, unittest_type, error_type, check, & & test_failed use mctc_io, only : structure_type, new + use mctc_io_constants, only : pi use mstore, only : get_structure implicit none private @@ -98,10 +100,13 @@ subroutine collect_fourier(testsuite) & new_unittest("gradient-slab", test_gradient_acetic), & & new_unittest("hessian-mb01", test_hessian_mb01), & & new_unittest("fourier-transform", test_fourier_transform), & + & new_unittest("fft-mesh-size", test_fft_mesh_size), & + & new_unittest("fft-transform", test_fft_transform), & & new_unittest("ewald-molecular", test_ewald_molecular), & & new_unittest("ewald-unsupported-damping", test_ewald_unsupported), & & new_unittest("spme-energy", test_spme_energy), & & new_unittest("spme-gradient", test_spme_gradient), & + & new_unittest("spme-zero-mixed-mesh", test_spme_zero_mixed_mesh), & & new_unittest("ewald-hessian-rejected", test_ewald_hessian), & & new_unittest("ewald-pairwise-rejected", test_ewald_pairwise), & & new_unittest("ewald-converged-bj", test_ewald_converged_bj), & @@ -167,6 +172,65 @@ subroutine get_cubic(mol, alat, rep, periodic) end subroutine get_cubic +!> Select the smallest supported length, including the large zero-damping mesh +subroutine test_fft_mesh_size(error) + type(error_type), allocatable, intent(out) :: error + integer :: ii + integer, parameter :: requested(*) = [1, 2, 3, 4, 5, 7, 9, 10, 13, 17, 19, 25, 28, 33, 37, 49, 114, 271] + integer, parameter :: expected(*) = [1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 27, 32, 36, 48, 54, 128, 288] + + do ii = 1, size(requested) + call check(error, valid_mesh_size(requested(ii)), expected(ii)) + if (allocated(error)) return + end do +end subroutine test_fft_mesh_size + + +!> Check both signs against a direct DFT, then check the unnormalised round trip +subroutine test_fft_transform(error) + type(error_type), allocatable, intent(out) :: error + type(fft_mesh) :: fmesh + complex(wp), allocatable :: grid(:, :, :), input(:, :, :) + complex(wp) :: reference + real(wp) :: phase + integer :: icase, isign, ii, i1, i2, i3, j1, j2, j3, mesh(3) + integer, parameter :: shapes(3, 4) = reshape([4, 6, 9, 1, 8, 3, 8, 8, 8, 288, 1, 1], [3, 4]) + + do icase = 1, size(shapes, 2) + mesh = shapes(:, icase) + call new_fft_mesh(fmesh, mesh) + allocate(input(mesh(1), mesh(2), mesh(3))) + input = reshape([(cmplx(sin(0.37_wp*ii), cos(0.13_wp*ii), wp), ii=1, product(mesh))], mesh) + do isign = -1, 1, 2 + grid = input + call fft_3d(fmesh, grid, isign) + do i3 = 1, mesh(3) + do i2 = 1, mesh(2) + do i1 = 1, mesh(1) + reference = cmplx(0.0_wp, 0.0_wp, wp) + do j3 = 1, mesh(3) + do j2 = 1, mesh(2) + do j1 = 1, mesh(1) + phase = 2*pi*isign*sum(real([i1, i2, i3] - 1, wp) & + & * real([j1, j2, j3] - 1, wp) / real(mesh, wp)) + reference = reference + input(j1, j2, j3) * cmplx(cos(phase), sin(phase), wp) + end do + end do + end do + call check(error, abs(grid(i1, i2, i3) - reference), 0.0_wp, thr=1.0e-10_wp) + if (allocated(error)) return + end do + end do + end do + end do + call fft_3d(fmesh, grid, -1) + call check(error, maxval(abs(grid/product(mesh) - input)), 0.0_wp, thr=1.0e-12_wp) + if (allocated(error)) return + deallocate(input) + end do +end subroutine test_fft_transform + + !> Cyclic Jacobi rotations reproduce the input matrix and orthogonal eigenvectors subroutine test_jacobi(error) @@ -692,16 +756,21 @@ subroutine test_fourier_transform(error) !> Error handling type(error_type), allocatable, intent(out) :: error - integer :: ik + integer :: ik, it real(wp) :: kval, bval, phi, dphi, ref, kb type(fourier_term) :: term + type(fourier_kernel) :: kernel + type(fourier_term), parameter :: terms(*) = [ & + & fourier_term(1.0_wp, 0, 6, 4.5_wp), fourier_term(1.0_wp, 0, 8, 4.5_wp), & + & fourier_term(1.0_wp, 8, 14, 4.5_wp), fourier_term(1.0_wp, 8, 16, 4.5_wp)] real(wp), parameter :: pi = 3.1415926535897932384626433832795029_wp + bval = 4.5_wp + term = fourier_term(1.0_wp, 0, 6, bval) + kernel = new_fourier_kernel(term) do ik = 0, 20 kval = 0.05_wp * ik - bval = 4.5_wp - term = fourier_term(1.0_wp, 0, 6, bval) - call get_fourier_transform(term, kval, phi, dphi) + call get_fourier_transform(kernel, kval, phi, dphi, grad=.false.) kb = kval * bval if (kval > 0.0_wp) then @@ -715,13 +784,15 @@ subroutine test_fourier_transform(error) if (allocated(error)) return end do - ! numerical derivative of the transform - term = fourier_term(1.0_wp, 0, 6, 4.5_wp) - call get_fourier_transform(term, 1.0_wp, phi, dphi) - call get_fourier_transform(term, 1.0_wp + 1.0e-6_wp, ref, kb) - call get_fourier_transform(term, 1.0_wp - 1.0e-6_wp, kval, kb) - call check(error, dphi, 0.5_wp*(ref - kval)/1.0e-6_wp, thr=1.0e-6_wp) - if (allocated(error)) return + ! numerical derivatives of the prepared BJ and zero-damping kernels + do it = 1, size(terms) + kernel = new_fourier_kernel(terms(it)) + call get_fourier_transform(kernel, 1.0_wp, phi, dphi, grad=.true.) + call get_fourier_transform(kernel, 1.0_wp + 1.0e-6_wp, ref, kb, grad=.false.) + call get_fourier_transform(kernel, 1.0_wp - 1.0e-6_wp, kval, kb, grad=.false.) + call check(error, dphi, 0.5_wp*(ref - kval)/1.0e-6_wp, thr=1.0e-6_wp) + if (allocated(error)) return + end do ! bounded potential at the origin call check(error, get_potential_zero(term), 1.0_wp/4.5_wp**6, thr=thr) @@ -864,6 +935,37 @@ subroutine test_spme_gradient(error) end subroutine test_spme_gradient +!> Zero damping on a skew cell exercises different mixed-radix lengths per axis +subroutine test_spme_zero_mixed_mesh(error) + type(error_type), allocatable, intent(out) :: error + type(structure_type) :: mol + type(d3_model) :: d3lr, d3pm + type(zero_damping_param) :: param + real(wp) :: sigma(3, 3), sigma_ref(3, 3), lattice(3, 3) + real(wp), allocatable :: energies(:), energies_ref(:) + real(wp), allocatable :: gradient(:, :), gradient_ref(:, :) + + call get_cubic(mol, 8.0_wp, 1) + lattice = reshape([8.0_wp, 0.0_wp, 0.0_wp, 1.2_wp, 9.0_wp, 0.0_wp, 0.6_wp, -0.8_wp, 7.0_wp], [3, 3]) + mol%xyz = matmul(lattice, mol%xyz / 8.0_wp) + mol%lattice = lattice + call new_d3_model(d3lr, mol, lowrank=d3_lowrank_config(rank=10000, kcut=20.0_wp, mesh=-1)) + call new_d3_model(d3pm, mol, lowrank=d3_lowrank_config(rank=10000, kcut=20.0_wp)) + call new_zero_damping(param, pbe_zero) + + allocate(energies(mol%nat), energies_ref(mol%nat)) + allocate(gradient(3, mol%nat), gradient_ref(3, mol%nat)) + call get_dispersion(mol, d3lr, param, cutoff, energies_ref, gradient_ref, sigma_ref) + call get_dispersion(mol, d3pm, param, cutoff, energies, gradient, sigma) + + call check(error, sum(energies), sum(energies_ref), thr=1.0e-8_wp) + if (allocated(error)) return + call check(error, maxval(abs(gradient - gradient_ref)), 0.0_wp, thr=1.0e-8_wp) + if (allocated(error)) return + call check(error, maxval(abs(sigma - sigma_ref)), 0.0_wp, thr=1.0e-7_wp) +end subroutine test_spme_zero_mixed_mesh + + !> The second derivatives are only available from the real space summation subroutine test_ewald_hessian(error) @@ -1180,7 +1282,7 @@ subroutine test_ewald_gradient(error) end subroutine test_ewald_gradient -!> Analytical virial of the reciprocal summation +!> Analytical virial of both reciprocal summations on a skew cell subroutine test_ewald_sigma(error) !> Error handling @@ -1189,52 +1291,61 @@ subroutine test_ewald_sigma(error) type(structure_type) :: mol type(d3_model) :: d3lr type(rational_damping_param) :: param - integer :: ic, jc + integer :: ic, jc, iconfig real(wp) :: sigma(3, 3), numsigma(3, 3), er, el real(wp) :: eps(3, 3), lattice(3, 3) real(wp), allocatable :: energies(:), gradient(:, :), xyz(:, :) real(wp), parameter :: step = 1.0e-5_wp + type(d3_lowrank_config), parameter :: configs(*) = [tight, d3_lowrank_config(rank=10000, mesh=6)] real(wp), parameter :: unity(3, 3) = reshape(& & [1.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 1.0_wp, 0.0_wp, 0.0_wp, 0.0_wp, 1.0_wp], & & [3, 3]) call get_cubic(mol, 8.0_wp, 1) - call new_d3_model(d3lr, mol, lowrank=tight) call new_rational_damping(param, pbe_bj) allocate(energies(mol%nat), gradient(3, mol%nat)) - xyz = mol%xyz lattice(:, :) = mol%lattice - - do ic = 1, 3 - do jc = 1, 3 - eps(:, :) = unity - eps(jc, ic) = eps(jc, ic) + step - mol%xyz(:, :) = matmul(eps, xyz) - mol%lattice(:, :) = matmul(eps, lattice) - call get_dispersion(mol, d3lr, param, cutoff, energies) - er = sum(energies) - - eps(:, :) = unity - eps(jc, ic) = eps(jc, ic) - step - mol%xyz(:, :) = matmul(eps, xyz) - mol%lattice(:, :) = matmul(eps, lattice) - call get_dispersion(mol, d3lr, param, cutoff, energies) - el = sum(energies) - - numsigma(ic, jc) = 0.5_wp*(er - el)/step + ! Keep periodic images away from the CN cutoff during finite differences. + lattice(1, 2) = 2.1_wp + xyz = matmul(lattice, mol%xyz / 8.0_wp) + mol%xyz = xyz + mol%lattice = lattice + + ! A coarse even mesh makes the Nyquist planes significant, including their + ! lack of inversion symmetry after aliasing in a skew reciprocal lattice. + do iconfig = 1, size(configs) + call new_d3_model(d3lr, mol, lowrank=configs(iconfig)) + do ic = 1, 3 + do jc = 1, 3 + eps(:, :) = unity + eps(jc, ic) = eps(jc, ic) + step + mol%xyz(:, :) = matmul(eps, xyz) + mol%lattice(:, :) = matmul(eps, lattice) + call get_dispersion(mol, d3lr, param, cutoff, energies) + er = sum(energies) + + eps(:, :) = unity + eps(jc, ic) = eps(jc, ic) - step + mol%xyz(:, :) = matmul(eps, xyz) + mol%lattice(:, :) = matmul(eps, lattice) + call get_dispersion(mol, d3lr, param, cutoff, energies) + el = sum(energies) + + numsigma(ic, jc) = 0.5_wp*(er - el)/step + end do end do - end do - mol%xyz(:, :) = xyz - mol%lattice(:, :) = lattice - call get_dispersion(mol, d3lr, param, cutoff, energies, gradient, sigma) + mol%xyz(:, :) = xyz + mol%lattice(:, :) = lattice + call get_dispersion(mol, d3lr, param, cutoff, energies, gradient, sigma) - if (any(abs(sigma - numsigma) > 1.0e-7_wp)) then - call test_failed(error, "Virial does not match numerical differentiation") - print "(3es21.13)", sigma - numsigma - return - end if + if (any(abs(sigma - numsigma) > 1.0e-7_wp)) then + call test_failed(error, "Virial does not match numerical differentiation") + print "(3es21.13)", sigma - numsigma + return + end if + end do end subroutine test_ewald_sigma