From f8b4f78d625bd5f60c3b761d5ad311c71280319c Mon Sep 17 00:00:00 2001 From: LiYuqiii <139907896+LiYuqiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:49:35 +0800 Subject: [PATCH 1/4] SDFT: fix the high-temperature DOS blow-up and the Ne/TS precision asymmetry Four defects made SDFT/DOS unusable at high temperature: * checkconverge() uses tmin == 0 as its "uninitialized" sentinel, so a positive trial Rayleigh quotient leaves Emin > 0 and excludes every bound state; the upper bound is underestimated in the same path. * the DOS stage re-derived the range from (0, 0) instead of inheriting the converged SCF range, and Stochastic_WF::nchi was never initialized, so the range probe always used random vectors. * dos_scale widened the reported window by 0.5% per side without widening the Chebyshev interval, so T_n(|x| > 1) grew exponentially: DOS values of 1e26--1e64 instead of the 2*N_pw integral. * the entropy density computed 1 - f by subtraction, and returned 0 for |x| > 36: the sqrt(g) coefficient tail was lifted from ~1e-19 to ~1e-12, which made E_entropy(-TS) two orders of magnitude too large while Ne stayed exact. Stochastic_Iter::dot() also ignored its arguments, so the reported precision was meaningless. Fixes: repair the range at the call sites, inherit the SCF range in the DOS stage, initialize nchi, expand the Chebyshev interval to contain the output grid, evaluate the entropy density with s = min(f, 1-f) and log1p(-s), and make dot() use the passed arrays. Adds a unit test for the entropy kernels. --- source/source_pw/module_stodft/CMakeLists.txt | 1 + source/source_pw/module_stodft/sto_dos.cpp | 148 ++++++++++++- source/source_pw/module_stodft/sto_func.cpp | 94 +++++---- source/source_pw/module_stodft/sto_iter.cpp | 26 +++ source/source_pw/module_stodft/sto_tool.cpp | 40 +++- source/source_pw/module_stodft/sto_wf.cpp | 10 + .../module_stodft/unittests/CMakeLists.txt | 9 + .../module_stodft/unittests/test_sto_func.cpp | 194 ++++++++++++++++++ 8 files changed, 473 insertions(+), 49 deletions(-) create mode 100644 source/source_pw/module_stodft/unittests/CMakeLists.txt create mode 100644 source/source_pw/module_stodft/unittests/test_sto_func.cpp diff --git a/source/source_pw/module_stodft/CMakeLists.txt b/source/source_pw/module_stodft/CMakeLists.txt index fb863199d61..3481a2ce153 100644 --- a/source/source_pw/module_stodft/CMakeLists.txt +++ b/source/source_pw/module_stodft/CMakeLists.txt @@ -22,5 +22,6 @@ endif() if(BUILD_TESTING) if(ENABLE_MPI) add_subdirectory(test) + add_subdirectory(unittests) endif() endif() diff --git a/source/source_pw/module_stodft/sto_dos.cpp b/source/source_pw/module_stodft/sto_dos.cpp index eb78c6700f3..a87a4b6b98f 100644 --- a/source/source_pw/module_stodft/sto_dos.cpp +++ b/source/source_pw/module_stodft/sto_dos.cpp @@ -6,6 +6,12 @@ #include "source_base/tool_title.h" #include "source_io/module_parameter/parameter.h" #include "sto_tool.h" + +#include +#include +#include +#include + template Sto_DOS::~Sto_DOS() { @@ -28,7 +34,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 +53,84 @@ 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) + { + GlobalV::ofs_running << " DOS: reset Chebyshev Emin from " << *p_hamilt_sto->emin << " Ry to " + << safe_emin << " Ry (lowest KS eigenvalue = " << det_emin << " Ry)" + << std::endl; + *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 +154,33 @@ 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."); + } + + // A Gaussian centred outside the Chebyshev interval requires T_n(x) with + // |x| > 1, which grows exponentially with n. The default dos_scale path + // deliberately makes the output window slightly wider than the spectral + // range, so evaluating the Gaussian at those edge points used to be the + // final trigger for the 1e36-scale DOS values. Expand the Chebyshev + // interval itself (never the other way round) so that every requested + // output energy satisfies |x| <= 1. + const double output_emin_ry = this->emin / ModuleBase::Ry_to_eV; + const double output_emax_ry = this->emax / ModuleBase::Ry_to_eV; + const double guard_ry = std::max(1.0e-6, 1.0e-6 * (*p_hamilt_sto->emax - *p_hamilt_sto->emin)); + if (output_emin_ry - guard_ry < *p_hamilt_sto->emin) + { + *p_hamilt_sto->emin = output_emin_ry - guard_ry; + } + if (output_emax_ry + guard_ry > *p_hamilt_sto->emax) + { + *p_hamilt_sto->emax = output_emax_ry + guard_ry; + } + + GlobalV::ofs_running << " DOS: Chebyshev range = [" << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax + << "] Ry; output window = [" << this->emin << ", " << this->emax << "] eV" << std::endl; } template @@ -168,13 +274,47 @@ 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."; + GlobalV::ofs_running << " WARNING: " << msg.str() << std::endl; + std::cout << " WARNING: " << msg.str() << std::endl; + } + } 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 d8935c7f7fa..6b435fb5517 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 6a121064866..92398e18adb 100644 --- a/source/source_pw/module_stodft/sto_iter.cpp +++ b/source/source_pw/module_stodft/sto_iter.cpp @@ -13,6 +13,9 @@ #include "source_hsolver/para_lin_tf.h" #include "source_io/module_parameter/parameter.h" +#include +#include + template Stochastic_Iter::Stochastic_Iter() { @@ -211,6 +214,29 @@ 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. + if (!std::isfinite(*p_hamilt_sto->emin) || *p_hamilt_sto->emin > 0) + { + const double safe_emin = -std::max(5.0, 0.01 * std::abs(*p_hamilt_sto->emax)); + GlobalV::ofs_running << " WARNING: positive automatic Chebyshev Emin " + << *p_hamilt_sto->emin << " Ry is reset to " << safe_emin << " Ry" << std::endl; + *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 ecut_floor = 1.05 * PARAM.inp.ecutwfc; + if (PARAM.inp.ecutwfc > 0 && *p_hamilt_sto->emax < ecut_floor) + { + GlobalV::ofs_running << " WARNING: Chebyshev Emax " << *p_hamilt_sto->emax + << " Ry is raised to the ecutwfc-based floor " << ecut_floor << " Ry" << std::endl; + *p_hamilt_sto->emax = ecut_floor; + } + } 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 f63a8707236..9e273eca5bd 100644 --- a/source/source_pw/module_stodft/sto_tool.cpp +++ b/source/source_pw/module_stodft/sto_tool.cpp @@ -9,6 +9,8 @@ #ifdef __MPI #include "mpi.h" #endif +#include +#include #include template @@ -48,14 +50,22 @@ 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" + // 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); + if (use_random) { randchi_d.resize(1, 1, npw); } - int ntest = std::min(ntest0, p_stowf->nchip[ik]); + int ntest = use_random ? 1 : std::min(ntest0, p_stowf->nchip[ik]); for (int i = 0; i < ntest; ++i) { - if (nbands_sto == 0) + if (use_random) { std::vector> randchi(npw); for (int ig = 0; ig < npw; ++ig) @@ -108,6 +118,30 @@ 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. + if (!std::isfinite(*p_hamilt_sto->emin) || *p_hamilt_sto->emin > 0) + { + const double safe_emin = -std::max(5.0, 0.01 * std::abs(*p_hamilt_sto->emax)); + GlobalV::ofs_running << " WARNING: positive automatic Chebyshev Emin " + << *p_hamilt_sto->emin << " Ry is reset to " << safe_emin << " Ry" << std::endl; + *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 ecut_floor = 1.05 * PARAM.inp.ecutwfc; + if (PARAM.inp.ecutwfc > 0 && *p_hamilt_sto->emax < ecut_floor) + { + GlobalV::ofs_running << " WARNING: Chebyshev Emax " << *p_hamilt_sto->emax + << " Ry is raised to the ecutwfc-based floor " << ecut_floor << " Ry" << std::endl; + *p_hamilt_sto->emax = ecut_floor; + } + } 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 2fca88e4824..bcff5141252 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 00000000000..b51097f074b --- /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 00000000000..0a143992f4e --- /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); + } +} From 2cfcb5741737b5f3e604b045f83d62dda23d05b9 Mon Sep 17 00:00:00 2001 From: LiYuqiii <139907896+LiYuqiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:51:07 +0800 Subject: [PATCH 2/4] SDFT DOS: pure-function window guard, runtime quality warnings, unit tests Add ModuleIO::sto_dos_quality with two groups of pure (global-state free, unit-tested) helpers: * sanitize_che_range(): repairs the Chebyshev window so that it covers the known deterministic eigenvalues, the plane-wave spectrum top (1.05*ecutwfc) and the requested DOS output grid. Healthy input is returned bit for bit unchanged. Used by both the SCF range check (Sto_Tool::check_che_op) and the DOS stage (Sto_DOS::decide_param), replacing two copies of an inline heuristic that read PARAM directly. * check_dos_parameters() / check_dos_result(): warn (never abort) when dos_edelta_ev and dos_sigma are mismatched, dos_nche cannot resolve range/sigma (reporting the estimated order), the range/sigma ratio is prohibitive, the DOS integral does not reproduce 2*sum_k npwk, the curve goes visibly negative, or an output energy left the Chebyshev interval. The integral check is skipped when the window truncates the spectrum on purpose. Adds unittests/test_sto_dos_quality.cpp (14 cases). --- source/source_pw/module_stodft/CMakeLists.txt | 1 + source/source_pw/module_stodft/sto_dos.cpp | 249 ++++++++++------ source/source_pw/module_stodft/sto_dos.h | 19 ++ .../module_stodft/sto_dos_quality.cpp | 267 ++++++++++++++++++ .../source_pw/module_stodft/sto_dos_quality.h | 100 +++++++ source/source_pw/module_stodft/sto_tool.cpp | 43 ++- .../module_stodft/unittests/CMakeLists.txt | 8 + .../unittests/test_sto_dos_quality.cpp | 251 ++++++++++++++++ 8 files changed, 828 insertions(+), 110 deletions(-) create mode 100644 source/source_pw/module_stodft/sto_dos_quality.cpp create mode 100644 source/source_pw/module_stodft/sto_dos_quality.h create mode 100644 source/source_pw/module_stodft/unittests/test_sto_dos_quality.cpp diff --git a/source/source_pw/module_stodft/CMakeLists.txt b/source/source_pw/module_stodft/CMakeLists.txt index 3481a2ce153..cf07a45c1c0 100644 --- a/source/source_pw/module_stodft/CMakeLists.txt +++ b/source/source_pw/module_stodft/CMakeLists.txt @@ -5,6 +5,7 @@ list( sto_hsolver_pw.cpp sto_iter.cpp sto_che.cpp + sto_dos_quality.cpp sto_wf.cpp sto_func.cpp sto_forces.cpp diff --git a/source/source_pw/module_stodft/sto_dos.cpp b/source/source_pw/module_stodft/sto_dos.cpp index a87a4b6b98f..aef7a37702b 100644 --- a/source/source_pw/module_stodft/sto_dos.cpp +++ b/source/source_pw/module_stodft/sto_dos.cpp @@ -3,6 +3,7 @@ #include "source_base/parallel_comm.h" #include "source_base/parallel_reduce.h" #include "source_base/timer.h" +#include "source_pw/module_stodft/sto_dos_quality.h" #include "source_base/tool_title.h" #include "source_io/module_parameter/parameter.h" #include "sto_tool.h" @@ -17,6 +18,46 @@ Sto_DOS::~Sto_DOS() { } +namespace +{ + +/// Lowest deterministic (Kohn-Sham) eigenvalue over all k points and bands. +/// Returns false when no eigenvalue is available. The result is already +/// reduced over all pools. +bool minimum_ks_eigenvalue(const elecstate::ElecState* pelec, double& det_min) +{ + det_min = std::numeric_limits::max(); + bool found = false; + if (pelec != nullptr) + { + const auto& ekb = pelec->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_min = std::min(det_min, e); + found = true; + } + } + } + } +#ifdef __MPI + double global_min = found ? det_min : std::numeric_limits::max(); + Parallel_Reduce::reduce_min(global_min); + if (global_min < std::numeric_limits::max()) + { + det_min = global_min; + found = true; + } +#endif + return found; +} + +} // namespace + template Sto_DOS::Sto_DOS(ModulePW::PW_Basis_K* p_wfcpw_in, K_Vectors* p_kv_in, @@ -87,100 +128,134 @@ void Sto_DOS::decide_param(const int& dos_nche, // 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 + double det_emin = 0.0; + const bool has_det_emin = minimum_ks_eigenvalue(this->p_elec, det_emin); + // Deterministic (Kohn-Sham) eigenvalues are a reliable lower bound of the + // spectrum even at high temperature; the pure, unit-tested sanitiser is + // used for this and for the output-window consistency check below. + std::vector det_eigs; 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) - { - GlobalV::ofs_running << " DOS: reset Chebyshev Emin from " << *p_hamilt_sto->emin << " Ry to " - << safe_emin << " Ry (lowest KS eigenvalue = " << det_emin << " Ry)" - << std::endl; - *p_hamilt_sto->emin = safe_emin; - } + det_eigs.push_back(det_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; - } - else - { - this->emax = *p_hamilt_sto->emax * ModuleBase::Ry_to_eV; - } - if (dos_setemin) - { - this->emin = dos_emin_ev; - } - else + this->setup_output_window(dos_setemin, dos_setemax, dos_emin_ev, dos_emax_ev, dos_scale); + + // A Gaussian centred outside the Chebyshev interval requires T_n(x) with + // |x| > 1, which grows exponentially with n; the default dos_scale path + // deliberately makes the output window slightly wider than the spectral + // range, so evaluating the Gaussian at those edge points used to be the + // final trigger for the 1e36-scale DOS values. Expand the Chebyshev + // interval itself (never the other way round) so that every requested + // output energy satisfies |x| <= 1. This is the `output_window` clause of + // the same sanitiser used at the SCF stage. + const double output_emin_ry = this->emin / ModuleBase::Ry_to_eV; + const double output_emax_ry = this->emax / ModuleBase::Ry_to_eV; + const double guard_ry = std::max(1.0e-6, 1.0e-6 * (*p_hamilt_sto->emax - *p_hamilt_sto->emin)); + ModuleIO::CheRange requested; + requested.emin = output_emin_ry - guard_ry; + requested.emax = output_emax_ry + guard_ry; + const ModuleIO::CheRange fixed = ModuleIO::sanitize_che_range(*p_hamilt_sto->emin, + *p_hamilt_sto->emax, + PARAM.inp.ecutwfc, + det_eigs, + &requested); + if (fixed.emin_repaired || fixed.emax_repaired || fixed.degenerate) { - this->emin = *p_hamilt_sto->emin * ModuleBase::Ry_to_eV; + GlobalV::ofs_running << " DOS: Chebyshev range repaired from [" + << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax << "] to [" + << fixed.emin << ", " << fixed.emax << "] Ry" + << (has_det_emin ? " (lowest KS eigenvalue = " + std::to_string(det_emin) + " Ry)" : "") + << std::endl; } + *p_hamilt_sto->emin = fixed.emin; + *p_hamilt_sto->emax = fixed.emax; + + GlobalV::ofs_running << " DOS: Chebyshev range = [" << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax + << "] Ry; output window = [" << this->emin << ", " << this->emax << "] eV" << std::endl; +} + +template +void Sto_DOS::setup_output_window(const bool& dos_setemin, + const bool& dos_setemax, + const double& dos_emin_ev, + const double& dos_emax_ev, + const double& dos_scale) +{ + this->emax = dos_setemax ? dos_emax_ev : *p_hamilt_sto->emax * ModuleBase::Ry_to_eV; + this->emin = dos_setemin ? dos_emin_ev : *p_hamilt_sto->emin * ModuleBase::Ry_to_eV; if (!dos_setemax && !dos_setemin) { - double delta = (emax - emin) * dos_scale; - this->emax = emax + delta / 2.0; - this->emin = emin - delta / 2.0; + // Widen the reported window slightly on both sides (dos_scale); the + // Chebyshev interval is extended accordingly below. + const double delta = (this->emax - this->emin) * dos_scale; + this->emax += delta / 2.0; + this->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."); } +} - // A Gaussian centred outside the Chebyshev interval requires T_n(x) with - // |x| > 1, which grows exponentially with n. The default dos_scale path - // deliberately makes the output window slightly wider than the spectral - // range, so evaluating the Gaussian at those edge points used to be the - // final trigger for the 1e36-scale DOS values. Expand the Chebyshev - // interval itself (never the other way round) so that every requested - // output energy satisfies |x| <= 1. - const double output_emin_ry = this->emin / ModuleBase::Ry_to_eV; - const double output_emax_ry = this->emax / ModuleBase::Ry_to_eV; - const double guard_ry = std::max(1.0e-6, 1.0e-6 * (*p_hamilt_sto->emax - *p_hamilt_sto->emin)); - if (output_emin_ry - guard_ry < *p_hamilt_sto->emin) +template +void Sto_DOS::check_and_report_dos_result(const std::vector& ks_dos, + const std::vector& sto_dos, + const double& de, + const double& max_abs_t) const +{ + // Post-run diagnostics: the DOS integral must reproduce the number of + // plane-wave states when the window covers the spectrum, the curve must not + // go visibly negative, and no output energy may leave the Chebyshev + // interval. Warnings only; a long run is never aborted here. + double dos_integral = 0.0; + double dos_min = 0.0; + for (std::size_t ie = 0; ie < ks_dos.size(); ++ie) { - *p_hamilt_sto->emin = output_emin_ry - guard_ry; + const double dos = 2.0 * (ks_dos[ie] + sto_dos[ie]) / ModuleBase::Ry_to_eV; + dos_integral += dos * de; + dos_min = std::min(dos_min, dos); } - if (output_emax_ry + guard_ry > *p_hamilt_sto->emax) + double expected_states = -1.0; + // The integral only has to reproduce the number of plane-wave states when + // the requested window actually covers the whole spectrum. A user who + // restricts dos_emin_ev/dos_emax_ev on purpose expects a smaller integral, + // so the check is skipped there to avoid a misleading warning. + const double ecut_ev = PARAM.inp.ecutwfc * ModuleBase::Ry_to_eV; + const bool window_covers_spectrum = (ecut_ev <= 0.0) || (this->emax >= 0.95 * ecut_ev); + if (PARAM.inp.nspin == 1 && window_covers_spectrum && this->p_kv != nullptr && this->p_wfcpw != nullptr) { - *p_hamilt_sto->emax = output_emax_ry + guard_ry; + // npwk[ik] is the number of plane waves held by THIS rank, so the sum has + // to be reduced over the pool. Twice the total number of plane-wave + // states is what the DOS integral converges to (verified both on a + // Gamma-only and on a 2x2x2 case). + double local_npw = 0.0; + for (int ik = 0; ik < this->p_kv->get_nks(); ++ik) + { + local_npw += static_cast(this->p_wfcpw->npwk[ik]); + } +#ifdef __MPI + Parallel_Reduce::reduce_pool(local_npw); +#endif + expected_states = 2.0 * local_npw; } - GlobalV::ofs_running << " DOS: Chebyshev range = [" << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax - << "] Ry; output window = [" << this->emin << ", " << this->emax << "] eV" << std::endl; + const std::vector dos_warnings + = ModuleIO::check_dos_result(dos_integral, expected_states, dos_min, max_abs_t); + for (const std::string& msg: dos_warnings) + { + GlobalV::ofs_running << " WARNING: DOS: " << msg << std::endl; + if (GlobalV::MY_RANK == 0) + { + std::cout << " WARNING: DOS: " << msg << std::endl; + } + } } template @@ -285,29 +360,16 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons } 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. + // Parameter sanity checks (pure functions, unit tested). They only report; + // a long run is never aborted by a quality suggestion. 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) + for (const std::string& msg: ModuleIO::check_dos_parameters(range_ev, sigma_ev, de, this->dos_nche)) { - 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."; - GlobalV::ofs_running << " WARNING: " << msg.str() << std::endl; - std::cout << " WARNING: " << msg.str() << std::endl; - } + GlobalV::ofs_running << " WARNING: DOS: " << msg << std::endl; + std::cout << " WARNING: DOS: " << msg << std::endl; } + ModuleBase::timer::end("Sto_DOS", "Tracepoly"); std::cout << "2. Dos:" << std::endl; @@ -319,11 +381,20 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons std::vector sto_dos(ndos); std::vector ks_dos(ndos); std::vector error(ndos); + // Diagnostics for the post-run check: |t| of every grid point in the + // Chebyshev variable, and the smallest DOS value on the curve. + double max_abs_t = 0.0; + const double ebar_ry = 0.5 * (*this->stofunc.Emax + *this->stofunc.Emin); + const double de_ry = 0.5 * (*this->stofunc.Emax - *this->stofunc.Emin); for (int ie = 0; ie < ndos; ++ie) { double tmpks = 0; double tmpsto = 0; this->stofunc.targ_e = (emin + ie * de) / ModuleBase::Ry_to_eV; + if (de_ry > 0.0) + { + max_abs_t = std::max(max_abs_t, std::fabs((this->stofunc.targ_e - ebar_ry) / de_ry)); + } if (this->method_sto == 1) { auto ngauss = std::bind(&Sto_Func::ngauss, &this->stofunc, std::placeholders::_1); @@ -380,6 +451,8 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons Parallel_Reduce::reduce_all(sto_dos.data(), ndos); Parallel_Reduce::reduce_all(error.data(), ndos); #endif + this->check_and_report_dos_result(ks_dos, sto_dos, de, max_abs_t); + if (GlobalV::MY_RANK == 0) { std::string dosfile = PARAM.globalv.global_out_dir + "dos_sdft.txt"; diff --git a/source/source_pw/module_stodft/sto_dos.h b/source/source_pw/module_stodft/sto_dos.h index ffd1cfc08c0..d0eedaca2d9 100644 --- a/source/source_pw/module_stodft/sto_dos.h +++ b/source/source_pw/module_stodft/sto_dos.h @@ -48,6 +48,25 @@ class Sto_DOS */ void caldos(const double sigmain, const double de, const int npart); + /** + * @brief Translate the DOS request into the reported energy window + * [emin, emax] (eV) and validate it. + */ + /** + * @brief Report DOS quality problems (integral, negative values, |t| > 1) + * as warnings; never aborts. + */ + void check_and_report_dos_result(const std::vector& ks_dos, + const std::vector& sto_dos, + const double& de, + const double& max_abs_t) const; + + void setup_output_window(const bool& dos_setemin, + const bool& dos_setemax, + const double& dos_emin_ev, + const double& dos_emax_ev, + const double& dos_scale); + protected: int nbands_ks = 0; ///< number of KS bands int nbands_sto = 0; ///< number of stochastic bands diff --git a/source/source_pw/module_stodft/sto_dos_quality.cpp b/source/source_pw/module_stodft/sto_dos_quality.cpp new file mode 100644 index 00000000000..44d99bc2d87 --- /dev/null +++ b/source/source_pw/module_stodft/sto_dos_quality.cpp @@ -0,0 +1,267 @@ +#include "sto_dos_quality.h" + +#include +#include +#include + +namespace +{ +// --------------------------------------------------------------------------- +// Constants of the Chebyshev-window sanitiser +// --------------------------------------------------------------------------- +const double det_margin = 1.0e-3; ///< safety margin below/above deterministic eigenvalues [Ry] +const double min_width = 1.0e-6; ///< minimal window width [Ry], avoids division by zero +const double ecut_margin = 1.05; ///< Emax floor relative to ecutwfc + +/// Conservative fallback for a pathological lower bound. +double fallback_emin(double emax) +{ + return -std::max(5.0, 0.01 * std::fabs(emax)); +} + +// --------------------------------------------------------------------------- +// Constants of the DOS parameter / result checks +// --------------------------------------------------------------------------- +const double integral_rel_tol = 1.0e-2; ///< relative tolerance on the number of states +const double negative_dos_rel_tol = 1.0e-4; ///< negative DOS below this fraction is noise +const double de_over_sigma_min = 0.02; ///< grid much finer than the broadening (waste) +const double de_over_sigma_max = 3.0; ///< grid coarser than the broadening (information loss) +const double order_prefactor = std::sqrt(2.0 * std::log(1.0e6)); ///< target 1e-6 in the Gaussian +const double max_abs_t_tol = 1.0e-9; ///< tolerance on |t| <= 1 + +std::string format_double(const double value) +{ + std::ostringstream os; + os << value; + return os.str(); +} + +// --------------------------------------------------------------------------- +// Rules of the Chebyshev-window sanitiser, in the order they are applied +// --------------------------------------------------------------------------- + +/// Rule 1: reset non-finite or inverted windows. +void repair_degenerate(double emin, double emax, double ecut_floor, ModuleIO::CheRange& out) +{ + const bool finite_in = std::isfinite(emin) && std::isfinite(emax); + if (finite_in && (emax - emin) > 0.0) + { + return; + } + const double abs_emax = std::isfinite(emax) ? std::fabs(emax) : 0.0; + out.emax = std::max(ecut_floor, abs_emax); + out.emin = fallback_emin(out.emax); + out.degenerate = true; + out.emin_repaired = true; + out.emax_repaired = true; +} + +/// Rule 2: the window has to contain every known deterministic eigenvalue. +void cover_deterministic_eigenvalues(const std::vector& det_eigs, ModuleIO::CheRange& out) +{ + if (det_eigs.empty()) + { + return; + } + const double det_min = *std::min_element(det_eigs.begin(), det_eigs.end()); + const double det_max = *std::max_element(det_eigs.begin(), det_eigs.end()); + if (std::isfinite(det_min) && out.emin > det_min - det_margin) + { + out.emin = det_min - det_margin; + out.emin_repaired = true; + } + if (std::isfinite(det_max) && out.emax < det_max + det_margin) + { + out.emax = det_max + det_margin; + out.emax_repaired = true; + } +} + +/// Rule 3: a positive lower bound cannot describe a spectrum with occupied +/// states; replace it by a conservative negative value. +void repair_positive_emin(ModuleIO::CheRange& out) +{ + if (out.emin <= 0.0) + { + return; + } + out.emin = fallback_emin(out.emax); + out.emin_repaired = true; +} + +/// Rule 4: the highest plane-wave eigenvalue is bounded by roughly ecutwfc. +void raise_emax_to_ecut_floor(double ecut_floor, ModuleIO::CheRange& out) +{ + if (ecut_floor > 0.0 && out.emax < ecut_floor) + { + out.emax = ecut_floor; + out.emax_repaired = true; + } +} + +/// Rule 5: the requested output grid must be inside the window (|t| <= 1). +void cover_output_window(const ModuleIO::CheRange* output_window, ModuleIO::CheRange& out) +{ + if (output_window == nullptr) + { + return; + } + const bool usable = std::isfinite(output_window->emin) && std::isfinite(output_window->emax) + && output_window->emax > output_window->emin; + if (!usable) + { + return; + } + if (out.emin > output_window->emin) + { + out.emin = output_window->emin; + out.emin_repaired = true; + } + if (out.emax < output_window->emax) + { + out.emax = output_window->emax; + out.emax_repaired = true; + } +} + +/// Rule 6: enforce a minimal, strictly positive width. +void enforce_min_width(ModuleIO::CheRange& out) +{ + if (out.emax - out.emin < min_width) + { + out.emax = out.emin + min_width; + out.emax_repaired = true; + } +} +} // namespace + +namespace ModuleIO +{ + +CheRange sanitize_che_range(double emin, + double emax, + double ecutwfc, + const std::vector& det_eigs, + const CheRange* output_window) +{ + CheRange out; + out.emin = emin; + out.emax = emax; + + const double ecut_floor = (ecutwfc > 0.0) ? ecut_margin * ecutwfc : 0.0; + + repair_degenerate(emin, emax, ecut_floor, out); + cover_deterministic_eigenvalues(det_eigs, out); + repair_positive_emin(out); + raise_emax_to_ecut_floor(ecut_floor, out); + cover_output_window(output_window, out); + enforce_min_width(out); + + return out; +} + +std::vector check_dos_parameters(double range_ev, + double sigma_ev, + double de_ev, + int dos_nche) +{ + std::vector warnings; + + if (de_ev <= 0.0) + { + warnings.push_back("dos_edelta_ev must be positive; the DOS grid cannot be built."); + return warnings; + } + if (!(sigma_ev > 0.0)) + { + warnings.push_back("dos_sigma = " + format_double(sigma_ev) + + " eV is not positive; a zero-width Gaussian makes the DOS a sum of delta " + "spikes that no finite dos_nche can resolve."); + return warnings; + } + + // Grid vs broadening: the two must be comparable, otherwise the curve is + // either oversampled noise or undersampled peaks. + if (de_ev < de_over_sigma_min * sigma_ev) + { + warnings.push_back("dos_edelta_ev = " + format_double(de_ev) + " eV is much smaller than dos_sigma = " + + format_double(sigma_ev) + " eV; the extra grid points carry no independent " + "information and will show Chebyshev ringing. Consider dos_edelta_ev ~ dos_sigma."); + } + if (de_ev > de_over_sigma_max * sigma_ev) + { + warnings.push_back("dos_edelta_ev = " + format_double(de_ev) + " eV is much larger than dos_sigma = " + + format_double(sigma_ev) + " eV; the Gaussian is narrower than the grid spacing, so " + "peaks can fall between grid points. Use dos_edelta_ev <~ dos_sigma."); + } + + // Chebyshev order needed to resolve a Gaussian of width sigma on this range. + if (range_ev > 0.0) + { + const double nche_needed = 0.5 * range_ev / sigma_ev * order_prefactor; + if (nche_needed > static_cast(dos_nche)) + { + std::ostringstream os; + os << "dos_sigma = " << sigma_ev << " eV is narrower than the Chebyshev expansion can resolve: " + << "range = " << range_ev << " eV, dos_nche = " << dos_nche + << ", estimated order needed ~ " << static_cast(std::ceil(nche_needed)) + << ". Increase dos_nche or use a larger dos_sigma; otherwise the DOS may show spurious " + "oscillations or negative values."; + warnings.push_back(os.str()); + } + if (range_ev / sigma_ev > 1.0e4) + { + warnings.push_back("the Chebyshev range (" + format_double(range_ev) + + " eV) is more than 1e4 times dos_sigma; with such a wide range the required " + "Chebyshev order is prohibitive and the DOS will be under-resolved. Consider " + "restricting dos_emin_ev/dos_emax_ev to the energy window of interest."); + } + } + + return warnings; +} + +std::vector check_dos_result(double integral, + double expected_states, + double min_dos, + double max_abs_t) +{ + std::vector warnings; + + if (max_abs_t > 1.0 + max_abs_t_tol) + { + warnings.push_back("an output energy lies outside the Chebyshev interval (max |t| = " + + format_double(max_abs_t) + + " > 1). T_n(t) grows exponentially there, so the DOS is not trustworthy; " + "this indicates an inconsistency between the DOS window and the Chebyshev range."); + } + + if (expected_states > 0.0 && std::isfinite(integral)) + { + const double rel = std::fabs(integral - expected_states) / expected_states; + if (rel > integral_rel_tol) + { + std::ostringstream os; + os << "the DOS integral over the output window is " << integral << ", but the number of plane-wave " + << "states is " << expected_states << " (relative deviation " << rel * 100.0 << "%). The window " + << "may cut off part of the spectrum, or dos_nche / dos_sigma are too coarse."; + warnings.push_back(os.str()); + } + } + + if (std::isfinite(min_dos) && min_dos < 0.0) + { + // Allow tiny ringing but flag anything visible on the scale of the curve. + const double scale = std::max(1.0, std::fabs(integral)); + if (std::fabs(min_dos) > negative_dos_rel_tol * scale) + { + warnings.push_back("the DOS takes negative values (minimum " + format_double(min_dos) + + "): the Chebyshev expansion is under-resolved. Increase dos_nche or use a " + "larger dos_sigma."); + } + } + + return warnings; +} + +} // namespace ModuleIO diff --git a/source/source_pw/module_stodft/sto_dos_quality.h b/source/source_pw/module_stodft/sto_dos_quality.h new file mode 100644 index 00000000000..f422eb80626 --- /dev/null +++ b/source/source_pw/module_stodft/sto_dos_quality.h @@ -0,0 +1,100 @@ +#ifndef STO_DOS_QUALITY_H +#define STO_DOS_QUALITY_H + +#include +#include + +/** + * @file sto_dos_quality.h + * @brief Quality guards for the SDFT/MDFT stochastic DOS pipeline. + * + * Pure, global-state free helpers, all unit tested in + * `unittests/test_sto_dos_quality.cpp`: + * + * 1. `sanitize_che_range()` repairs the Chebyshev energy window [Emin, Emax] + * so that it covers the known deterministic eigenvalues, the physical + * plane-wave spectrum (`ecutwfc`) and the requested DOS output grid. + * Without it a positive lower bound excludes every occupied state, and an + * output energy outside the window makes T_n(|x| > 1) grow exponentially + * (the historical 1e26--1e64 DOS values). + * + * 2. `check_dos_parameters()` / `check_dos_result()` report DOS settings that + * are silently useless at high temperature (grid spacing vs Gaussian + * broadening, Chebyshev order vs range/sigma) and a DOS curve that does + * not integrate to the number of plane-wave states, goes negative, or was + * evaluated outside the Chebyshev window. + * + * Both groups only report through their return values; the caller decides what + * to print, so a long run is never aborted by a quality suggestion. + */ + +namespace ModuleIO +{ + +/// A Chebyshev energy window plus the flags telling whether it was repaired. +struct CheRange +{ + double emin = 0.0; ///< lower bound [Ry] + double emax = 0.0; ///< upper bound [Ry] + bool emin_repaired = false; ///< whether the lower bound was modified + bool emax_repaired = false; ///< whether the upper bound was modified + bool degenerate = false; ///< input was non-finite/inverted and was reset +}; + +/** + * @brief Check and, if necessary, repair the Chebyshev spectral window. + * + * @param[in] emin automatic/user lower bound [Ry] + * @param[in] emax automatic/user upper bound [Ry] + * @param[in] ecutwfc wavefunction cutoff [Ry]; when > 0 it is used as + * the lower bound of Emax (`1.05 * ecutwfc`) + * @param[in] det_eigs known deterministic (Kohn-Sham) eigenvalues [Ry]; + * may be empty + * @param[in] output_window optional output (DOS) grid that has to be covered, + * so that |t| <= 1 holds by construction. May be null. + * + * Rules, applied in this fixed order (kept simple so the behaviour is testable): + * 1. non-finite or inverted input is reset to a conservative interval; + * 2. deterministic eigenvalues are covered (margin 1e-3 Ry); + * 3. a pathological positive Emin is replaced by `-max(5, 0.01*|emax|)`; + * 4. `Emax >= 1.05 * ecutwfc` when `ecutwfc > 0`; + * 5. the optional output window is covered; + * 6. a minimum width of 1e-6 Ry is enforced. + * + * Healthy input is returned bit for bit unchanged. + */ +CheRange sanitize_che_range(double emin, + double emax, + double ecutwfc, + const std::vector& det_eigs, + const CheRange* output_window); + +/** + * @brief Parameter-level DOS checks, called before the DOS loop. + * + * @param range_ev width of the Chebyshev interval [eV] + * @param sigma_ev `dos_sigma` [eV] (may be zero or negative on bad input) + * @param de_ev `dos_edelta_ev` [eV] + * @param dos_nche number of Chebyshev orders used for the DOS expansion + * @return one human-readable warning per detected problem; empty when sane + */ +std::vector check_dos_parameters(double range_ev, + double sigma_ev, + double de_ev, + int dos_nche); + +/// Result-level checks, called after the DOS curve has been reduced. +/// @param integral \int DOS(E) dE over the output window +/// @param expected_states 2 * sum_k npwk(k) summed over the pool; a negative +/// value skips the check (spin-polarized runs, or a +/// window that truncates the spectrum on purpose) +/// @param min_dos smallest DOS value on the grid +/// @param max_abs_t max |t| of the output grid in the Chebyshev variable +std::vector check_dos_result(double integral, + double expected_states, + double min_dos, + double max_abs_t); + +} // namespace ModuleIO + +#endif // STO_DOS_QUALITY_H diff --git a/source/source_pw/module_stodft/sto_tool.cpp b/source/source_pw/module_stodft/sto_tool.cpp index 9e273eca5bd..1ebe279ac5d 100644 --- a/source/source_pw/module_stodft/sto_tool.cpp +++ b/source/source_pw/module_stodft/sto_tool.cpp @@ -5,6 +5,7 @@ #include "source_base/parallel_device.h" #include "source_base/parallel_reduce.h" #include "source_base/timer.h" +#include "source_pw/module_stodft/sto_dos_quality.h" #include "source_io/module_parameter/parameter.h" #ifdef __MPI #include "mpi.h" @@ -118,29 +119,27 @@ 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. - if (!std::isfinite(*p_hamilt_sto->emin) || *p_hamilt_sto->emin > 0) + // checkconverge() probes the spectrum with Rayleigh quotients of + // trial vectors and can leave the lower bound positive (the vectors + // sit near the middle of the plane-wave spectrum) or underestimate + // the upper bound. Run the pure, unit-tested sanitiser instead of + // an inline heuristic: it only repairs out-of-range windows, so + // healthy cases keep their previous numbers bit for bit. + // The deterministic (Kohn-Sham) eigenvalues are not available at + // this call site; callers that own an ElecState pass them there. + std::vector det_eigs; + const ModuleIO::CheRange fixed = ModuleIO::sanitize_che_range(*p_hamilt_sto->emin, + *p_hamilt_sto->emax, + PARAM.inp.ecutwfc, + det_eigs, + nullptr); + if (fixed.emin_repaired || fixed.emax_repaired) { - const double safe_emin = -std::max(5.0, 0.01 * std::abs(*p_hamilt_sto->emax)); - GlobalV::ofs_running << " WARNING: positive automatic Chebyshev Emin " - << *p_hamilt_sto->emin << " Ry is reset to " << safe_emin << " Ry" << std::endl; - *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 ecut_floor = 1.05 * PARAM.inp.ecutwfc; - if (PARAM.inp.ecutwfc > 0 && *p_hamilt_sto->emax < ecut_floor) - { - GlobalV::ofs_running << " WARNING: Chebyshev Emax " << *p_hamilt_sto->emax - << " Ry is raised to the ecutwfc-based floor " << ecut_floor << " Ry" << std::endl; - *p_hamilt_sto->emax = ecut_floor; - } + GlobalV::ofs_running << " WARNING: Chebyshev window repaired: [" + << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax << "] -> [" + << fixed.emin << ", " << fixed.emax << "] Ry" << std::endl; + *p_hamilt_sto->emin = fixed.emin; + *p_hamilt_sto->emax = fixed.emax; } GlobalV::ofs_running << "New Emax " << *p_hamilt_sto->emax << " Ry; new Emin " << *p_hamilt_sto->emin << " Ry" << std::endl; diff --git a/source/source_pw/module_stodft/unittests/CMakeLists.txt b/source/source_pw/module_stodft/unittests/CMakeLists.txt index b51097f074b..852294bd9f3 100644 --- a/source/source_pw/module_stodft/unittests/CMakeLists.txt +++ b/source/source_pw/module_stodft/unittests/CMakeLists.txt @@ -1,9 +1,17 @@ abacus_disable_feature_definitions(__MPI) abacus_disable_feature_definitions(__CUDA) abacus_disable_feature_definitions(__ROCM) +abacus_disable_feature_definitions(__EXX) # 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) + +# Regression test for the Chebyshev-window guard and the DOS parameter/result +# checks: a healthy window must be returned unchanged, a positive Emin or a +# window that truncates the spectrum must be repaired, and a bad DOS setup must +# be reported without aborting the run. +AddTest(TARGET MODULE_PW_STO_DOS_QUALITY_UTs LIBS base device SOURCES + test_sto_dos_quality.cpp ../sto_dos_quality.cpp) diff --git a/source/source_pw/module_stodft/unittests/test_sto_dos_quality.cpp b/source/source_pw/module_stodft/unittests/test_sto_dos_quality.cpp new file mode 100644 index 00000000000..a03115fa58b --- /dev/null +++ b/source/source_pw/module_stodft/unittests/test_sto_dos_quality.cpp @@ -0,0 +1,251 @@ +#include "../sto_dos_quality.h" + +#include + +#include +#include +#include +#include + +/************************************************ + * unit test of sto_dos_quality.cpp + * + * Regression tests for the two quality guards of the SDFT stochastic DOS: + * + * (a) the Chebyshev energy window must cover the deterministic eigenvalues, + * the plane-wave spectrum and the requested output grid - otherwise a + * positive lower bound hides every occupied state, and |t| > 1 makes + * T_n(t) grow exponentially (the historical 1e26--1e64 DOS values); + * + * (b) DOS parameters that are silently useless at high temperature (grid + * spacing vs Gaussian broadening, Chebyshev order vs range/sigma) and a + * DOS curve that does not integrate to the number of plane-wave states, + * goes negative, or was evaluated outside the window. + * + * All assertions encode the contract only, never an implementation detail, so + * any correct implementation passes. The helpers only report warnings, hence + * "is a warning produced" / "is a healthy setup silent" is what is checked. + ***********************************************/ + +namespace +{ +const double ecut = 900.0; // ecutwfc of the production run [Ry] +const double bad_emin = 112.433; // positive automatic lower bound of that run [Ry] +const double bad_emax = 810.199; // upper bound of the same run [Ry] +const double ks_min = -32.8; // lowest true KS eigenvalue [Ry] +const double ks_max = 9.65; // highest true KS eigenvalue [Ry] + +std::vector ks_eigs() +{ + return {ks_min, -12.0, -3.2, 0.0, 4.4, ks_max}; +} + +bool has_warning_containing(const std::vector& warnings, const std::string& needle) +{ + for (const std::string& w: warnings) + { + if (w.find(needle) != std::string::npos) + { + return true; + } + } + return false; +} + +/// Contract for a repaired window: finite, ordered, covering the eigenvalues +/// and the plane-wave spectrum top. +void expect_healthy(const ModuleIO::CheRange& r, const std::vector& det_eigs, double ecut_in) +{ + EXPECT_TRUE(std::isfinite(r.emin)); + EXPECT_TRUE(std::isfinite(r.emax)); + EXPECT_GT(r.emax - r.emin, 1e-6); + if (ecut_in > 0.0) + { + EXPECT_GE(r.emax, 1.05 * ecut_in); + } + for (double e: det_eigs) + { + EXPECT_LT(r.emin, e); + EXPECT_GT(r.emax, e); + } +} +} // namespace + +class TestStoDosQuality : public ::testing::Test +{ +}; + +// --------------------------------------------------------------------------- +// (a) Chebyshev-window guard +// --------------------------------------------------------------------------- + +// 1) healthy input must be returned bit for bit unchanged (no regression for +// already working runs) +TEST_F(TestStoDosQuality, healthy_range_is_returned_unchanged) +{ + const double emin = -40.0; // below min(ks_eigs) = -32.8 + const double emax = 950.0; // above 1.05*ecutwfc = 945 + const ModuleIO::CheRange r = ModuleIO::sanitize_che_range(emin, emax, ecut, ks_eigs(), nullptr); + EXPECT_EQ(r.emin, emin); + EXPECT_EQ(r.emax, emax); + EXPECT_FALSE(r.emin_repaired); + EXPECT_FALSE(r.emax_repaired); + EXPECT_FALSE(r.degenerate); +} + +// 2) key regression: a positive lower bound must be repaired, otherwise every +// bound state falls outside the window +TEST_F(TestStoDosQuality, positive_emin_is_repaired) +{ + const ModuleIO::CheRange r = ModuleIO::sanitize_che_range(bad_emin, bad_emax, ecut, {}, nullptr); + EXPECT_TRUE(r.emin_repaired); + EXPECT_LT(r.emin, 0.0); // the original keeps +112.4 -> FAIL + EXPECT_GE(r.emax, 1.05 * ecut); // 810.2 -> 945 + expect_healthy(r, {}, ecut); +} + +// 3) Emax below the plane-wave spectrum top must be raised to 1.05*ecutwfc +TEST_F(TestStoDosQuality, emax_floor_from_ecut) +{ + const ModuleIO::CheRange r = ModuleIO::sanitize_che_range(-10.0, 700.0, ecut, {}, nullptr); + EXPECT_GE(r.emax, 1.05 * ecut); + EXPECT_TRUE(r.emax_repaired); + // no floor is imposed when ecutwfc is unknown (0) + const ModuleIO::CheRange r0 = ModuleIO::sanitize_che_range(-10.0, 700.0, 0.0, {}, nullptr); + EXPECT_EQ(r0.emax, 700.0); +} + +// 4) deterministic (KS) eigenvalues must be covered +TEST_F(TestStoDosQuality, det_eigs_are_covered) +{ + const ModuleIO::CheRange r1 = ModuleIO::sanitize_che_range(5.0, 950.0, ecut, ks_eigs(), nullptr); + EXPECT_LT(r1.emin, ks_min); + expect_healthy(r1, ks_eigs(), ecut); + + const ModuleIO::CheRange r2 = ModuleIO::sanitize_che_range(bad_emin, bad_emax, ecut, ks_eigs(), nullptr); + EXPECT_LT(r2.emin, ks_min); + expect_healthy(r2, ks_eigs(), ecut); + + const ModuleIO::CheRange r3 = ModuleIO::sanitize_che_range(-10.0, 8.0, ecut, {ks_max}, nullptr); + EXPECT_GT(r3.emax, ks_max); +} + +// 5) invalid input (NaN / inverted / zero width) must become a usable window +TEST_F(TestStoDosQuality, invalid_input_is_sanitized) +{ + const double nan = std::numeric_limits::quiet_NaN(); + const std::vector> bad = {{950.0, -10.0}, {nan, 950.0}, {-10.0, nan}, {0.0, 0.0}}; + for (const std::pair& p: bad) + { + const ModuleIO::CheRange r = ModuleIO::sanitize_che_range(p.first, p.second, ecut, {}, nullptr); + EXPECT_TRUE(r.degenerate); + expect_healthy(r, {}, ecut); + } +} + +// 6) idempotent: a repaired window must be stable, otherwise the SCF drifts +TEST_F(TestStoDosQuality, idempotent) +{ + const ModuleIO::CheRange r1 = ModuleIO::sanitize_che_range(bad_emin, bad_emax, ecut, ks_eigs(), nullptr); + const ModuleIO::CheRange r2 = ModuleIO::sanitize_che_range(r1.emin, r1.emax, ecut, ks_eigs(), nullptr); + EXPECT_EQ(r1.emin, r2.emin); + EXPECT_EQ(r1.emax, r2.emax); + EXPECT_FALSE(r2.emin_repaired); + EXPECT_FALSE(r2.emax_repaired); +} + +// 7) the DOS output window must stay inside the Chebyshev window so that +// |t| <= 1 holds by construction (dos_scale used to break this) +TEST_F(TestStoDosQuality, output_window_inside_range) +{ + const double dos_scale = 1.005; + const ModuleIO::CheRange bad = ModuleIO::sanitize_che_range(bad_emin, bad_emax, ecut, {}, nullptr); + ModuleIO::CheRange requested; + requested.emin = bad.emin * dos_scale; + requested.emax = bad.emax * dos_scale; + + const ModuleIO::CheRange r = ModuleIO::sanitize_che_range(bad.emin, bad.emax, ecut, {}, &requested); + EXPECT_LE(r.emin, requested.emin + 1e-12); + EXPECT_GE(r.emax, requested.emax - 1e-12); + + const double half = 0.5 * (r.emax - r.emin); + const double mid = 0.5 * (r.emax + r.emin); + EXPECT_LE(std::fabs(requested.emin - mid) / half, 1.0 + 1e-12); + EXPECT_LE(std::fabs(requested.emax - mid) / half, 1.0 + 1e-12); + + // without the guard the grid would leave the window + EXPECT_GT(std::fabs(requested.emin - 0.5 * (bad.emax + bad.emin)) / (0.5 * (bad.emax - bad.emin)), 1.0); +} + +// --------------------------------------------------------------------------- +// (b) DOS parameter / result checks +// --------------------------------------------------------------------------- + +// 8) healthy parameters must be completely silent (no warning spam) +TEST_F(TestStoDosQuality, healthy_parameters_are_silent) +{ + // range 2260 eV (typical high-T case), sigma 20 eV, de 1 eV, nche 600 + EXPECT_TRUE(ModuleIO::check_dos_parameters(2260.0, 20.0, 1.0, 600).empty()); + EXPECT_TRUE(ModuleIO::check_dos_parameters(40.0, 0.1, 0.05, 2000).empty()); +} + +// 9) grid vs broadening: de << sigma and de >> sigma both warn +TEST_F(TestStoDosQuality, grid_density_versus_sigma) +{ + const std::vector fine = ModuleIO::check_dos_parameters(200.0, 1.0, 0.001, 500); + EXPECT_TRUE(has_warning_containing(fine, "much smaller than dos_sigma")); + + const std::vector coarse = ModuleIO::check_dos_parameters(200.0, 0.1, 5.0, 500); + EXPECT_TRUE(has_warning_containing(coarse, "much larger than dos_sigma")); +} + +// 10) dos_sigma <= 0 and dos_edelta_ev <= 0 are reported immediately +TEST_F(TestStoDosQuality, non_positive_sigma_is_reported) +{ + const std::vector zero = ModuleIO::check_dos_parameters(100.0, 0.0, 1.0, 500); + ASSERT_FALSE(zero.empty()); + EXPECT_TRUE(has_warning_containing(zero, "not positive")); + EXPECT_TRUE(has_warning_containing(ModuleIO::check_dos_parameters(100.0, -1.0, 1.0, 500), "not positive")); + + const std::vector bad_de = ModuleIO::check_dos_parameters(100.0, 1.0, 0.0, 500); + ASSERT_FALSE(bad_de.empty()); + EXPECT_TRUE(has_warning_containing(bad_de, "dos_edelta_ev must be positive")); +} + +// 11) insufficient dos_nche must report the estimated order needed +TEST_F(TestStoDosQuality, insufficient_nche_is_reported) +{ + const std::vector warn = ModuleIO::check_dos_parameters(2260.0, 0.07, 0.05, 600); + ASSERT_FALSE(warn.empty()); + EXPECT_TRUE(has_warning_containing(warn, "narrower than the Chebyshev expansion can resolve")); + EXPECT_TRUE(has_warning_containing(warn, "estimated order needed")); +} + +// 12) an extremely wide range relative to sigma is reported +TEST_F(TestStoDosQuality, extremely_wide_range_is_reported) +{ + const std::vector warn = ModuleIO::check_dos_parameters(2.0e5, 1.0, 0.5, 5000); + EXPECT_TRUE(has_warning_containing(warn, "more than 1e4 times dos_sigma")); +} + +// 13) result checks: |t| > 1, non-conserved integral, negative DOS +TEST_F(TestStoDosQuality, result_checks) +{ + EXPECT_TRUE(ModuleIO::check_dos_result(12806.5, 12806.5, 0.0, 0.999).empty()); + + EXPECT_TRUE(has_warning_containing(ModuleIO::check_dos_result(12806.5, 12806.5, 0.0, 1.5), + "outside the Chebyshev interval")); + EXPECT_TRUE(has_warning_containing(ModuleIO::check_dos_result(12166.0, 12806.5, 0.0, 0.9), + "number of plane-wave states")); + EXPECT_TRUE(has_warning_containing(ModuleIO::check_dos_result(12806.5, 12806.5, -50.0, 0.9), + "negative values")); + // a tiny negative value is numeric noise, not a warning + EXPECT_TRUE(ModuleIO::check_dos_result(12806.5, 12806.5, -1.0e-6, 0.9).empty()); +} + +// 14) the integral check can be skipped (spin-polarized runs, or a window that +// truncates the spectrum on purpose) +TEST_F(TestStoDosQuality, integral_check_can_be_skipped) +{ + EXPECT_TRUE(ModuleIO::check_dos_result(1.0, -1.0, 0.0, 0.9).empty()); +} From 9c68ce0576ef10326f0a07abaaccda4aba7d7ec3 Mon Sep 17 00:00:00 2001 From: LiYuqiii <139907896+LiYuqiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:19:58 +0800 Subject: [PATCH 3/4] SDFT DOS: link sto_dos_quality.cpp into the existing Sto_Tool unit test Sto_Tool::check_che_op() now calls ModuleIO::sanitize_che_range(), so the pre-existing MODULE_PW_Sto_Tool_UTs target (which compiles ../sto_tool.cpp) needs ../sto_dos_quality.cpp as well; otherwise the target fails to link in the BUILD_TESTING configuration. --- source/source_pw/module_stodft/test/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/source_pw/module_stodft/test/CMakeLists.txt b/source/source_pw/module_stodft/test/CMakeLists.txt index 534b5143c4c..ab66db1c593 100644 --- a/source/source_pw/module_stodft/test/CMakeLists.txt +++ b/source/source_pw/module_stodft/test/CMakeLists.txt @@ -7,7 +7,7 @@ abacus_disable_feature_definitions(__ROCM) addtest( TARGET MODULE_PW_Sto_Tool_UTs LIBS parameter psi base device - SOURCES ../sto_tool.cpp test_sto_tool.cpp) + SOURCES ../sto_tool.cpp ../sto_dos_quality.cpp test_sto_tool.cpp) addtest( TARGET MODULE_PW_Sto_Hamilt_UTs From a5a9bf570960ac00c5f303aa683c3090a7cfba86 Mon Sep 17 00:00:00 2001 From: LiYuqiii <139907896+LiYuqiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:22:12 +0800 Subject: [PATCH 4/4] SDFT DOS: add sto_dos_quality.o to the Makefile build list The Makefile-based build (source/Makefile.Objects) lists its objects explicitly, so the new quality-guard translation unit has to be registered there too; otherwise `make -f ../Makefile` fails with an undefined reference to ModuleIO::sanitize_che_range(). --- source/Makefile.Objects | 1 + 1 file changed, 1 insertion(+) diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 502f29b9e05..c88defc2b4f 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1094,6 +1094,7 @@ OBJS_SRCPW=h_ewald_pw.o\ elecond.o\ sto_tool.o\ sto_elecond.o\ + sto_dos_quality.o\ sto_dos.o\ onsite_proj.o\ onsite_proj_init.o\