From c35f07786de3781c76045f21d0951d56961cf01d Mon Sep 17 00:00:00 2001 From: LiYuqiii <139907896+LiYuqiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:43:10 +0800 Subject: [PATCH 1/2] SDFT/MDFT: dump plane-wave wavefunctions via out_wfc_pw 3.11 only writes wfk*_pw.txt for esolver_type=ksdft: ESolver_SDFT_PW overrides iter_finish() and never reaches ModuleIO::write_wfc_pw, so SDFT/MDFT runs cannot be inspected in real space at all. Reuse out_wfc_pw as the switch and dump, from after_scf(), the deterministic (Kohn-Sham) orbitals, the raw stochastic orbitals, the ones orthogonalized against the KS subspace, and the occupation-filtered ones sqrt(f(H))|chi> that enter the charge density. The writer reuses the wfk{k}_pw.txt text layout, so the existing post-processing (FFT to real space) works unchanged. --- source/source_esolver/esolver_sdft_pw.cpp | 95 +++++++++ source/source_esolver/esolver_sdft_pw.h | 3 + .../module_parameter/read_inp_out.cpp | 9 +- source/source_pw/module_stodft/CMakeLists.txt | 3 +- .../source_pw/module_stodft/sto_wfc_out.cpp | 190 ++++++++++++++++++ source/source_pw/module_stodft/sto_wfc_out.h | 73 +++++++ 6 files changed, 370 insertions(+), 3 deletions(-) create mode 100644 source/source_pw/module_stodft/sto_wfc_out.cpp create mode 100644 source/source_pw/module_stodft/sto_wfc_out.h diff --git a/source/source_esolver/esolver_sdft_pw.cpp b/source/source_esolver/esolver_sdft_pw.cpp index d648da97604..dbba7d5ab8a 100644 --- a/source/source_esolver/esolver_sdft_pw.cpp +++ b/source/source_esolver/esolver_sdft_pw.cpp @@ -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 #include @@ -129,9 +130,103 @@ void ESolver_SDFT_PW::after_scf(UnitCell &ucell, const int istep, con // 1) call after_scf() of ESolver_KS_PW ESolver_KS_PW::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 +void ESolver_SDFT_PW::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; + } + // The text writer supports complex 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>::value && std::is_same::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_") 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_\")." << 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> *psi; + int max_nbands; + }; + std::vector 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> *>(this->stowf.shchi), 4}); + } + if (this->inp_->nbands > 0 && this->stowf.chiortho != nullptr) + { + jobs.push_back( + {"wfc_chiortho_", reinterpret_cast> *>(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); + } +} + template void ESolver_SDFT_PW::hamilt2rho_single( UnitCell &ucell, diff --git a/source/source_esolver/esolver_sdft_pw.h b/source/source_esolver/esolver_sdft_pw.h index 680d66dbff4..af037e2299d 100644 --- a/source/source_esolver/esolver_sdft_pw.h +++ b/source/source_esolver/esolver_sdft_pw.h @@ -53,6 +53,9 @@ class ESolver_SDFT_PW : public ESolver_KS_PW 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 }; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 5b66f054b10..687656a3a4d 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -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*`). Available values are: * `0`: Do not write wavefunction coefficients. @@ -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); } diff --git a/source/source_pw/module_stodft/CMakeLists.txt b/source/source_pw/module_stodft/CMakeLists.txt index fb863199d61..c64250eca6a 100644 --- a/source/source_pw/module_stodft/CMakeLists.txt +++ b/source/source_pw/module_stodft/CMakeLists.txt @@ -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}) diff --git a/source/source_pw/module_stodft/sto_wfc_out.cpp b/source/source_pw/module_stodft/sto_wfc_out.cpp new file mode 100644 index 00000000000..61b0d377016 --- /dev/null +++ b/source/source_pw/module_stodft/sto_wfc_out.cpp @@ -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 + +namespace +{ + +/// Header block plus the reciprocal lattice and the opening "" 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; + ofs << "\n" << 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 << "\n" << std::endl; + ofs << "" << 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>& 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>& 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; + } + 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 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"; + 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(); + } + } + } +#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 + 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 << "\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 diff --git a/source/source_pw/module_stodft/sto_wfc_out.h b/source/source_pw/module_stodft/sto_wfc_out.h new file mode 100644 index 00000000000..124b7dc8d2e --- /dev/null +++ b/source/source_pw/module_stodft/sto_wfc_out.h @@ -0,0 +1,73 @@ +#ifndef STO_WFC_OUT_H +#define STO_WFC_OUT_H + +#include "source_basis/module_pw/pw_basis_k.h" +#include "source_cell/klist.h" +#include "source_psi/psi.h" + +#include +#include + +namespace ModuleIO +{ + +/** + * @file sto_wfc_out.h + * @brief Dump selected rows (bands/orbitals) of a plane-wave wavefunction in the + * same text layout that `out_wfc_pw 1` produces for KSDFT + * (`wfk{k}_pw.txt`), so that one post-processing tool can read both. + * + * `out_wfc_pw` is only implemented for the KSDFT solver; the SDFT/MDFT solver + * overrides `iter_finish()` and therefore never reaches the writer. This helper + * is called from `ESolver_SDFT_PW::after_scf()` instead, where the + * deterministic (Kohn-Sham) orbitals, the raw stochastic orbitals, the ones + * orthogonalized against the Kohn-Sham subspace, and the occupation-filtered + * ones that enter the charge density are all available. + * + * File name: `${out_dir}/${spec.prefix}k{k index}_pw.txt`. + * The header is followed by a `# FFT grid (wave functions) = nx ny nz` comment + * line, from which the reader can build the real-space FFT box. + * + * Only complex / CPU wavefunctions and collinear (npol == 1) cases are + * supported; the caller must guarantee that. + */ + +/// What to dump: which rows of `psi` and how to name the file. +struct WfcDumpSpec +{ + std::string prefix; ///< file name prefix, e.g. "wfc_sto_" -> wfc_sto_k1_pw.txt + int band_begin = 0; ///< first row of `psi` to write + int nbands_out = 0; ///< number of consecutive rows to write +}; + +/// Parallel layout and header information shared by all dumps of one call site. +struct WfcDumpContext +{ + int kpar = 1; ///< number of k-point pools + int my_pool = 0; ///< this process' pool index + int nspin = 1; ///< spin channels (header only) + int rank_in_pool = 0; ///< rank inside POOL_WORLD + int nproc_in_pool = 1; ///< size of POOL_WORLD + double ecutwfc = 0.0; ///< cutoff [Ry], written in the header + std::string out_dir; ///< directory of the output files +}; + +/** + * @brief Write `psi` rows [spec.band_begin, spec.band_begin + spec.nbands_out) + * for every k point of this pool into `${out_dir}/${prefix}k{k}_pw.txt`. + * + * The coefficients of one band are distributed over the ranks of `POOL_WORLD` + * (each rank owns its own G-vector subset), so the file is produced by letting + * the ranks append their chunk in rank order, synchronised with + * `MPI_Barrier(POOL_WORLD)`. + */ +void write_wfc_pw_txt_selected(const WfcDumpSpec& spec, + const WfcDumpContext& ctx, + const psi::Psi>& psi, + const K_Vectors& kv, + const ModulePW::PW_Basis_K* wfcpw, + std::ofstream& ofs_running); + +} // namespace ModuleIO + +#endif // STO_WFC_OUT_H From 6240e726920fe06f3ccb0a68dd96acbd48d9ac53 Mon Sep 17 00:00:00 2001 From: LiYuqiii <139907896+LiYuqiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:22:03 +0800 Subject: [PATCH 2/2] SDFT/MDFT: add sto_wfc_out.o to the Makefile build list The Makefile-based build (source/Makefile.Objects) lists its objects explicitly, so the new writer has to be registered there as well; otherwise `make -f ../Makefile` fails with an undefined reference to ModuleIO::write_wfc_pw_txt_selected(). --- source/Makefile.Objects | 1 + 1 file changed, 1 insertion(+) diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 502f29b9e05..b91b4d0c6b3 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -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\