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
6 changes: 5 additions & 1 deletion source/source_io/module_parameter/read_inp_postproc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
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 @@ -23,4 +23,5 @@ if(BUILD_TESTING)
if(ENABLE_MPI)
add_subdirectory(test)
endif()
add_subdirectory(unittests)
endif()
184 changes: 180 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,27 @@
#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>

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 <typename FPTYPE, typename Device>
Sto_DOS<FPTYPE, Device>::~Sto_DOS()
{
Expand All @@ -28,7 +49,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 +68,85 @@ 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)
{
std::ostringstream reset_msg;
reset_msg << " DOS: reset Chebyshev Emin from " << *p_hamilt_sto->emin << " Ry to " << safe_emin
<< " Ry (lowest KS eigenvalue = " << det_emin << " Ry)";
dos_log(reset_msg.str(), false);
*p_hamilt_sto->emin = safe_emin;
}
}
if (!std::isfinite(*p_hamilt_sto->emax) || *p_hamilt_sto->emax <= *p_hamilt_sto->emin)
{
*p_hamilt_sto->emax = *p_hamilt_sto->emin + 1.0;
}

if (dos_setemax)
{
this->emax = dos_emax_ev;
Expand All @@ -75,6 +170,54 @@ 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.");
}

// 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;
Comment on lines +196 to +198

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.

[P3] Measure the removed window widths with positive signs

Both differences are nonpositive by construction: clipped_emin_ev >= requested_emin_ev and clipped_emax_ev <= requested_emax_ev. Consequently report_clip is always false for a valid interval, even when a large portion of the requested window is removed. If clipping is retained, reverse both subtractions so the promised warning can be emitted.

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 <typename FPTYPE, typename Device>
Expand Down Expand Up @@ -168,13 +311,46 @@ 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.";

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: please qualify “method 2 with sufficient memory” for the very large orders now described in the INPUT help. Method 2 still forms dos_nche * dos_nche and matrix indices as signed-int products, so an order of 1e5 overflows on platforms with 32-bit int before available memory is the limiting condition. Recommend method 1 for such orders, or require checked dimension/index arithmetic as well as adequate memory.

dos_log(" WARNING: " + msg.str(), true);
}
}
ModuleBase::timer::end("Sto_DOS", "Tracepoly");

std::cout << "2. Dos:" << std::endl;
ModuleBase::timer::start("Sto_DOS", "DOS Loop");
int n10 = ndos / 10;
// For very small output windows ndos/10 is zero; the old modulus then
// divided by zero and terminated the run with SIGFPE.
int n10 = std::max(1, ndos / 10);
int percent = 10;
std::vector<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
Loading
Loading