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/Makefile.Objects
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,7 @@ OBJS_SRCPW=h_ewald_pw.o\
sto_tool.o\
sto_elecond.o\
sto_dos.o\
sto_wfc_out.o\
onsite_proj.o\
onsite_proj_init.o\
onsite_proj_overlap.o\
Expand Down
95 changes: 95 additions & 0 deletions source/source_esolver/esolver_sdft_pw.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "source_pw/module_stodft/sto_forces.h"
#include "source_pw/module_stodft/sto_hsolver_pw.h"
#include "source_pw/module_stodft/sto_stress_pw.h"
#include "source_pw/module_stodft/sto_wfc_out.h"

#include <algorithm>
#include <fstream>
Expand Down Expand Up @@ -129,9 +130,103 @@ void ESolver_SDFT_PW<T, Device>::after_scf(UnitCell &ucell, const int istep, con
// 1) call after_scf() of ESolver_KS_PW
ESolver_KS_PW<T, Device>::after_scf(ucell, istep, conv_esolver);

// 2) dump wavefunctions of the SDFT/MDFT run.
// `out_wfc_pw` is not implemented for the SDFT solver, so it is reused
// here as a switch: the deterministic (KS) orbitals and the stochastic
// orbitals are written with the same text layout as `wfk{k}_pw.txt`
// (KSDFT), so that the same post-processing tool can Fourier transform
// them into real space.
this->output_wfc_sdft(ucell, istep, conv_esolver);

ModuleBase::timer::end("ESolver_SDFT_PW", "after_scf");
}

template <typename T, typename Device>
void ESolver_SDFT_PW<T, Device>::output_wfc_sdft(const UnitCell &ucell, const int istep, const bool conv_esolver)
{
(void)ucell;
(void)conv_esolver;

// `out_wfc_pw` is only implemented for the KSDFT solver, so it is reused
// here as the switch for the SDFT/MDFT dumps; write once, at the first
// ionic step.
if (this->inp_->out_wfc_pw == 0 || this->inp_->basis_type != "pw" || istep != 0)
{
return;
}
Comment on lines +153 to +156

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] Make the SDFT format selection match the INPUT help

out_wfc_pw=2 is now accepted for SDFT and documented as binary output, but this nonzero check always dispatches the text writer and creates only *_pw.txt files. Implement the binary mode or restrict SDFT to the supported text value and document that distinction.

// The text writer supports complex<double> wavefunctions on the CPU only.
// A run-time test on compile-time constants keeps the code C++11 compatible
// (ABACUS baseline) and lets the compiler fold the dead branch away.
const bool text_dump_supported =
std::is_same<T, std::complex<double>>::value && std::is_same<Device, base_device::DEVICE_CPU>::value;
if (!text_dump_supported)
{
return;
}

ModuleBase::TITLE("ESolver_SDFT_PW", "output_wfc_sdft");
std::ofstream &ofs = GlobalV::ofs_running;

// With band parallelism the rows are split over the band groups; every group
// writes its own files (prefix suffix "bg<i>_") so that no two groups
// overwrite each other and all ranks still join the collective writes.
std::string bg = "";
if (this->inp_->bndpar > 1)
{
bg = "bg" + std::to_string(GlobalV::MY_BNDGROUP) + "_";
ofs << " WARNING: output_wfc_sdft: bndpar = " << this->inp_->bndpar
<< " > 1, each band group writes its own wavefunction files (suffix \"bg<i>_\")." << std::endl;
}

ModuleIO::WfcDumpContext ctx;
ctx.kpar = this->inp_->kpar;
ctx.my_pool = GlobalV::MY_POOL; // pool index is not exposed by PW_Basis_K
ctx.nspin = this->inp_->nspin;
// pool decomposition is available from the plane-wave basis itself
ctx.rank_in_pool = this->pw_wfc->poolrank;
ctx.nproc_in_pool = this->pw_wfc->poolnproc;
ctx.ecutwfc = this->inp_->ecutwfc;
ctx.out_dir = PARAM.globalv.global_out_dir;

