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\ diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index a9acc3c4d0a..3c83d064af7 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 fb863199d61..2dd72578957 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 @@ -23,4 +24,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 eb78c6700f3..de9ebcd731c 100644 --- a/source/source_pw/module_stodft/sto_dos.cpp +++ b/source/source_pw/module_stodft/sto_dos.cpp @@ -5,7 +5,29 @@ #include "source_base/timer.h" #include "source_base/tool_title.h" #include "source_io/module_parameter/parameter.h" +#include "sto_dos_quality.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 +50,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 +69,71 @@ 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 range determined by the SCF check only learns the high-energy end + // reliably. Run the pure, unit-tested sanitiser (module + // sto_dos_quality): it covers the known deterministic eigenvalues and the + // plane-wave spectrum top, so an occupied state outside the interval (T_n + // grows exponentially there) and an underestimated upper bound are both + // removed. Healthy ranges are returned bit for bit unchanged. + { + std::vector det_eigs; + 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_eigs.push_back(e); + } + } + } + } + const ModuleIO::CheRange fixed + = ModuleIO::sanitize_che_range(*p_hamilt_sto->emin, *p_hamilt_sto->emax, PARAM.inp.ecutwfc, det_eigs); + if (fixed.emin_repaired || fixed.emax_repaired || fixed.degenerate) + { + std::ostringstream range_msg; + range_msg << " DOS: Chebyshev range repaired from [" << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax + << "] to [" << fixed.emin << ", " << fixed.emax << "] Ry"; + dos_log(range_msg.str(), false); + } + *p_hamilt_sto->emin = fixed.emin; + *p_hamilt_sto->emax = fixed.emax; + } + if (dos_setemax) { this->emax = dos_emax_ev; @@ -75,6 +157,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 +298,36 @@ 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; + + // Report DOS settings that cannot resolve the curve: grid spacing versus + // Gaussian broadening, and Chebyshev order versus range/sigma. The checks + // are pure functions (unittests/test_sto_dos_quality.cpp) and 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); + for (const std::string& msg: ModuleIO::check_dos_parameters(range_ev, sigma_ev, de, this->dos_nche)) + { + dos_log(" WARNING: DOS: " + msg, 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); @@ -246,6 +399,7 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons ofsdos.open(dosfile.c_str()); double maxerror = 0; double sum = 0; + double min_dos = std::numeric_limits::max(); ofsdos << ndos << " # number of points" << std::endl; ofsdos << "#" << std::setw(19) << "energy(eV)" @@ -259,6 +413,7 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons maxerror = tmperror; } double dos = 2.0 * (ks_dos[ie] + sto_dos[ie]) / ModuleBase::Ry_to_eV; + min_dos = std::min(min_dos, dos); sum += dos; ofsdos << std::setw(20) << emin + ie * de << std::setw(20) << dos << std::setw(20) << sum * de << std::setw(20) << tmperror << std::endl; @@ -267,6 +422,18 @@ void Sto_DOS::caldos(const double sigmain, const double de, cons std::cout << "Finish DOS" << std::endl; std::cout << std::scientific << "DOS max absolute Chebyshev Error: " << maxerror << std::endl; ofsdos.close(); + + // Result-level checks: a curve that goes visibly negative, or an output + // energy outside the Chebyshev interval, means the printed numbers must + // not be used without changing dos_sigma / dos_nche / the window. + const double dE = *this->stofunc.Emax - *this->stofunc.Emin; + const double t_lo = (2.0 * this->emin / ModuleBase::Ry_to_eV - *this->stofunc.Emax - *this->stofunc.Emin) / dE; + const double t_hi = (2.0 * this->emax / ModuleBase::Ry_to_eV - *this->stofunc.Emax - *this->stofunc.Emin) / dE; + const double max_abs_t = std::max(std::fabs(t_lo), std::fabs(t_hi)); + for (const std::string& msg: ModuleIO::check_dos_result(min_dos, max_abs_t)) + { + dos_log(" WARNING: DOS: " + msg, true); + } } ModuleBase::timer::end("Sto_DOS", "DOS Loop"); ModuleBase::timer::end("Sto_DOS", "caldos"); 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..7232c97b63a --- /dev/null +++ b/source/source_pw/module_stodft/sto_dos_quality.cpp @@ -0,0 +1,220 @@ +#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 negative_dos_abs_tol = 1.0e-6; ///< |min DOS| below this is ringing 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: guarantee a finite, non-degenerate 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) +{ + 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); + 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 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; " + "check dos_emin_ev / dos_emax_ev against the interval printed above."); + } + + if (std::isfinite(min_dos) && min_dos < 0.0) + { + // Allow the tiny ringing of a well-resolved expansion, flag anything visible. + if (std::fabs(min_dos) > negative_dos_abs_tol) + { + 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..d5abe485cd3 --- /dev/null +++ b/source/source_pw/module_stodft/sto_dos_quality.h @@ -0,0 +1,90 @@ +#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 and the physical + * plane-wave spectrum (`ecutwfc`). Without it a positive lower bound + * excludes every occupied state and T_n(|x| > 1) grows exponentially + * (the historical 1e26--1e64 DOS values). The interval is a property of + * the spectrum and is deliberately *not* widened to fit a requested DOS + * output grid: at a fixed order that would lower the resolution. + * + * 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 + * + * 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. 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); + +/** + * @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 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 min_dos, double max_abs_t); + +} // namespace ModuleIO + +#endif // STO_DOS_QUALITY_H 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..610a42172df 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 f63a8707236..0febffdf46d 100644 --- a/source/source_pw/module_stodft/sto_tool.cpp +++ b/source/source_pw/module_stodft/sto_tool.cpp @@ -1,5 +1,8 @@ +#include "sto_dos_quality.h" #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 +12,8 @@ #ifdef __MPI #include "mpi.h" #endif +#include +#include #include template @@ -48,14 +53,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,9 +124,33 @@ 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 - GlobalV::ofs_running << "New Emax " << *p_hamilt_sto->emax << " Ry; new Emin " << *p_hamilt_sto->emin - << " Ry" << std::endl; - change = false; + // 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. The repair itself is the + // pure, unit-tested sanitiser from module sto_dos_quality. + const bool emin_is_automatic = (PARAM.inp.emin_sto == 0.0); + if (emin_is_automatic) + { + const std::vector no_eigs; + const ModuleIO::CheRange fixed + = ModuleIO::sanitize_che_range(*p_hamilt_sto->emin, *p_hamilt_sto->emax, PARAM.inp.ecutwfc, no_eigs); + if (fixed.emin_repaired || fixed.emax_repaired || fixed.degenerate) + { + std::ostringstream range_msg; + range_msg << " WARNING: Chebyshev range repaired from [" << *p_hamilt_sto->emin << ", " + << *p_hamilt_sto->emax << "] to [" << fixed.emin << ", " << fixed.emax << "] Ry"; + GlobalV::ofs_running << range_msg.str() << std::endl; + } + *p_hamilt_sto->emin = fixed.emin; + *p_hamilt_sto->emax = fixed.emax; + } } } } 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/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 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..dca92282095 --- /dev/null +++ b/source/source_pw/module_stodft/unittests/CMakeLists.txt @@ -0,0 +1,14 @@ +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) + +# Regression test for the pure DOS quality guards: the Chebyshev-window +# sanitiser and the DOS parameter / result checks. +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..114d19ddc39 --- /dev/null +++ b/source/source_pw/module_stodft/unittests/test_sto_dos_quality.cpp @@ -0,0 +1,219 @@ +#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()); + 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, {}); + 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, {}); + 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, {}); + 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()); + 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()); + 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}); + 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, {}); + 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()); + const ModuleIO::CheRange r2 = ModuleIO::sanitize_che_range(r1.emin, r1.emax, ecut, ks_eigs()); + 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, 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, result_checks_are_silent_for_a_healthy_curve) +{ + // |t| <= 1 and a positive curve: nothing to report. + EXPECT_TRUE(ModuleIO::check_dos_result(0.5, 1.0).empty()); +} + +TEST_F(TestStoDosQuality, result_check_reports_energies_outside_the_interval) +{ + // One output energy at |t| = 1.5: T_n(t) diverges there. + const std::vector w = ModuleIO::check_dos_result(0.5, 1.5); + ASSERT_EQ(w.size(), 1u); + EXPECT_NE(w[0].find("outside the Chebyshev interval"), std::string::npos); +} + +TEST_F(TestStoDosQuality, result_check_reports_a_negative_curve) +{ + const std::vector w = ModuleIO::check_dos_result(-3.0, 0.9); + ASSERT_EQ(w.size(), 1u); + EXPECT_NE(w[0].find("negative"), std::string::npos); +} 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); + } +}