diff --git a/CMakeLists.txt b/CMakeLists.txt index d224ee9acba..73b701ca42f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,7 @@ option(ENABLE_ABACUS_LIBM "Build libmath from source for old systems" OFF) option(ENABLE_FLOAT_FFTW "Enable using single-precision FFTW library." OFF) option(ENABLE_LIBXC "Enable using the LibXC package" OFF) +option(ENABLE_LIBVDWXC "Enable using the libvdwxc package" OFF) option(ENABLE_DFTD4 "Enable DFT-D4 dispersion correction" OFF) option(ENABLE_PLUMED "Enable using the PLUMED enhanced-sampling library" OFF) option(ENABLE_JSON "Enable JSON output" OFF) @@ -240,6 +241,10 @@ if(ENABLE_DFTD4 OR ENABLE_PEXSI) enable_language(C) enable_language(Fortran) endif() +# The libvdwxc package configuration looks up MPI for C when libvdwxc was built with MPI. +if(ENABLE_LIBVDWXC) + enable_language(C) +endif() macro(set_if_higher VARIABLE VALUE) if(${VARIABLE} LESS ${VALUE}) @@ -605,6 +610,24 @@ if(ENABLE_LIBXC) endif() endif() +if(ENABLE_LIBVDWXC) + find_package(libvdwxc CONFIG REQUIRED) + # An MPI build calls vdwxc_init_mpi, which only an MPI-enabled libvdwxc provides. + if(ENABLE_MPI AND NOT VDWXC_ENABLE_MPI) + message( + FATAL_ERROR + "ENABLE_LIBVDWXC with ENABLE_MPI requires libvdwxc configured with -DVDWXC_ENABLE_MPI=ON" + ) + endif() + # vdwxc_init_mpi creates FFTW-MPI plans, which the FFTW interface of MKL or KML cannot execute. + if(ENABLE_MPI AND (MKL_FOUND OR USE_KML)) + message( + FATAL_ERROR + "ENABLE_LIBVDWXC with ENABLE_MPI requires ABACUS built with FFTW3, not with the FFTW interface of MKL or KML" + ) + endif() +endif() + if(DEFINED DeePMD_DIR) find_package(DeePMD REQUIRED) endif() diff --git a/cmake/CollectBuildInfoVars.cmake b/cmake/CollectBuildInfoVars.cmake index 94cfd82fb32..904d28f74b9 100644 --- a/cmake/CollectBuildInfoVars.cmake +++ b/cmake/CollectBuildInfoVars.cmake @@ -192,6 +192,12 @@ else() set(ABACUS_DFTD4_VERSION "no") endif() +if(ENABLE_LIBVDWXC) + set(ABACUS_LIBVDWXC_VERSION "yes (v${libvdwxc_VERSION})") +else() + set(ABACUS_LIBVDWXC_VERSION "no") +endif() + # Accelerators if(USE_CUDA AND CUDAToolkit_VERSION) set(ABACUS_CUDA_VERSION "yes (v${CUDAToolkit_VERSION})") @@ -480,6 +486,7 @@ message(" Features : Libxc = ${ABACUS_LIBXC_VERSION}") message(" LibRI = ${ABACUS_LIBRI_VERSION}") message(" LibRI GPU = ${ENABLE_LIBRI_GPU}") message(" DFT-D4 = ${ABACUS_DFTD4_VERSION}") +message(" libvdwxc = ${ABACUS_LIBVDWXC_VERSION}") message(" JSON = ${ABACUS_JSON_VERSION}") message(" PEXSI = ${ABACUS_PEXSI_VERSION}") message(" CNPY = ${ABACUS_CNPY_VERSION}") diff --git a/docs/CITATIONS.md b/docs/CITATIONS.md index 43176829a1d..88a32d7fccd 100644 --- a/docs/CITATIONS.md +++ b/docs/CITATIONS.md @@ -55,3 +55,13 @@ 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. + + A. H. Larsen, M. Kuisma, J. Löfgren, Y. Pouillon, P. Erhart, and P. Hyldgaard. "libvdwxc: a library for exchange-correlation functionals in the vdW-DF family." Modelling and Simulation in Materials Science and Engineering 25, 065004 (2017). DOI: 10.1088/1361-651X/aa7320. + + For SCAN+rVV10 and r2SCAN+rVV10, also cite the parametrization: H. Peng, Z.-H. Yang, J. P. Perdew, and J. Sun. "Versatile van der Waals density functional based on a meta-generalized gradient approximation." Physical Review X 6, 041005 (2016). DOI: 10.1103/PhysRevX.6.041005; J. Ning, M. Kothakonda, J. W. Furness, A. D. Kaplan, S. Ehlert, J. G. Brandenburg, J. P. Perdew, and J. Sun. "Workhorse minimally empirical dispersion-corrected density functional with tests for weakly bound systems: r2SCAN+rVV10." Physical Review B 106, 075422 (2022). DOI: 10.1103/PhysRevB.106.075422. diff --git a/docs/advanced/install.md b/docs/advanced/install.md index 1d786c03b20..7085eae112d 100644 --- a/docs/advanced/install.md +++ b/docs/advanced/install.md @@ -161,6 +161,25 @@ vdw_d4_model d4 # or d4s for the smooth D4S model If `vdw_d4_xc` is set to `default`, ABACUS will infer the functional name from `dft_functional` or pseudopotential metadata and pass it to the DFT-D4 library. The `vdw_d4_model` keyword selects the dispersion model inside the DFT-D4 library; the default is `d4`, while `d4s` enables the smooth D4S model. +## Build with libvdwxc support + +`vdw_method rvv10` evaluates the rVV10 nonlocal correlation with the external [libvdwxc](https://gitlab.com/libvdwxc/libvdwxc) library. Until a tagged libvdwxc release contains the rVV10 interface, build the branch of [libvdwxc merge request !32](https://gitlab.com/libvdwxc/libvdwxc/-/merge_requests/32) with libvdwxc's CMake build, which installs the package that ABACUS looks up, and against the FFTW that ABACUS uses. For an MPI build of ABACUS, configure libvdwxc with MPI, which needs FFTW with its MPI library: + +```bash +cmake -S libvdwxc -B build-libvdwxc -DBUILD_SHARED_LIBS=ON -DVDWXC_ENABLE_MPI=ON -DCMAKE_INSTALL_PREFIX=/path/to/libvdwxc +cmake --build build-libvdwxc && cmake --install build-libvdwxc +``` + +Then pass `-DENABLE_LIBVDWXC=ON` to CMake for ABACUS and add `/path/to/libvdwxc` to `CMAKE_PREFIX_PATH`. rVV10 works with the built-in functionals; functionals such as rPW86 (`GGA_X_RPW86+GGA_C_PBE`) or SCAN also need `-DENABLE_LIBXC=ON`. Each k-point pool evaluates the nonlocal convolution with libvdwxc's distributed interface; an evaluation needs about 300 bytes per grid point, shared by the processes of the pool and released afterwards. libvdwxc's MPI build plans its FFTs with FFTW-MPI, so an MPI build of ABACUS with libvdwxc must use FFTW3 rather than the FFTW interface of MKL or KML; CMake stops otherwise. The legacy Makefile does not build this feature. + +In the input file: + +```text +dft_functional GGA_X_RPW86+GGA_C_PBE +vdw_method rvv10 +vdw_rvv10_b 6.3 # optional; the default follows dft_functional for rPW86-PBE, SCAN and r2SCAN +``` + ## Build with JSON support ABACUS uses [nlohmann-json](https://github.com/nlohmann/json) for optional JSON output. To build ABACUS with JSON support, pass `-DENABLE_JSON=ON` to CMake. diff --git a/docs/advanced/scf/advanced.md b/docs/advanced/scf/advanced.md index a01280344bb..07501b93135 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 (requires [libvdwxc](../install.md#build-with-libvdwxc-support)). 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 `vdw_rvv10_b` depends on `dft_functional`. 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/docs/quick_start/easy_install.md b/docs/quick_start/easy_install.md index a770c49bd00..f50540d2fdd 100644 --- a/docs/quick_start/easy_install.md +++ b/docs/quick_start/easy_install.md @@ -163,13 +163,14 @@ Here, 'build' is the path for building ABACUS; and '-D' is used for setting up s - `LIBCOMM_DIR`: (Optional) Path to LibComm when `ENABLE_LIBRI=ON`. ```{important} -For some dependencies built with CMake, such as Libxc, dftd4, cereal, and nlohmann-json, you'll have to add their prefix paths to the environment variable `CMAKE_PREFIX_PATH` so that CMake can correctly find and use their CMake configuration files. A non-general variable such as `PKG_DIR` is discouraged for these packages. +For some dependencies built with CMake, such as Libxc, dftd4, libvdwxc, cereal, and nlohmann-json, you'll have to add their prefix paths to the environment variable `CMAKE_PREFIX_PATH` so that CMake can correctly find and use their CMake configuration files. A non-general variable such as `PKG_DIR` is discouraged for these packages. ``` - Components: The values of these variables should be 'ON', '1' or 'OFF', '0'. The default values are given below. - `ENABLE_LCAO=ON`: Enable LCAO calculation. If SCALAPACK, ELPA or CEREAL is absent and only require plane-wave calculations, the feature of calculating LCAO basis can be turned off. - `ENABLE_LIBXC=OFF`: [Enable Libxc](../advanced/install.md#add-libxc-support) to suppport variety of functionals. - `ENABLE_LIBRI=OFF`: [Enable LibRI](../advanced/install.md#add-libri-support) and its LibComm dependency for hybrid-functional calculations. Set `LIBRI_DIR` and `LIBCOMM_DIR` to use manually installed libraries. + - `ENABLE_LIBVDWXC=OFF`: [Enable libvdwxc](../advanced/install.md#build-with-libvdwxc-support) for the rVV10 nonlocal correlation (`vdw_method rvv10`). - `ENABLE_JSON=OFF`: [Enable JSON output](../advanced/install.md#build-with-json-support) through nlohmann-json. - `ENABLE_OPENMP=ON`: Enable OpenMP support. Building ABACUS without OpenMP is not fully tested yet. - `BUILD_TESTING=OFF`: [Build unit tests](../advanced/install.md#build-unit-tests). diff --git a/generate_build_info.sh b/generate_build_info.sh index 6b87ce6fbbb..72d0b209e56 100755 --- a/generate_build_info.sh +++ b/generate_build_info.sh @@ -293,6 +293,7 @@ sed \ -e "s#@ABACUS_OPENMP_VERSION@#$OPENMP_VERSION#g" \ -e "s#@ABACUS_MKL_SUPPORT@#$MKL_SUPPORT#g" \ -e "s#@ABACUS_LIBXC_VERSION@#$LIBXC_VERSION#g" \ + -e "s#@ABACUS_LIBVDWXC_VERSION@#no#g" \ -e "s#@ABACUS_FFTW_VERSION@#$FFTW3_VERSION#g" \ -e "s#@ABACUS_CUDA_VERSION@#$CUDA_VERSION#g" \ -e "s#@ABACUS_ROCM_VERSION@#$ROCM_VERSION#g" \ diff --git a/source/CMakeLists.txt b/source/CMakeLists.txt index d716756782e..31e5bf8a92c 100644 --- a/source/CMakeLists.txt +++ b/source/CMakeLists.txt @@ -69,6 +69,7 @@ set(_abacus_feature_definitions $<$:ABACUS_LIBXC_CUDA> $<$:ABACUS_LIBXC_REQUIRES_HOST_FLAG> $<$:__DFTD4> + $<$:__LIBVDWXC> $<$:__NEP> $<$:GATHER_INFO>) @@ -416,6 +417,7 @@ foreach( ELPA::ELPA Libxc::xc dftd4::dftd4 + libvdwxc::vdwxc DeePMD::deepmd_c DeePMD::deepmd_cc nep::nep_cpu diff --git a/source/source_base/parallel_device.cpp b/source/source_base/parallel_device.cpp index 8ba8c3ae8ed..9ca6bcbc6a1 100644 --- a/source/source_base/parallel_device.cpp +++ b/source/source_base/parallel_device.cpp @@ -350,6 +350,10 @@ void gatherv_data(const std::complex* sendbuf, int sendcount, std::comple { MPI_Allgatherv(sendbuf, sendcount, MPI_COMPLEX, recvbuf, recvcounts, displs, MPI_COMPLEX, comm); } +void alltoallv_data(const double* sendbuf, const int* sendcounts, const int* sdispls, double* recvbuf, const int* recvcounts, const int* rdispls, const MPI_Comm& comm) +{ + MPI_Alltoallv(sendbuf, sendcounts, sdispls, MPI_DOUBLE, recvbuf, recvcounts, rdispls, MPI_DOUBLE, comm); +} #ifndef __CUDA_MPI template diff --git a/source/source_base/parallel_device.h b/source/source_base/parallel_device.h index 7826e4b4653..ddd61d5b5c7 100644 --- a/source/source_base/parallel_device.h +++ b/source/source_base/parallel_device.h @@ -31,6 +31,7 @@ void gatherv_data(const double* sendbuf, int sendcount, double* recvbuf, const i void gatherv_data(const std::complex* sendbuf, int sendcount, std::complex* recvbuf, const int* recvcounts, const int* displs, MPI_Comm& comm); void gatherv_data(const float* sendbuf, int sendcount, float* recvbuf, const int* recvcounts, const int* displs, MPI_Comm& comm); void gatherv_data(const std::complex* sendbuf, int sendcount, std::complex* recvbuf, const int* recvcounts, const int* displs, MPI_Comm& comm); +void alltoallv_data(const double* sendbuf, const int* sendcounts, const int* sdispls, double* recvbuf, const int* recvcounts, const int* rdispls, const MPI_Comm& comm); #if defined(__NCCL_PARALLEL_DEVICE) void nccl_bcast_data(double* object, const int& n, MPI_Comm& comm, int root = 0); diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt index 5381e4f9f59..4670fc96d48 100644 --- a/source/source_base/unittests/CMakeLists.txt +++ b/source/source_base/unittests/CMakeLists.txt @@ -11,3 +11,17 @@ AddTest( LIBS parameter base device SOURCES test_filename.cpp ) + +# alltoallv_data is an MPI wrapper, so this target keeps __MPI. +addtest( + TARGET MODULE_BASE_test_parallel_device + LIBS MPI::MPI_CXX base device parameter + SOURCES test_parallel_device.cpp ../test/mpi_test_main.cpp + KEEP_FEATURE_DEFINITIONS __MPI) + +add_test( + NAME MODULE_BASE_test_parallel_device_np4 + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) +set_tests_properties(MODULE_BASE_test_parallel_device_np4 + PROPERTIES PROCESSORS 4 TIMEOUT 120) diff --git a/source/source_base/unittests/test_parallel_device.cpp b/source/source_base/unittests/test_parallel_device.cpp new file mode 100644 index 00000000000..70804033d8e --- /dev/null +++ b/source/source_base/unittests/test_parallel_device.cpp @@ -0,0 +1,45 @@ +// parallel_device.cpp: the all-to-all exchange used by the rVV10 adapter to move grid planes between distributions. +#include "source_base/parallel_device.h" + +#include "source_base/parallel_cell.h" + +#include "gtest/gtest.h" +#include + +TEST(ParallelDevice, AlltoallvExchangesUnevenBlocks) +{ + const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); + const MPI_Comm communicator = domain.communicator(); + const int rank = domain.rank(); + const int size = domain.size(); + // rank r sends (r + p) % 2 + 1 copies of 100 r + p to rank p + std::vector send_counts(size); + std::vector send_offsets(size); + std::vector recv_counts(size); + std::vector recv_offsets(size); + std::vector sent; + int received_total = 0; + for (int peer = 0; peer < size; ++peer) + { + const double value = 100.0 * rank + peer; + send_counts[peer] = (rank + peer) % 2 + 1; + send_offsets[peer] = static_cast(sent.size()); + sent.insert(sent.end(), send_counts[peer], value); + recv_counts[peer] = send_counts[peer]; + recv_offsets[peer] = received_total; + received_total += recv_counts[peer]; + } + std::vector received(received_total); + Parallel_Common::alltoallv_data( + sent.data(), send_counts.data(), send_offsets.data(), received.data(), recv_counts.data(), recv_offsets.data(), + communicator); + for (int peer = 0; peer < size; ++peer) + { + const double expected = 100.0 * peer + rank; + for (int index = 0; index < recv_counts[peer]; ++index) + { + const int position = recv_offsets[peer] + index; + EXPECT_EQ(received[position], expected); + } + } +} diff --git a/source/source_esolver/esolver_fp.cpp b/source/source_esolver/esolver_fp.cpp index 5af7569829f..d7509f36267 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.vdw_rvv10_b; + xc_parameters.rvv10_c = inp.vdw_rvv10_c; XC_Functional::set_runtime_parameters(xc_parameters); ModuleBase::TITLE("ESolver_FP", "before_all_runners"); 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..b8762ef8750 --- /dev/null +++ b/source/source_hamilt/module_vdw/nonlocal_xc.cpp @@ -0,0 +1,417 @@ +#include "nonlocal_xc.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" + +// vdwxc.h includes inside an extern "C" block. Include the C++ header first so that +// libc++ does not parse its templates with C linkage, then drop the I macro. +#include +#include +#include +#ifdef __MPI +#include +#endif +#undef I + +#include +#include +#include + +namespace vdw +{ +namespace +{ + +/// Cartesian components of the stress tensor returned by vdwxc_stress, 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; } + +/// z planes [begin, end) of the libvdwxc slab of process rank: FFTW-MPI blocks of ceil(nz / nproc) planes. +void libvdwxc_slab( + const int nz, + const int nproc, + const int rank, + int &begin, + int &end) +{ + const int block = (nz + nproc - 1) / nproc; + const int first_plane = rank * block; + begin = std::min(first_plane, nz); + const int block_end = begin + block; + end = std::min(block_end, nz); +} + +/** + * @brief Moves a field between the ABACUS distribution of pw and the libvdwxc slabs of the pool. + * + * libvdwxc gets the lattice vectors in the cyclic order (a3, a1, a2), so that the first axis of its grid is the + * z axis that ABACUS distributes. It splits that axis into blocks of ceil(nz/P) planes, the FFTW-MPI default; + * vdwxc_init_mpi does not report the local slab, so the same rule is applied here. The slab of a process is + * stored as [z][x][y], the transpose of the ABACUS layout [x][y][z], and whole z planes are moved between the + * two distributions by all-to-all exchanges. + */ +class SlabExchange +{ + public: + explicit SlabExchange(const ModulePW::PW_Basis &pw) : pw_(pw) + { + const int nproc = pw.poolnproc; + int slab_start = 0; + int slab_end = 0; + libvdwxc_slab(pw.nz, nproc, pw.poolrank, slab_start, slab_end); + const int plane_end = pw.startz_current + pw.nplane; + send_count_.assign(nproc, 0); + send_offset_.assign(nproc, 0); + recv_count_.assign(nproc, 0); + recv_offset_.assign(nproc, 0); + for (int ip = 0; nproc > 1 && ip < nproc; ++ip) + { + // ABACUS planes of this process that lie in the slab of ip + int slab_start_of_ip = 0; + int slab_end_of_ip = 0; + libvdwxc_slab(pw.nz, nproc, ip, slab_start_of_ip, slab_end_of_ip); + int low = std::max(pw.startz_current, slab_start_of_ip); + int high = std::min(plane_end, slab_end_of_ip); + if (high > low) + { + send_count_[ip] = (high - low) * pw.nxy; + send_offset_[ip] = (low - pw.startz_current) * pw.nxy; + } + // ABACUS planes of ip that lie in the slab of this process + const int plane_end_of_ip = pw.startz[ip] + pw.numz[ip]; + low = std::max(pw.startz[ip], slab_start); + high = std::min(plane_end_of_ip, slab_end); + if (high > low) + { + recv_count_[ip] = (high - low) * pw.nxy; + recv_offset_[ip] = (low - slab_start) * pw.nxy; + } + } + // libvdwxc expects valid pointers also for an empty slab + const int slab_points = (slab_end - slab_start) * pw.nxy; + slab_size_ = std::max(1, slab_points); + // the transposed ABACUS planes are only needed for the exchange between processes + const int planes_size = (nproc > 1) ? std::max(1, pw.nrxx) : 0; + planes_.resize(planes_size); + } + + /// Number of doubles of the libvdwxc slab of this process. + int slab_size() const { return slab_size_; } + + /// field on the nrxx points of this process to the libvdwxc slab + void to_slab(const std::vector &field, std::vector &slab) + { + std::vector &planes = (pw_.poolnproc > 1) ? planes_ : slab; +#ifdef _OPENMP +#pragma omp parallel for schedule(static) +#endif + for (int ixy = 0; ixy < pw_.nxy; ++ixy) + { + for (int iz = 0; iz < pw_.nplane; ++iz) + { + planes[iz * pw_.nxy + ixy] = field[ixy * pw_.nplane + iz]; + } + } +#ifdef __MPI + if (pw_.poolnproc > 1) + { + Parallel_Common::alltoallv_data( + planes_.data(), send_count_.data(), send_offset_.data(), slab.data(), recv_count_.data(), + recv_offset_.data(), pw_.pool_world); + } +#endif + } + + /// libvdwxc slab to field on the nrxx points of this process + void to_grid(const std::vector &slab, std::vector &field) + { +#ifdef __MPI + if (pw_.poolnproc > 1) + { + Parallel_Common::alltoallv_data( + slab.data(), recv_count_.data(), recv_offset_.data(), planes_.data(), send_count_.data(), + send_offset_.data(), pw_.pool_world); + } +#endif + const std::vector &planes = (pw_.poolnproc > 1) ? planes_ : slab; +#ifdef _OPENMP +#pragma omp parallel for schedule(static) +#endif + for (int ixy = 0; ixy < pw_.nxy; ++ixy) + { + for (int iz = 0; iz < pw_.nplane; ++iz) + { + field[ixy * pw_.nplane + iz] = planes[iz * pw_.nxy + ixy]; + } + } + } + + private: + const ModulePW::PW_Basis &pw_; + // planes moved to (send) and from (recv) each process, in doubles + std::vector send_count_; + std::vector send_offset_; + std::vector recv_count_; + std::vector recv_offset_; + int slab_size_ = 1; + // the ABACUS planes of this process as [z][xy] + std::vector planes_; +}; + +/** + * @brief rVV10 energy and derivatives of an ABACUS-distributed density, from libvdwxc. + * + * The libvdwxc object lives for this one evaluation, like the Libxc functionals of an XC evaluation: its + * kernel table is static and its FFT plans are FFTW_ESTIMATE plans, so making it is cheap next to the + * evaluation, and nothing is left to release at the end of the run. + * + * @param pw grid and pool of the density (chr.rhopw) + * @param parameters the rVV10 parameters b and C + * @param rho total density on the nrxx points of this process + * @param sigma |grad rho|^2 on the same points + * @param dedn dE/dn on the same points, or nullptr when it is not needed; the choice is collective + * @param dedsigma dE/dsigma on the same points + * @param stress with stress != nullptr also the explicit strain derivative, 9 Cartesian components + * (Ha, not divided by the volume) + * @return the energy in Ha, reduced over the pool + */ +double evaluate_libvdwxc( + const ModulePW::PW_Basis &pw, + const XCFunctionalParameters ¶meters, + const std::vector &rho, + const std::vector &sigma, + std::vector *dedn, + std::vector &dedsigma, + double *stress) +{ + ModuleBase::timer::start("vdw", "evaluate_libvdwxc"); + vdwxc_data data = vdwxc_new(VDWXC_RVV10); + if (vdwxc_set_rvv10_parameters(data, parameters.rvv10_b, parameters.rvv10_c) != 0) + { + ModuleBase::WARNING_QUIT("vdw::evaluate_libvdwxc", "libvdwxc rejected vdw_rvv10_b or vdw_rvv10_c"); + } + // libvdwxc integrates with the signed cell volume, and inverting a left-handed cell leaves rVV10 unchanged + ModuleBase::Matrix3 a = pw.latvec * pw.lat0; + if (a.Det() < 0.0) + { + a = a * -1.0; + } + // the cell must be known before the FFT plans are made + vdwxc_set_unit_cell(data, pw.nz, pw.nx, pw.ny, a.e31, a.e32, a.e33, a.e11, a.e12, a.e13, a.e21, a.e22, a.e23); + const bool distributed = pw.poolnproc > 1; +#ifdef __MPI + if (distributed) + { + vdwxc_init_mpi(data, pw.pool_world); + } +#endif + if (!distributed) + { + vdwxc_init_serial(data); + } + + SlabExchange exchange(pw); + const int slab_size = exchange.slab_size(); + std::vector slab_rho(slab_size); + std::vector slab_sigma(slab_size); + std::vector slab_dedn(slab_size); + std::vector slab_dedsigma(slab_size); + exchange.to_slab(rho, slab_rho); + exchange.to_slab(sigma, slab_sigma); + double energy = 0.0; + if (stress == nullptr) + { + energy = vdwxc_calculate(data, slab_rho.data(), slab_sigma.data(), slab_dedn.data(), slab_dedsigma.data()); + } + else + { + energy = vdwxc_stress(data, stress, slab_rho.data(), slab_sigma.data(), slab_dedn.data(), slab_dedsigma.data()); + } + vdwxc_finalize(&data); + if (dedn != nullptr) + { + exchange.to_grid(slab_dedn, *dedn); + } + exchange.to_grid(slab_dedsigma, dedsigma); +#ifdef __MPI + // the distributed backend returns the contribution of this process + if (distributed) + { + Parallel_Common::reduce_data(&energy, 1, pw.pool_world); + if (stress != nullptr) + { + Parallel_Common::reduce_data(stress, stress_components, pw.pool_world); + } + } +#endif + ModuleBase::timer::end("vdw", "evaluate_libvdwxc"); + return energy; +} + +/// rVV10 energy (Ha) of the total density of chr (valence plus core), with the plane-wave gradient of that +/// density (a copy of total_gradient when that is given), 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, + const std::vector> *total_gradient, + 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]; + } + } + // the branch is collective (the transforms are): the caller decides it for the whole pool + if (total_gradient != nullptr) + { + assert(total_gradient->size() == static_cast(nrxx)); + grad = *total_gradient; + } + else + { + 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 evaluate_libvdwxc(pw, parameters, rho, sigma, dedn, dedsigma, stress); +} +} // namespace + +void add_rvv10( + const XCFunctionalParameters ¶meters, + const Charge &chr, + const std::vector> *total_gradient, + 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, total_gradient, 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, nullptr, 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 from libvdwxc. 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 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..46bc42144ae --- /dev/null +++ b/source/source_hamilt/module_vdw/nonlocal_xc.h @@ -0,0 +1,65 @@ +#ifndef NONLOCAL_XC_H +#define NONLOCAL_XC_H + +#include + +class Charge; +struct XCFunctionalParameters; +namespace ModuleBase +{ +class matrix; +template +class Vector3; +} // namespace ModuleBase + +namespace vdw +{ + +// rVV10 nonlocal correlation of vdw_method rvv10, evaluated by libvdwxc. 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 libvdwxc they are empty, so that the callers need no preprocessor +// branch; vdw_method rvv10 then stops in make_vdw. + +#ifdef __LIBVDWXC +/** + * @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 total_gradient plane-wave gradient of that total density on the nrxx points of this process, if the + * caller holds it, which saves four FFTs; nullptr computes it here. The choice is + * collective, so a process without grid points passes its empty vector, not nullptr. + * @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, + const std::vector> *total_gradient, + 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 &, + const std::vector> *, + 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/unittests/CMakeLists.txt b/source/source_hamilt/module_vdw/unittests/CMakeLists.txt index b362cdb4aac..05789fac5e0 100644 --- a/source/source_hamilt/module_vdw/unittests/CMakeLists.txt +++ b/source/source_hamilt/module_vdw/unittests/CMakeLists.txt @@ -18,3 +18,50 @@ if(ENABLE_DFTD4 AND ENABLE_MPI) ${MPIEXEC_POSTFLAGS} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) endif() + +if(ENABLE_LIBVDWXC AND 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) + # a collective-path regression shows as a hang, so every run gets a timeout + set_tests_properties(MODULE_HAMILT_nonlocal_xcTest + PROPERTIES ENVIRONMENT "OMP_NUM_THREADS=1" TIMEOUT 300) + 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 TIMEOUT 300) + # 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 TIMEOUT 300) + # four processes give an uneven z distribution, an empty libvdwxc slab 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 TIMEOUT 300) +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..fdc632b970b --- /dev/null +++ b/source/source_hamilt/module_vdw/unittests/test_nonlocal_xc.cpp @@ -0,0 +1,644 @@ +// nonlocal_xc.cpp, the rVV10 adapter to libvdwxc: libvdwxc called directly as the reference, the potential and the +// stress as derivatives of the energy, every XC evaluator that adds the term, and the exchange between the ABACUS +// planes and the libvdwxc slabs on the processes of the test. +#include "source_hamilt/module_vdw/nonlocal_xc.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 reference calls libvdwxc directly. Include its C header after the C++ headers. +#include +#include +#undef I + +// 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, against libvdwxc's 3 + 3 + 3 + 0, which exercises the redistribution and an empty slab. +/// Odd ny and nz leave no Nyquist plane on libvdwxc's halved axis (ABACUS y in the adapter's (z, x, y) order, +/// ABACUS z in the direct call's (x, y, z) order), so libvdwxc's result does not depend on the axis order. +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, nullptr, 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, nullptr, 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 cell handed to libvdwxc. + 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, MatchesDirectLibvdwxc) +{ + // unpolarized and spin-polarized layouts against libvdwxc called directly in the ABACUS axis order + 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); + + // reference: libvdwxc on the total density in the ABACUS axis order, Hartree units + 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(); + } + vdwxc_data direct = vdwxc_new(VDWXC_RVV10); + ASSERT_NE(direct, nullptr); + ASSERT_EQ(vdwxc_set_rvv10_parameters(direct, rvv10_b_rpw86, rvv10_c_rpw86), 0); + const ModuleBase::Matrix3 a = serial.latvec * serial.lat0; + const int nx = serial.nx; + const int ny = serial.ny; + const int nz = serial.nz; + vdwxc_set_unit_cell(direct, nx, ny, nz, a.e11, a.e12, a.e13, a.e21, a.e22, a.e23, a.e31, a.e32, a.e33); + vdwxc_init_serial(direct); + const double energy_ha = vdwxc_calculate(direct, total.data(), sigma.data(), dedn.data(), dedsigma.data()); + vdwxc_finalize(&direct); + 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); + + // b and C reach libvdwxc: other values give the energy that libvdwxc gives for them + 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, nullptr, other_etxc, other_vtxc, other_v); + direct = vdwxc_new(VDWXC_RVV10); + ASSERT_EQ(vdwxc_set_rvv10_parameters(direct, other_b, other_c), 0); + vdwxc_set_unit_cell(direct, nx, ny, nz, a.e11, a.e12, a.e13, a.e21, a.e22, a.e23, a.e31, a.e32, a.e33); + vdwxc_init_serial(direct); + const double other_energy_ha = vdwxc_calculate(direct, total.data(), sigma.data(), dedn.data(), dedsigma.data()); + vdwxc_finalize(&direct); + const double other_expected = ModuleBase::e2 * other_energy_ha; + 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 exchange between the ABACUS planes and the libvdwxc slabs, uneven and with an empty slab on four processes + expect_distributed_matches_complete(pw, serial); +} + +TEST_F(NonlocalXCTest, BigGridDistributionMatchesCompleteGrid) +{ + // The density grid of a run is a PW_Basis_Big, which hands out whole blocks of bz planes: on two + // processes 8 + 4 against libvdwxc's 6 + 6, on four 4 + 4 + 4 + 0 against 3 + 3 + 3 + 3, so that a + // process may own no plane at all and one ABACUS block may span two libvdwxc slabs. + 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, LeftHandedCellGivesTheMirrorImageResult) +{ + // A mirror image has the same result; libvdwxc's 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 c1dd3ffb2e1..3fc37911053 100644 --- a/source/source_hamilt/module_vdw/unittests/test_vdw.cpp +++ b/source/source_hamilt/module_vdw/unittests/test_vdw.cpp @@ -942,6 +942,22 @@ TEST_F(vdwd4Test, EmptyAtomsAreExcludedForD4S) #endif // __DFTD4 +// rVV10 is part of the XC functional (nonlocal_xc.cpp), so make_vdw returns no pairwise correction; +// without libvdwxc it stops with a rebuild hint +TEST(vdwRvv10Test, MakeVdwHasNoPairwiseTerm) +{ + UnitCell ucell; + Input_para input; + input.vdw_method = "rvv10"; +#ifdef __LIBVDWXC + EXPECT_TRUE(vdw::make_vdw(ucell, input) == nullptr); +#else + testing::internal::CaptureStdout(); + EXPECT_EXIT(vdw::make_vdw(ucell, input), ::testing::ExitedWithCode(1), ""); + testing::internal::GetCapturedStdout(); +#endif +} + 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 db025a3747b..7dd3379360a 100644 --- a/source/source_hamilt/module_vdw/vdw.cpp +++ b/source/source_hamilt/module_vdw/vdw.cpp @@ -94,6 +94,21 @@ 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") + { +#ifndef __LIBVDWXC + ModuleBase::WARNING_QUIT( + "ModuleHamiltGeneral::ModuleVDW::make_vdw", "rVV10 support was not enabled at build time. " + "Rebuild ABACUS with -DENABLE_LIBVDWXC=ON."); +#endif + // rVV10 is evaluated inside XC_Functional, so there is no pairwise term here + if (plog != nullptr) + { + *plog << "\nrVV10 nonlocal correlation (libvdwxc): b=" << input.vdw_rvv10_b << " C=" << input.vdw_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..d2c6fee33b4 100644 --- a/source/source_hamilt/module_xc/CMakeLists.txt +++ b/source/source_hamilt/module_xc/CMakeLists.txt @@ -29,6 +29,12 @@ if(ENABLE_COVERAGE) add_coverage(xc_) endif() +if(ENABLE_LIBVDWXC) + # 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) + target_link_libraries(xc_ PUBLIC libvdwxc::vdwxc) +endif() + 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 b068d607955..db2fc8ec0e0 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 @@ -536,6 +537,11 @@ 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(); + // with one spin channel, gdr[0] is the gradient of the total density that add_rvv10 would recompute + const bool share_gradient = is_gga && nspin == 1 && !use_lca; + const std::vector> *total_gradient = share_gradient ? &gdr[0] : nullptr; + vdw::add_rvv10(xc_parameters, *chr, total_gradient, etxc, vtxc, v); XC_Functional_Libxc::finish_func(funcs); @@ -850,6 +856,11 @@ std::tuple XC_Functional etxc *= omega / chr->rhopw->nxyz; vtxc *= omega / chr->rhopw->nxyz; + const XCFunctionalParameters &xc_parameters = XC_Functional::get_runtime_parameters(); + // as in v_xc_libxc; every meta-GGA has a gradient, so nspin alone decides whether gdr[0] is the total density + const bool share_gradient = nspin == 1; + const std::vector> *total_gradient = share_gradient ? &gdr[0] : nullptr; + vdw::add_rvv10(xc_parameters, *chr, total_gradient, 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..7a490ab39d3 100644 --- a/source/source_hamilt/module_xc/test/CMakeLists.txt +++ b/source/source_hamilt/module_xc/test/CMakeLists.txt @@ -1,3 +1,7 @@ +# The targets in this directory compile xc_pot.cpp or libxc_pot.cpp against a +# mocked PW basis, without the libvdwxc adapter. +abacus_disable_feature_definitions(__LIBVDWXC) + addtest( TARGET MODULE_HAMILT_RpaCutoffConfig LIBS parameter base device diff --git a/source/source_hamilt/module_xc/xc_functional.cpp b/source/source_hamilt/module_xc/xc_functional.cpp index 77817772ff3..1592b3776a0 100644 --- a/source/source_hamilt/module_xc/xc_functional.cpp +++ b/source/source_hamilt/module_xc/xc_functional.cpp @@ -3,6 +3,7 @@ #include "source_base/global_function.h" #include "source_base/tool_title.h" #include +#include #ifdef __LIBXC #include "libxc_abacus.h" @@ -50,11 +51,8 @@ void XC_Functional::ScopedType::restore() noexcept XC_Functional::use_libxc = use_libxc_; XC_Functional::hybrid_alpha = hybrid_alpha_; XC_Functional::hse_omega = hse_omega_; - XC_Functional::runtime_parameters.xc_temperature = runtime_parameters_.xc_temperature; - XC_Functional::runtime_parameters.exx_fock_alpha.swap(runtime_parameters_.exx_fock_alpha); - XC_Functional::runtime_parameters.exx_erfc_alpha.swap(runtime_parameters_.exx_erfc_alpha); - XC_Functional::runtime_parameters.xc_exch_ext.swap(runtime_parameters_.xc_exch_ext); - XC_Functional::runtime_parameters.xc_corr_ext.swap(runtime_parameters_.xc_corr_ext); + // the whole struct, so that a new parameter cannot be forgotten here; its members move without allocating + std::swap(XC_Functional::runtime_parameters, runtime_parameters_); XC_Functional::scaling_factor_xc.swap(scaling_factor_xc_); } diff --git a/source/source_hamilt/module_xc/xc_functional.h b/source/source_hamilt/module_xc/xc_functional.h index bd147675faa..4953cf3121b 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..a1d93b822fd 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, nullptr, 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, nullptr, 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/build_info.h.in b/source/source_io/build_info.h.in index 543ef3e1b41..a7eb5e89950 100644 --- a/source/source_io/build_info.h.in +++ b/source/source_io/build_info.h.in @@ -52,6 +52,7 @@ // --- Other Libraries --- #define ABACUS_DFTD4_VERSION "@ABACUS_DFTD4_VERSION@" +#define ABACUS_LIBVDWXC_VERSION "@ABACUS_LIBVDWXC_VERSION@" #define ABACUS_JSON_VERSION "@ABACUS_JSON_VERSION@" #define ABACUS_PEXSI_VERSION "@ABACUS_PEXSI_VERSION@" #define ABACUS_CNPY_VERSION "@ABACUS_CNPY_VERSION@" diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 7673609daf8..390c921201e 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 vdw_rvv10_b = 6.3; ///< rVV10 parameter b + double vdw_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 98996980508..c008f57ac33 100644 --- a/source/source_io/module_parameter/read_inp_model.cpp +++ b/source/source_io/module_parameter/read_inp_model.cpp @@ -3,6 +3,10 @@ #include "read_input.h" #include "read_input_tool.h" #include "read_inp_sccs.h" + +#include +#include + namespace ModuleIO { void ReadInput::item_model() @@ -264,8 +268,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 +281,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 with the external libvdwxc library and added to the exchange-correlation energy, potential, forces and stress of dft_functional; see vdw_rvv10_b and vdw_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 +321,60 @@ Available options are: read_sync_string(input.vdw_d4_model); this->add_item(item); } + { + Input_Item item("vdw_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 and depends on dft_functional. If not set, ABACUS uses 15.7 for dft_functional scan or MGGA_X_SCAN+MGGA_C_SCAN, 11.95 for MGGA_X_R2SCAN+MGGA_C_R2SCAN and otherwise 6.3, the value of the original rVV10 (GGA_X_RPW86+GGA_C_PBE), with a warning for any other functional.)"; + item.default_value = "6.3"; + item.unit = ""; + item.set_availability("vdw_method==rvv10"); + item.reset_value = [](const Input_Item& item, Parameter& para) { + // the published pairings of b with the functional, unless the user chose b + if (item.is_read() || para.input.vdw_method != "rvv10") + { + return; + } + const double rvv10_b_scan = 15.7; + const double rvv10_b_r2scan = 11.95; + const std::string& dft_functional = para.input.dft_functional; + std::string dft_functional_lower = dft_functional; + std::transform(dft_functional.begin(), dft_functional.end(), dft_functional_lower.begin(), ::tolower); + if (dft_functional_lower == "scan" || dft_functional_lower == "mgga_x_scan+mgga_c_scan") + { + para.input.vdw_rvv10_b = rvv10_b_scan; + } + else if (dft_functional_lower == "mgga_x_r2scan+mgga_c_r2scan") + { + para.input.vdw_rvv10_b = rvv10_b_r2scan; + } + else if (dft_functional_lower != "gga_x_rpw86+gga_c_pbe") + { + const std::string message + = "vdw_rvv10_b is not set: the rPW86-PBE value 6.3 is used with dft_functional " + dft_functional; + ModuleBase::WARNING("ReadInput", message); + } + }; + read_sync_double(input.vdw_rvv10_b); + this->add_item(item); + } + { + Input_Item item("vdw_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.vdw_rvv10_c); + this->add_item(item); + } { Input_Item item("vdw_s6"); item.annotation = "scale parameter of d2/d3_0/d3_bj"; @@ -548,7 +613,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/parse_args.cpp b/source/source_io/parse_args.cpp index 54b77c1bdb8..61a8f7c4bdb 100644 --- a/source/source_io/parse_args.cpp +++ b/source/source_io/parse_args.cpp @@ -166,6 +166,7 @@ void print_build_info() // --- 11. Other Libraries --- print_section("Other Libraries"); print_info("DFT-D4 Support", ABACUS_DFTD4_VERSION); + print_info("libvdwxc Support", ABACUS_LIBVDWXC_VERSION); print_info("JSON Support", ABACUS_JSON_VERSION); print_info("PEXSI Support", ABACUS_PEXSI_VERSION); print_info("cnpy Support", ABACUS_CNPY_VERSION); diff --git a/source/source_io/unittests/CMakeLists.txt b/source/source_io/unittests/CMakeLists.txt index db7afae58f5..64ef4bee6bd 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 out_dmk_zero_precision out_hsk_zero_precision @@ -108,6 +109,13 @@ 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..ae2ce38a27b --- /dev/null +++ b/source/source_io/unittests/test_read_inp_model.cpp @@ -0,0 +1,126 @@ +// read_inp_model.cpp: the rVV10 INPUT items. vdw_method accepts rvv10 and declares the unsupported DFPT and +// LR-TDDFT force calculations; vdw_rvv10_b follows dft_functional unless it is set; vdw_rvv10_b and +// vdw_rvv10_c have 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, ReadsTheParametersAndPairsBWithTheFunctional) +{ + Parameter param; + read_input("vdw_method rvv10\ndft_functional scan\nvdw_rvv10_b 15.7\ncalculation cell-relax\n", param); + EXPECT_EQ(param.inp.vdw_method, "rvv10"); + EXPECT_DOUBLE_EQ(param.inp.vdw_rvv10_b, 15.7); + EXPECT_DOUBLE_EQ(param.inp.vdw_rvv10_c, 0.0093); + // b follows dft_functional unless it is set: SCAN 15.7, r2SCAN 11.95, otherwise the rPW86-PBE value 6.3 + const std::vector> b_cases = {{"vdw_method rvv10\ndft_functional scan\n", 15.7}, + {"vdw_method rvv10\ndft_functional MGGA_X_SCAN+MGGA_C_SCAN\n", 15.7}, + {"vdw_method rvv10\ndft_functional mgga_x_r2scan+mgga_c_r2scan\n", 11.95}, + {"vdw_method rvv10\ndft_functional scan\nvdw_rvv10_b 9.0\n", 9.0}, + {"vdw_method rvv10\ndft_functional pbe\n", 6.3}, {"vdw_method rvv10\n", 6.3}}; + for (const std::pair &b_case : b_cases) + { + Parameter param_b; + read_input(b_case.first, param_b); + EXPECT_DOUBLE_EQ(param_b.inp.vdw_rvv10_b, b_case.second) << b_case.first; + } +} + +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("vdw_rvv10_b"); + const ModuleIO::Input_Item &c = items.at("vdw_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.vdw_rvv10_b = 0.0; + rvv10_input.vdw_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 3ded92054ad..989e9b7a8e3 100644 --- a/source/source_io/unittests/test_read_input.cmake +++ b/source/source_io/unittests/test_read_input.cmake @@ -31,6 +31,13 @@ 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.") diff --git a/source/source_pw/module_pwdft/stress_gga.cpp b/source/source_pw/module_pwdft/stress_gga.cpp index 1716bd093db..fc1c27c2b5e 100644 --- a/source/source_pw/module_pwdft/stress_gga.cpp +++ b/source/source_pw/module_pwdft/stress_gga.cpp @@ -1,6 +1,7 @@ #include "stress_func.h" #include "source_base/parallel_reduce.h" #include "source_hamilt/module_xc/xc_functional.h" +#include "source_hamilt/module_vdw/nonlocal_xc.h" //calculate the GGA stress correction in PW and LCAO template @@ -15,6 +16,9 @@ void Stress_Func::stress_gga(const UnitCell& ucell, { 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..0ea4ff07eee --- /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 +vdw_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..25e78f80da6 --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/README @@ -0,0 +1,2 @@ +rVV10 (vdw_method rvv10, libvdwxc) on native PBE for GaAs with NLCC pseudopotentials and two spin channels: energy, forces, stress. Needs ENABLE_LIBVDWXC; 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..d7aeb1b0b20 --- /dev/null +++ b/tests/01_PW/215_PW_rvv10_GaAs/result.ref @@ -0,0 +1,5 @@ +etotref -4652.4575341047466281 +etotperatomref -2326.2287670524 +totalforceref 2.114464 +totalstressref 64465.540461 +totaltimeref 1.46 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..f4521d2f95b --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/README @@ -0,0 +1,2 @@ +rVV10 (vdw_method rvv10, libvdwxc) on rPW86-PBE through libxc for AB graphite with one atom displaced: energy, forces, stress in PW. +Needs ENABLE_LIBXC and ENABLE_LIBVDWXC; 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..25e867c8da5 --- /dev/null +++ b/tests/01_PW/216_PW_rvv10_graphite/result.ref @@ -0,0 +1,5 @@ +etotref -618.5481767916140825 +etotperatomref -154.6370441979 +totalforceref 4.093748 +totalstressref 639.350069 +totaltimeref 1.43 diff --git a/tests/01_PW/CASES_LIBVDWXC.txt b/tests/01_PW/CASES_LIBVDWXC.txt new file mode 100644 index 00000000000..12c0422176d --- /dev/null +++ b/tests/01_PW/CASES_LIBVDWXC.txt @@ -0,0 +1 @@ +215_PW_rvv10_GaAs diff --git a/tests/01_PW/CASES_LIBVDWXC_LIBXC.txt b/tests/01_PW/CASES_LIBVDWXC_LIBXC.txt new file mode 100644 index 00000000000..eff3c4e3bd0 --- /dev/null +++ b/tests/01_PW/CASES_LIBVDWXC_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..be9b7005bf8 100644 --- a/tests/01_PW/CMakeLists.txt +++ b/tests/01_PW/CMakeLists.txt @@ -12,3 +12,21 @@ else() COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto WORKING_DIRECTORY ${ABACUS_TEST_DIR}/01_PW) endif() + +# rVV10 with a built-in functional +if(ENABLE_LIBVDWXC) + add_test( + NAME 01_PW_libvdwxc + COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto + -f CASES_LIBVDWXC.txt + WORKING_DIRECTORY ${ABACUS_TEST_DIR}/01_PW) +endif() + +# rVV10 with the Libxc functional rPW86-PBE +if(ENABLE_LIBVDWXC AND ENABLE_LIBXC) + add_test( + NAME 01_PW_libvdwxc_libxc + COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto + -f CASES_LIBVDWXC_LIBXC.txt + WORKING_DIRECTORY ${ABACUS_TEST_DIR}/01_PW) +endif() diff --git a/tests/03_NAO_multik/CASES_LIBVDWXC_LIBXC.txt b/tests/03_NAO_multik/CASES_LIBVDWXC_LIBXC.txt new file mode 100644 index 00000000000..50341037c7c --- /dev/null +++ b/tests/03_NAO_multik/CASES_LIBVDWXC_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 b1d048fdcbb..4b60584c7bd 100644 --- a/tests/03_NAO_multik/CMakeLists.txt +++ b/tests/03_NAO_multik/CMakeLists.txt @@ -35,3 +35,12 @@ if(ENABLE_CNPY) -f CASES_CNPY.txt WORKING_DIRECTORY ${ABACUS_TEST_DIR}/03_NAO_multik) endif() + +# rVV10 with the Libxc functional rPW86-PBE +if(ENABLE_LIBVDWXC AND ENABLE_LIBXC) + add_test( + NAME 03_NAO_multik_libvdwxc_libxc + COMMAND ${BASH} ../integrate/Autotest.sh -a ${ABACUS_BIN_PATH} -n 4 -j auto + -f CASES_LIBVDWXC_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..132708ab1d6 --- /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 and ENABLE_LIBVDWXC; 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..bae615aa234 --- /dev/null +++ b/tests/03_NAO_multik/relax_cell_rvv10/result.ref @@ -0,0 +1,5 @@ +etotref -4139.0534388218002277 +etotperatomref -2069.5267194109 +totalforceref 0.812874 +totalstressref 17.813108 +totaltimeref 1.45