// Deterministic (Kohn-Sham) orbitals of MDFT, the raw stochastic orbitals
// |chi>, the occupation-filtered ones sqrt(f(H))|chi~> (these are the ones
// that enter the charge density), and the ones orthogonalized against the
// Kohn-Sham subspace.
struct DumpJob
{
std::string prefix;
const psi::Psi<std::complex<double>> *psi;
int max_nbands;
};
std::vector<DumpJob> jobs;
if (this->inp_->nbands > 0 && this->stp.psi_cpu != nullptr)
{
jobs.push_back({"wfc_ks_", this->stp.psi_cpu, 4});
}
if (this->inp_->nbands_sto > 0 && this->stowf.chi0_cpu != nullptr)
{
jobs.push_back({"wfc_sto_", this->stowf.chi0_cpu, 4});
}
if (this->stowf.shchi != nullptr)
{
jobs.push_back({"wfc_shchi_", reinterpret_cast<const psi::Psi<std::complex<double>> *>(this->stowf.shchi), 4});
}
if (this->inp_->nbands > 0 && this->stowf.chiortho != nullptr)
{
jobs.push_back(
{"wfc_chiortho_", reinterpret_cast<const psi::Psi<std::complex<double>> *>(this->stowf.chiortho), 2});
}

for (const DumpJob &job: jobs)
{
ModuleIO::WfcDumpSpec spec;
spec.prefix = job.prefix + bg;
spec.band_begin = 0;
spec.nbands_out = std::min(job.psi->get_nbands(), job.max_nbands);
ModuleIO::write_wfc_pw_txt_selected(spec, ctx, *job.psi, this->kv, this->pw_wfc, ofs);
Comment on lines +224 to +226

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] Select valid rows separately for each k point

For nbands_sto=all, get_nbands() is the common allocation capacity nchip_max, while calTnchi_ik() fills only stowf.nchip[ik] rows. If a k point has fewer valid rows than this capped count (for example local counts 3 and 4), its shchi dump includes an uncomputed padding row. Pass the per-k valid counts into the writer and use them for both the header and coefficient loop.

}
}

template <typename T, typename Device>
void ESolver_SDFT_PW<T, Device>::hamilt2rho_single(
UnitCell &ucell,
Expand Down
3 changes: 3 additions & 0 deletions source/source_esolver/esolver_sdft_pw.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ class ESolver_SDFT_PW : public ESolver_KS_PW<T, Device>
virtual void after_all_runners(BaseCell &basecell) override;

private:
/** @brief Dump deterministic (KS) and stochastic orbitals when `out_wfc_pw` is set. */
void output_wfc_sdft(const UnitCell &ucell, const int istep, const bool conv_esolver);

int nche_sto; ///< norder of Chebyshev
int method_sto; ///< method of SDFT
};
Expand Down
9 changes: 7 additions & 2 deletions source/source_io/module_parameter/read_inp_out.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,12 @@ The optional second integer controls the output precision. If not provided, the
item.annotation = "output wave functions";
item.category = "Output information";
item.type = "Integer";
item.description = R"(Controls whether plane-wave Kohn-Sham wavefunction coefficients are written to `OUT.${suffix}/`.
item.description = R"(Controls whether plane-wave wavefunction coefficients are written to `OUT.${suffix}/`.
For `esolver_type=ksdft` the Kohn-Sham coefficients are written; for `esolver_type=sdft`
this parameter also switches on the SDFT/MDFT dumps of the deterministic (Kohn-Sham) orbitals,
the raw stochastic orbitals, the stochastic orbitals orthogonalized against the Kohn-Sham
subspace, and the occupation-filtered stochastic orbitals that enter the charge density
(`wfc_ks_k*, wfc_sto_k*, wfc_chiortho_k*, wfc_shchi_k*`).
Comment on lines +320 to +324

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: document that SDFT writes only at ionic step zero, only on CPU, and only the first four KS/raw/filtered orbitals and first two chiortho orbitals per band group. The general frequency/append description below otherwise implies later MD or relaxation frames, and the fixed sampling limits are currently undisclosed.


Available values are:
* `0`: Do not write wavefunction coefficients.
Expand All @@ -332,7 +337,7 @@ With `init_wfc file binary`, ABACUS reads only unindexed binary `wf*_pw.dat` fil
[NOTE] In the 3.10-LTS version, the binary files are named `WAVEFUNC1.dat`, `WAVEFUNC2.dat`, etc.)";
item.default_value = "0";
item.unit = "";
item.set_availability("basis_type==pw and esolver_type==ksdft");
item.set_availability("basis_type==pw and (esolver_type==ksdft or esolver_type==sdft)");
read_sync_int(input.out_wfc_pw);
this->add_item(item);
}
Expand Down
3 changes: 2 additions & 1 deletion source/source_pw/module_stodft/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ list(
sto_stress_pw.cpp
sto_tool.cpp
sto_elecond.cpp
sto_dos.cpp)
sto_dos.cpp
sto_wfc_out.cpp)

add_library(module_stodft OBJECT ${hamilt_stodft_srcs})

