diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index a9acc3c4d0..3c83d064af 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -82,7 +82,11 @@ void ReadInput::item_postprocess() item.annotation = "orders of Chebyshev expansions for dos"; item.category = "Density of states"; item.type = "Integer"; - item.description = "The order of Chebyshev expansions when using Stochastic Density Functional Theory (SDFT) to calculate DOS."; + item.description = "The order of Chebyshev expansions when using Stochastic Density Functional Theory (SDFT) to calculate DOS." + "\n\nIt must be at least 2. The order has to grow with the ratio between the spectral range and " + "`dos_sigma`: resolving a Gaussian of width `dos_sigma` over a range of a few thousand eV can " + "require an order of 1e5 or more, so a value that is too small gives an under-resolved curve. " + "The code warns when the requested order cannot resolve `range/dos_sigma`."; item.default_value = "100"; item.unit = ""; read_sync_int(input.dos_nche); diff --git a/source/source_pw/module_stodft/CMakeLists.txt b/source/source_pw/module_stodft/CMakeLists.txt index fb863199d6..2ac12a5466 100644 --- a/source/source_pw/module_stodft/CMakeLists.txt +++ b/source/source_pw/module_stodft/CMakeLists.txt @@ -23,4 +23,5 @@ if(BUILD_TESTING) if(ENABLE_MPI) add_subdirectory(test) endif() + add_subdirectory(unittests) endif() diff --git a/source/source_pw/module_stodft/sto_dos.cpp b/source/source_pw/module_stodft/sto_dos.cpp index eb78c6700f..0da59f1965 100644 --- a/source/source_pw/module_stodft/sto_dos.cpp +++ b/source/source_pw/module_stodft/sto_dos.cpp @@ -6,6 +6,27 @@ #include "source_base/tool_title.h" #include "source_io/module_parameter/parameter.h" #include "sto_tool.h" + +#include +#include +#include +#include + +namespace +{ +/// Single entry point for the DOS diagnostics of this file. Keeping the +/// running-log reference here (instead of at every call site) keeps the global +/// dependency of this module to one place; none of these messages aborts a run. +void dos_log(const std::string& message, const bool also_stdout) +{ + GlobalV::ofs_running << message << std::endl; + if (also_stdout) + { + std::cout << message << std::endl; + } +} +} // namespace + template Sto_DOS::~Sto_DOS() { @@ -28,7 +49,10 @@ Sto_DOS::Sto_DOS(ModulePW::PW_Basis_K* p_wfcpw_in, this->p_hamilt_sto = static_cast>*>(p_hamilt_in); this->p_stowf = p_stowf_in; this->nbands_ks = p_psi_in->get_nbands(); - this->nbands_sto = p_stowf_in->nchi; + // Stochastic_WF::nchi is now initialized by allocate_chi0() (MDFT) and + // init_com_orbitals() (complete basis). Keep a safe fallback for old + // restart paths where only nchip is available. + this->nbands_sto = (p_stowf_in->nchi > 0) ? p_stowf_in->nchi : p_stowf_in->nchip_max; this->method_sto = stoche.method_sto; this->stofunc.set_E_range((double*)&stoche.emin_sto, (double*)&stoche.emax_sto); } @@ -44,14 +68,85 @@ void Sto_DOS::decide_param(const int& dos_nche, const double& dos_scale) { this->dos_nche = dos_nche; + if (this->dos_nche < 2) + { + ModuleBase::WARNING_QUIT("Sto_DOS", "dos_nche should be at least 2."); + } + + // If emin_sto/emax_sto are left at zero, keep the bounds already found by + // the SCF range check instead of resetting them to the bare input defaults. + // The repeated reset discarded a valid converged range and made the DOS + // range check depend on the random test vector alone. + double try_emin = emin_sto; + double try_emax = emax_sto; + if (try_emin == 0.0) + { + try_emin = *p_hamilt_sto->emin; + } + if (try_emax == 0.0) + { + try_emax = *p_hamilt_sto->emax; + } + check_che_op()( this->dos_nche, - emin_sto, - emax_sto, + try_emin, + try_emax, this->nbands_sto, this->p_kv, reinterpret_cast, Device>*>(this->p_stowf), reinterpret_cast, Device>*>(this->p_hamilt_sto)); + + // The stochastic range check learns only the high-energy end reliably. + // The lowest deterministic KS eigenvalue is a much safer lower bound; if + // the automatic Emin lies above it, the Chebyshev interval would exclude + // occupied states and T_n(H) would grow exponentially outside [-1,1]. + // Extending the interval below the lowest eigenvalue is always harmless. + double det_emin = std::numeric_limits::max(); + bool has_det_emin = false; + if (this->p_elec != nullptr) + { + const auto& ekb = this->p_elec->ekb; + for (int ik = 0; ik < ekb.nr; ++ik) + { + for (int ib = 0; ib < ekb.nc; ++ib) + { + const double e = ekb(ik, ib); + if (std::isfinite(e)) + { + det_emin = std::min(det_emin, e); + has_det_emin = true; + } + } + } + } +#ifdef __MPI + double global_det_emin = has_det_emin ? det_emin : std::numeric_limits::max(); + Parallel_Reduce::reduce_min(global_det_emin); + if (global_det_emin < std::numeric_limits::max()) + { + det_emin = global_det_emin; + has_det_emin = true; + } +#endif + if (has_det_emin) + { + const double margin_ry = 1.0e-3; + const double safe_emin = det_emin - margin_ry; + if (safe_emin < *p_hamilt_sto->emin) + { + std::ostringstream reset_msg; + reset_msg << " DOS: reset Chebyshev Emin from " << *p_hamilt_sto->emin << " Ry to " << safe_emin + << " Ry (lowest KS eigenvalue = " << det_emin << " Ry)"; + dos_log(reset_msg.str(), false); + *p_hamilt_sto->emin = safe_emin; + } + } + if (!std::isfinite(*p_hamilt_sto->emax) || *p_hamilt_sto->emax <= *p_hamilt_sto->emin) + { + *p_hamilt_sto->emax = *p_hamilt_sto->emin + 1.0; + } + if (dos_setemax) { this->emax = dos_emax_ev; @@ -75,6 +170,54 @@ void Sto_DOS::decide_param(const int& dos_nche, this->emax = emax + delta / 2.0; this->emin = emin - delta / 2.0; } + + if (!std::isfinite(this->emin) || !std::isfinite(this->emax) || this->emax <= this->emin) + { + ModuleBase::WARNING_QUIT("Sto_DOS", "Invalid DOS energy range: dos_emax_ev must be larger than dos_emin_ev."); + } + + // The Chebyshev interval is a property of the spectrum and is kept as it is: + // widening it to fit the requested output window would reduce the resolution + // of a fixed-order expansion and could hide a peak that a narrower interval + // resolves. A requested window that sticks out of the interval is therefore + // clipped to it (the `dos_scale` widening above makes that routine) and the + // change is reported, because energies outside the interval cannot be + // represented by the expansion at all. + const double interval_emin_ev = *p_hamilt_sto->emin * ModuleBase::Ry_to_eV; + const double interval_emax_ev = *p_hamilt_sto->emax * ModuleBase::Ry_to_eV; + const double requested_emin_ev = this->emin; + const double requested_emax_ev = this->emax; + const double clipped_emin_ev = std::max(requested_emin_ev, interval_emin_ev); + const double clipped_emax_ev = std::min(requested_emax_ev, interval_emax_ev); + // The `dos_scale` widening above intentionally makes the window a little wider + // than the spectrum, so a sub-percent clip is expected and is not reported; + // only a window that really asks for energies outside the interval is. + const double interval_span_ev = interval_emax_ev - interval_emin_ev; + const double dropped_ev + = std::max(requested_emin_ev - clipped_emin_ev, clipped_emax_ev - requested_emax_ev); + const bool report_clip = dropped_ev > 0.01 * interval_span_ev; + if (clipped_emax_ev > clipped_emin_ev) + { + // Always clip, so that |t| <= 1 holds by construction for every output + // energy. Only a clip that removes a visible part of the window is + // reported, because `dos_scale` intentionally widens the window by a + // fraction of a percent. + if (report_clip) + { + std::ostringstream clip_msg; + clip_msg << " DOS: output window clipped from [" << requested_emin_ev << ", " << requested_emax_ev << "] to [" + << clipped_emin_ev << ", " << clipped_emax_ev << "] eV to stay inside the Chebyshev interval [" + << interval_emin_ev << ", " << interval_emax_ev << "] eV"; + dos_log(clip_msg.str(), false); + } + this->emin = clipped_emin_ev; + this->emax = clipped_emax_ev; + } + + std::ostringstream range_msg; + range_msg << " DOS: Chebyshev range = [" << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax + << "] Ry; output window = [" << this->emin << ", " << this->emax << "] eV"; + dos_log(range_msg.str(), false); } template @@ -168,13 +311,46 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons allorderchi.shrink_to_fit(); std::ofstream ofsdos; + if (de <= 0.0) + { + ModuleBase::WARNING_QUIT("Sto_DOS", "dos_edelta_ev must be positive."); + } int ndos = int((emax - emin) / de) + 1; + if (ndos < 1) + { + ModuleBase::WARNING_QUIT("Sto_DOS", "The DOS output window is empty; check dos_emin_ev/dos_emax_ev."); + } this->stofunc.sigma = sigmain / ModuleBase::Ry_to_eV; + + // Estimate the Chebyshev order needed to resolve a Gaussian of width + // sigmain over the actual spectral range. Reporting this explicitly + // prevents a silently under-resolved DOS: with a large ecut and the + // default dos_sigma (0.07 eV) the required order can be thousands or more, + // while method 2 stores an nche x nche matrix and becomes prohibitively + // expensive. + const double range_ev = (*this->stofunc.Emax - *this->stofunc.Emin) * ModuleBase::Ry_to_eV; + const double sigma_ev = std::abs(sigmain); + if (sigma_ev > 0.0 && range_ev > 0.0) + { + const double prefactor = std::sqrt(2.0 * std::log(1.0e6)); + const double nche_needed = 0.5 * range_ev / sigma_ev * prefactor; + if (nche_needed > static_cast(this->dos_nche)) + { + std::ostringstream msg; + msg << "dos_sigma = " << sigma_ev << " eV is narrower than the Chebyshev expansion can resolve: " + << "range = " << range_ev << " eV, dos_nche = " << this->dos_nche + << ", estimated order needed ~ " << static_cast(std::ceil(nche_needed)) + << ". Increase dos_nche (method 1 or method 2 with sufficient memory) or use a larger dos_sigma."; + dos_log(" WARNING: " + msg.str(), true); + } + } ModuleBase::timer::end("Sto_DOS", "Tracepoly"); std::cout << "2. Dos:" << std::endl; ModuleBase::timer::start("Sto_DOS", "DOS Loop"); - int n10 = ndos / 10; + // For very small output windows ndos/10 is zero; the old modulus then + // divided by zero and terminated the run with SIGFPE. + int n10 = std::max(1, ndos / 10); int percent = 10; std::vector sto_dos(ndos); std::vector ks_dos(ndos); diff --git a/source/source_pw/module_stodft/sto_func.cpp b/source/source_pw/module_stodft/sto_func.cpp index d8935c7f7f..6b435fb551 100644 --- a/source/source_pw/module_stodft/sto_func.cpp +++ b/source/source_pw/module_stodft/sto_func.cpp @@ -1,8 +1,53 @@ #include "sto_func.h" #include "source_estate/occupy.h" + +#include + #define TWOPI 6.283185307179586 +namespace +{ +// Evaluate the Fermi-Dirac entropy density f*ln(f) + (1-f)*ln(1-f) +// from ne_mu = (E - mu)/kT without the cancellation that the literal +// expression suffers when f is tiny: +// (1-f)*ln(1-f) ~ -f, +// but in double precision 1-f rounds to 1 as soon as f < ~1e-16, so the +// literal expression drops this -f term and leaves an error of order f +// (relative error ~1/|ln f|, i.e. percent level) in the deep tail. +// The resulting non-smooth error seeds spurious high-order Chebyshev +// coefficients (~1e-12) which are then amplified by T_n(x) for any +// eigenvalue outside the expansion interval. Using s = min(f, 1-f) +// computed directly (no subtraction) and log1p(-s) keeps full relative +// accuracy for all temperatures. +template +inline REAL entropy_density_from_ne_mu(const REAL ne_mu) +{ + REAL s; // s = min(f, 1-f), always in [0, 0.5] + if (ne_mu >= 0) + { + if (ne_mu > 700) + { + return 0; + } + s = 1 / (1 + std::exp(ne_mu)); + } + else + { + if (ne_mu < -700) + { + return 0; + } + s = 1 / (1 + std::exp(-ne_mu)); + } + if (s <= 0) + { + return 0; + } + return s * std::log(s) + (1 - s) * std::log1p(-s); +} +} // namespace + template Sto_Func::Sto_Func() { @@ -85,20 +130,8 @@ REAL Sto_Func::nxfd(REAL rawe) const template REAL Sto_Func::fdlnfd(REAL e) const { - REAL e_mu = (e - mu) / this->tem; - if (e_mu > 36) { - return 0; - } else if (e_mu < -36) { - return 0; - } else - { - REAL f = 1 / (1 + exp(e_mu)); - if (f == 0 || f == 1) { - return 0; - } else { - return (f * log(f) + (1.0 - f) * log(1.0 - f)); -} - } + const REAL e_mu = (e - mu) / this->tem; + return entropy_density_from_ne_mu(e_mu); } template @@ -106,20 +139,8 @@ REAL Sto_Func::nfdlnfd(REAL rawe) const { REAL Ebar = (*Emin + *Emax) / 2; REAL DeltaE = (*Emax - *Emin) / 2; - REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; - if (ne_mu > 36) { - return 0; - } else if (ne_mu < -36) { - return 0; - } else - { - REAL f = 1 / (1 + exp(ne_mu)); - if (f == 0 || f == 1) { - return 0; - } else { - return f * log(f) + (1 - f) * log(1 - f); -} - } + const REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; + return entropy_density_from_ne_mu(ne_mu); } template @@ -127,20 +148,9 @@ REAL Sto_Func::n_root_fdlnfd(REAL rawe) const { REAL Ebar = (*Emin + *Emax) / 2; REAL DeltaE = (*Emax - *Emin) / 2; - REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; - if (ne_mu > 36) { - return 0; - } else if (ne_mu < -36) { - return 0; - } else - { - REAL f = 1 / (1 + exp(ne_mu)); - if (f == 0 || f == 1) { - return 0; - } else { - return sqrt(-f * log(f) - (1 - f) * log(1 - f)); -} - } + const REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; + const REAL g = -entropy_density_from_ne_mu(ne_mu); + return (g > 0) ? std::sqrt(g) : 0; } template diff --git a/source/source_pw/module_stodft/sto_iter.cpp b/source/source_pw/module_stodft/sto_iter.cpp index 6a12106486..610a42172d 100644 --- a/source/source_pw/module_stodft/sto_iter.cpp +++ b/source/source_pw/module_stodft/sto_iter.cpp @@ -1,5 +1,7 @@ #include "sto_iter.h" +#include + #include "source_base/kernels/math_kernel_op.h" #include "source_base/para_gemm.h" #include "source_base/parallel_comm.h" @@ -13,6 +15,9 @@ #include "source_hsolver/para_lin_tf.h" #include "source_io/module_parameter/parameter.h" +#include +#include + template Stochastic_Iter::Stochastic_Iter() { @@ -29,9 +34,13 @@ Stochastic_Iter::~Stochastic_Iter() template void Stochastic_Iter::dot(const int& n, const Real* x, const int& incx, const Real* y, const int& incy, Real& result) { + // Use the arrays the caller passes: the previous implementation ignored x, incx, y and incy and + // always reduced p_che->coef_real against spolyv, so every caller that wanted a different + // contraction (for example the two staggered sums in checkemm) silently got the same number, and + // the reported Chebyshev "precision" of the stochastic trace was not the quantity it claimed. Real* result_device = nullptr; resmem_var_op()(result_device, 1); - container::kernels::blas_dot()(n, p_che->coef_real, 1, spolyv, 1, result_device); + container::kernels::blas_dot()(n, x, incx, y, incy, result_device); syncmem_var_d2h_op()(&result, result_device, 1); delmem_var_op()(result_device); } @@ -211,6 +220,40 @@ void Stochastic_Iter::checkemm(const int& ik, Parallel_Reduce::reduce_min(*p_hamilt_sto->emin); MPI_Allreduce(MPI_IN_PLACE, &change, 1, MPI_CHAR, MPI_LOR, MPI_COMM_WORLD); #endif + // checkconverge() treats (0,0) as "unset" and can end with a + // positive Emin when the trial Rayleigh quotient is positive. This + // removes all bound states from the Chebyshev interval and makes the + // Fermi-level search fail at high temperature. Correct only that + // pathological final bound; negative bounds are left untouched so + // normal SDFT results do not change. + // A positive lower bound is only pathological when it came from the + // automatic search: a user-provided emin_sto (or a genuinely positive + // spectrum) is a valid interval, and moving it downwards would enlarge + // the interval and change the fixed-order occupation and entropy sums. + const bool emin_is_automatic = (PARAM.inp.emin_sto == 0.0); + if (emin_is_automatic && (!std::isfinite(*p_hamilt_sto->emin) || *p_hamilt_sto->emin > 0)) + { + const double positive_emin = *p_hamilt_sto->emin; + const double emax_abs = std::abs(*p_hamilt_sto->emax); + const double fallback_span = std::max(5.0, 0.01 * emax_abs); + const double safe_emin = -fallback_span; + std::ostringstream range_msg; + range_msg << " WARNING: positive automatic Chebyshev Emin " << positive_emin << " Ry is reset to " + << safe_emin << " Ry"; + *p_hamilt_sto->emin = safe_emin; + // The same pathological Krylov path also underestimates the upper + // bound. The highest plane-wave eigenvalue cannot exceed roughly + // ecutwfc, so use the cutoff as a safe floor. + const double ecutwfc = PARAM.inp.ecutwfc; + const double ecut_floor = 1.05 * ecutwfc; + if (ecutwfc > 0 && *p_hamilt_sto->emax < ecut_floor) + { + range_msg << "; Chebyshev Emax " << *p_hamilt_sto->emax << " Ry is raised to the ecutwfc-based floor " + << ecut_floor << " Ry"; + *p_hamilt_sto->emax = ecut_floor; + } + GlobalV::ofs_running << range_msg.str() << std::endl; + } if (change) { GlobalV::ofs_running << "New Emax Ry" << *p_hamilt_sto->emax << " ; new Emin " << *p_hamilt_sto->emin diff --git a/source/source_pw/module_stodft/sto_tool.cpp b/source/source_pw/module_stodft/sto_tool.cpp index f63a870723..250744c557 100644 --- a/source/source_pw/module_stodft/sto_tool.cpp +++ b/source/source_pw/module_stodft/sto_tool.cpp @@ -1,5 +1,7 @@ #include "sto_tool.h" +#include + #include "source_base/math_chebyshev.h" #include "source_base/parallel_comm.h" #include "source_base/parallel_device.h" @@ -9,6 +11,8 @@ #ifdef __MPI #include "mpi.h" #endif +#include +#include #include template @@ -48,14 +52,25 @@ void check_che_op::operator()(const int& nche_in, const int npw = p_kv->ngk[ik]; std::complex* pchi = nullptr; psi::Psi, Device> randchi_d; - if (nbands_sto == 0) // For case: PARAM.inp.nbands_sto = "all" - { - randchi_d.resize(1, 1, npw); - } - int ntest = std::min(ntest0, p_stowf->nchip[ik]); + randchi_d.resize(1, 1, npw); // holds the independent random probe of this k point + // Use the real stochastic (or complete-basis) orbitals whenever they + // exist. Previously this decision was based only on "nbands_sto==0", + // while Stochastic_WF::nchi was never initialized; as a result the DOS + // range check always used random vectors, even for MDFT. Random + // vectors have a Rayleigh quotient close to the mean spectral energy + // and cannot locate a low-lying eigenvalue, so Emin could be set far + // above the occupied states. + const bool use_random = (p_stowf->nchi <= 0) || (nbands_sto == 0 && p_stowf->nchip_max <= 0); + const int ntest_real = use_random ? 0 : std::min(ntest0, p_stowf->nchip[ik]); + // Always add one independent random probe on top of the real orbitals. + // With `nbands_sto all` the stochastic orbitals are coordinate vectors, + // so a handful of them can miss a diagonal state of another invariant + // subspace; a dense random vector does not depend on that choice. + const int ntest = use_random ? 1 : ntest_real + 1; for (int i = 0; i < ntest; ++i) { - if (nbands_sto == 0) + const bool use_this_random = use_random || i == ntest_real; + if (use_this_random) { std::vector> randchi(npw); for (int ig = 0; ig < npw; ++ig) @@ -108,6 +123,40 @@ void check_che_op::operator()(const int& nche_in, Parallel_Reduce::reduce_max(*p_hamilt_sto->emax); Parallel_Reduce::reduce_min(*p_hamilt_sto->emin); #endif + // checkconverge() starts from the user's (0,0) defaults and can + // leave the automatic lower bound positive when the first trial + // Rayleigh quotient is positive. A positive Emin excludes every + // bound state and is the root of the high-temperature SCF and DOS + // failures. Only correct that pathological outcome here so that + // cases whose final bound is already negative keep the original + // numerical result bit for bit. + // Only an automatically determined bound may be repaired: a positive + // emin_sto given by the user (or a genuinely positive spectrum) is a + // valid interval and must be preserved. + const bool emin_is_automatic = (PARAM.inp.emin_sto == 0.0); + if (emin_is_automatic && (!std::isfinite(*p_hamilt_sto->emin) || *p_hamilt_sto->emin > 0)) + { + const double positive_emin = *p_hamilt_sto->emin; + const double emax_abs = std::abs(*p_hamilt_sto->emax); + const double fallback_span = std::max(5.0, 0.01 * emax_abs); + const double safe_emin = -fallback_span; + std::ostringstream range_msg; + range_msg << " WARNING: positive automatic Chebyshev Emin " << positive_emin << " Ry is reset to " + << safe_emin << " Ry"; + *p_hamilt_sto->emin = safe_emin; + // The pathological path that produced a positive Emin also + // tends to underestimate Emax. The highest plane-wave + // eigenvalue is bounded by roughly ecutwfc; use it as a floor. + const double ecutwfc = PARAM.inp.ecutwfc; + const double ecut_floor = 1.05 * ecutwfc; + if (ecutwfc > 0 && *p_hamilt_sto->emax < ecut_floor) + { + range_msg << "; Chebyshev Emax " << *p_hamilt_sto->emax + << " Ry is raised to the ecutwfc-based floor " << ecut_floor << " Ry"; + *p_hamilt_sto->emax = ecut_floor; + } + GlobalV::ofs_running << range_msg.str() << std::endl; + } GlobalV::ofs_running << "New Emax " << *p_hamilt_sto->emax << " Ry; new Emin " << *p_hamilt_sto->emin << " Ry" << std::endl; change = false; diff --git a/source/source_pw/module_stodft/sto_wf.cpp b/source/source_pw/module_stodft/sto_wf.cpp index 2fca88e482..bcff514125 100644 --- a/source/source_pw/module_stodft/sto_wf.cpp +++ b/source/source_pw/module_stodft/sto_wf.cpp @@ -108,6 +108,11 @@ void Stochastic_WF::allocate_chi0() } this->nchip_max = tmpnchip; + // Record that real stochastic orbitals have been allocated. This member + // was previously left at its default value of zero, so downstream code + // (notably the DOS range check) mistakenly used random test vectors even + // when chi0/chiortho were available. + this->nchi = nchi; size_t size = this->nchip_max * npwx * nks; this->chi0_cpu = new psi::Psi(nks, this->nchip_max, npwx, this->ngk, true); ModuleBase::Memory::record("SDFT::chi0_cpu", size * sizeof(T)); @@ -204,6 +209,10 @@ void Stochastic_WF::init_com_orbitals() this->nchip_max = std::max(tmpnchip, this->nchip_max); delete[] npwip; } + // In the complete-basis ("all") mode nbands_sto is zero, but chi0 still + // contains real orbitals. Keep nchi nonzero so that consumers such as + // check_che_op know that actual orbitals are available. + this->nchi = this->nchip_max; size_t size = this->nchip_max * npwx * nks; this->chi0_cpu = new psi::Psi>(nks, this->nchip_max, npwx, this->ngk, true); this->chi0_cpu->zero_out(); @@ -277,6 +286,7 @@ void Stochastic_WF::init_com_orbitals() this->chi0_cpu->operator()(ik, ichi, ichi) = 1; } } + this->nchi = this->nchip_max; // allocate chi0 Device* ctx = {}; diff --git a/source/source_pw/module_stodft/unittests/CMakeLists.txt b/source/source_pw/module_stodft/unittests/CMakeLists.txt new file mode 100644 index 0000000000..b51097f074 --- /dev/null +++ b/source/source_pw/module_stodft/unittests/CMakeLists.txt @@ -0,0 +1,9 @@ +abacus_disable_feature_definitions(__MPI) +abacus_disable_feature_definitions(__CUDA) +abacus_disable_feature_definitions(__ROCM) + +# Regression test for the occupation / entropy kernels of the SDFT solver: +# `1 - f` must not be computed by subtraction and the expanded function must +# not contain an artificial cutoff (|x| > 36 used to return exactly 0). +AddTest(TARGET MODULE_PW_STO_FUNC_UTs LIBS parameter base device SOURCES + test_sto_func.cpp ../sto_func.cpp ../../../source_estate/occupy.cpp) diff --git a/source/source_pw/module_stodft/unittests/test_sto_func.cpp b/source/source_pw/module_stodft/unittests/test_sto_func.cpp new file mode 100644 index 0000000000..0a143992f4 --- /dev/null +++ b/source/source_pw/module_stodft/unittests/test_sto_func.cpp @@ -0,0 +1,194 @@ +#include "../sto_func.h" + +#include + +#include + +/************************************************ + * unit test of sto_func.cpp (occupation / entropy kernels of SDFT) + * + * Goal: turn the "Ne vs TS Chebyshev precision asymmetry" failure into a + * self-checking regression test. Two known failure modes: + * (1) computing `1 - f` by subtraction loses accuracy when f -> 1 or f -> 0, + * which destroys the relative accuracy of the entropy density g; + * (2) an artificial cutoff such as `if (x > 36) return 0` introduces a + * discontinuity in the expanded function, which lifts the tail of the + * Chebyshev coefficients by several orders of magnitude and is then + * amplified by |x| > 1 into an O(1) spurious entropy. + * + * Only mathematical/physical properties are asserted here (no implementation + * detail), so any correct implementation passes. + * + * Sign convention of sto_func.cpp (must be respected, otherwise TS flips sign): + * fdlnfd(e) = f ln f + (1-f) ln(1-f) <= 0 (i.e. -g) + * nfdlnfd(rawe) = the same negative value (i.e. -g) + * n_root_fdlnfd(rawe) = sqrt(g) >= 0 (expanded by method 2) + * with g = -f ln f - (1-f) ln(1-f) >= 0 the true entropy density. + * The "n*" variants take the normalized Chebyshev coordinate rawe in [-1,1] + * and restore the energy through [Emin, Emax]. + ***********************************************/ + +namespace +{ +const double kT = 25.57754484; // 348 eV, the production temperature [Ry] +const double mu = 0.3; // arbitrary chemical potential inside the spectrum [Ry] + +// Independent closed form (equivalent, but free of cancellation): +// g(x) = ln(2cosh(x/2)) - (x/2)tanh(x/2) = |x|*y/(1+y) + ln(1+y), y = exp(-|x|) +// It follows a completely different path than "compute f, then take log" in +// ABACUS and agrees with a 50-digit mpmath reference to ~1e-16 relative +// for |x| <= 60. +double g_reference(double x) +{ + const double y = std::exp(-std::fabs(x)); + return std::fabs(x) * y / (1.0 + y) + std::log1p(y); +} +} // namespace + +/** + * - Tested Functions: + * - Sto_Func::fd / root_fd (occupation f and sqrt(f), input = physical energy) + * - Sto_Func::nroot_fd (sqrt(f), input = normalized coordinate) + * - Sto_Func::fdlnfd (f ln f + (1-f) ln(1-f) = -g, input = physical energy) + * - Sto_Func::n_root_fdlnfd (sqrt(g), input = normalized coordinate) + */ +class TestStoFunc : public ::testing::Test +{ + protected: + Sto_Func sto; + double emin = 0.0; + double emax = 0.0; + double xc = 0.0; // centre of [xmin,xmax] in units of x=(E-mu)/kT + double xh = 1.0; // half width + + void SetUp() override + { + sto.tem = kT; + sto.mu = mu; + set_x_range(-10.0, 50.0); + } + + // Chebyshev interval used by the "n*" variants: x in [xmin,xmax] <=> rawe in [-1,1] + void set_x_range(double xmin, double xmax) + { + xc = 0.5 * (xmin + xmax); + xh = 0.5 * (xmax - xmin); + emin = mu + xmin * kT; + emax = mu + xmax * kT; + sto.set_E_range(&emin, &emax); + } + + double to_rawe(double x) const + { + return (x - xc) / xh; + } +}; + +// 1) identities and independent reference: f(x)+f(-x)=1, g symmetric, sqrt(g)^2=g, f(0)=1/2, g(0)=ln2 +TEST_F(TestStoFunc, identities_and_independent_reference) +{ + EXPECT_NEAR(sto.fd(mu), 0.5, 1e-16); + EXPECT_NEAR(-sto.fdlnfd(mu), std::log(2.0), 1e-14); + EXPECT_NEAR(sto.n_root_fdlnfd(to_rawe(0.0)), std::sqrt(std::log(2.0)), 1e-13); + + set_x_range(-20.0, 20.0); + for (double x = -20.0; x <= 20.0; x += 0.5) + { + const double e = mu + x * kT; + const double e_neg = mu - x * kT; + const double g = -sto.fdlnfd(e); + + EXPECT_NEAR(sto.fd(e) + sto.fd(e_neg), 1.0, 1e-14); // particle-hole symmetry + EXPECT_NEAR(g, -sto.fdlnfd(e_neg), 1e-13); // g is even in x + EXPECT_GE(g, 0.0); // entropy is non-negative + EXPECT_LE(sto.fdlnfd(e), 0.0); // sign convention + EXPECT_NEAR(g, g_reference(x), 1e-13 * (1.0 + std::fabs(g_reference(x)))); + EXPECT_NEAR(sto.n_root_fdlnfd(to_rawe(x)) * sto.n_root_fdlnfd(to_rawe(x)), g, 1e-13); + EXPECT_GE(sto.fd(e), 0.0); + EXPECT_LE(sto.fd(e), 1.0); + } +} + +// 2) key regression: the expanded function must not contain an artificial jump. +// The true value is still 1e-13 ... 9e-8 for x in (36,45); `if (x>36) return 0` +// flattens it, leaving a step of sqrt(g(36)) = 9.26e-8 whose Chebyshev +// coefficient tail is ~2e-9, whereas a correct implementation stays ~1e-15. +TEST_F(TestStoFunc, no_artificial_cutoff_jump) +{ + // (a) for x in (36,45) g must still be positive and match the reference + for (double x = 36.5; x <= 45.0; x += 0.5) + { + const double e = mu + x * kT; + const double g = -sto.fdlnfd(e); + const double g_ref = g_reference(x); + EXPECT_GT(g, 0.0); // the original returns 0 here -> FAIL + EXPECT_NEAR(g, g_ref, 1e-12 * g_ref + 1e-300); + EXPECT_GT(sto.n_root_fdlnfd(to_rawe(x)), 0.0); // same for sqrt(g) + } + + // (b) sqrt(g) is continuous on [33,45]: with a 1e-2 step the difference + // between neighbours must stay far below the 9.3e-8 artificial step. + // The steepest legitimate slope in this range is at x=33, + // |d sqrt(g)/dx| ~ 0.5*sqrt(g(33)) ~ 2.5e-7, i.e. ~2.5e-9 per 1e-2 step. + double max_step = 0.0; + double prev = sto.n_root_fdlnfd(to_rawe(33.0)); + for (int i = 1; i <= 1200; ++i) + { + const double x = 33.0 + 0.01 * i; + const double cur = sto.n_root_fdlnfd(to_rawe(x)); + max_step = std::max(max_step, std::fabs(cur - prev)); + EXPECT_LE(cur, prev + 1e-15); // sqrt(g) is non-increasing for x>0 + prev = cur; + } + EXPECT_LE(max_step, 1e-8); // artificial step 9.3e-8 -> FAIL +} + +// 3) tail asymptotics and extremes: no NaN/Inf, and no crude truncation of a meaningful tail +TEST_F(TestStoFunc, tail_asymptotics_and_extremes) +{ + set_x_range(-800.0, 800.0); + for (double x: {50.0, 80.0, 120.0, 200.0}) + { + const double g = -sto.fdlnfd(mu + x * kT); + const double asym = std::exp(-x) * (x + 1.0); + EXPECT_GT(g, 0.0); // the original is 0 for x>36 -> FAIL + EXPECT_NEAR(g / asym, 1.0, 1e-9); + } + for (double x: {-50.0, -80.0, -120.0, -200.0}) + { + const double g = -sto.fdlnfd(mu + x * kT); + const double asym = std::exp(x) * (-x + 1.0); + EXPECT_GT(g, 0.0); + EXPECT_NEAR(g / asym, 1.0, 1e-9); + } + for (double x: {-700.0, 700.0, -745.0, 745.0, 1000.0, -1000.0}) + { + const double e = mu + x * kT; + EXPECT_TRUE(std::isfinite(sto.fd(e))); + EXPECT_TRUE(std::isfinite(sto.fdlnfd(e))); + EXPECT_TRUE(std::isfinite(sto.n_root_fdlnfd(to_rawe(x)))); + EXPECT_GE(sto.fd(e), 0.0); + EXPECT_LE(sto.fd(e), 1.0); + EXPECT_GE(-sto.fdlnfd(e), 0.0); + } +} + +// 4) monotonicity and sqrt(f) consistency (method 2 uses sqrt(f) for Ne) +TEST_F(TestStoFunc, monotonicity_and_sqrt_f) +{ + set_x_range(-50.0, 50.0); + double prev = sto.fd(mu - 50.0 * kT); + for (int i = -5000; i <= 5000; ++i) + { + const double x = 0.01 * i; + const double e = mu + x * kT; + const double cur = sto.fd(e); + EXPECT_LE(cur, prev + 1e-16); // f is non-increasing + prev = cur; + const double sf = sto.root_fd(e); + EXPECT_GE(sf, 0.0); + EXPECT_NEAR(sf * sf, cur, 1e-14); + const double nsf = sto.nroot_fd(to_rawe(x)); + EXPECT_NEAR(nsf * nsf, cur, 1e-13); + } +}