diff --git a/source/source_pw/module_stodft/CMakeLists.txt b/source/source_pw/module_stodft/CMakeLists.txt index fb863199d6..3481a2ce15 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 eb78c6700f..a87a4b6b98 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 d8935c7f7f..6b435fb551 100644 --- a/source/source_pw/module_stodft/sto_func.cpp +++ b/source/source_pw/module_stodft/sto_func.cpp @@ -1,8 +1,53 @@ #include "sto_func.h" #include "source_estate/occupy.h" + +#include + #define TWOPI 6.283185307179586 +namespace +{ +// Evaluate the Fermi-Dirac entropy density f*ln(f) + (1-f)*ln(1-f) +// from ne_mu = (E - mu)/kT without the cancellation that the literal +// expression suffers when f is tiny: +// (1-f)*ln(1-f) ~ -f, +// but in double precision 1-f rounds to 1 as soon as f < ~1e-16, so the +// literal expression drops this -f term and leaves an error of order f +// (relative error ~1/|ln f|, i.e. percent level) in the deep tail. +// The resulting non-smooth error seeds spurious high-order Chebyshev +// coefficients (~1e-12) which are then amplified by T_n(x) for any +// eigenvalue outside the expansion interval. Using s = min(f, 1-f) +// computed directly (no subtraction) and log1p(-s) keeps full relative +// accuracy for all temperatures. +template +inline REAL entropy_density_from_ne_mu(const REAL ne_mu) +{ + REAL s; // s = min(f, 1-f), always in [0, 0.5] + if (ne_mu >= 0) + { + if (ne_mu > 700) + { + return 0; + } + s = 1 / (1 + std::exp(ne_mu)); + } + else + { + if (ne_mu < -700) + { + return 0; + } + s = 1 / (1 + std::exp(-ne_mu)); + } + if (s <= 0) + { + return 0; + } + return s * std::log(s) + (1 - s) * std::log1p(-s); +} +} // namespace + template Sto_Func::Sto_Func() { @@ -85,20 +130,8 @@ REAL Sto_Func::nxfd(REAL rawe) const template REAL Sto_Func::fdlnfd(REAL e) const { - REAL e_mu = (e - mu) / this->tem; - if (e_mu > 36) { - return 0; - } else if (e_mu < -36) { - return 0; - } else - { - REAL f = 1 / (1 + exp(e_mu)); - if (f == 0 || f == 1) { - return 0; - } else { - return (f * log(f) + (1.0 - f) * log(1.0 - f)); -} - } + const REAL e_mu = (e - mu) / this->tem; + return entropy_density_from_ne_mu(e_mu); } template @@ -106,20 +139,8 @@ REAL Sto_Func::nfdlnfd(REAL rawe) const { REAL Ebar = (*Emin + *Emax) / 2; REAL DeltaE = (*Emax - *Emin) / 2; - REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; - if (ne_mu > 36) { - return 0; - } else if (ne_mu < -36) { - return 0; - } else - { - REAL f = 1 / (1 + exp(ne_mu)); - if (f == 0 || f == 1) { - return 0; - } else { - return f * log(f) + (1 - f) * log(1 - f); -} - } + const REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; + return entropy_density_from_ne_mu(ne_mu); } template @@ -127,20 +148,9 @@ REAL Sto_Func::n_root_fdlnfd(REAL rawe) const { REAL Ebar = (*Emin + *Emax) / 2; REAL DeltaE = (*Emax - *Emin) / 2; - REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; - if (ne_mu > 36) { - return 0; - } else if (ne_mu < -36) { - return 0; - } else - { - REAL f = 1 / (1 + exp(ne_mu)); - if (f == 0 || f == 1) { - return 0; - } else { - return sqrt(-f * log(f) - (1 - f) * log(1 - f)); -} - } + const REAL ne_mu = (rawe * DeltaE + Ebar - mu) / this->tem; + const REAL g = -entropy_density_from_ne_mu(ne_mu); + return (g > 0) ? std::sqrt(g) : 0; } template diff --git a/source/source_pw/module_stodft/sto_iter.cpp b/source/source_pw/module_stodft/sto_iter.cpp index 6a12106486..92398e18ad 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 f63a870723..9e273eca5b 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 2fca88e482..bcff514125 100644 --- a/source/source_pw/module_stodft/sto_wf.cpp +++ b/source/source_pw/module_stodft/sto_wf.cpp @@ -108,6 +108,11 @@ void Stochastic_WF::allocate_chi0() } this->nchip_max = tmpnchip; + // Record that real stochastic orbitals have been allocated. This member + // was previously left at its default value of zero, so downstream code + // (notably the DOS range check) mistakenly used random test vectors even + // when chi0/chiortho were available. + this->nchi = nchi; size_t size = this->nchip_max * npwx * nks; this->chi0_cpu = new psi::Psi(nks, this->nchip_max, npwx, this->ngk, true); ModuleBase::Memory::record("SDFT::chi0_cpu", size * sizeof(T)); @@ -204,6 +209,10 @@ void Stochastic_WF::init_com_orbitals() this->nchip_max = std::max(tmpnchip, this->nchip_max); delete[] npwip; } + // In the complete-basis ("all") mode nbands_sto is zero, but chi0 still + // contains real orbitals. Keep nchi nonzero so that consumers such as + // check_che_op know that actual orbitals are available. + this->nchi = this->nchip_max; size_t size = this->nchip_max * npwx * nks; this->chi0_cpu = new psi::Psi>(nks, this->nchip_max, npwx, this->ngk, true); this->chi0_cpu->zero_out(); @@ -277,6 +286,7 @@ void Stochastic_WF::init_com_orbitals() this->chi0_cpu->operator()(ik, ichi, ichi) = 1; } } + this->nchi = this->nchip_max; // allocate chi0 Device* ctx = {}; diff --git a/source/source_pw/module_stodft/unittests/CMakeLists.txt b/source/source_pw/module_stodft/unittests/CMakeLists.txt new file mode 100644 index 0000000000..b51097f074 --- /dev/null +++ b/source/source_pw/module_stodft/unittests/CMakeLists.txt @@ -0,0 +1,9 @@ +abacus_disable_feature_definitions(__MPI) +abacus_disable_feature_definitions(__CUDA) +abacus_disable_feature_definitions(__ROCM) + +# Regression test for the occupation / entropy kernels of the SDFT solver: +# `1 - f` must not be computed by subtraction and the expanded function must +# not contain an artificial cutoff (|x| > 36 used to return exactly 0). +AddTest(TARGET MODULE_PW_STO_FUNC_UTs LIBS parameter base device SOURCES + test_sto_func.cpp ../sto_func.cpp ../../../source_estate/occupy.cpp) diff --git a/source/source_pw/module_stodft/unittests/test_sto_func.cpp b/source/source_pw/module_stodft/unittests/test_sto_func.cpp new file mode 100644 index 0000000000..0a143992f4 --- /dev/null +++ b/source/source_pw/module_stodft/unittests/test_sto_func.cpp @@ -0,0 +1,194 @@ +#include "../sto_func.h" + +#include + +#include + +/************************************************ + * unit test of sto_func.cpp (occupation / entropy kernels of SDFT) + * + * Goal: turn the "Ne vs TS Chebyshev precision asymmetry" failure into a + * self-checking regression test. Two known failure modes: + * (1) computing `1 - f` by subtraction loses accuracy when f -> 1 or f -> 0, + * which destroys the relative accuracy of the entropy density g; + * (2) an artificial cutoff such as `if (x > 36) return 0` introduces a + * discontinuity in the expanded function, which lifts the tail of the + * Chebyshev coefficients by several orders of magnitude and is then + * amplified by |x| > 1 into an O(1) spurious entropy. + * + * Only mathematical/physical properties are asserted here (no implementation + * detail), so any correct implementation passes. + * + * Sign convention of sto_func.cpp (must be respected, otherwise TS flips sign): + * fdlnfd(e) = f ln f + (1-f) ln(1-f) <= 0 (i.e. -g) + * nfdlnfd(rawe) = the same negative value (i.e. -g) + * n_root_fdlnfd(rawe) = sqrt(g) >= 0 (expanded by method 2) + * with g = -f ln f - (1-f) ln(1-f) >= 0 the true entropy density. + * The "n*" variants take the normalized Chebyshev coordinate rawe in [-1,1] + * and restore the energy through [Emin, Emax]. + ***********************************************/ + +namespace +{ +const double kT = 25.57754484; // 348 eV, the production temperature [Ry] +const double mu = 0.3; // arbitrary chemical potential inside the spectrum [Ry] + +// Independent closed form (equivalent, but free of cancellation): +// g(x) = ln(2cosh(x/2)) - (x/2)tanh(x/2) = |x|*y/(1+y) + ln(1+y), y = exp(-|x|) +// It follows a completely different path than "compute f, then take log" in +// ABACUS and agrees with a 50-digit mpmath reference to ~1e-16 relative +// for |x| <= 60. +double g_reference(double x) +{ + const double y = std::exp(-std::fabs(x)); + return std::fabs(x) * y / (1.0 + y) + std::log1p(y); +} +} // namespace + +/** + * - Tested Functions: + * - Sto_Func::fd / root_fd (occupation f and sqrt(f), input = physical energy) + * - Sto_Func::nroot_fd (sqrt(f), input = normalized coordinate) + * - Sto_Func::fdlnfd (f ln f + (1-f) ln(1-f) = -g, input = physical energy) + * - Sto_Func::n_root_fdlnfd (sqrt(g), input = normalized coordinate) + */ +class TestStoFunc : public ::testing::Test +{ + protected: + Sto_Func sto; + double emin = 0.0; + double emax = 0.0; + double xc = 0.0; // centre of [xmin,xmax] in units of x=(E-mu)/kT + double xh = 1.0; // half width + + void SetUp() override + { + sto.tem = kT; + sto.mu = mu; + set_x_range(-10.0, 50.0); + } + + // Chebyshev interval used by the "n*" variants: x in [xmin,xmax] <=> rawe in [-1,1] + void set_x_range(double xmin, double xmax) + { + xc = 0.5 * (xmin + xmax); + xh = 0.5 * (xmax - xmin); + emin = mu + xmin * kT; + emax = mu + xmax * kT; + sto.set_E_range(&emin, &emax); + } + + double to_rawe(double x) const + { + return (x - xc) / xh; + } +}; + +// 1) identities and independent reference: f(x)+f(-x)=1, g symmetric, sqrt(g)^2=g, f(0)=1/2, g(0)=ln2 +TEST_F(TestStoFunc, identities_and_independent_reference) +{ + EXPECT_NEAR(sto.fd(mu), 0.5, 1e-16); + EXPECT_NEAR(-sto.fdlnfd(mu), std::log(2.0), 1e-14); + EXPECT_NEAR(sto.n_root_fdlnfd(to_rawe(0.0)), std::sqrt(std::log(2.0)), 1e-13); + + set_x_range(-20.0, 20.0); + for (double x = -20.0; x <= 20.0; x += 0.5) + { + const double e = mu + x * kT; + const double e_neg = mu - x * kT; + const double g = -sto.fdlnfd(e); + + EXPECT_NEAR(sto.fd(e) + sto.fd(e_neg), 1.0, 1e-14); // particle-hole symmetry + EXPECT_NEAR(g, -sto.fdlnfd(e_neg), 1e-13); // g is even in x + EXPECT_GE(g, 0.0); // entropy is non-negative + EXPECT_LE(sto.fdlnfd(e), 0.0); // sign convention + EXPECT_NEAR(g, g_reference(x), 1e-13 * (1.0 + std::fabs(g_reference(x)))); + EXPECT_NEAR(sto.n_root_fdlnfd(to_rawe(x)) * sto.n_root_fdlnfd(to_rawe(x)), g, 1e-13); + EXPECT_GE(sto.fd(e), 0.0); + EXPECT_LE(sto.fd(e), 1.0); + } +} + +// 2) key regression: the expanded function must not contain an artificial jump. +// The true value is still 1e-13 ... 9e-8 for x in (36,45); `if (x>36) return 0` +// flattens it, leaving a step of sqrt(g(36)) = 9.26e-8 whose Chebyshev +// coefficient tail is ~2e-9, whereas a correct implementation stays ~1e-15. +TEST_F(TestStoFunc, no_artificial_cutoff_jump) +{ + // (a) for x in (36,45) g must still be positive and match the reference + for (double x = 36.5; x <= 45.0; x += 0.5) + { + const double e = mu + x * kT; + const double g = -sto.fdlnfd(e); + const double g_ref = g_reference(x); + EXPECT_GT(g, 0.0); // the original returns 0 here -> FAIL + EXPECT_NEAR(g, g_ref, 1e-12 * g_ref + 1e-300); + EXPECT_GT(sto.n_root_fdlnfd(to_rawe(x)), 0.0); // same for sqrt(g) + } + + // (b) sqrt(g) is continuous on [33,45]: with a 1e-2 step the difference + // between neighbours must stay far below the 9.3e-8 artificial step. + // The steepest legitimate slope in this range is at x=33, + // |d sqrt(g)/dx| ~ 0.5*sqrt(g(33)) ~ 2.5e-7, i.e. ~2.5e-9 per 1e-2 step. + double max_step = 0.0; + double prev = sto.n_root_fdlnfd(to_rawe(33.0)); + for (int i = 1; i <= 1200; ++i) + { + const double x = 33.0 + 0.01 * i; + const double cur = sto.n_root_fdlnfd(to_rawe(x)); + max_step = std::max(max_step, std::fabs(cur - prev)); + EXPECT_LE(cur, prev + 1e-15); // sqrt(g) is non-increasing for x>0 + prev = cur; + } + EXPECT_LE(max_step, 1e-8); // artificial step 9.3e-8 -> FAIL +} + +// 3) tail asymptotics and extremes: no NaN/Inf, and no crude truncation of a meaningful tail +TEST_F(TestStoFunc, tail_asymptotics_and_extremes) +{ + set_x_range(-800.0, 800.0); + for (double x: {50.0, 80.0, 120.0, 200.0}) + { + const double g = -sto.fdlnfd(mu + x * kT); + const double asym = std::exp(-x) * (x + 1.0); + EXPECT_GT(g, 0.0); // the original is 0 for x>36 -> FAIL + EXPECT_NEAR(g / asym, 1.0, 1e-9); + } + for (double x: {-50.0, -80.0, -120.0, -200.0}) + { + const double g = -sto.fdlnfd(mu + x * kT); + const double asym = std::exp(x) * (-x + 1.0); + EXPECT_GT(g, 0.0); + EXPECT_NEAR(g / asym, 1.0, 1e-9); + } + for (double x: {-700.0, 700.0, -745.0, 745.0, 1000.0, -1000.0}) + { + const double e = mu + x * kT; + EXPECT_TRUE(std::isfinite(sto.fd(e))); + EXPECT_TRUE(std::isfinite(sto.fdlnfd(e))); + EXPECT_TRUE(std::isfinite(sto.n_root_fdlnfd(to_rawe(x)))); + EXPECT_GE(sto.fd(e), 0.0); + EXPECT_LE(sto.fd(e), 1.0); + EXPECT_GE(-sto.fdlnfd(e), 0.0); + } +} + +// 4) monotonicity and sqrt(f) consistency (method 2 uses sqrt(f) for Ne) +TEST_F(TestStoFunc, monotonicity_and_sqrt_f) +{ + set_x_range(-50.0, 50.0); + double prev = sto.fd(mu - 50.0 * kT); + for (int i = -5000; i <= 5000; ++i) + { + const double x = 0.01 * i; + const double e = mu + x * kT; + const double cur = sto.fd(e); + EXPECT_LE(cur, prev + 1e-16); // f is non-increasing + prev = cur; + const double sf = sto.root_fd(e); + EXPECT_GE(sf, 0.0); + EXPECT_NEAR(sf * sf, cur, 1e-14); + const double nsf = sto.nroot_fd(to_rawe(x)); + EXPECT_NEAR(nsf * nsf, cur, 1e-13); + } +}