diff --git a/docs/CITATIONS.md b/docs/CITATIONS.md index 43176829a1d..afd01d34578 100644 --- a/docs/CITATIONS.md +++ b/docs/CITATIONS.md @@ -55,3 +55,11 @@ The following references are required to be cited when using ABACUS. Specificall Eike Caldeweyher, Jan-Michael Mewes, Sebastian Ehlert, and Stefan Grimme. "Extension and evaluation of the D4 London-dispersion model for periodic systems." Physical Chemistry Chemical Physics 22, 8499-8512 (2020). DOI: 10.1039/D0CP00502A. Nikolay V. Tkachenko, Linus B. Dittmer, Rebecca Tomann, and Martin Head-Gordon. "Smooth D4S model." The Journal of Physical Chemistry Letters 15, 10629-10637 (2024). DOI: 10.1021/acs.jpclett.4c02653. + +- **If the rVV10 nonlocal correlation (`vdw_method rvv10`) is used:** + + O. A. Vydrov and T. Van Voorhis. "Nonlocal van der Waals density functional: The simpler the better." The Journal of Chemical Physics 133, 244103 (2010). DOI: 10.1063/1.3521275. + + R. Sabatini, T. Gorni, and S. de Gironcoli. "Nonlocal van der Waals density functional made simple and efficient." Physical Review B 87, 041108(R) (2013). DOI: 10.1103/PhysRevB.87.041108. + + G. Román-Pérez and J. M. Soler. "Efficient implementation of a van der Waals density functional: Application to double-wall carbon nanotubes." Physical Review Letters 103, 096102 (2009). DOI: 10.1103/PhysRevLett.103.096102. diff --git a/docs/advanced/scf/advanced.md b/docs/advanced/scf/advanced.md index a01280344bb..22fc9500974 100644 --- a/docs/advanced/scf/advanced.md +++ b/docs/advanced/scf/advanced.md @@ -96,6 +96,7 @@ To use VdW-correction, users need to supply value to the `vdw_method` keyword in - d2: DFT-D2 method - d3_0: DFT-D3(0) method - d3_bj: DFT-D3(BJ) method + - rvv10: rVV10 nonlocal correlation. Unlike the DFT-D methods, it depends on the electron density and is added self-consistently to the exchange-correlation energy and potential; its parameter `rvv10_b` defaults to 6.3 (rPW86-PBE); use the value published for the chosen functional (15.7 for SCAN, 11.95 for r2SCAN). Furthermore, ABACUS also provides a [list of keywords](../input_files/input-main.md#vdw-correction) to control relevant parmeters used in calculating the VdW correction, such as the scale factor (s6) term. Recommended values of such parameters can be found on the [webpage](https://www.chemie.uni-bonn.de/pctc/mulliken-center/software/dft-d3). The default values of the parameters in ABACUS are set to be the recommended values for PBE. diff --git a/source/CMakeLists.txt b/source/CMakeLists.txt index 07aa5999d69..4ba4ab3d68b 100644 --- a/source/CMakeLists.txt +++ b/source/CMakeLists.txt @@ -31,6 +31,10 @@ include(CompilerConfiguration) set(_abacus_feature_definitions __FFTW3 + # The nonlocal vdW correction is always built. Focused unit tests that compile an XC evaluator + # without the plane-wave basis switch it off with abacus_disable_feature_definitions(__RVV10), + # which leaves the empty inline hooks of module_vdw/nonlocal_xc.h in their place. + __RVV10 $<$:__JSON> $<$:__CUDA_ON_DCU> $<$:__CUDA_MPI> diff --git a/source/source_esolver/esolver_fp.cpp b/source/source_esolver/esolver_fp.cpp index ae39b2444ed..c6e29d8f59c 100644 --- a/source/source_esolver/esolver_fp.cpp +++ b/source/source_esolver/esolver_fp.cpp @@ -58,6 +58,9 @@ void ESolver_FP::before_all_runners(BaseCell &basecell, const Input_para &inp) xc_parameters.exx_erfc_alpha = inp.exx_erfc_alpha; xc_parameters.xc_exch_ext = inp.xc_exch_ext; xc_parameters.xc_corr_ext = inp.xc_corr_ext; + xc_parameters.rvv10 = inp.vdw_method == "rvv10"; + xc_parameters.rvv10_b = inp.rvv10_b; + xc_parameters.rvv10_c = inp.rvv10_c; XC_Functional::set_runtime_parameters(xc_parameters); ModuleBase::TITLE("ESolver_FP", "before_all_runners"); diff --git a/source/source_hamilt/module_surchem/test/CMakeLists.txt b/source/source_hamilt/module_surchem/test/CMakeLists.txt index e6953e28ca6..51ba3b2bd27 100644 --- a/source/source_hamilt/module_surchem/test/CMakeLists.txt +++ b/source/source_hamilt/module_surchem/test/CMakeLists.txt @@ -1,3 +1,6 @@ +# These targets compile an XC evaluator without the plane-wave basis, so they take the empty rVV10 hooks. +abacus_disable_feature_definitions(__RVV10) + abacus_disable_feature_definitions(__LCAO) abacus_disable_feature_definitions(__LIBXC) abacus_copy_test_files(support) diff --git a/source/source_hamilt/module_vdw/CMakeLists.txt b/source/source_hamilt/module_vdw/CMakeLists.txt index 59f94dbb5c8..17e53c3de08 100644 --- a/source/source_hamilt/module_vdw/CMakeLists.txt +++ b/source/source_hamilt/module_vdw/CMakeLists.txt @@ -12,6 +12,8 @@ if(ENABLE_DFTD4) list(APPEND vdw_sources vdwd4.cpp) endif() +# nonlocal_xc.cpp and rvv10_kernel.cpp are not listed above: they call XC_Functional and the plane-wave +# basis, so module_xc/CMakeLists.txt compiles them into the xc_ target instead of this object library. add_library(vdw OBJECT ${vdw_sources}) if(ENABLE_DFTD4) diff --git a/source/source_hamilt/module_vdw/nonlocal_xc.cpp b/source/source_hamilt/module_vdw/nonlocal_xc.cpp new file mode 100644 index 00000000000..1ca752c3a28 --- /dev/null +++ b/source/source_hamilt/module_vdw/nonlocal_xc.cpp @@ -0,0 +1,178 @@ +#include "nonlocal_xc.h" + +#ifdef __RVV10 + +#include "rvv10_kernel.h" +#include "source_base/constants.h" +#include "source_base/matrix.h" +#include "source_base/matrix3.h" +#include "source_base/parallel_device.h" +#include "source_base/timer.h" +#include "source_base/tool_quit.h" +#include "source_base/tool_title.h" +#include "source_base/vector3.h" +#include "source_basis/module_pw/pw_basis.h" +#include "source_estate/module_charge/charge.h" +#include "source_hamilt/module_xc/xc_functional.h" + +#include +#include +#include + +namespace vdw +{ +namespace +{ + +/// Cartesian components of the explicit strain derivative, stored as [3 * a + b]. +const int stress_components = 9; + +/// Spin channels of chr.rho that add up to the valence density (for nspin = 4, rho[0] is the total density). +int density_channels(const Charge &chr) { return (chr.nspin == 2) ? 2 : 1; } + +/// rVV10 energy (Ha) of the total density of chr (valence plus core), with the plane-wave gradient of that +/// density, dE/dn (unless dedn is nullptr), dE/dsigma for sigma = |grad n|^2 and, with stress != nullptr, +/// the explicit strain derivative. +double evaluate_total_density( + const XCFunctionalParameters ¶meters, + const Charge &chr, + std::vector> &grad, + std::vector *dedn, + std::vector &dedsigma, + double *stress) +{ + const ModulePW::PW_Basis &pw = *chr.rhopw; + const int nrxx = chr.nrxx; + const int nspin0 = density_channels(chr); + const double *core_begin = chr.rho_core; + const double *core_end = core_begin + nrxx; + std::vector rho(core_begin, core_end); + for (int is = 0; is < nspin0; ++is) + { +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int ir = 0; ir < nrxx; ++ir) + { + rho[ir] += chr.rho[is][ir]; + } + } + std::vector> rhog(pw.npw); + pw.real2recip(rho.data(), rhog.data()); + grad.resize(nrxx); + XC_Functional::grad_rho(rhog.data(), grad.data(), &pw, pw.tpiba); + std::vector sigma(nrxx); +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int ir = 0; ir < nrxx; ++ir) + { + sigma[ir] = grad[ir].norm2(); + } + if (dedn != nullptr) + { + dedn->resize(nrxx); + } + dedsigma.resize(nrxx); + return rvv10_energy(pw, parameters.rvv10_b, parameters.rvv10_c, rho, sigma, dedn, dedsigma, stress); +} +} // namespace + +void add_rvv10( + const XCFunctionalParameters ¶meters, + const Charge &chr, + double &etxc, + double &vtxc, + ModuleBase::matrix &v) +{ + if (!parameters.rvv10) + { + return; + } + ModuleBase::TITLE("vdw", "add_rvv10"); + ModuleBase::timer::start("vdw", "add_rvv10"); + const ModulePW::PW_Basis &pw = *chr.rhopw; + const int nrxx = chr.nrxx; + std::vector> grad; + std::vector dedn; + std::vector dedsigma; + const double energy = evaluate_total_density(parameters, chr, grad, &dedn, dedsigma, nullptr); + // v = dE/dn - div(2 dE/dsigma grad n), Hartree to Ry by e2 +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int ir = 0; ir < nrxx; ++ir) + { + grad[ir] *= 2.0 * dedsigma[ir]; + } + std::vector divergence(nrxx); + XC_Functional::grad_dot(grad.data(), divergence.data(), &pw, pw.tpiba); + // for nspin = 4 the potential of the total density goes to v(0) only + const int nspin0 = density_channels(chr); + // this reduction and the one of the stress stay serial, so the result does not depend on the thread count + double vtxc_nl = 0.0; + for (int ir = 0; ir < nrxx; ++ir) + { + const double v_nl = ModuleBase::e2 * (dedn[ir] - divergence[ir]); + for (int is = 0; is < nspin0; ++is) + { + v(is, ir) += v_nl; + vtxc_nl += v_nl * chr.rho[is][ir]; + } + } +#ifdef __MPI + Parallel_Common::reduce_data(&vtxc_nl, 1, pw.pool_world); +#endif + etxc += ModuleBase::e2 * energy; + vtxc += vtxc_nl * pw.omega / pw.nxyz; + ModuleBase::timer::end("vdw", "add_rvv10"); +} + +void add_rvv10_stress(const XCFunctionalParameters ¶meters, const Charge &chr, ModuleBase::matrix &sigma) +{ + if (!parameters.rvv10) + { + return; + } + ModuleBase::TITLE("vdw", "add_rvv10_stress"); + ModuleBase::timer::start("vdw", "add_rvv10_stress"); + const ModulePW::PW_Basis &pw = *chr.rhopw; + const int nrxx = chr.nrxx; + std::vector> grad; + std::vector dedsigma; + double explicit_stress[stress_components] = {0.0}; + // the stress needs dE/dsigma only + const double energy = evaluate_total_density(parameters, chr, grad, nullptr, dedsigma, explicit_stress); + // integral of dE/dsigma d_a n d_b n, in units of the volume element + double gradient_term[stress_components] = {0.0}; + for (int ir = 0; ir < nrxx; ++ir) + { + const double g[3] = {grad[ir].x, grad[ir].y, grad[ir].z}; + for (int a = 0; a < 3; ++a) + { + for (int b = 0; b < 3; ++b) + { + gradient_term[3 * a + b] += dedsigma[ir] * g[a] * g[b]; + } + } + } +#ifdef __MPI + Parallel_Common::reduce_data(gradient_term, stress_components, pw.pool_world); +#endif + // The full strain derivative is T - delta_ab Int(n dE/dn + 2 sigma dE/dsigma) - 2 Int dE/dsigma d_a n d_b n, + // T the explicit part of the kernel. The XC diagonal -(etxc - vtxc)/omega in PW (in LCAO -etxc/omega plus the + // Pulay term of the potential) already holds -e2 (E - Int(n dE/dn + 2 sigma dE/dsigma)) / omega; the rest is below. + for (int a = 0; a < 3; ++a) + { + for (int b = 0; b < 3; ++b) + { + const double diagonal = (a == b) ? energy : 0.0; + sigma(a, b) += -ModuleBase::e2 / pw.omega * (explicit_stress[3 * a + b] - diagonal) + + 2.0 * ModuleBase::e2 * gradient_term[3 * a + b] / pw.nxyz; + } + } + ModuleBase::timer::end("vdw", "add_rvv10_stress"); +} + +} // namespace vdw +#endif // __RVV10 diff --git a/source/source_hamilt/module_vdw/nonlocal_xc.h b/source/source_hamilt/module_vdw/nonlocal_xc.h new file mode 100644 index 00000000000..0cae544ba59 --- /dev/null +++ b/source/source_hamilt/module_vdw/nonlocal_xc.h @@ -0,0 +1,57 @@ +#ifndef NONLOCAL_XC_H +#define NONLOCAL_XC_H + +class Charge; +struct XCFunctionalParameters; +namespace ModuleBase +{ +class matrix; +} // namespace ModuleBase + +namespace vdw +{ + +// rVV10 nonlocal correlation of vdw_method rvv10. Both functions do nothing unless parameters.rvv10 is set. +// They use the total density of chr (valence plus core) and are collective over the pool communicator of +// chr.rhopw. Without __RVV10 they are empty, so that an XC evaluator can be unit-tested without the +// plane-wave basis; the production build always defines it. + +#ifdef __RVV10 + +/** + * @brief Add the rVV10 energy and potential to the result of an XC evaluation. + * @param parameters rVV10 switch and the parameters b and C + * @param chr density; the valence density plus rho_core is used, distributed over chr.rhopw + * @param[in,out] etxc XC energy (Ry), already reduced over the pool + * @param[in,out] vtxc integral of v_xc n (Ry), already reduced over the pool + * @param[in,out] v XC potential (Ry) on the nrxx points of this process; for nspin = 4 only v(0) is changed + */ +void add_rvv10( + const XCFunctionalParameters ¶meters, + const Charge &chr, + double &etxc, + double &vtxc, + ModuleBase::matrix &v); + +/** + * @brief Add the rVV10 stress (Ry/Bohr^3) that the XC diagonal and potential terms do not contain. + * @param parameters rVV10 switch and the parameters b and C + * @param chr density, as in add_rvv10 + * @param[in,out] sigma 3 x 3 stress tensor + */ +void add_rvv10_stress(const XCFunctionalParameters ¶meters, const Charge &chr, ModuleBase::matrix &sigma); +#else +inline void add_rvv10( + const XCFunctionalParameters &, + const Charge &, + double &, + double &, + ModuleBase::matrix &) +{ +} +inline void add_rvv10_stress(const XCFunctionalParameters &, const Charge &, ModuleBase::matrix &) {} +#endif + +} // namespace vdw + +#endif // NONLOCAL_XC_H diff --git a/source/source_hamilt/module_vdw/rvv10_kernel.cpp b/source/source_hamilt/module_vdw/rvv10_kernel.cpp new file mode 100644 index 00000000000..bfa65d4ada4 --- /dev/null +++ b/source/source_hamilt/module_vdw/rvv10_kernel.cpp @@ -0,0 +1,742 @@ +#include "rvv10_kernel.h" + +#ifdef __RVV10 + +#include "source_base/constants.h" +#include "source_base/cubic_spline.h" +#include "source_base/math_integral.h" +#include "source_base/module_external/blas_connector.h" +#include "source_base/parallel_device.h" +#include "source_base/timer.h" +#include "source_base/tool_quit.h" +#include "source_basis/module_pw/pw_basis.h" +#include "source_basis/module_pw/pw_basis_big.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace vdw +{ +namespace +{ + +// Numerical choices (formulas 2.3, 3.3, 4.1). Only q_c has a published dimensioned value. +// Self-consistent densities put nearly all their weight at 0.007 < q < 0.15 (graphite and +// MoS2 with b = 6.3; q scales as 1/b, so b = 15.7 moves it down by 2.5). The interpolation +// error is set by the node spacing there, so the nodes are geometric with a fixed ratio on +// [qa, qb] and widen outwards, each step by a constant factor, up to qmin and q_c. +struct TableGrid +{ + double qmin = 1e-3; // bohr^-2 + double qa = 5e-3; // bohr^-2, start of the uniform core + double qb = 0.3; // bohr^-2, end of the uniform core + int ncore = 28; // core intervals: node ratio (qb/qa)^(1/28) = 1.157 + double growth = 1.5; + double qc = 3.0; // bohr^-2; Obata et al., J. Phys. Soc. Jpn. 84, 024715 (2015), Table I. + int nk = 321; // radial samples, more closely spaced near zero where the transform varies fastest +}; + +std::vector q_nodes(const TableGrid &grid) +{ + const double step = std::log(grid.qb / grid.qa) / grid.ncore; + // log q outwards from one end of the core, ending exactly at the bound + auto widen = [&](const double from, const double bound) + { + std::vector out; + const double sign = bound > from ? 1.0 : -1.0; + double x = from; + double s = step; + while (sign * (bound - x) > 1e-12) + { + s *= grid.growth; + x = (sign * (bound - x) < 1.5 * s) ? bound : x + sign * s; + out.push_back(x); + } + return out; + }; + std::vector log_q = widen(std::log(grid.qa), std::log(grid.qmin)); + std::reverse(log_q.begin(), log_q.end()); + for (int i = 0; i <= grid.ncore; ++i) + { + log_q.push_back(std::log(grid.qa) + i * step); + } + const std::vector upper = widen(std::log(grid.qb), std::log(grid.qc)); + log_q.insert(log_q.end(), upper.begin(), upper.end()); + std::vector nodes(log_q.size()); + std::transform(log_q.begin(), log_q.end(), nodes.begin(), [](double x) { return std::exp(x); }); + nodes.front() = std::min(grid.qmin, grid.qa); + nodes.back() = std::max(grid.qc, grid.qb); + return nodes; +} + +using KernelSpline = ModuleBase::CubicSpline; +using Complex = std::complex; +using Tensor = std::array; + +// Formulas 2.2, 3.2, 4.1: universal transform of -3/4 (1+u^2)^-3. +// Differentiating int_0^inf u sin(a u) / (u^2 + s) du = pi/2 exp(-a sqrt(s)) +// twice with respect to s gives the elementary closed form +// int_0^inf u^2 j0(z u) (1+u^2)^-3 du = pi (1+z) exp(-z) / 16, +// so the reduced transform needs no radial quadrature at all. Its z=0 value +// is the same integral with j0(0)=1, not zero; its slope there is zero. +double radial_shape(const double z) { return -3.0 * ModuleBase::PI * ModuleBase::PI * (1.0 + z) * std::exp(-z) / 16.0; } + +// Formulas 2.2, 3.2: writing A=1+aR^2, B=1+bR^2, M=(A+B)/2, +// 1/(ABM) = integral W(Q)/(1+Q R^2)^3 dQ. Two integrations of +// d^2/dQ^2 [1/(1+Q R^2)] give the unit-area triangular weight +// W(Q)=4 min(Q-a,b-Q)/(b-a)^2 on [a,b]. This lets every pair share +// one closed-form radial transform (radial_shape), even when a is close to b. +// Here a is q_low/q_high and b=1; integrate each half in log Q. +std::vector mixed_shape(double a, const std::vector &z) +{ + const int order = 32; + const double midpoint = 0.5 * (1.0 + a); + const double width = 1.0 - a; + const double ends[3] = {a, midpoint, 1.0}; + std::vector shape(z.size(), 0.0); + for (int half = 0; half < 2; ++half) + { + double x[order]; + double weights[order]; + const double lo = std::log(ends[half]); + const double hi = std::log(ends[half + 1]); + ModuleBase::Integral::Gauss_Legendre_grid_and_weight(lo, hi, order, x, weights); + for (int ix = 0; ix < order; ++ix) + { + const double q = std::exp(x[ix]); + const double inv_sqrt = 1.0 / std::sqrt(q); + const double dist = half == 0 ? q - a : 1.0 - q; + // dQ=Q d(log Q); Fourier scaling contributes Q^-3/2. + const double weight = 4.0 * dist * weights[ix] * inv_sqrt / (width * width); + for (size_t iz = 0; iz < z.size(); ++iz) + { + const double arg = z[iz] * inv_sqrt; + if (arg >= z.back()) + { + // exp(-40) and beyond; the consumer clamps the same way. + break; + } + shape[iz] += weight * radial_shape(arg); + } + } + } + return shape; +} + +// Position of one density point on the q lattice, found once per evaluation and +// shared by every channel (formulas 3.3-3.4). +struct Cell +{ + int left = 0; // interval [node(left), node(left + 1)] + double t = 0.0; // fractional position in it + bool inside = true; // false where q was clamped to an end of the lattice +}; + +class KernelTable +{ + public: + explicit KernelTable(const TableGrid &grid) + : nodes_(q_nodes(grid)), nq_(static_cast(nodes_.size())), length_(nq_), volume_(nq_), slopes_(nq_ * nq_), + z_(radial_grid(grid.nk)), transform_(grid.nk, z_.data()) + { + ModuleBase::timer::start("vdw", "kernel_table"); + for (int i = 0; i < nq_; ++i) + { + length_[i] = 1.0 / std::sqrt(nodes_[i]); + volume_[i] = length_[i] / nodes_[i]; + } + // Each cardinal function P_i is the not-a-knot spline through delta_ij. A cubic + // spline is the Hermite cubic of its knot values and knot slopes on every + // interval, so the slopes are all that has to be stored. + std::vector delta(nq_, 0.0); + std::vector slope(nq_); + for (int i = 0; i < nq_; ++i) + { + delta[i] = 1.0; + KernelSpline::build(nq_, nodes_.data(), delta.data(), {}, {}, slope.data()); + delta[i] = 0.0; + for (int k = 0; k < nq_; ++k) + { + slopes_[k * nq_ + i] = slope[k]; + } + } + // One curve per node pair, pair(lo, hi) = hi (hi + 1) / 2 + lo, all on the same z. + const KernelSpline::BoundaryCondition flat{KernelSpline::BoundaryType::first_deriv, 0.0}; + transform_.reserve(nq_ * (nq_ + 1) / 2); + std::vector shape(grid.nk); + for (int hi = 0; hi < nq_; ++hi) + { + for (int lo = 0; lo < hi; ++lo) + { + transform_.add(mixed_shape(nodes_[lo] / nodes_[hi], z_).data(), flat, flat); + } + std::transform(z_.begin(), z_.end(), shape.begin(), radial_shape); + transform_.add(shape.data(), flat, flat); + } + pairs_.resize(nq_ * (nq_ + 1) / 2); + std::iota(pairs_.begin(), pairs_.end(), 0); + ModuleBase::timer::end("vdw", "kernel_table"); + } + + int size() const { return nq_; } + double cutoff() const { return nodes_.back(); } + + // Formulas 3.3-3.4: outside the lattice the nearest end value is kept and + // the cardinal slopes vanish there (the weight derivative does not). + Cell locate(const double q) const + { + Cell cell; + const double x = std::max(nodes_.front(), std::min(nodes_.back(), q)); + cell.inside = (x == q); + const std::vector::const_iterator upper = std::upper_bound(nodes_.begin(), nodes_.end(), x); + cell.left = std::min(static_cast(upper - nodes_.begin()) - 1, nq_ - 2); + cell.left = std::max(cell.left, 0); + cell.t = (x - nodes_[cell.left]) / (nodes_[cell.left + 1] - nodes_[cell.left]); + return cell; + } + + // P_i(q) and, if requested, dP_i/dq at a located point. + double cardinal(const int i, const Cell &cell, double *dp = nullptr) const + { + const int k = cell.left; + const double t = cell.t; + const double s = 1.0 - t; + const double h = nodes_[k + 1] - nodes_[k]; + const double sk = slopes_[k * nq_ + i]; + const double sk1 = slopes_[(k + 1) * nq_ + i]; + const double yk = (i == k) ? 1.0 : 0.0; + const double yk1 = (i == k + 1) ? 1.0 : 0.0; + if (dp) + { + *dp = + cell.inside ? 6.0 * t * s * (yk1 - yk) / h + sk * s * (1.0 - 3.0 * t) + sk1 * t * (3.0 * t - 2.0) : 0.0; + } + return yk * s * s * (1.0 + 2.0 * t) + yk1 * t * t * (3.0 - 2.0 * t) + h * t * s * (sk * s - sk1 * t); + } + + // Kernel matrix phi_ij(k) and, if slope is given, d phi_ij / dk (formulas 3.1, 4.1). + void matrix(const double k, double *value, double *slope) const + { + std::vector v(nq_); + std::vector dv(nq_); + for (int hi = 0; hi < nq_; ++hi) + { + const double z = k * length_[hi]; + if (z >= zmax_) + { + std::fill(v.begin(), v.begin() + hi + 1, 0.0); + std::fill(dv.begin(), dv.begin() + hi + 1, 0.0); + } + else + { + transform_.multi_eval( + hi + 1, pairs_.data() + hi * (hi + 1) / 2, z, v.data(), slope ? dv.data() : nullptr); + } + for (int lo = 0; lo <= hi; ++lo) + { + value[hi * nq_ + lo] = value[lo * nq_ + hi] = v[lo] * volume_[hi]; + if (slope) + { + slope[hi * nq_ + lo] = slope[lo * nq_ + hi] = dv[lo] * volume_[hi] * length_[hi]; + } + } + } + } + + private: + // Radial samples in z = k/sqrt(q_high): denser near zero, where unlike pairs + // peak; beyond z = 40 the transform is below exp(-40) and taken as zero. + static constexpr double zmax_ = 40.0; + static constexpr double zscale_ = 0.125; + static std::vector radial_grid(const int nk) + { + std::vector z(nk); + for (int i = 0; i < nk; ++i) + { + z[i] = zscale_ * std::expm1(std::log1p(zmax_ / zscale_) * i / (nk - 1)); + } + z.back() = zmax_; + return z; + } + std::vector nodes_; + int nq_; + std::vector length_; // q^-1/2 + std::vector volume_; // q^-3/2 + std::vector slopes_; // [k * nq + i]: dP_i/dq at node k + std::vector z_; + KernelSpline transform_; + std::vector pairs_; +}; + +// The table depends on the lattice only, not on b or C; it is built once per process. +const KernelTable &kernel_table() +{ + static const KernelTable table{TableGrid()}; + return table; +} + +// Formulas 1.5: this shift cancels the uniform-gas pair energy. +double uniform_shift(const double b) +{ + const double t = 3.0 / (b * b); + return std::pow(t, 0.75) / 32.0; +} + +struct LocalPoint +{ + double q = 0.0; // Saturated q (bohr^-2) + double weight = 0.0; // n / kappa^(3/2) + double dw = 0.0; // Partial derivative of weight with respect to n + double wqn = 0.0; // weight * dh/dq * dq/dn + double wqs = 0.0; // weight * dh/dq * dq/dsigma + Cell cell; // position on the q lattice +}; + +// Formulas 1.3, 1.4, 2.2, 2.5 (A14, A15, A19), 3.4. +LocalPoint local_point( + const double n, + const double sigma, + const double b, + const double c, + const double cutoff) +{ + LocalPoint point; + if (n <= 0.0) + { + return point; // Numerical noise in vacuum; no positive-density cutoff. + } + const double kappa = 1.5 * ModuleBase::PI * b * std::pow(n, 1.0 / 6.0) / std::pow(9.0 * ModuleBase::PI, 1.0 / 6.0); + point.weight = n / (kappa * std::sqrt(kappa)); + point.dw = 0.75 * (point.weight / n); + const double plasma = std::sqrt(ModuleBase::FOUR_PI / 3.0) * std::sqrt(n); + const double gap = (c > 0.0 && sigma > 0.0) ? std::sqrt(c) * (sigma / n) / n : 0.0; + const double omega = std::hypot(plasma, gap); + const double q = omega / kappa; + const double x = q / cutoff; + if (x >= 2.0) + { + // The m=12 exponential and its derivative are below double precision here. + point.q = cutoff; + return point; + } + + double exponent = 0.0; + double derivative = 0.0; + for (int m = 12; m > 0; --m) + { + exponent = exponent * x + 1.0 / m; + derivative = derivative * x + 1.0; + } + exponent *= x; + const double dh = std::exp(-exponent) * derivative; + point.q = -cutoff * std::expm1(-exponent); + const double fraction = gap / omega; + const double gamma = fraction * fraction; + point.wqn = (point.weight / n) * (dh * q) * (1.0 / 3.0 - 2.5 * gamma); + if (sigma > 0.0 && gap > 0.0) + { + point.wqs = (point.weight * dh * q * gamma) / sigma; + } + return point; +} + +std::vector project_density( + const KernelTable &table, + const std::vector &rho, + const std::vector &sigma, + const double b, + const double c) +{ + ModuleBase::timer::start("vdw", "project_density"); + const int nr = static_cast(rho.size()); + std::vector points(nr); +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int r = 0; r < nr; ++r) + { + points[r] = local_point(rho[r], sigma[r], b, c, table.cutoff()); + points[r].cell = table.locate(points[r].q); + } + ModuleBase::timer::end("vdw", "project_density"); + return points; +} + +// Channel spectra, channel-major with the plane waves sorted into shells of equal +// |G|, so that each shell of each channel is one contiguous block. On a gamma-only +// basis a plane wave off the plane x = 0 (y = 0 without xprime) also stands for -G. +struct Channels +{ + Channels(const ModulePW::PW_Basis &pw, const int count) + : nq(count), npw(pw.npw), order(pw.npw), weight(pw.npw, 1.0), spectrum(static_cast(count) * pw.npw) + { + std::iota(order.begin(), order.end(), 0); + std::sort(order.begin(), order.end(), [&pw](int a, int b) { return pw.gg[a] < pw.gg[b]; }); + for (int p = 0; p < npw; ++p) + { + if (p == 0 || pw.gg[order[p]] != pw.gg[order[p - 1]]) + { + shells.push_back(p); + } + } + shells.push_back(npw); + if (pw.gamma_only) + { + for (int p = 0; p < npw; ++p) + { + const ModuleBase::Vector3 &g = pw.gdirect[order[p]]; + const double halved = pw.xprime ? g.x : g.y; + weight[p] = (std::abs(halved) < 0.5) ? 1.0 : 2.0; + } + } + } + Complex *channel(const int i) { return spectrum.data() + static_cast(i) * npw; } + const int nq; + const int npw; + std::vector order; // sorted position -> plane-wave index + std::vector shells; // first sorted position of each shell, then npw + std::vector weight; // multiplicity of each sorted plane wave in the full sphere + std::vector spectrum; +}; + +// Formulas 2.2, 3.1: the forward transform already divides by nxyz. +void forward_channels( + const ModulePW::PW_Basis &pw, + const KernelTable &table, + const std::vector &points, + Channels &channels) +{ + ModuleBase::timer::start("vdw", "forward_channels"); + std::vector real(std::max(1, pw.nrxx)); + std::vector reciprocal(std::max(1, pw.npw)); + for (int i = 0; i < channels.nq; ++i) + { +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int r = 0; r < pw.nrxx; ++r) + { + real[r] = points[r].weight * table.cardinal(i, points[r].cell); + } + pw.real2recip(real.data(), reciprocal.data()); + Complex *theta = channels.channel(i); + for (int p = 0; p < pw.npw; ++p) + { + theta[p] = reciprocal[channels.order[p]]; + } + } + ModuleBase::timer::end("vdw", "forward_channels"); +} + +struct ShellSum +{ + double quadratic = 0.0; + Tensor metric{}; +}; + +// Formulas 3.1, 2.6: on one shell every channel coefficient is multiplied by the same +// symmetric kernel matrix, a real product on the (Re, Im) rows of the block. The +// response replaces the coefficients in place. Sums are weighted by the multiplicity. +ShellSum apply_shell( + const ModulePW::PW_Basis &pw, + const KernelTable &table, + const int shell, + const bool stress, + Channels &channels) +{ + const int nq = channels.nq; + const int first = channels.shells[shell]; + const int rows = 2 * (channels.shells[shell + 1] - first); + const int ld = 2 * channels.npw; + const double k = std::sqrt(pw.gg[channels.order[first]] * pw.tpiba2); + const bool radial = stress && k > 0.0; + std::vector kernel(nq * nq); + std::vector slope(radial ? nq * nq : 0); + double *const slope_out = radial ? slope.data() : nullptr; + table.matrix(k, kernel.data(), slope_out); + double *block = reinterpret_cast(channels.spectrum.data()) + 2 * first; + std::vector product(static_cast(rows) * nq); + ShellSum result; + if (radial) + { + BlasConnector::gemm_cm('N', 'N', rows, nq, nq, 1.0, block, ld, slope.data(), nq, 0.0, product.data(), rows); + for (int row = 0; row < rows; ++row) + { + double overlap = 0.0; + for (int i = 0; i < nq; ++i) + { + overlap += + block[static_cast(i) * ld + row] * product[static_cast(i) * rows + row]; + } + const ModuleBase::Vector3 &gcar = pw.gcar[channels.order[first + row / 2]]; + const double gv[3] = {gcar.x, gcar.y, gcar.z}; + const double factor = -channels.weight[first + row / 2] * overlap * pw.tpiba2 / k; + for (int a = 0; a < 3; ++a) + { + for (int b = 0; b < 3; ++b) + { + result.metric[3 * a + b] += factor * gv[a] * gv[b]; + } + } + } + } + BlasConnector::gemm_cm('N', 'N', rows, nq, nq, 1.0, block, ld, kernel.data(), nq, 0.0, product.data(), rows); + for (int i = 0; i < nq; ++i) + { + double *column = block + static_cast(i) * ld; + const double *response = product.data() + static_cast(i) * rows; + for (int row = 0; row < rows; ++row) + { + result.quadratic += channels.weight[first + row / 2] * column[row] * response[row]; + column[row] = response[row]; + } + } + return result; +} + +ShellSum convolve_channels( + const ModulePW::PW_Basis &pw, + const KernelTable &table, + const bool stress, + Channels &channels) +{ + ModuleBase::timer::start("vdw", "convolve_channels"); + const int nshell = static_cast(channels.shells.size()) - 1; + std::vector sums(std::max(nshell, 0)); +#ifdef _OPENMP +#pragma omp parallel for schedule(dynamic) +#endif + for (int s = 0; s < nshell; ++s) + { + sums[s] = apply_shell(pw, table, s, stress, channels); + } + ShellSum total; + for (const ShellSum &shell : sums) + { + total.quadratic += shell.quadratic; + for (int ab = 0; ab < 9; ++ab) + { + total.metric[ab] += shell.metric[ab]; + } + } + ModuleBase::timer::end("vdw", "convolve_channels"); + return total; +} + +// Formulas 2.5 and 3.1: the inverse transform has no additional volume or grid factor. +// The divergence is taken by the caller. +void inverse_channels( + const ModulePW::PW_Basis &pw, + const KernelTable &table, + const std::vector &points, + Channels &channels, + std::vector *a, + std::vector &b) +{ + ModuleBase::timer::start("vdw", "inverse_channels"); + std::vector reciprocal(std::max(1, pw.npw)); + std::vector real(std::max(1, pw.nrxx)); + for (int i = 0; i < channels.nq; ++i) + { + const Complex *response = channels.channel(i); + for (int p = 0; p < pw.npw; ++p) + { + reciprocal[channels.order[p]] = response[p]; + } + pw.recip2real(reciprocal.data(), real.data()); +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int r = 0; r < pw.nrxx; ++r) + { + const LocalPoint &point = points[r]; + double slope = 0.0; + const double value = table.cardinal(i, point.cell, &slope); + if (a) + { + (*a)[r] += real[r] * (point.dw * value + point.wqn * slope); + } + b[r] += real[r] * point.wqs * slope; + } + } + ModuleBase::timer::end("vdw", "inverse_channels"); +} + +// Every channel is the transform of a real field, so half of the G sphere carries all of +// it. The half-sphere basis below is gamma-only with the FFT grid, the cutoff and the +// real-space planes of pw and keeps x >= 0 (y >= 0 without xprime), with both G and -G on +// the plane x = 0; its transforms are real-to-complex. +struct HalfSphereKey +{ + std::array real; + std::array count; + bool operator==(const HalfSphereKey &other) const { return real == other.real && count == other.count; } +}; + +// The density grid of a run hands out whole blocks of bz planes; a plain PW_Basis hands out +// single planes, which is PW_Basis_Big with blocks of one. +std::array plane_blocks(const ModulePW::PW_Basis &pw) +{ + const ModulePW::PW_Basis_Big *big = dynamic_cast(&pw); + if (big == nullptr) + { + return {{1, 1, 1}}; + } + return {{big->bx, big->by, big->bz}}; +} + +HalfSphereKey half_sphere_key(const ModulePW::PW_Basis &pw, const std::array &block) +{ + const ModuleBase::Matrix3 &v = pw.latvec; + return {{{pw.lat0, pw.ggecut, v.e11, v.e12, v.e13, v.e21, v.e22, v.e23, v.e31, v.e32, v.e33}}, + {{pw.nx, pw.ny, pw.nz, pw.poolnproc, pw.poolrank, pw.xprime ? 1 : 0, pw.distribution_type, pw.full_pw ? 1 : 0, + block[0], block[1], block[2]}}}; +} + +double pool_sum(double value, const ModulePW::PW_Basis &pw) +{ +#ifdef __MPI + Parallel_Common::reduce_data(&value, 1, pw.pool_world); +#endif + return value; +} + +// Whether the half sphere leaves every process of the pool with plane waves: pw must +// distribute sticks (not whole planes), and the pool must hold at least two kept sticks +// per process. +bool half_sphere_fits(const ModulePW::PW_Basis &pw) +{ + if (pw.full_pw || pw.distribution_type != 1) + { + return false; + } + double kept = 0.0; + for (int is = 0; is < pw.nst; ++is) + { + int ix = pw.is2fftixy[is] / pw.fftny; + int iy = pw.is2fftixy[is] % pw.fftny; + ix -= (ix >= pw.nx / 2 + 1) ? pw.nx : 0; + iy -= (iy >= pw.ny / 2 + 1) ? pw.ny : 0; + kept += ((pw.xprime ? ix : iy) >= 0) ? 1.0 : 0.0; + } + return pool_sum(kept, pw) >= 2.0 * pw.poolnproc; +} + +// Sets up half for pw; true if its real-space planes are those of pw on every process. +bool build_half_sphere(const ModulePW::PW_Basis &pw, const std::array &block, ModulePW::PW_Basis_Big &half) +{ + half.setbxyz(block[0], block[1], block[2]); +#ifdef __MPI + half.initmpi(pw.poolnproc, pw.poolrank, pw.pool_world); +#endif + half.initgrids(pw.lat0, pw.latvec, pw.nx, pw.ny, pw.nz); + half.initparameters(true, pw.ggecut * pw.tpiba2, 1, pw.xprime); + // PW_Basis_Sup hides the plain setuptransform() of PW_Basis; the plain one is meant here. + ModulePW::PW_Basis &plain = half; + plain.setuptransform(); + half.collect_local_pw(); + const bool same_planes = + half.nrxx == pw.nrxx && half.nplane == pw.nplane && half.startz_current == pw.startz_current; + const double differs = same_planes ? 0.0 : 1.0; + return pool_sum(differs, pw) == 0.0; +} + +// The half-sphere basis of pw, rebuilt when the cell, the grid or the pool changes; nullptr, +// on every process alike, where it does not fit and the full sphere of pw is used instead. +const ModulePW::PW_Basis *half_sphere(const ModulePW::PW_Basis &pw) +{ + const std::array block = plane_blocks(pw); + const HalfSphereKey key = half_sphere_key(pw, block); + static ModulePW::PW_Basis_Big half("cpu", "double"); + static bool cached = false; + static bool usable = false; + static HalfSphereKey built; +#ifdef __MPI + static MPI_Comm built_comm = MPI_COMM_NULL; + const bool same_comm = pw.pool_world == built_comm; + built_comm = pw.pool_world; +#else + const bool same_comm = true; +#endif + if (!(cached && same_comm && key == built)) + { + cached = true; + built = key; + usable = half_sphere_fits(pw) && build_half_sphere(pw, block, half); + } + return usable ? &half : nullptr; +} +} // namespace + +double rvv10_energy( + const ModulePW::PW_Basis &pw, + const double b, + const double c, + const std::vector &rho, + const std::vector &sigma, + std::vector *dedn, + std::vector &dedsigma, + double *stress) +{ + if (pw.gamma_only) + { + ModuleBase::WARNING_QUIT("rvv10_energy", "The rVV10 density basis must contain the full G sphere."); + } + if (!(b > 0.0) || !std::isfinite(b) || !(c >= 0.0) || !std::isfinite(c)) + { + ModuleBase::WARNING_QUIT("rvv10_energy", "rVV10 requires finite b > 0 and C >= 0."); + } + const KernelTable &table = kernel_table(); + const std::vector points = project_density(table, rho, sigma, b, c); + const ModulePW::PW_Basis *half = half_sphere(pw); + const ModulePW::PW_Basis &basis = half ? *half : pw; + Channels channels(basis, table.size()); + forward_channels(basis, table, points, channels); + const bool need_stress = stress != nullptr; + const ShellSum sum = convolve_channels(basis, table, need_stress, channels); + + // Formulas 1.5 and 3.1. Use the same positive density for the beta shift and its variation. + const double beta = uniform_shift(b); + double electrons = 0.0; + for (int r = 0; r < pw.nrxx; ++r) + { + const bool positive = rho[r] > 0.0; + electrons += positive ? rho[r] : 0.0; + if (dedn) + { + (*dedn)[r] = positive ? beta : 0.0; + } + dedsigma[r] = 0.0; + } + inverse_channels(basis, table, points, channels, dedn, dedsigma); + + const double half_volume = 0.5 * pw.omega; + double energy = half_volume * sum.quadratic + beta * (pw.omega / pw.nxyz) * electrons; +#ifdef __MPI + Parallel_Common::reduce_data(&energy, 1, pw.pool_world); +#endif + if (stress) + { + for (int ab = 0; ab < 9; ++ab) + { + stress[ab] = half_volume * sum.metric[ab]; + } +#ifdef __MPI + Parallel_Common::reduce_data(stress, 9, pw.pool_world); +#endif + // Formulas 2.6, 3.1: once for the explicit Omega in reciprocal space. + // beta*N cancels its potential term in the caller's fixed-N XC diagonal. + for (int a = 0; a < 3; ++a) + { + stress[3 * a + a] += energy; + } + } + return energy; +} +} // namespace vdw +#endif // __RVV10 diff --git a/source/source_hamilt/module_vdw/rvv10_kernel.h b/source/source_hamilt/module_vdw/rvv10_kernel.h new file mode 100644 index 00000000000..d4764a7551b --- /dev/null +++ b/source/source_hamilt/module_vdw/rvv10_kernel.h @@ -0,0 +1,46 @@ +#ifndef RVV10_KERNEL_H +#define RVV10_KERNEL_H + +#include + +namespace ModulePW +{ +class PW_Basis; +} + +namespace vdw +{ + +/** + * @brief rVV10 nonlocal correlation of one density, evaluated on the plane-wave grid of pw. + * + * The energy is the double integral of the rVV10 kernel over the density, evaluated with the + * Roman-Perez--Soler expansion: the density is projected on a mesh of the local variable q, each + * projection is convolved with the tabulated kernel in reciprocal space, and the result is + * contracted back. Collective over the pool communicator of pw; every process holds the planes of + * its own slice and the returned energy and stress are already reduced over the pool. + * + * @param pw plane-wave basis of the density grid + * @param b rVV10 parameter b (short-range damping), > 0 + * @param c rVV10 parameter C (gradient dependence of the local polarizability), >= 0 + * @param rho total density (valence plus core) on the nrxx points of this process + * @param sigma |grad rho|^2 on the same points + * @param[out] dedn dE/drho, or nullptr when only the energy and the stress are wanted + * @param[out] dedsigma dE/dsigma, resized by the caller + * @param[out] stress explicit strain derivative as 9 Cartesian components [3 * a + b], or + * nullptr when it is not wanted + * @return the nonlocal correlation energy in Hartree + */ +double rvv10_energy( + const ModulePW::PW_Basis &pw, + double b, + double c, + const std::vector &rho, + const std::vector &sigma, + std::vector *dedn, + std::vector &dedsigma, + double *stress); + +} // namespace vdw + +#endif // RVV10_KERNEL_H diff --git a/source/source_hamilt/module_vdw/unittests/CMakeLists.txt b/source/source_hamilt/module_vdw/unittests/CMakeLists.txt index b362cdb4aac..0434870fbaa 100644 --- a/source/source_hamilt/module_vdw/unittests/CMakeLists.txt +++ b/source/source_hamilt/module_vdw/unittests/CMakeLists.txt @@ -18,3 +18,46 @@ if(ENABLE_DFTD4 AND ENABLE_MPI) ${MPIEXEC_POSTFLAGS} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) endif() + +if(ENABLE_MPI) + set(nonlocal_xc_test_libs + xc_ + planewave + parameter + MPI::MPI_CXX + psi + device + container + base) + if(ENABLE_LIBXC) + list(APPEND nonlocal_xc_test_libs Libxc::xc) + endif() + addtest( + TARGET MODULE_HAMILT_nonlocal_xcTest + LIBS ${nonlocal_xc_test_libs} + SOURCES test_nonlocal_xc.cpp ../../../source_base/test/mpi_test_main.cpp) + set_tests_properties(MODULE_HAMILT_nonlocal_xcTest + PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=1") + add_test( + NAME MODULE_HAMILT_nonlocal_xcTest_2np + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) + set_tests_properties(MODULE_HAMILT_nonlocal_xcTest_2np + PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=1" PROCESSORS 2) + # the same with two threads: the element-wise loops of the adapter are + # OpenMP-parallel + add_test( + NAME MODULE_HAMILT_nonlocal_xcTest_2np_2threads + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) + set_tests_properties(MODULE_HAMILT_nonlocal_xcTest_2np_2threads + PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=2" PROCESSORS 4) + # four processes give an uneven z distribution and, on the big-cell grid, + # a process without any point + add_test( + NAME MODULE_HAMILT_nonlocal_xcTest_4np + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) + set_tests_properties(MODULE_HAMILT_nonlocal_xcTest_4np + PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=1" PROCESSORS 4) +endif() diff --git a/source/source_hamilt/module_vdw/unittests/test_nonlocal_xc.cpp b/source/source_hamilt/module_vdw/unittests/test_nonlocal_xc.cpp new file mode 100644 index 00000000000..7cae4e2eb4e --- /dev/null +++ b/source/source_hamilt/module_vdw/unittests/test_nonlocal_xc.cpp @@ -0,0 +1,714 @@ +// Native rVV10 kernel, total-density adapter, variational derivatives and parallel layouts. +#include "source_hamilt/module_vdw/nonlocal_xc.h" +#include "source_hamilt/module_vdw/rvv10_kernel.h" + +#include "source_base/constants.h" +#include "source_base/matrix.h" +#include "source_base/matrix3.h" +#include "source_base/parallel_cell.h" +#include "source_base/parallel_comm.h" +#include "source_base/parallel_device.h" +#include "source_basis/module_pw/pw_basis.h" +#include "source_basis/module_pw/pw_basis_big.h" +#include "source_cell/unitcell.h" +#include "source_estate/module_charge/charge.h" +#include "source_hamilt/module_xc/xc_functional.h" +#ifdef __LIBXC +#include "source_hamilt/module_xc/libxc_abacus.h" +#endif + +#include "gtest/gtest.h" +#include +#include +#include +#include + +// The target links PW/XC objects only; the tests own the charge storage. +Charge::Charge() {} +Charge::~Charge() {} +UnitCell::UnitCell() {} +UnitCell::~UnitCell() {} +Magnetism::Magnetism() {} +Magnetism::~Magnetism() {} +SepPot::SepPot() {} +SepPot::~SepPot() {} +Sep_Cell::Sep_Cell() noexcept {} +Sep_Cell::~Sep_Cell() noexcept {} + +namespace +{ +typedef std::tuple VxcResult; +// rVV10 parameters of the rPW86-PBE pairing +const double rvv10_b_rpw86 = 6.3; +const double rvv10_c_rpw86 = 0.0093; +// Independent evaluations of one density differ by rounding only (FFT layout, order of the sums). +const double rounding_tolerance = 2.0e-12; +const double basis_cutoff = 4.0; + +/// A smooth test field; the arguments are the grid coordinates as phases 2 pi i / n. +typedef double (*GridFunction)(const double ax, const double ay, const double az); + +double valence_density(const double ax, const double ay, const double az) +{ + const double ayz = ay + az; + return 0.004 + 0.006 * (1.0 + 0.25 * std::sin(ax) + 0.15 * std::cos(ayz)); +} + +double core_density(const double, const double, const double az) { return 0.002 * (1.0 + std::cos(az)); } + +#ifdef __LIBXC +double kinetic_density(const double, const double ay, const double) { return 0.003 * (1.0 + 0.2 * std::cos(ay)); } +#endif + +double perturbation(const double ax, const double ay, const double) +{ + const double axy = ax + ay; + const double ay2 = 2.0 * ay; + return std::sin(axy) + 0.3 * std::cos(ay2); +} + +/// Values of f on the z planes of this process, in the ABACUS layout [ixy * nplane + iz]. +std::vector local_grid(const ModulePW::PW_Basis &pw, GridFunction f) +{ + std::vector values(pw.nrxx); + for (int ix = 0; ix < pw.nx; ++ix) + { + const double ax = ModuleBase::TWO_PI * ix / pw.nx; + for (int iy = 0; iy < pw.ny; ++iy) + { + const double ay = ModuleBase::TWO_PI * iy / pw.ny; + for (int iz = 0; iz < pw.nplane; ++iz) + { + const int global_z = pw.startz_current + iz; + const double az = ModuleBase::TWO_PI * global_z / pw.nz; + values[(ix * pw.ny + iy) * pw.nplane + iz] = f(ax, ay, az); + } + } + } + return values; +} + +/// The valence density as two spin channels (nspin = 2) or as the density and a magnetization (nspin = 4). +std::vector> spin_components(const std::vector &valence, const int nspin) +{ + std::vector> components(nspin, valence); + for (std::size_t ir = 0; ir < valence.size(); ++ir) + { + if (nspin == 2) + { + components[0][ir] = 0.7 * valence[ir]; + components[1][ir] = valence[ir] - components[0][ir]; + } + else + { + components[1][ir] = 0.1 * valence[ir]; + components[2][ir] = -0.05 * valence[ir]; + components[3][ir] = 0.2 * valence[ir]; + } + } + return components; +} + +/// Oblique lattice; z_sign = -1 gives its left-handed mirror image. +ModuleBase::Matrix3 oblique_lattice(const double z_sign) +{ + const double c3 = 2.0 * z_sign; + const double b2 = std::sqrt(0.75); + return ModuleBase::Matrix3(1.0, 0.0, 0.0, -0.5, b2, 0.0, 0.0, 0.0, c3); +} + +/// The lattice after the strain eps_ab = h: every lattice vector gets a_i[a] += h * a_i[b]. +ModuleBase::Matrix3 strained_lattice( + const ModuleBase::Matrix3 &lattice, + const int a, + const int b, + const double h) +{ + double m[3][3] = {{lattice.e11, lattice.e12, lattice.e13}, {lattice.e21, lattice.e22, lattice.e23}, + {lattice.e31, lattice.e32, lattice.e33}}; + for (int i = 0; i < 3; ++i) + { + m[i][a] += h * m[i][b]; + } + return ModuleBase::Matrix3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]); +} + +/// Basis on the 5 x 7 x nz FFT grid of the given cell. With nz = 9 the z planes split 5 + 4 on two processes and +/// 3 + 2 + 2 + 2 on four, so that the plane distribution of the channels and their collective transforms are +/// exercised. Odd ny and nz leave no Nyquist plane on either axis. +void setup_grid( + ModulePW::PW_Basis &basis, + const ModuleBase::Matrix3 &lattice, + const double cutoff, + const int nz) +{ + basis.initgrids(10.0, lattice, 5, 7, nz); + basis.initparameters(false, cutoff, 1, true); + basis.setuptransform(); + basis.collect_local_pw(); +} + +/// XC runtime parameters with the rVV10 switch set as given and the parameters of the rPW86-PBE pairing. +XCFunctionalParameters rvv10_parameters(const bool rvv10) +{ + XCFunctionalParameters parameters = XC_Functional::get_runtime_parameters(); + parameters.rvv10 = rvv10; + parameters.rvv10_b = rvv10_b_rpw86; + parameters.rvv10_c = rvv10_c_rpw86; + return parameters; +} + +/// Sets the XC runtime parameters for the lifetime of the object, as ESolver_FP does. +class RuntimeParameters +{ + public: + explicit RuntimeParameters(const bool rvv10) + { + saved_ = XC_Functional::get_runtime_parameters(); + const XCFunctionalParameters parameters = rvv10_parameters(rvv10); + XC_Functional::set_runtime_parameters(parameters); + } + ~RuntimeParameters() { XC_Functional::set_runtime_parameters(saved_); } + + private: + XCFunctionalParameters saved_; +}; + +/// A Charge on pw that owns its density components, core density and the G-space buffers of gradcorr. +class ChargeOnGrid : public Charge +{ + public: + ChargeOnGrid( + ModulePW::PW_Basis &pw, const std::vector> &channels, const std::vector &core) + { + channels_ = channels; + core_ = core; + const std::size_t ncomponents = channels.size(); + const std::vector> reciprocal(pw.npw); + rhog_.assign(ncomponents, reciprocal); + core_g_ = reciprocal; + for (std::size_t is = 0; is < ncomponents; ++is) + { + rows_.push_back(channels_[is].data()); + rhog_rows_.push_back(rhog_[is].data()); + } + rhopw = &pw; + nrxx = pw.nrxx; + nspin = static_cast(ncomponents); + rho = rows_.data(); + rhog = rhog_rows_.data(); + rho_core = core_.data(); + rhog_core = core_g_.data(); + } + + private: + std::vector> channels_; + std::vector rows_; + std::vector core_; + std::vector>> rhog_; + std::vector *> rhog_rows_; + std::vector> core_g_; +}; + +/// rVV10 contribution for the given valence channels and core density on pw. +VxcResult rvv10_result( + ModulePW::PW_Basis &pw, const std::vector> &channels, const std::vector &core) +{ + const ChargeOnGrid charge(pw, channels, core); + const XCFunctionalParameters parameters = rvv10_parameters(true); + double etxc = 0.0; + double vtxc = 0.0; + ModuleBase::matrix v(charge.nspin, pw.nrxx); + vdw::add_rvv10(parameters, charge, etxc, vtxc, v); + return VxcResult(etxc, vtxc, v); +} + +/// rVV10 stress beyond the XC diagonal term for the given density on pw. +ModuleBase::matrix rvv10_stress( + ModulePW::PW_Basis &pw, const std::vector> &channels, const std::vector &core) +{ + const ChargeOnGrid charge(pw, channels, core); + const XCFunctionalParameters parameters = rvv10_parameters(true); + ModuleBase::matrix sigma(3, 3); + vdw::add_rvv10_stress(parameters, charge, sigma); + return sigma; +} + +/// The energies, vtxc and the potentials on every point agree to rounding. +void expect_same_result(const VxcResult &actual, const VxcResult &expected) +{ + EXPECT_NEAR(std::get<0>(actual), std::get<0>(expected), rounding_tolerance); + EXPECT_NEAR(std::get<1>(actual), std::get<1>(expected), rounding_tolerance); + const ModuleBase::matrix &v = std::get<2>(actual); + const ModuleBase::matrix &w = std::get<2>(expected); + ASSERT_EQ(v.nr, w.nr); + ASSERT_EQ(v.nc, w.nc); + for (int is = 0; is < v.nr; ++is) + { + for (int ir = 0; ir < v.nc; ++ir) + { + EXPECT_NEAR(v(is, ir), w(is, ir), rounding_tolerance); + } + } +} + +/// A functional evaluated with rVV10 equals the evaluation without it plus add_rvv10. +void expect_rvv10_added(const VxcResult &total, VxcResult semilocal, const Charge &chr) +{ + const XCFunctionalParameters parameters = rvv10_parameters(true); + double &etxc = std::get<0>(semilocal); + double &vtxc = std::get<1>(semilocal); + ModuleBase::matrix &v = std::get<2>(semilocal); + vdw::add_rvv10(parameters, chr, etxc, vtxc, v); + expect_same_result(total, semilocal); +} + +/// XC_Functional::v_xc for the given functional and density with and without rVV10; a four-component density is +/// evaluated as a magnetized one. +void expect_vxc_adds_rvv10(const char *functional, const Charge &chr, const int gga_grad) +{ + XC_Functional::ScopedType scope(functional); + UnitCell ucell; + ucell.omega = chr.rhopw->omega; + ucell.tpiba = chr.rhopw->tpiba; + ucell.magnet.lsign_ = false; + const int nrxx = chr.nrxx; + const int nspin = chr.nspin; + const bool domag = nspin == 4; + const bool domag_z = false; + const double hybrid_alpha = 0.0; + const double hse_omega = 0.0; + VxcResult total; + VxcResult semilocal; + for (int with_rvv10 = 0; with_rvv10 < 2; ++with_rvv10) + { + const bool rvv10 = with_rvv10 == 1; + RuntimeParameters parameters(rvv10); + VxcResult &result = rvv10 ? total : semilocal; + result = XC_Functional::v_xc(nrxx, &chr, &ucell, nspin, domag, domag_z, gga_grad, hybrid_alpha, hse_omega); + } + expect_rvv10_added(total, semilocal, chr); +} + +/// The result on the distributed grid equals the result on the complete grid, on the planes of this process, for +/// the energy, vtxc, the potential and the stress. +void expect_distributed_matches_complete(ModulePW::PW_Basis &distributed, ModulePW::PW_Basis &complete) +{ + const std::vector valence = local_grid(distributed, valence_density); + const std::vector core = local_grid(distributed, core_density); + const std::vector valence_complete = local_grid(complete, valence_density); + const std::vector core_complete = local_grid(complete, core_density); + const VxcResult result = rvv10_result(distributed, {valence}, core); + const VxcResult reference = rvv10_result(complete, {valence_complete}, core_complete); + EXPECT_NEAR(std::get<0>(result), std::get<0>(reference), rounding_tolerance); + EXPECT_NEAR(std::get<1>(result), std::get<1>(reference), rounding_tolerance); + for (int ixy = 0; ixy < distributed.nxy; ++ixy) + { + for (int iz = 0; iz < distributed.nplane; ++iz) + { + const int local = ixy * distributed.nplane + iz; + const int global = ixy * distributed.nz + distributed.startz_current + iz; + EXPECT_NEAR(std::get<2>(result)(0, local), std::get<2>(reference)(0, global), rounding_tolerance); + } + } + const ModuleBase::matrix stress = rvv10_stress(distributed, {valence}, core); + const ModuleBase::matrix stress_complete = rvv10_stress(complete, {valence_complete}, core_complete); + // a lower bound that shows the compared stress is not trivially zero + const double nonzero_stress = 1.0e-10; + const double stress_magnitude = std::abs(stress_complete(0, 0)); + EXPECT_GT(stress_magnitude, nonzero_stress); + for (int a = 0; a < 3; ++a) + { + for (int b = 0; b < 3; ++b) + { + EXPECT_NEAR(stress(a, b), stress_complete(a, b), rounding_tolerance); + } + } +} + +class NonlocalXCTest : public testing::Test +{ + protected: + void SetUp() override + { + // the XC evaluators reduce over POOL_WORLD, which the shared main of the MPI tests leaves unset + const ModuleBase::CommunicationDomain world = ModuleBase::world_comm_domain(); + const int nproc = world.size(); + const int rank = world.rank(); + POOL_WORLD = world.communicator(); + // The oblique cell catches row/column mistakes in the reciprocal metric of the kernel. + const ModuleBase::Matrix3 lattice = oblique_lattice(1.0); + pw.initmpi(nproc, rank, POOL_WORLD); + serial.initmpi(1, 0, MPI_COMM_SELF); + setup_grid(pw, lattice, basis_cutoff, 9); + setup_grid(serial, lattice, basis_cutoff, 9); + } + + /// grid on an oblique cell, distributed over the processes of the test + ModulePW::PW_Basis pw{"cpu", "double"}; + /// the same grid, complete on every process + ModulePW::PW_Basis serial{"cpu", "double"}; +}; + +TEST_F(NonlocalXCTest, NativeKernelMatchesSingleModeTransform) +{ + // Kernel inputs n and sigma are independent. Choose them so q stays constant and w=w0*(1+t*cos(Gz*z)). + // For equal q the reduced kernel is -3/[4(1+q R^2)^3]. Its radial transform is + // F(k) = F(0)*(1+x)*exp(-x), x=k/sqrt(q). Each endpoint supplies half of dF/dq by symmetry. + const double b = rvv10_b_rpw86; + const double c = rvv10_c_rpw86; + const double n0 = 0.012; + const double q = 0.045; + const double t = 0.45; + const double pi = ModuleBase::PI; + const double kappa0 = 1.5 * pi * b * std::pow(n0 / (9.0 * pi), 1.0 / 6.0); + const double w0 = n0 / std::pow(kappa0, 1.5); + const double beta = std::pow(3.0 / (b * b), 0.75) / 32.0; + const double gz = 0.5 * serial.tpiba; // the third oblique_lattice vector is (0,0,2)*lat0 + const double x = gz / std::sqrt(q); + const double f0 = -3.0 * pi * pi / (16.0 * std::pow(q, 1.5)); + const double f1 = f0 * (1.0 + x) * std::exp(-x); + const double df0 = -1.5 * f0 / q; + const double df1 = f0 * std::exp(-x) * (x * x - 3.0 * (1.0 + x)) / (2.0 * q); + const double pair = 0.5 * serial.omega * w0 * w0 * (f0 + 0.5 * t * t * f1); + std::vector density(serial.nrxx), sigma(serial.nrxx), a_ref(serial.nrxx), b_ref(serial.nrxx); + std::vector a(serial.nrxx), d_sigma(serial.nrxx); + double nsum = 0.0; + for (int ir = 0; ir < serial.nrxx; ++ir) + { + const int iz = ir % serial.nz; + const double phase = ModuleBase::TWO_PI * iz / serial.nz; + const double harmonic = t * std::cos(phase); + const double n = n0 * std::pow(1.0 + harmonic, 4.0 / 3.0); + const double w = w0 * (1.0 + harmonic); + const double kappa = kappa0 * std::pow(n / n0, 1.0 / 6.0); + const double frequency2 = q * q * kappa * kappa; + const double gap2 = frequency2 - 4.0 * pi * n / 3.0; + ASSERT_GT(gap2, 0.0); + sigma[ir] = n * n * std::sqrt(gap2 / c); + density[ir] = n; + nsum += n; + const double gamma = gap2 / frequency2; + const double convolution = w0 * (f0 + harmonic * f1); + const double dq_convolution = 0.5 * w0 * (df0 + harmonic * df1); + a_ref[ir] = beta + w * (0.75 * convolution + q * (1.0 / 3.0 - 2.5 * gamma) * dq_convolution) / n; + b_ref[ir] = w * q * gamma * dq_convolution / sigma[ir]; + } + const double expected_energy = pair + beta * nsum * serial.omega / serial.nxyz; + const double energy = vdw::rvv10_energy(serial, b, c, density, sigma, &a, d_sigma, nullptr); + // The continuum reference has no q interpolation, saturation or radial truncation. + const double energy_tolerance = 1.0e-3 * std::abs(pair); + EXPECT_NEAR(energy, expected_energy, energy_tolerance); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + const double a_tolerance = 3.0e-3 * beta; + const double b_tolerance = 3.0e-3 * std::abs(b_ref[ir]); + EXPECT_NEAR(a[ir], a_ref[ir], a_tolerance); + EXPECT_NEAR(d_sigma[ir], b_ref[ir], b_tolerance); + } +} + +TEST_F(NonlocalXCTest, PassesTotalDensityAndParametersToNativeKernel) +{ + // Exercise the adapter independently of the analytic kernel benchmark above. + const std::vector valence = local_grid(serial, valence_density); + const std::vector core = local_grid(serial, core_density); + const VxcResult result = rvv10_result(serial, {valence}, core); + + // Form the analytic valence plus core density explicitly, then construct the expected host potential. + std::vector total(serial.nrxx); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + total[ir] = valence[ir] + core[ir]; + } + std::vector> rhog(serial.npw); + serial.real2recip(total.data(), rhog.data()); + std::vector> grad(serial.nrxx); + XC_Functional::grad_rho(rhog.data(), grad.data(), &serial, serial.tpiba); + std::vector sigma(serial.nrxx); + std::vector dedn(serial.nrxx); + std::vector dedsigma(serial.nrxx); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + sigma[ir] = grad[ir].norm2(); + } + const double energy_ha = + vdw::rvv10_energy(serial, rvv10_b_rpw86, rvv10_c_rpw86, total, sigma, &dedn, dedsigma, nullptr); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + grad[ir] *= 2.0 * dedsigma[ir]; + } + std::vector divergence(serial.nrxx); + XC_Functional::grad_dot(grad.data(), divergence.data(), &serial, serial.tpiba); + + ModuleBase::matrix v(1, serial.nrxx); + double vtxc = 0.0; + for (int ir = 0; ir < serial.nrxx; ++ir) + { + const double potential = ModuleBase::e2 * (dedn[ir] - divergence[ir]); + v(0, ir) = potential; + vtxc += potential * valence[ir]; + } + const double etxc = ModuleBase::e2 * energy_ha; + vtxc *= serial.omega / serial.nxyz; + const VxcResult expected(etxc, vtxc, v); + expect_same_result(result, expected); + + // Changing the host parameters must be equivalent to passing those values to the kernel. + const double other_b = 15.7; + const double other_c = 0.02; + // a lower bound that shows the energy depends on the parameters + const double distinct_energy = 1.0e-8; + XCFunctionalParameters other = rvv10_parameters(true); + other.rvv10_b = other_b; + other.rvv10_c = other_c; + const ChargeOnGrid charge(serial, {valence}, core); + double other_etxc = 0.0; + double other_vtxc = 0.0; + ModuleBase::matrix other_v(1, serial.nrxx); + vdw::add_rvv10(other, charge, other_etxc, other_vtxc, other_v); + const double other_expected = + ModuleBase::e2 * vdw::rvv10_energy(serial, other_b, other_c, total, sigma, &dedn, dedsigma, nullptr); + EXPECT_NEAR(other_etxc, other_expected, rounding_tolerance); + const double energy_change = std::abs(other_etxc - etxc); + EXPECT_GT(energy_change, distinct_energy); + + // spin channels share the total density: same energy and vtxc, and each channel gets the potential + const std::vector> collinear = spin_components(valence, 2); + const VxcResult polarized = rvv10_result(serial, collinear, core); + EXPECT_NEAR(std::get<0>(polarized), etxc, rounding_tolerance); + EXPECT_NEAR(std::get<1>(polarized), vtxc, rounding_tolerance); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + EXPECT_NEAR(std::get<2>(polarized)(0, ir), v(0, ir), rounding_tolerance); + EXPECT_NEAR(std::get<2>(polarized)(1, ir), v(0, ir), rounding_tolerance); + } + + // four-component layout: rho[0] is the total valence density, and only v(0) gets the potential + const std::vector> magnetized = spin_components(valence, 4); + const VxcResult noncollinear = rvv10_result(serial, magnetized, core); + EXPECT_NEAR(std::get<0>(noncollinear), etxc, rounding_tolerance); + EXPECT_NEAR(std::get<1>(noncollinear), vtxc, rounding_tolerance); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + EXPECT_NEAR(std::get<2>(noncollinear)(0, ir), v(0, ir), rounding_tolerance); + for (int is = 1; is < 4; ++is) + { + EXPECT_EQ(std::get<2>(noncollinear)(is, ir), 0.0); + } + } +} + +TEST_F(NonlocalXCTest, PotentialIsTheDerivativeOfTheEnergy) +{ + // central difference of the energy along a smooth perturbation: the truncation error is of order step^2 + const double finite_difference_step = 1.0e-5; + const double finite_difference_tolerance = 2.0e-6; + const std::vector valence = local_grid(pw, valence_density); + const std::vector core = local_grid(pw, core_density); + const std::vector direction = local_grid(pw, perturbation); + std::vector plus = valence; + std::vector minus = valence; + for (int ir = 0; ir < pw.nrxx; ++ir) + { + plus[ir] += finite_difference_step * direction[ir]; + minus[ir] -= finite_difference_step * direction[ir]; + } + const VxcResult reference = rvv10_result(pw, {valence}, core); + const VxcResult result_plus = rvv10_result(pw, {plus}, core); + const VxcResult result_minus = rvv10_result(pw, {minus}, core); + const double energy_difference = std::get<0>(result_plus) - std::get<0>(result_minus); + const double finite_difference = energy_difference / (2.0 * finite_difference_step); + + double contraction = 0.0; + for (int ir = 0; ir < pw.nrxx; ++ir) + { + contraction += std::get<2>(reference)(0, ir) * direction[ir]; + } + Parallel_Common::reduce_data(&contraction, 1, pw.pool_world); + contraction *= pw.omega / pw.nxyz; + EXPECT_NEAR(finite_difference, contraction, finite_difference_tolerance); +} + +TEST_F(NonlocalXCTest, StressIsTheStrainDerivativeOfTheEnergy) +{ + // A strain keeps the grid and every G component of the density, so the stress is the exact derivative + // of the discrete energy: sigma_ab = -(1/omega) dE/d(eps_ab) at a fixed electron number. + const double strain_step = 1.0e-4; + const double strain_tolerance = 1.0e-5; + // PW_Basis lowers a larger cutoff to the largest G sphere inside the FFT box. The test densities have + // only first-shell G components, well inside that sphere, so a small strain changes none of them. + const double largest_sphere_cutoff = 1.0e6; + ModulePW::PW_Basis box{"cpu", "double"}; + box.initmpi(1, 0, MPI_COMM_SELF); + const ModuleBase::Matrix3 lattice = oblique_lattice(1.0); + setup_grid(box, lattice, largest_sphere_cutoff, 9); + const std::vector density = local_grid(box, valence_density); + const std::vector no_core(box.nrxx, 0.0); + const VxcResult reference = rvv10_result(box, {density}, no_core); + const ModuleBase::matrix extra = rvv10_stress(box, {density}, no_core); + // the XC diagonal term that ABACUS adds from etxc and vtxc + const double diagonal = -(std::get<0>(reference) - std::get<1>(reference)) / box.omega; + + const int components[4][2] = {{0, 0}, {2, 2}, {0, 1}, {1, 2}}; + for (const int *ab : components) + { + const int a = ab[0]; + const int b = ab[1]; + double energy[2] = {0.0, 0.0}; + for (int side = 0; side < 2; ++side) + { + const double h = (side == 0) ? strain_step : -strain_step; + ModulePW::PW_Basis strained{"cpu", "double"}; + strained.initmpi(1, 0, MPI_COMM_SELF); + const ModuleBase::Matrix3 strained_cell = strained_lattice(lattice, a, b, h); + setup_grid(strained, strained_cell, largest_sphere_cutoff, 9); + // keep the electron number: the density scales with the inverse volume ratio + const double volume_ratio = strained.omega / box.omega; + std::vector scaled = density; + for (double &value : scaled) + { + value /= volume_ratio; + } + const VxcResult strained_result = rvv10_result(strained, {scaled}, no_core); + energy[side] = std::get<0>(strained_result); + } + const double finite_difference = -(energy[0] - energy[1]) / (2.0 * strain_step * box.omega); + const double analytic = extra(a, b) + ((a == b) ? diagonal : 0.0); + const double tolerance = strain_tolerance * std::abs(analytic) + 1.0e-12; + SCOPED_TRACE(testing::Message() << "component " << a << b); + EXPECT_NEAR(analytic, finite_difference, tolerance); + } +} + +TEST_F(NonlocalXCTest, VxcAddsRvv10ToEveryFunctionalPath) +{ + // v_xc and v_xc_meta with rVV10 equal the semilocal result plus add_rvv10, for native PBE (final + // return), noncollinear PBE with gga_grad 0 (collinear-mapped branch) and 2 (NCGGA return), and with + // Libxc a libxc GGA (v_xc_libxc) in the same layouts and unpolarized, and SCAN (v_xc_meta). + const std::vector valence = local_grid(pw, valence_density); + const std::vector core = local_grid(pw, core_density); + const std::vector> collinear = spin_components(valence, 2); + const std::vector> noncollinear = spin_components(valence, 4); + const ChargeOnGrid polarized(pw, collinear, core); + const ChargeOnGrid magnetized(pw, noncollinear, core); + expect_vxc_adds_rvv10("PBE", polarized, 0); + expect_vxc_adds_rvv10("PBE", magnetized, 2); + expect_vxc_adds_rvv10("PBE", magnetized, 0); +#ifdef __LIBXC + expect_vxc_adds_rvv10("GGA_X_RPW86+GGA_C_PBE", polarized, 0); + expect_vxc_adds_rvv10("GGA_X_RPW86+GGA_C_PBE", magnetized, 0); + expect_vxc_adds_rvv10("GGA_X_RPW86+GGA_C_PBE", magnetized, 2); + const std::vector> unpolarized(1, valence); + const ChargeOnGrid single(pw, unpolarized, core); + expect_vxc_adds_rvv10("GGA_X_RPW86+GGA_C_PBE", single, 0); + + XC_Functional::ScopedType scan("SCAN"); + std::vector kinetic = local_grid(pw, kinetic_density); + std::vector kinetic_rows(1, kinetic.data()); + ChargeOnGrid charge(pw, unpolarized, core); + charge.kin_r = kinetic_rows.data(); + const std::vector func_id = XC_Functional::get_func_id(); + const int nspin = 1; + const double hybrid_alpha = 0.0; + const double hse_omega = 0.0; + typedef std::tuple MetaResult; + VxcResult results[2]; + for (int with_rvv10 = 0; with_rvv10 < 2; ++with_rvv10) + { + const bool rvv10 = with_rvv10 == 1; + RuntimeParameters parameters(rvv10); + const MetaResult meta = XC_Functional_Libxc::v_xc_meta( + func_id, pw.nrxx, pw.omega, pw.tpiba, &charge, nspin, hybrid_alpha, hse_omega); + results[with_rvv10] = VxcResult(std::get<0>(meta), std::get<1>(meta), std::get<2>(meta)); + } + expect_rvv10_added(results[1], results[0], charge); +#endif +} + +TEST_F(NonlocalXCTest, DistributedGridMatchesCompleteGrid) +{ + // the plane and stick distributions of the channels, uneven and with an empty share on four processes + expect_distributed_matches_complete(pw, serial); + // The density grid of a run is a PW_Basis_Big, which hands out whole blocks of bz planes: on two + // processes 8 + 4 and on four 4 + 4 + 4 + 0, so that a process may own no plane at all while it still + // takes part in every collective transform and reduction. + ModulePW::PW_Basis_Big big{"cpu", "double"}; + big.setbxyz(1, 1, 4); + big.initmpi(pw.poolnproc, pw.poolrank, pw.pool_world); + ModulePW::PW_Basis complete{"cpu", "double"}; + complete.initmpi(1, 0, MPI_COMM_SELF); + const ModuleBase::Matrix3 lattice = oblique_lattice(1.0); + setup_grid(big, lattice, basis_cutoff, 12); + setup_grid(complete, lattice, basis_cutoff, 12); + ASSERT_EQ(big.nz, 12); + ASSERT_EQ(big.nplane % 4, 0); + if (pw.poolnproc == 4) + { + EXPECT_EQ(big.numz[3], 0); + } + expect_distributed_matches_complete(big, complete); + // the XC evaluator calls add_rvv10 on every process of the pool, also on one without points + const std::vector valence = local_grid(big, valence_density); + const std::vector core = local_grid(big, core_density); + const std::vector> unpolarized(1, valence); + const ChargeOnGrid single(big, unpolarized, core); +#ifdef __LIBXC + expect_vxc_adds_rvv10("GGA_X_RPW86+GGA_C_PBE", single, 0); +#else + expect_vxc_adds_rvv10("PBE", single, 0); +#endif +} + +TEST_F(NonlocalXCTest, FullSphereMatchesHalfSphere) +{ + // The channels are transformed on a gamma-only half sphere built from the density basis. With the second + // plane-wave distribution the kernel keeps them on the full sphere of the density basis instead; both + // evaluate the same sums, so the results differ by rounding only. + ModulePW::PW_Basis full{"cpu", "double"}; + full.initmpi(1, 0, MPI_COMM_SELF); + full.initgrids(10.0, oblique_lattice(1.0), 5, 7, 9); + full.initparameters(false, basis_cutoff, 2, true); + full.setuptransform(); + full.collect_local_pw(); + ASSERT_EQ(full.nrxx, serial.nrxx); + const std::vector density = local_grid(serial, valence_density); + const std::vector bump = local_grid(serial, perturbation); + std::vector sigma(serial.nrxx); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + sigma[ir] = 1.0e-4 * (1.5 + bump[ir]); // any positive field is a valid kernel input + } + std::vector a_half(serial.nrxx), b_half(serial.nrxx), a_full(serial.nrxx), b_full(serial.nrxx); + double t_half[9] = {}, t_full[9] = {}; + const double b = rvv10_b_rpw86; + const double c = rvv10_c_rpw86; + const double e_half = vdw::rvv10_energy(serial, b, c, density, sigma, &a_half, b_half, t_half); + const double e_full = vdw::rvv10_energy(full, b, c, density, sigma, &a_full, b_full, t_full); + EXPECT_NEAR(e_full, e_half, rounding_tolerance); + for (int ir = 0; ir < serial.nrxx; ++ir) + { + EXPECT_NEAR(a_full[ir], a_half[ir], rounding_tolerance); + EXPECT_NEAR(b_full[ir], b_half[ir], rounding_tolerance); + } + for (int ab = 0; ab < 9; ++ab) + { + EXPECT_NEAR(t_full[ab], t_half[ab], rounding_tolerance); + } +} + +TEST_F(NonlocalXCTest, LeftHandedCellGivesTheMirrorImageResult) +{ + // A mirror image has the same result; a signed cell volume would flip the sign of the energy. + ModulePW::PW_Basis mirror{"cpu", "double"}; + mirror.initmpi(1, 0, MPI_COMM_SELF); + const ModuleBase::Matrix3 mirrored = oblique_lattice(-1.0); + setup_grid(mirror, mirrored, basis_cutoff, 9); + ASSERT_LT(mirror.latvec.Det(), 0.0); + const std::vector valence = local_grid(serial, valence_density); + const std::vector core = local_grid(serial, core_density); + const VxcResult right_handed = rvv10_result(serial, {valence}, core); + const VxcResult left_handed = rvv10_result(mirror, {valence}, core); + expect_same_result(left_handed, right_handed); +} +} // namespace diff --git a/source/source_hamilt/module_vdw/unittests/test_vdw.cpp b/source/source_hamilt/module_vdw/unittests/test_vdw.cpp index 3c61014e2e9..0e9d04553ad 100644 --- a/source/source_hamilt/module_vdw/unittests/test_vdw.cpp +++ b/source/source_hamilt/module_vdw/unittests/test_vdw.cpp @@ -943,6 +943,15 @@ TEST_F(vdwd4Test, EmptyAtomsAreExcludedForD4S) #endif // __DFTD4 +// rVV10 is part of the XC functional (nonlocal_xc.cpp), so make_vdw returns no pairwise correction +TEST(vdwRvv10Test, MakeVdwHasNoPairwiseTerm) +{ + UnitCell ucell; + Input_para input; + input.vdw_method = "rvv10"; + EXPECT_TRUE(vdw::make_vdw(ucell, input) == nullptr); +} + int main(int argc, char **argv) { MPI_Init(&argc, &argv); diff --git a/source/source_hamilt/module_vdw/vdw.cpp b/source/source_hamilt/module_vdw/vdw.cpp index 19d2e3524c2..da6055e5452 100644 --- a/source/source_hamilt/module_vdw/vdw.cpp +++ b/source/source_hamilt/module_vdw/vdw.cpp @@ -94,6 +94,16 @@ std::unique_ptr make_vdw(const UnitCell &ucell, const Input_para &input, st "Rebuild ABACUS with -DENABLE_DFTD4=ON."); #endif } + else if (input.vdw_method == "rvv10") + { + // rVV10 is evaluated inside XC_Functional, so there is no pairwise term here + if (plog != nullptr) + { + *plog << "\nrVV10 nonlocal correlation: b=" << input.rvv10_b << " C=" << input.rvv10_c + << "\nincluded in the exchange-correlation energy, potential, forces and stress" << std::endl; + } + return nullptr; + } else if (input.vdw_method != "none") { ModuleBase::WARNING_QUIT( diff --git a/source/source_hamilt/module_xc/CMakeLists.txt b/source/source_hamilt/module_xc/CMakeLists.txt index 2e852f0458a..ded6fc2a924 100644 --- a/source/source_hamilt/module_xc/CMakeLists.txt +++ b/source/source_hamilt/module_xc/CMakeLists.txt @@ -29,6 +29,9 @@ if(ENABLE_COVERAGE) add_coverage(xc_) endif() +# The XC evaluators (v_xc, v_xc_libxc, v_xc_meta) and Stress_Func::stress_gga add rVV10 through this adapter. +target_sources(xc_ PRIVATE ../module_vdw/nonlocal_xc.cpp ../module_vdw/rvv10_kernel.cpp) + if(BUILD_TESTING) if(ENABLE_MPI) if(ENABLE_LIBXC) diff --git a/source/source_hamilt/module_xc/libxc_pot.cpp b/source/source_hamilt/module_xc/libxc_pot.cpp index fd2babcf957..0982e2794de 100644 --- a/source/source_hamilt/module_xc/libxc_pot.cpp +++ b/source/source_hamilt/module_xc/libxc_pot.cpp @@ -10,6 +10,7 @@ #ifdef __EXX #include "source_hamilt/module_xc/exx_info.h" #endif +#include "source_hamilt/module_vdw/nonlocal_xc.h" #include @@ -537,6 +538,8 @@ std::tuple XC_Functional_Libxc::v_xc_libxc( etxc *= omega / chr->rhopw->nxyz; vtxc *= omega / chr->rhopw->nxyz; + const XCFunctionalParameters &xc_parameters = XC_Functional::get_runtime_parameters(); + vdw::add_rvv10(xc_parameters, *chr, etxc, vtxc, v); XC_Functional_Libxc::finish_func(funcs); @@ -851,6 +854,8 @@ std::tuple XC_Functional etxc *= omega / chr->rhopw->nxyz; vtxc *= omega / chr->rhopw->nxyz; + const XCFunctionalParameters &xc_parameters = XC_Functional::get_runtime_parameters(); + vdw::add_rvv10(xc_parameters, *chr, etxc, vtxc, v); XC_Functional_Libxc::finish_func(funcs); diff --git a/source/source_hamilt/module_xc/test/CMakeLists.txt b/source/source_hamilt/module_xc/test/CMakeLists.txt index b47f67d6193..e6e82411b8d 100644 --- a/source/source_hamilt/module_xc/test/CMakeLists.txt +++ b/source/source_hamilt/module_xc/test/CMakeLists.txt @@ -1,3 +1,6 @@ +# These targets compile an XC evaluator without the plane-wave basis, so they take the empty rVV10 hooks. +abacus_disable_feature_definitions(__RVV10) + addtest( TARGET MODULE_HAMILT_RpaCutoffConfig LIBS parameter base device diff --git a/source/source_hamilt/module_xc/xc_functional.h b/source/source_hamilt/module_xc/xc_functional.h index 0e609ae32a3..9d47bb6977f 100644 --- a/source/source_hamilt/module_xc/xc_functional.h +++ b/source/source_hamilt/module_xc/xc_functional.h @@ -38,6 +38,10 @@ struct XCFunctionalParameters std::vector exx_erfc_alpha = {"default"}; std::vector xc_exch_ext; std::vector xc_corr_ext; + /// rVV10 nonlocal correlation (vdw_method rvv10) added to any functional, and its parameters b and C + bool rvv10 = false; + double rvv10_b = 0.0; + double rvv10_c = 0.0; }; class XC_Functional diff --git a/source/source_hamilt/module_xc/xc_pot.cpp b/source/source_hamilt/module_xc/xc_pot.cpp index d6f6adaa515..04aab7c89ac 100644 --- a/source/source_hamilt/module_xc/xc_pot.cpp +++ b/source/source_hamilt/module_xc/xc_pot.cpp @@ -16,6 +16,7 @@ #include "source_hamilt/module_xc/exx_info.h" #endif #endif +#include "source_hamilt/module_vdw/nonlocal_xc.h" // [etxc, vtxc, v] = XC_Functional::v_xc(...) std::tuple XC_Functional::v_xc( @@ -60,7 +61,13 @@ std::tuple XC_Functional::v_xc( // Evaluate the regularized mapped-density local-collinear graph. if (nspin == 4 && (domag || domag_z) && gga_grad == 2) { - return ModuleXC::NCGGA_SF_Builtin::v_xc_ncgga_sf_builtin(nrxx, ucell->omega, ucell->tpiba, chr); + std::tuple etxc_vtxc_v = + ModuleXC::NCGGA_SF_Builtin::v_xc_ncgga_sf_builtin(nrxx, ucell->omega, ucell->tpiba, chr); + double &etxc = std::get<0>(etxc_vtxc_v); + double &vtxc = std::get<1>(etxc_vtxc_v); + ModuleBase::matrix &v = std::get<2>(etxc_vtxc_v); + vdw::add_rvv10(runtime_parameters, *chr, etxc, vtxc, v); + return etxc_vtxc_v; } ModuleBase::timer::start("XC_Functional", "v_xc"); @@ -211,6 +218,7 @@ std::tuple XC_Functional::v_xc( #endif etxc *= ucell->omega / chr->rhopw->nxyz; vtxc *= ucell->omega / chr->rhopw->nxyz; + vdw::add_rvv10(runtime_parameters, *chr, etxc, vtxc, v); ModuleBase::timer::end("XC_Functional", "v_xc"); return std::make_tuple(etxc, vtxc, std::move(v)); diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 5d21f6d7b61..76cbe180c64 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -662,6 +662,8 @@ struct Input_para std::string vdw_cn_thr_unit = "Bohr"; ///< unit of cn_thr, Bohr or Angstrom std::string vdw_d4_xc = "default"; ///< functional name passed to DFT-D4 std::string vdw_d4_model = "d4"; ///< DFT-D4 dispersion model (d4 or d4s) + double rvv10_b = 6.3; ///< rVV10 parameter b + double rvv10_c = 0.0093; ///< rVV10 parameter C ModuleBase::Vector3 vdw_cutoff_period = {3, 3, 3}; ///< periods of periodic structure // ============== #Parameters (15.exx) ==================== diff --git a/source/source_io/module_parameter/read_inp_model.cpp b/source/source_io/module_parameter/read_inp_model.cpp index 526448c995d..0b8f2c67a83 100644 --- a/source/source_io/module_parameter/read_inp_model.cpp +++ b/source/source_io/module_parameter/read_inp_model.cpp @@ -264,8 +264,12 @@ void ReadInput::item_model() // vdW Correction { Input_Item item("vdw_method"); - item.domain.set_choices({"none", "d2", "d3_0", "d3_bj", "d4"}); - item.annotation = "the method of calculating vdw (none ; d2 ; d3_0 ; d3_bj ; d4)"; + item.domain.set_choices({"none", "d2", "d3_0", "d3_bj", "d4", "rvv10"}); + // The rVV10 response kernel needed by DFPT and LR-TDDFT forces is not implemented. + item.domain.add_requirement( + "vdw_method==rvv10", + "esolver_type!=dfpt and (cal_force==false or (esolver_type!=lr and esolver_type!=ks-lr))"); + item.annotation = "the method of calculating vdw (none ; d2 ; d3_0 ; d3_bj ; d4 ; rvv10)"; item.category = "vdW correction"; item.type = "String"; item.description = R"(Specifies the method used for Van der Waals (VdW) correction. Available options are: @@ -273,9 +277,12 @@ void ReadInput::item_model() * d3_0: Grimme's DFT-D3(0) dispersion correction method (zero-damping) * d3_bj: Grimme's DFTD3(BJ) dispersion correction method (BJ-damping) * d4: Grimme's DFT-D4 dispersion correction method using the external DFT-D4 library +* rvv10: rVV10 nonlocal correlation evaluated self-consistently and added to the exchange-correlation energy, potential, forces and stress of dft_functional; see rvv10_b and rvv10_c * none: no vdW correction -[NOTE] ABACUS automatically loads DFT-D3 parameters for supported functionals according to dft_functional setting. Individual user values overwrite the corresponding tabulated values. Setting all four of vdw_s6, vdw_s8, vdw_a1 and vdw_a2 defines a fully custom set and bypasses functional lookup.)"; +[NOTE] ABACUS automatically loads DFT-D3 parameters for supported functionals according to dft_functional setting. Individual user values overwrite the corresponding tabulated values. Setting all four of vdw_s6, vdw_s8, vdw_a1 and vdw_a2 defines a fully custom set and bypasses functional lookup. + +[NOTE] vdw_method rvv10 does not support DFPT or LR-TDDFT forces. LR-TDDFT spectra use the kernel selected by xc_kernel, without the rVV10 response.)"; item.default_value = "none"; item.unit = ""; read_sync_string(input.vdw_method); @@ -310,6 +317,34 @@ Available options are: read_sync_string(input.vdw_d4_model); this->add_item(item); } + { + Input_Item item("rvv10_b"); + item.domain.set_rule("value>0"); + item.annotation = "rVV10 parameter b"; + item.category = "vdW correction"; + item.type = "Real"; + item.description + = R"(Parameter b of rVV10, which sets the short-range damping. Choose the value published for the intended functional: 6.3 of the original rVV10 (rPW86-PBE), 15.7 for SCAN, 11.95 for r2SCAN.)"; + item.default_value = "6.3"; + item.unit = ""; + item.set_availability("vdw_method==rvv10"); + read_sync_double(input.rvv10_b); + this->add_item(item); + } + { + Input_Item item("rvv10_c"); + item.domain.set_rule("value>=0"); + item.annotation = "rVV10 parameter C"; + item.category = "vdW correction"; + item.type = "Real"; + item.description = "Parameter C of rVV10, which sets the gradient dependence of the local polarizability; " + "0.0093 in the original rVV10 and in the SCAN and r2SCAN parametrizations."; + item.default_value = "0.0093"; + item.unit = ""; + item.set_availability("vdw_method==rvv10"); + read_sync_double(input.rvv10_c); + this->add_item(item); + } { Input_Item item("vdw_s6"); item.annotation = "scale parameter of d2/d3_0/d3_bj"; @@ -548,7 +583,8 @@ Namely, each line contains the element name and the corresponding parameter.)"; } }; item.check_value = [](const Input_Item& item, const Parameter& para) { - if (std::stod(para.input.vdw_cutoff_radius) <= 0 && para.input.vdw_method != "none") + if (std::stod(para.input.vdw_cutoff_radius) <= 0 && para.input.vdw_method != "none" + && para.input.vdw_method != "rvv10") { ModuleBase::WARNING_QUIT("ReadInput", "vdw_cutoff_radius <= 0 is not allowd"); } diff --git a/source/source_io/unittests/CMakeLists.txt b/source/source_io/unittests/CMakeLists.txt index 491a2e022b2..439342a1b41 100644 --- a/source/source_io/unittests/CMakeLists.txt +++ b/source/source_io/unittests/CMakeLists.txt @@ -67,6 +67,7 @@ foreach( duplicate_string_eof invalid_value invalid_dependency + rvv10_lr_relax unsupported_libxc_cuda dftu_default dftu_fll @@ -125,6 +126,15 @@ addtest( # io_input references stru_frame_io::extract_last_frame without linking cell. ../../source_cell/stru_frame_io.cpp) +addtest( + TARGET MODULE_IO_test_read_inp_model + LIBS parameter base device io_input + SOURCES + test_read_inp_model.cpp + ../../source_base/test/mpi_test_main.cpp + # io_input references stru_frame_io::extract_last_frame without linking cell. + ../../source_cell/stru_frame_io.cpp) + add_test( NAME MODULE_IO_input_test_para_4 COMMAND mpirun -np 4 "$" diff --git a/source/source_io/unittests/test_read_inp_model.cpp b/source/source_io/unittests/test_read_inp_model.cpp new file mode 100644 index 00000000000..efca3e4b24d --- /dev/null +++ b/source/source_io/unittests/test_read_inp_model.cpp @@ -0,0 +1,118 @@ +// read_inp_model.cpp: the rVV10 INPUT items. vdw_method accepts rvv10 and declares the unsupported DFPT and +// LR-TDDFT force calculations; rvv10_b and rvv10_c have defaults and domains. Complete INPUT files are read +// for valid input; invalid values are checked on the declared domains, because a rejected INPUT ends the +// process in an MPI build. +#include "source_io/module_parameter/parameter.h" +#include "source_io/module_parameter/read_input.h" + +#include "gtest/gtest.h" +#include +#include +#include +#include +#include + +/// Parameter grants this class write access to its INPUT values (see parameter.h). +class TestParameters +{ + public: + static Input_para &input(Parameter ¶m) { return param.input; } +}; + +namespace +{ + +/// The INPUT items by label. +std::map input_items() +{ + ModuleIO::ReadInput reader(0); + std::map items; + for (const std::pair &entry : reader.get_input_lists()) + { + items.emplace(entry.first, entry.second); + } + return items; +} + +/// Domain and requirement errors of item for the values in param, as read_parameters reports them. +std::string domain_errors(const ModuleIO::Input_Item &item, const Parameter ¶m) +{ + ModuleIO::ReadInput schema(0); + ModuleIO::InputValues values; + for (const std::pair &entry : schema.get_input_lists()) + { + if (entry.second.domain.bound()) + { + values[entry.first] = entry.second.domain.value(param); + } + } + std::string errors = item.domain.validate_resolved(item.label, values); + errors += item.domain.validate_requirements(item.label, values); + return errors; +} + +/// Writes parameters to an INPUT file and reads it. +void read_input(const std::string ¶meters, Parameter ¶m) +{ + const std::string filename = testing::TempDir() + "rvv10_INPUT"; + { + std::ofstream input(filename.c_str()); + input << "INPUT_PARAMETERS\n" << parameters; + } + // the test runs on one process + ModuleIO::ReadInput reader(0); + reader.check_ntype_flag = false; + reader.read_parameters(param, filename); + std::remove(filename.c_str()); +} + +} // namespace + +TEST(ReadInpModelRvv10, ReadsTheParameters) +{ + Parameter param; + read_input("vdw_method rvv10\ndft_functional scan\nrvv10_b 15.7\ncalculation cell-relax\n", param); + EXPECT_EQ(param.inp.vdw_method, "rvv10"); + EXPECT_DOUBLE_EQ(param.inp.rvv10_b, 15.7); + EXPECT_DOUBLE_EQ(param.inp.rvv10_c, 0.0093); + Parameter defaults; + read_input("vdw_method rvv10\n", defaults); + EXPECT_DOUBLE_EQ(defaults.inp.rvv10_b, 6.3); + EXPECT_DOUBLE_EQ(defaults.inp.rvv10_c, 0.0093); +} + +TEST(ReadInpModelRvv10, DeclaresTheUnsupportedCalculationsAndTheDomains) +{ + const std::map items = input_items(); + const ModuleIO::Input_Item &method = items.at("vdw_method"); + EXPECT_TRUE(method.domain.validate_explicit("vdw_method", {"rvv10"}).empty()); + EXPECT_FALSE(method.domain.validate_explicit("vdw_method", {"RVV10"}).empty()); + + Parameter param; + Input_para &input = TestParameters::input(param); + input.vdw_method = "rvv10"; + EXPECT_TRUE(domain_errors(method, param).empty()); + input.esolver_type = "dfpt"; + EXPECT_NE(domain_errors(method, param).find("Requires esolver_type!=dfpt"), std::string::npos); + // LR-TDDFT forces; relax and cell-relax set cal_force, which the requirement sees + for (const std::string esolver : {"lr", "ks-lr"}) + { + input.esolver_type = esolver; + input.cal_force = true; + EXPECT_FALSE(domain_errors(method, param).empty()) << esolver; + input.cal_force = false; + EXPECT_TRUE(domain_errors(method, param).empty()) << esolver; + } + + const ModuleIO::Input_Item &b = items.at("rvv10_b"); + const ModuleIO::Input_Item &c = items.at("rvv10_c"); + Parameter rvv10; + Input_para &rvv10_input = TestParameters::input(rvv10); + rvv10_input.vdw_method = "rvv10"; + EXPECT_TRUE(domain_errors(b, rvv10).empty()); + EXPECT_TRUE(domain_errors(c, rvv10).empty()); + rvv10_input.rvv10_b = 0.0; + rvv10_input.rvv10_c = -0.1; + EXPECT_FALSE(domain_errors(b, rvv10).empty()); + EXPECT_FALSE(domain_errors(c, rvv10).empty()); +} diff --git a/source/source_io/unittests/test_read_input.cmake b/source/source_io/unittests/test_read_input.cmake index 78d13883fc2..a9a153a9fb1 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -31,21 +31,35 @@ elseif(INPUT_CASE STREQUAL "invalid_dependency") string(APPEND contents "nspin 2\nnoncolin true\n") set(expected "Requires nspin==4") set(expected_manual "input-main.html#nspin") +elseif(INPUT_CASE STREQUAL "rvv10_lr_relax") + # relax turns the forces on before the requirement of vdw_method rvv10 is + # checked, so LR-TDDFT relaxation is rejected without an explicit cal_force. + string(APPEND contents + "vdw_method rvv10\nesolver_type ks-lr\ncalculation relax\n") + set(expected "Requires esolver_type!=dfpt") + set(expected_manual "input-main.html#vdw-method") elseif(INPUT_CASE STREQUAL "unsupported_libxc_cuda") string(APPEND contents "device gpu\ndevice_xc gpu\n") - set(expected "device_xc gpu requires ABACUS built with -DENABLE_LIBXC_CUDA=ON.") + set(expected + "device_xc gpu requires ABACUS built with -DENABLE_LIBXC_CUDA=ON.") set(expected_manual "input-main.html#device-xc") elseif(INPUT_CASE STREQUAL "out_dmk_zero_precision") string(APPEND contents "out_dmk 1 0\n") - set(expected "Invalid INPUT parameter 'out_dmk': precision must be a positive integer.") + set(expected + "Invalid INPUT parameter 'out_dmk': precision must be a positive integer." + ) set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_hsk_zero_precision") string(APPEND contents "out_hsk 1 0\n") - set(expected "Invalid INPUT parameter 'out_hsk': precision must be a positive integer.") + set(expected + "Invalid INPUT parameter 'out_hsk': precision must be a positive integer." + ) set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_tk_zero_precision") string(APPEND contents "out_mat_tk 1 0\n") - set(expected "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer.") + set(expected + "Invalid INPUT parameter 'out_mat_tk': precision must be a positive integer." + ) set(expected_manual "") elseif(INPUT_CASE STREQUAL "out_mat_p_invalid_boolean") string(APPEND contents "out_mat_p maybe\n") diff --git a/source/source_pw/module_pwdft/stress_gga.cpp b/source/source_pw/module_pwdft/stress_gga.cpp index 375f790c7c4..1b38ee3be7e 100644 --- a/source/source_pw/module_pwdft/stress_gga.cpp +++ b/source/source_pw/module_pwdft/stress_gga.cpp @@ -1,4 +1,5 @@ #include "source_base/parallel_reduce.h" +#include "source_hamilt/module_vdw/nonlocal_xc.h" #include "source_hamilt/module_xc/xc_functional.h" #include "stress_func.h" @@ -16,6 +17,9 @@ void Stress_Func::stress_gga( { ModuleBase::TITLE("Stress", "stress_gga"); ModuleBase::timer::start("Stress", "stress_gga"); + // rVV10 is added before the LDA return below; stress_gga is the XC stress hook of PW, LCAO, SDFT and OFDFT + const XCFunctionalParameters &xc_parameters = XC_Functional::get_runtime_parameters(); + vdw::add_rvv10_stress(xc_parameters, *chr, sigma); int func_type = XC_Functional::get_func_type(); if (func_type == 0 || func_type == 1) diff --git a/tests/01_PW/215_PW_rvv10_GaAs/INPUT b/tests/01_PW/215_PW_rvv10_GaAs/INPUT new file mode 100644 index 00000000000..9e1249ed47e --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/INPUT @@ -0,0 +1,18 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +pseudo_dir ../../PP_ORB +basis_type pw +nspin 2 +ecutwfc 30 +scf_thr 1e-8 +scf_nmax 100 +dft_functional pbe +vdw_method rvv10 +rvv10_b 6.3 +cal_force 1 +cal_stress 1 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 diff --git a/tests/01_PW/215_PW_rvv10_GaAs/KPT b/tests/01_PW/215_PW_rvv10_GaAs/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/01_PW/215_PW_rvv10_GaAs/README b/tests/01_PW/215_PW_rvv10_GaAs/README new file mode 100644 index 00000000000..604654fbda3 --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/README @@ -0,0 +1,2 @@ +rVV10 (vdw_method rvv10) on native PBE for GaAs with NLCC pseudopotentials and two spin channels: energy, forces, stress. Reference from 4 MPI ranks. +The native XC path is used on purpose: in PW, the stress of a libxc functional with NLCC pseudopotentials counts the core term twice (a separate, pre-existing issue). diff --git a/tests/01_PW/215_PW_rvv10_GaAs/STRU b/tests/01_PW/215_PW_rvv10_GaAs/STRU new file mode 100644 index 00000000000..f7e0c21fe40 --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/STRU @@ -0,0 +1,24 @@ +ATOMIC_SPECIES +Ga 69.723 Ga_dojo_nsoc.upf +As 74.922 As_dojo_nsoc.upf + +LATTICE_CONSTANT +1.8897261246 + +LATTICE_VECTORS +0.0000 2.8265 2.8265 +2.8265 0.0000 2.8265 +2.8265 2.8265 0.0000 + +ATOMIC_POSITIONS +Direct + +Ga +0.0 +1 +0.00 0.00 0.00 1 1 1 + +As +0.0 +1 +0.26 0.25 0.24 1 1 1 diff --git a/tests/01_PW/215_PW_rvv10_GaAs/result.ref b/tests/01_PW/215_PW_rvv10_GaAs/result.ref new file mode 100644 index 00000000000..c7e88b9b52f --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/result.ref @@ -0,0 +1,5 @@ +etotref -4652.4581712440922274 +etotperatomref -2326.2290856220 +totalforceref 2.113614 +totalstressref 64465.536061 +totaltimeref 1.39 diff --git a/tests/01_PW/216_PW_rvv10_graphite/INPUT b/tests/01_PW/216_PW_rvv10_graphite/INPUT new file mode 100644 index 00000000000..a626ecd83b6 --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/INPUT @@ -0,0 +1,16 @@ +INPUT_PARAMETERS +suffix autotest +calculation scf +pseudo_dir ../../PP_ORB +basis_type pw +ecutwfc 40 +scf_thr 1e-8 +scf_nmax 100 +dft_functional GGA_X_RPW86+GGA_C_PBE +vdw_method rvv10 +cal_force 1 +cal_stress 1 +smearing_method gaussian +smearing_sigma 0.01 +mixing_type broyden +mixing_beta 0.4 diff --git a/tests/01_PW/216_PW_rvv10_graphite/KPT b/tests/01_PW/216_PW_rvv10_graphite/KPT new file mode 100644 index 00000000000..6f37ec747ed --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +3 3 2 0 0 0 diff --git a/tests/01_PW/216_PW_rvv10_graphite/README b/tests/01_PW/216_PW_rvv10_graphite/README new file mode 100644 index 00000000000..020adcfdc29 --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/README @@ -0,0 +1,2 @@ +rVV10 (vdw_method rvv10) on rPW86-PBE through libxc for AB graphite with one atom displaced: energy, forces, stress in PW. +Needs ENABLE_LIBXC; reference from 4 MPI ranks. diff --git a/tests/01_PW/216_PW_rvv10_graphite/STRU b/tests/01_PW/216_PW_rvv10_graphite/STRU new file mode 100644 index 00000000000..580355c202d --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +C 12.011 C_ONCV_PBE-1.0.upf + +LATTICE_CONSTANT +1.8897261246 + +LATTICE_VECTORS +2.4640000000 0.0000000000 0.0000000000 +-1.2320000000 2.1338945522 0.0000000000 +0.0000000000 0.0000000000 6.7000000000 + +ATOMIC_POSITIONS +Direct + +C +0.0 +4 +0.0000000000 0.0000000000 0.2500000000 1 1 1 +0.0000000000 0.0000000000 0.7500000000 1 1 1 +0.3333333333 0.6666666667 0.2700000000 1 1 1 +0.6666666667 0.3333333333 0.7500000000 1 1 1 diff --git a/tests/01_PW/216_PW_rvv10_graphite/result.ref b/tests/01_PW/216_PW_rvv10_graphite/result.ref new file mode 100644 index 00000000000..ef93dbb924d --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/result.ref @@ -0,0 +1,5 @@ +etotref -618.5486802937051607 +etotperatomref -154.6371700734 +totalforceref 4.093673 +totalstressref 639.346655 +totaltimeref 1.33 diff --git a/tests/01_PW/CASES_CPU.txt b/tests/01_PW/CASES_CPU.txt index cc7571cd590..5723e33929c 100644 --- a/tests/01_PW/CASES_CPU.txt +++ b/tests/01_PW/CASES_CPU.txt @@ -140,3 +140,4 @@ scf_sccs_sa scf_sccs_sa_pcc_2d_lowpass dfpt_si_g dfpt_si_g_symm +215_PW_rvv10_GaAs diff --git a/tests/01_PW/CASES_LIBXC.txt b/tests/01_PW/CASES_LIBXC.txt new file mode 100644 index 00000000000..eff3c4e3bd0 --- /dev/null +++ b/tests/01_PW/CASES_LIBXC.txt @@ -0,0 +1 @@ +216_PW_rvv10_graphite diff --git a/tests/01_PW/CMakeLists.txt b/tests/01_PW/CMakeLists.txt index dd47e77df86..c62c9ad5d49 100644 --- a/tests/01_PW/CMakeLists.txt +++ b/tests/01_PW/CMakeLists.txt @@ -12,3 +12,12 @@ else() COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto WORKING_DIRECTORY ${ABACUS_TEST_DIR}/01_PW) endif() + +# rVV10 with the Libxc functional rPW86-PBE +if(ENABLE_LIBXC) + add_test( + NAME 01_PW_libxc + COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto + -f CASES_LIBXC.txt + WORKING_DIRECTORY ${ABACUS_TEST_DIR}/01_PW) +endif() diff --git a/tests/03_NAO_multik/CASES_LIBXC.txt b/tests/03_NAO_multik/CASES_LIBXC.txt new file mode 100644 index 00000000000..50341037c7c --- /dev/null +++ b/tests/03_NAO_multik/CASES_LIBXC.txt @@ -0,0 +1 @@ +relax_cell_rvv10 diff --git a/tests/03_NAO_multik/CMakeLists.txt b/tests/03_NAO_multik/CMakeLists.txt index c881d60dd0d..b09a6091de3 100644 --- a/tests/03_NAO_multik/CMakeLists.txt +++ b/tests/03_NAO_multik/CMakeLists.txt @@ -12,3 +12,12 @@ else() COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto WORKING_DIRECTORY ${ABACUS_TEST_DIR}/03_NAO_multik) endif() + +# rVV10 with the Libxc functional rPW86-PBE +if(ENABLE_LIBXC) + add_test( + NAME 03_NAO_multik_libxc + COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto + -f CASES_LIBXC.txt + WORKING_DIRECTORY ${ABACUS_TEST_DIR}/03_NAO_multik) +endif() diff --git a/tests/03_NAO_multik/relax_cell_rvv10/INPUT b/tests/03_NAO_multik/relax_cell_rvv10/INPUT new file mode 100644 index 00000000000..7b0c92086b2 --- /dev/null +++ b/tests/03_NAO_multik/relax_cell_rvv10/INPUT @@ -0,0 +1,23 @@ +INPUT_PARAMETERS + +ecutwfc 10 +scf_thr 1e-06 +scf_nmax 400 +basis_type lcao +ks_solver scalapack_gvx +smearing_method gaussian +relax_nmax 1 +smearing_sigma 0.02 +mixing_type broyden +mixing_beta 0.7 +vdw_method rvv10 +fixed_axes c +force_thr_ev 0.005 +stress_thr 0.1 +suffix autotest +calculation cell-relax +cal_force 1 +cal_stress 1 +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +dft_functional GGA_X_RPW86+GGA_C_PBE diff --git a/tests/03_NAO_multik/relax_cell_rvv10/KPT b/tests/03_NAO_multik/relax_cell_rvv10/KPT new file mode 100644 index 00000000000..6c7f2228767 --- /dev/null +++ b/tests/03_NAO_multik/relax_cell_rvv10/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Monkhorst-Pack +2 2 1 0 0 0 diff --git a/tests/03_NAO_multik/relax_cell_rvv10/README b/tests/03_NAO_multik/relax_cell_rvv10/README new file mode 100644 index 00000000000..72d1f5cf124 --- /dev/null +++ b/tests/03_NAO_multik/relax_cell_rvv10/README @@ -0,0 +1,2 @@ +One cell-relaxation step of SnTe in LCAO (relax_cell_vdw4_d4 with rVV10 instead of D4): energy, forces, stress through the LCAO grid. +Needs ENABLE_LIBXC; reference from 4 MPI ranks. diff --git a/tests/03_NAO_multik/relax_cell_rvv10/STRU b/tests/03_NAO_multik/relax_cell_rvv10/STRU new file mode 100644 index 00000000000..3097ac7b691 --- /dev/null +++ b/tests/03_NAO_multik/relax_cell_rvv10/STRU @@ -0,0 +1,28 @@ +ATOMIC_SPECIES +Sn 118.710 Sn_ONCV_PBE-1.0.upf +Te 127.603 Te_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +Sn_pbe_9.0au_100Ry_2s2p2d +Te_pbe_9.0au_100Ry_2s2p2d + +LATTICE_CONSTANT +1.89035917 + +LATTICE_VECTORS +4.646 0 0 #latvec1 +0 4.561 0 #latvec2 +0 0 16.32 #latvec3 + +ATOMIC_POSITIONS +Direct + +Sn #label +0 #magnetism +1 #number of atoms +0.5493 0.5000000000000000 0.2 1 1 1 + +Te #label +0 #magnetism +1 #number of atoms +0.0000000000000000 0.0000000000000000 0.2 1 1 1 diff --git a/tests/03_NAO_multik/relax_cell_rvv10/result.ref b/tests/03_NAO_multik/relax_cell_rvv10/result.ref new file mode 100644 index 00000000000..06bf02ef38b --- /dev/null +++ b/tests/03_NAO_multik/relax_cell_rvv10/result.ref @@ -0,0 +1,5 @@ +etotref -4139.0556719590958892 +etotperatomref -2069.5278359795 +totalforceref 0.816192 +totalstressref 17.631915 +totaltimeref 1.49