Skip to content
Draft
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/Makefile.Objects
Original file line number Diff line number Diff line change
Expand Up @@ -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\
Expand Down
2 changes: 2 additions & 0 deletions source/source_pw/module_stodft/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,5 +23,6 @@ endif()
if(BUILD_TESTING)
if(ENABLE_MPI)
add_subdirectory(test)
add_subdirectory(unittests)
endif()
endif()
245 changes: 229 additions & 16 deletions source/source_pw/module_stodft/sto_dos.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,61 @@
#include "source_base/parallel_comm.h"
#include "source_base/parallel_reduce.h"
#include "source_base/timer.h"
#include "source_pw/module_stodft/sto_dos_quality.h"
#include "source_base/tool_title.h"
#include "source_io/module_parameter/parameter.h"
#include "sto_tool.h"

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

template <typename FPTYPE, typename Device>
Sto_DOS<FPTYPE, Device>::~Sto_DOS()
{
}

namespace
{

/// Lowest deterministic (Kohn-Sham) eigenvalue over all k points and bands.
/// Returns false when no eigenvalue is available. The result is already
/// reduced over all pools.
bool minimum_ks_eigenvalue(const elecstate::ElecState* pelec, double& det_min)
{
det_min = std::numeric_limits<double>::max();
bool found = false;
if (pelec != nullptr)
{
const auto& ekb = pelec->ekb;
for (int ik = 0; ik < ekb.nr; ++ik)
{
for (int ib = 0; ib < ekb.nc; ++ib)
{
const double e = ekb(ik, ib);
if (std::isfinite(e))
{
det_min = std::min(det_min, e);
found = true;
}
}
}
}
#ifdef __MPI
double global_min = found ? det_min : std::numeric_limits<double>::max();
Parallel_Reduce::reduce_min(global_min);
if (global_min < std::numeric_limits<double>::max())
{
det_min = global_min;
found = true;
}
#endif
return found;
}

} // namespace

template <typename FPTYPE, typename Device>
Sto_DOS<FPTYPE, Device>::Sto_DOS(ModulePW::PW_Basis_K* p_wfcpw_in,
K_Vectors* p_kv_in,
Expand All @@ -28,7 +75,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,36 +94,167 @@ 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));
if (dos_setemax)

// 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 = 0.0;
const bool has_det_emin = minimum_ks_eigenvalue(this->p_elec, det_emin);
// Deterministic (Kohn-Sham) eigenvalues are a reliable lower bound of the
// spectrum even at high temperature; the pure, unit-tested sanitiser is
// used for this and for the output-window consistency check below.
std::vector<double> det_eigs;
if (has_det_emin)
{
this->emax = dos_emax_ev;
det_eigs.push_back(det_emin);
}
else
if (!std::isfinite(*p_hamilt_sto->emax) || *p_hamilt_sto->emax <= *p_hamilt_sto->emin)
{
this->emax = *p_hamilt_sto->emax * ModuleBase::Ry_to_eV;
*p_hamilt_sto->emax = *p_hamilt_sto->emin + 1.0;
}
if (dos_setemin)

this->setup_output_window(dos_setemin, dos_setemax, dos_emin_ev, dos_emax_ev, dos_scale);