Expand Down
190 changes: 190 additions & 0 deletions source/source_pw/module_stodft/sto_wfc_out.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
#include "sto_wfc_out.h"

#include "source_base/global_variable.h"
#include "source_base/parallel_comm.h"
#include "source_base/tool_title.h"

#ifdef __MPI
#include "mpi.h"
#endif

#include <iomanip>

namespace
{

/// Header block plus the reciprocal lattice and the opening "<G vectors>" tag.
void write_header(std::ofstream& ofs,
const ModuleIO::WfcDumpContext& ctx,
const ModuleIO::WfcDumpSpec& spec,
const K_Vectors& kv,
const int ik,
const int ikngtot,
const ModulePW::PW_Basis_K* wfcpw)
{
ofs << std::setprecision(6);
ofs << std::setw(10) << "Kpoint" << std::setw(10) << "nKpoint" << std::setw(10) << "kv.x"
<< std::setw(10) << "kv.y" << std::setw(10) << "kv.z" << std::setw(10) << "weight"
<< std::setw(10) << "ngtot" << std::setw(10) << "nband" << std::setw(10) << "ecut"
<< std::setw(10) << "lat0" << std::setw(12) << "2pi/lat0" << std::endl;
ofs << std::setw(10) << kv.ik2iktot[ik] + 1 << std::setw(10) << kv.get_nkstot() << std::setw(10)
<< kv.kvec_c[ik].x << std::setw(10) << kv.kvec_c[ik].y << std::setw(10) << kv.kvec_c[ik].z
<< std::setw(10) << kv.wk[ik] << std::setw(10) << ikngtot << std::setw(10)
<< spec.nbands_out << std::setw(10) << ctx.ecutwfc << std::setw(10) << wfcpw->lat0
<< std::setw(12) << wfcpw->tpiba << std::endl;
// Extra information needed by the real-space Fourier transform.
ofs << "# FFT grid (wave functions) = " << wfcpw->nx << " " << wfcpw->ny << " " << wfcpw->nz
<< std::endl;
ofs << "# band range in the solver array = [" << spec.band_begin + 1 << ", "
<< spec.band_begin + spec.nbands_out << "]" << std::endl;
Comment on lines +35 to +39

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 compatibility with the existing PW text reader

tests/integrate/validation_tools/collect_wfc_props.py expects <Reciprocal Lattice Vector> immediately after the two header lines and skips only blank lines. These added comments therefore make that reader reject the dump. Preserve the compatible layout or update the supported readers and retain a compatibility test.

ofs << "\n<Reciprocal Lattice Vector>" << std::endl;
ofs << std::setw(10) << wfcpw->G.e11 << std::setw(10) << wfcpw->G.e12 << std::setw(10)
<< wfcpw->G.e13 << std::endl;
ofs << std::setw(10) << wfcpw->G.e21 << std::setw(10) << wfcpw->G.e22 << std::setw(10)
<< wfcpw->G.e23 << std::endl;
ofs << std::setw(10) << wfcpw->G.e31 << std::setw(10) << wfcpw->G.e32 << std::setw(10)
<< wfcpw->G.e33 << std::endl;
ofs << "<Reciprocal Lattice Vector>\n" << std::endl;
ofs << "<G vectors>" << std::endl;
}

/// This rank's G-vector box indices (ix, iy, iz) for k point `ik`.
void write_gvectors(std::ofstream& ofs, const K_Vectors& kv, const int ik,
const ModulePW::PW_Basis_K* wfcpw)
{
for (int igl = 0; igl < wfcpw->npwk[ik]; ++igl)
{
const int isz = wfcpw->igl2isz_k[ik * wfcpw->npwk_max + igl];
const int iz = isz % wfcpw->nz;
const int is = isz / wfcpw->nz;
const int ixy = wfcpw->is2fftixy[is];
const int ix = ixy / wfcpw->fftny;
const int iy = ixy % wfcpw->fftny;
ofs << std::setw(10) << ix << std::setw(10) << iy << std::setw(10) << iz << std::endl;
}
}

/// This rank's coefficients of one band, written as "re im" pairs.
void write_band(std::ofstream& ofs, const psi::Psi<std::complex<double>>& psi, const int ib,
const int ng, const int rank_in_pool)
{
if (rank_in_pool == 0)
{
ofs << "\n< Band " << ib + 1 << " >" << std::endl;
}
ofs << std::scientific;
for (int ig = 0; ig < ng; ++ig)
{
if (ig % 4 == 0 && (ig != 0 || rank_in_pool != 0))
{
ofs << "\n";
}
ofs << std::setw(15) << psi(ib, ig).real() << std::setw(15) << psi(ib, ig).imag();
}
}

} // namespace

