Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions source/source_pw/module_stodft/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ endif()
if(BUILD_TESTING)
if(ENABLE_MPI)
add_subdirectory(test)
add_subdirectory(unittests)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: register the scalar entropy tests outside the ENABLE_MPI guard. Their own CMake file disables MPI and they exercise no parallel code, but this placement prevents MPI-off builds from running the new regression.

endif()
endif()
148 changes: 144 additions & 4 deletions source/source_pw/module_stodft/sto_dos.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
#include "source_base/tool_title.h"
#include "source_io/module_parameter/parameter.h"
#include "sto_tool.h"

#include <algorithm>
#include <cmath>
#include <limits>
#include <sstream>

template <typename FPTYPE, typename Device>
Sto_DOS<FPTYPE, Device>::~Sto_DOS()
{
Expand All @@ -28,7 +34,10 @@ Sto_DOS<FPTYPE, Device>::Sto_DOS(ModulePW::PW_Basis_K* p_wfcpw_in,
this->p_hamilt_sto = static_cast<StoHamiltPW<std::complex<double>>*>(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);
}
Expand All @@ -44,14 +53,84 @@ void Sto_DOS<FPTYPE, Device>::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<FPTYPE, Device>()(
this->dos_nche,
emin_sto,
emax_sto,
try_emin,
try_emax,
this->nbands_sto,
this->p_kv,
reinterpret_cast<Stochastic_WF<std::complex<FPTYPE>, Device>*>(this->p_stowf),
reinterpret_cast<StoHamiltPW<std::complex<FPTYPE>, 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<double>::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<double>::max();
Parallel_Reduce::reduce_min(global_det_emin);
if (global_det_emin < std::numeric_limits<double>::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;
Expand All @@ -75,6 +154,33 @@ void Sto_DOS<FPTYPE, Device>::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;
Comment on lines +173 to +179

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep output limits separate from the spectral interval

The output energy is the Gaussian centre; calcoef_real samples that Gaussian at cos(theta), while the recurrence evaluates T_n(H). Widening this interval at fixed dos_nche can therefore miss a previously resolved peak: with N=100, sigma=0.07 eV and an output window of ±10000 eV, every coefficient sample for a 2 eV peak lies beyond the Gaussian cutoff and returns zero. Keep the verified Hamiltonian interval independent of the output window, and test DOS at common energies when only the window changes.

}

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 <typename FPTYPE, typename Device>
Expand Down Expand Up @@ -168,13 +274,47 @@ void Sto_DOS<FPTYPE, Device>::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<double>(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<long long>(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<double> sto_dos(ndos);
std::vector<double> ks_dos(ndos);
Expand Down
94 changes: 52 additions & 42 deletions source/source_pw/module_stodft/sto_func.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,53 @@
#include "sto_func.h"

#include "source_estate/occupy.h"

#include <cmath>

#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 <typename REAL>
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 <typename REAL>
Sto_Func<REAL>::Sto_Func()
{
Expand Down Expand Up @@ -85,62 +130,27 @@ REAL Sto_Func<REAL>::nxfd(REAL rawe) const
template <typename REAL>
REAL Sto_Func<REAL>::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<REAL>(e_mu);
}

template <typename REAL>
REAL Sto_Func<REAL>::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<REAL>(ne_mu);
}

template <typename REAL>
REAL Sto_Func<REAL>::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<REAL>(ne_mu);
return (g > 0) ? std::sqrt(g) : 0;
}

template <typename REAL>
Expand Down
26 changes: 26 additions & 0 deletions source/source_pw/module_stodft/sto_iter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
#include "source_hsolver/para_lin_tf.h"
#include "source_io/module_parameter/parameter.h"

#include <algorithm>
#include <cmath>

template <typename T, typename Device>
Stochastic_Iter<T, Device>::Stochastic_Iter()
{
Expand Down Expand Up @@ -211,6 +214,29 @@ void Stochastic_Iter<T, Device>::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;
Comment on lines +223 to +228

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve valid positive trial bounds

This branch also replaces an explicitly supplied positive emin_sto after checkconverge() has accepted the interval. A positive kinetic or shifted spectrum is valid; forcing its lower bound below zero enlarges the interval and changes the fixed-order occupation/entropy approximation and chemical-potential search. Preserve validated positive bounds and use spectral evidence to trigger a fallback, with a positive/translated-spectrum regression; the same condition in check_che_op needs the same treatment.

// 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)
Comment on lines +232 to +233

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: the exception rationale also needs to cover the four new PARAM.inp.ecutwfc reads here and in sto_tool.cpp. They control the Hamiltonian interval, so the proposed ostream cleanup would leave this computational dependency in place. Pass the cutoff explicitly or include its scope, numerical risk and removal plan in the requested exception.

{
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
Expand Down
Loading
Loading