// A Gaussian centred outside the Chebyshev interval requires T_n(x) with
// |x| > 1, which grows exponentially with n; the default dos_scale path
// deliberately makes the output window slightly wider than the spectral
// range, so evaluating the Gaussian at those edge points used to be the
// final trigger for the 1e36-scale DOS values. Expand the Chebyshev
// interval itself (never the other way round) so that every requested
// output energy satisfies |x| <= 1. This is the `output_window` clause of
// the same sanitiser used at the SCF stage.
const double output_emin_ry = this->emin / ModuleBase::Ry_to_eV;
const double output_emax_ry = this->emax / ModuleBase::Ry_to_eV;
const double guard_ry = std::max(1.0e-6, 1.0e-6 * (*p_hamilt_sto->emax - *p_hamilt_sto->emin));
ModuleIO::CheRange requested;
requested.emin = output_emin_ry - guard_ry;
requested.emax = output_emax_ry + guard_ry;
const ModuleIO::CheRange fixed = ModuleIO::sanitize_che_range(*p_hamilt_sto->emin,
*p_hamilt_sto->emax,
PARAM.inp.ecutwfc,
det_eigs,
&requested);
if (fixed.emin_repaired || fixed.emax_repaired || fixed.degenerate)
{
this->emin = dos_emin_ev;
GlobalV::ofs_running << " DOS: Chebyshev range repaired from ["
<< *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax << "] to ["
<< fixed.emin << ", " << fixed.emax << "] Ry"
<< (has_det_emin ? " (lowest KS eigenvalue = " + std::to_string(det_emin) + " Ry)" : "")
<< std::endl;
}
else
*p_hamilt_sto->emin = fixed.emin;
*p_hamilt_sto->emax = fixed.emax;

GlobalV::ofs_running << " DOS: Chebyshev range = [" << *p_hamilt_sto->emin << ", " << *p_hamilt_sto->emax
<< "] Ry; output window = [" << this->emin << ", " << this->emax << "] eV" << std::endl;
}

template <typename FPTYPE, typename Device>
void Sto_DOS<FPTYPE, Device>::setup_output_window(const bool& dos_setemin,
const bool& dos_setemax,
const double& dos_emin_ev,
const double& dos_emax_ev,
const double& dos_scale)
{
this->emax = dos_setemax ? dos_emax_ev : *p_hamilt_sto->emax * ModuleBase::Ry_to_eV;
this->emin = dos_setemin ? dos_emin_ev : *p_hamilt_sto->emin * ModuleBase::Ry_to_eV;

if (!dos_setemax && !dos_setemin)
{
this->emin = *p_hamilt_sto->emin * ModuleBase::Ry_to_eV;
// Widen the reported window slightly on both sides (dos_scale); the
// Chebyshev interval is extended accordingly below.
const double delta = (this->emax - this->emin) * dos_scale;
this->emax += delta / 2.0;
this->emin -= delta / 2.0;
}

if (!dos_setemax && !dos_setemin)
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.");
}
}

template <typename FPTYPE, typename Device>
void Sto_DOS<FPTYPE, Device>::check_and_report_dos_result(const std::vector<double>& ks_dos,
const std::vector<double>& sto_dos,
const double& de,
const double& max_abs_t) const
{
// Post-run diagnostics: the DOS integral must reproduce the number of
// plane-wave states when the window covers the spectrum, the curve must not
// go visibly negative, and no output energy may leave the Chebyshev
// interval. Warnings only; a long run is never aborted here.
double dos_integral = 0.0;
double dos_min = 0.0;
for (std::size_t ie = 0; ie < ks_dos.size(); ++ie)
{
const double dos = 2.0 * (ks_dos[ie] + sto_dos[ie]) / ModuleBase::Ry_to_eV;
dos_integral += dos * de;
dos_min = std::min(dos_min, dos);
}
double expected_states = -1.0;
// The integral only has to reproduce the number of plane-wave states when
// the requested window actually covers the whole spectrum. A user who
// restricts dos_emin_ev/dos_emax_ev on purpose expects a smaller integral,
// so the check is skipped there to avoid a misleading warning.
const double ecut_ev = PARAM.inp.ecutwfc * ModuleBase::Ry_to_eV;
const bool window_covers_spectrum = (ecut_ev <= 0.0) || (this->emax >= 0.95 * ecut_ev);
if (PARAM.inp.nspin == 1 && window_covers_spectrum && this->p_kv != nullptr && this->p_wfcpw != nullptr)
{
// npwk[ik] is the number of plane waves held by THIS rank, so the sum has
// to be reduced over the pool. Twice the total number of plane-wave
// states is what the DOS integral converges to (verified both on a
// Gamma-only and on a 2x2x2 case).
double local_npw = 0.0;
for (int ik = 0; ik < this->p_kv->get_nks(); ++ik)
{
local_npw += static_cast<double>(this->p_wfcpw->npwk[ik]);
}
#ifdef __MPI
Parallel_Reduce::reduce_pool(local_npw);
#endif
expected_states = 2.0 * local_npw;
}

const std::vector<std::string> dos_warnings
= ModuleIO::check_dos_result(dos_integral, expected_states, dos_min, max_abs_t);
for (const std::string& msg: dos_warnings)
{
double delta = (emax - emin) * dos_scale;
this->emax = emax + delta / 2.0;
this->emin = emin - delta / 2.0;
GlobalV::ofs_running << " WARNING: DOS: " << msg << std::endl;
if (GlobalV::MY_RANK == 0)
{
std::cout << " WARNING: DOS: " << msg << std::endl;
}
}
}