namespace ModuleIO
{

void write_wfc_pw_txt_selected(const WfcDumpSpec& spec,
const WfcDumpContext& ctx,
const psi::Psi<std::complex<double>>& psi,
const K_Vectors& kv,
const ModulePW::PW_Basis_K* wfcpw,
std::ofstream& ofs_running)
{
ModuleBase::TITLE("ModuleIO", "write_wfc_pw_txt_selected");

const int nkstot = kv.get_nkstot();
const int nks = kv.get_nks();
if (nkstot <= 0 || nks <= 0 || spec.nbands_out <= 0)
{
return;
Comment on lines +102 to +104

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.

[P1] Keep empty band groups in the collective sequence

With nbands_sto=1, bndpar=2 and method_sto=1, one band group has zero rows and returns here while the other reaches MPI_Barrier(MPI_COMM_WORLD). If the solver reaches this output step, the world-collective sequence is inconsistent and may hang. Synchronize file creation within the writing pool, or make world participation unconditional before this local return.

}
if (spec.band_begin < 0 || spec.band_begin + spec.nbands_out > psi.get_nbands())
{
ModuleBase::WARNING_QUIT("write_wfc_pw_txt_selected",
"requested band range is outside the wavefunction, check nbands/nbands_sto.");
}

// Step 1: create/truncate one file per k point of this pool.
std::vector<std::string> wfilename(nks);
if (ctx.my_pool < ctx.kpar)
{
for (int ik = 0; ik < nks; ++ik)
{
const std::string fn = ctx.out_dir + spec.prefix + "k"
+ std::to_string(kv.ik2iktot[ik] + 1) + "_pw.txt";
Comment on lines +118 to +119

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: assign kv.ik2iktot[ik] + 1 to a named one-based k index before passing it to std::to_string, as required by root rule 14.

wfilename[ik] = fn;
ofs_running << " Write G-space wave functions to file: " << fn << std::endl;
if (ctx.rank_in_pool == 0)
{
std::ofstream ofs(fn.c_str());
ofs.close();
Comment on lines +121 to +125

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: check the create/append streams and propagate failures consistently across the writing pool. An unwritable target or failed write currently leaves missing, stale or partial output while the running log still announces the dump filename.

}
}
}
#ifdef __MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif

// Step 2: k points, then header + G table + coefficients, rank by rank.
if (ctx.my_pool >= ctx.kpar)
{
return;
}
for (int ik = 0; ik < nks; ++ik)
{
psi.fix_k(ik);
const int ng = kv.ngk[ik];
int ikngtot = 0;
#ifdef __MPI
MPI_Allreduce(&kv.ngk[ik], &ikngtot, 1, MPI_INT, MPI_SUM, POOL_WORLD);
#else
Comment on lines +142 to +145

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] Use internally guarded MPI wrappers

Root AGENTS.md rule 9 requires internally guarded MPI wrappers; this new file adds four direct calls. Use the guarded reduction/barrier wrappers with the correct file-owning pool. The requested global-dependency exception covers the four named global reads, not these MPI calls.

ikngtot = kv.ngk[ik];
#endif
for (int id = 0; id < ctx.nproc_in_pool; ++id)
{
#ifdef __MPI
MPI_Barrier(POOL_WORLD);
#endif
if (ctx.rank_in_pool != id)
{
continue;
}
std::ofstream ofs2(wfilename[ik].c_str(), std::ios::app);
if (id == 0)
{
write_header(ofs2, ctx, spec, kv, ik, ikngtot, wfcpw);
}
write_gvectors(ofs2, kv, ik, wfcpw);
if (id == ctx.nproc_in_pool - 1)
{
ofs2 << "<G vectors>\n" << std::endl;
}
}
for (int ib = spec.band_begin; ib < spec.band_begin + spec.nbands_out; ++ib)
{
for (int id = 0; id < ctx.nproc_in_pool; ++id)
{
#ifdef __MPI
MPI_Barrier(POOL_WORLD);
#endif
if (ctx.rank_in_pool != id)
{
continue;
}
std::ofstream ofs2(wfilename[ik].c_str(), std::ios::app);
write_band(ofs2, psi, ib, ng, ctx.rank_in_pool);
if (id == ctx.nproc_in_pool - 1)
{
ofs2 << "\n< Band " << ib + 1 << " >" << std::endl;
}
}
}
}
}

} // namespace ModuleIO
Loading
Loading