Expand Down Expand Up @@ -168,22 +349,52 @@ 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;

// Parameter sanity checks (pure functions, unit tested). They only report;
// a long run is never aborted by a quality suggestion.
const double range_ev = (*this->stofunc.Emax - *this->stofunc.Emin) * ModuleBase::Ry_to_eV;
const double sigma_ev = std::abs(sigmain);
for (const std::string& msg: ModuleIO::check_dos_parameters(range_ev, sigma_ev, de, this->dos_nche))
{
GlobalV::ofs_running << " WARNING: DOS: " << msg << std::endl;
std::cout << " WARNING: DOS: " << msg << std::endl;
}

ModuleBase::timer::end("Sto_DOS", "Tracepoly");

std::cout << "2. Dos:" << std::endl;
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);
std::vector<double> error(ndos);
// Diagnostics for the post-run check: |t| of every grid point in the
// Chebyshev variable, and the smallest DOS value on the curve.
double max_abs_t = 0.0;
const double ebar_ry = 0.5 * (*this->stofunc.Emax + *this->stofunc.Emin);
const double de_ry = 0.5 * (*this->stofunc.Emax - *this->stofunc.Emin);
for (int ie = 0; ie < ndos; ++ie)
{
double tmpks = 0;
double tmpsto = 0;
this->stofunc.targ_e = (emin + ie * de) / ModuleBase::Ry_to_eV;
if (de_ry > 0.0)
{
max_abs_t = std::max(max_abs_t, std::fabs((this->stofunc.targ_e - ebar_ry) / de_ry));
}
if (this->method_sto == 1)
{
auto ngauss = std::bind(&Sto_Func<double>::ngauss, &this->stofunc, std::placeholders::_1);
Expand Down Expand Up @@ -240,6 +451,8 @@ void Sto_DOS<FPTYPE, Device>::caldos(const double sigmain, const double de, cons
Parallel_Reduce::reduce_all(sto_dos.data(), ndos);
Parallel_Reduce::reduce_all(error.data(), ndos);
#endif
this->check_and_report_dos_result(ks_dos, sto_dos, de, max_abs_t);

if (GlobalV::MY_RANK == 0)
{
std::string dosfile = PARAM.globalv.global_out_dir + "dos_sdft.txt";
Expand Down
19 changes: 19 additions & 0 deletions source/source_pw/module_stodft/sto_dos.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,25 @@ class Sto_DOS
*/
void caldos(const double sigmain, const double de, const int npart);

/**
* @brief Translate the DOS request into the reported energy window
* [emin, emax] (eV) and validate it.
*/
/**
* @brief Report DOS quality problems (integral, negative values, |t| > 1)
* as warnings; never aborts.
*/
void check_and_report_dos_result(const std::vector<double>& ks_dos,
const std::vector<double>& sto_dos,
const double& de,
const double& max_abs_t) const;

void setup_output_window(const bool& dos_setemin,
const bool& dos_setemax,
const double& dos_emin_ev,
const double& dos_emax_ev,
const double& dos_scale);

protected:
int nbands_ks = 0; ///< number of KS bands
int nbands_sto = 0; ///< number of stochastic bands
Expand Down
Loading
Loading