From 625c3406cd9c22f3e025f2dadafc147ab9909fd7 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:55:44 +0800 Subject: [PATCH 01/15] feat: write and plot LCAO projected DOS in NumPy format --- docs/advanced/elec_properties/dos.md | 32 +++ source/Makefile.Objects | 2 + source/source_io/CMakeLists.txt | 2 + .../source_io/module_ctrl/ctrl_scf_lcao.cpp | 1 + .../source_io/module_dos/cal_pdos_gamma.cpp | 24 +- source/source_io/module_dos/cal_pdos_gamma.h | 13 +- .../source_io/module_dos/cal_pdos_multik.cpp | 24 +- source/source_io/module_dos/cal_pdos_multik.h | 13 +- source/source_io/module_dos/pdos_orbitals.cpp | 49 ++++ source/source_io/module_dos/pdos_orbitals.h | 25 ++ .../module_dos/unittests/CMakeLists.txt | 15 ++ .../unittests/test_write_pdos_npy.cpp | 92 +++++++ .../source_io/module_dos/write_dos_lcao.cpp | 60 +++-- source/source_io/module_dos/write_dos_lcao.h | 1 + .../source_io/module_dos/write_pdos_npy.cpp | 224 ++++++++++++++++++ source/source_io/module_dos/write_pdos_npy.h | 19 ++ .../source_io/module_dos/write_pdos_text.cpp | 63 +---- source/source_io/module_dos/write_pdos_text.h | 4 +- .../module_parameter/input_parameter.h | 1 + .../module_parameter/read_inp_out.cpp | 1 + .../module_parameter/read_inp_postproc.cpp | 18 ++ .../plot-tools/abacus_plot/dos.py | 76 +++++- .../plot-tools/abacus_plot/main.py | 8 +- .../plot-tools/tests/test_pdos_npy.py | 83 +++++++ 24 files changed, 712 insertions(+), 138 deletions(-) create mode 100644 source/source_io/module_dos/pdos_orbitals.cpp create mode 100644 source/source_io/module_dos/pdos_orbitals.h create mode 100644 source/source_io/module_dos/unittests/test_write_pdos_npy.cpp create mode 100644 source/source_io/module_dos/write_pdos_npy.cpp create mode 100644 source/source_io/module_dos/write_pdos_npy.h create mode 100644 tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 969998a46ff..0e0dff428d7 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -97,3 +97,35 @@ The PDOS file uses a plain-text format. Each row corresponds to one energy point The `# istep:` line is only present for geometry-optimization (istep) output. Within each angular momentum `l`, the `2l+1` columns follow the magnetic-quantum-number order `m = 0, +1, -1, +2, -2, ...`. For nspin=2, two files are written (pdoss1* and pdoss2*), one per spin channel. For nspin=4, the two spinor components are summed into a single file. The unit of PDOS is also `(number of states)/(eV * unitcell)`. + +### NumPy output for LCAO + +The default `pdos_format text` writes the text files above. To write projected DOS in NumPy format, use + +```text +out_dos 1 +pdos_format npy +``` + +This requires only an LCAO build. Total DOS continues to use `doss*.txt`. Each output is a standard, pickle-free NumPy 1.0 structured array with one row for each atom and each `(l,m)` channel present in its basis (all zeta components summed). The `pdos` field holds float64 spectra in 1/eV, with axes `(orbital, spin channel, energy point)` across the array. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. + +```python +import numpy as np + +rows = np.load("OUT.ABACUS/pdos.npy", allow_pickle=False, mmap_mode="r") +first = rows[0] +energy = first["energy_min_eV"] + np.arange(rows["pdos"].shape[-1]) * first["energy_step_eV"] +first_orbital = rows["pdos"][0, 0, :] # first orbital and first spin channel +``` + +Each row includes the one-based `atom_index`, UTF-8 byte string `species`, `l`, signed `m`, `nspin`, and one-based `ionic_step`. A single-point calculation uses step 1. The fields `schema_version` (1) and `record_bytes` (payload size of the complete array) identify the schema and delimit records for append recovery. + +Mode `out_app_flag 0` replaces `pdos.npy`. Mode 1 appends one complete NumPy array per write to that file, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps into `DOS/pdosgN.npy`. + +The plotting and data-export commands both accept the file via `pdosfile`. For an appended file, `pdos_record` selects the one-based record number and defaults to 1. + +```json +{"pdosfile": "OUT.ABACUS/pdos.npy", "pdos_record": 1, "species": ["Si"]} +``` + +Run `abacus-plot -d -p -f config.json` to plot, or `abacus-plot -d -o -f config.json` to export the selected species' curves. diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 5ca197fb512..f8b19e87673 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -752,6 +752,8 @@ OBJS_IO=module_parameter/input_conv.o\ module_dos/cal_pdos_gamma.o\ module_dos/cal_pdos_multik.o\ module_dos/write_pdos_text.o\ + module_dos/pdos_orbitals.o\ + module_dos/write_pdos_npy.o\ module_dos/cal_ldos.o\ module_bessel/numerical_descriptor.o\ module_bessel/numerical_basis.o\ diff --git a/source/source_io/CMakeLists.txt b/source/source_io/CMakeLists.txt index 01696065995..972b4652467 100644 --- a/source/source_io/CMakeLists.txt +++ b/source/source_io/CMakeLists.txt @@ -75,6 +75,8 @@ if(ENABLE_LCAO) module_dos/cal_pdos_gamma.cpp module_dos/cal_pdos_multik.cpp module_dos/write_pdos_text.cpp + module_dos/pdos_orbitals.cpp + module_dos/write_pdos_npy.cpp module_output/write_orb_info.cpp module_energy/write_proj_band_lcao.cpp module_chgpot/get_pchg_lcao.cpp diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index 5aaba39060c..74bc1e1622c 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -168,6 +168,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, + inp.pdos_format, out_app_flag, istep, inp.nspin, diff --git a/source/source_io/module_dos/cal_pdos_gamma.cpp b/source/source_io/module_dos/cal_pdos_gamma.cpp index 88702fbec49..e1b643f1e2f 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.cpp +++ b/source/source_io/module_dos/cal_pdos_gamma.cpp @@ -1,36 +1,29 @@ #include "cal_pdos_gamma.h" -#include "write_pdos_text.h" #include "source_base/parallel_reduce.h" #include "source_base/module_external/blas_connector.h" #include "source_base/module_external/scalapack_connector.h" #include "source_base/global_function.h" -#include "source_base/global_variable.h" #include "source_lcao/hamilt_lcao.h" -#include "source_io/module_output/write_orb_info.h" -void ModuleIO::cal_pdos( +std::vector ModuleIO::cal_pdos( const psi::Psi* psi, hamilt::Hamilt* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, - const int nspin0, + const int nspin, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, - const int nlocal, - const int nspin, - const std::string& global_out_dir) + const int nlocal) { ModuleBase::TITLE("ModuleIO", "cal_pdos_gamma"); - assert(nspin0>0); + const int nspin0 = nspin == 2 ? 2 : 1; + assert(nspin == 1 || nspin == 2 || nspin == 4); assert(emax>=emin); assert(dos_edelta_ev>0.0); @@ -146,10 +139,5 @@ void ModuleIO::cal_pdos( #endif } // is - if (GlobalV::MY_RANK == 0) - { - write_pdos_text(ucell, pdos.data(), nspin, nlocal, npoints, - emin, dos_edelta_ev, global_out_dir, istep, out_app_flag); - ModuleIO::write_orb_info(&ucell); - } + return pdos; } diff --git a/source/source_io/module_dos/cal_pdos_gamma.h b/source/source_io/module_dos/cal_pdos_gamma.h index 0af1fca0540..6457afa7c2c 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.h +++ b/source/source_io/module_dos/cal_pdos_gamma.h @@ -6,29 +6,24 @@ #include "source_psi/psi.h" // use psi::Psi #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals -#include +#include namespace ModuleIO { - void cal_pdos( + std::vector cal_pdos( const psi::Psi* psi, hamilt::Hamilt* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, - const int nspin0, + const int nspin, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, - const int nlocal, - const int nspin, - const std::string& global_out_dir); + const int nlocal); } diff --git a/source/source_io/module_dos/cal_pdos_multik.cpp b/source/source_io/module_dos/cal_pdos_multik.cpp index 3a8cee8add0..a582697199d 100644 --- a/source/source_io/module_dos/cal_pdos_multik.cpp +++ b/source/source_io/module_dos/cal_pdos_multik.cpp @@ -1,35 +1,28 @@ #include "cal_pdos_multik.h" -#include "write_pdos_text.h" #include "source_base/parallel_reduce.h" #include "source_base/module_external/blas_connector.h" #include "source_base/module_external/scalapack_connector.h" -#include "source_io/module_output/write_orb_info.h" #include "source_base/global_function.h" -#include "source_base/global_variable.h" #include "source_lcao/hamilt_lcao.h" -void ModuleIO::cal_pdos( +std::vector ModuleIO::cal_pdos( const psi::Psi>* psi, hamilt::Hamilt>* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, - const int nspin0, + const int nspin, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, - const int nlocal, - const int nspin, - const std::string& global_out_dir) + const int nlocal) { ModuleBase::TITLE("ModuleIO", "cal_pdos_multik"); - assert(nspin0>0); + const int nspin0 = nspin == 2 ? 2 : 1; + assert(nspin == 1 || nspin == 2 || nspin == 4); assert(emax>=emin); assert(dos_edelta_ev>0.0); @@ -186,10 +179,5 @@ void ModuleIO::cal_pdos( #endif } // is - if (GlobalV::MY_RANK == 0) - { - write_pdos_text(ucell, pdos.data(), nspin, nlocal, npoints, - emin, dos_edelta_ev, global_out_dir, istep, out_app_flag); - ModuleIO::write_orb_info(&ucell); - } + return pdos; } diff --git a/source/source_io/module_dos/cal_pdos_multik.h b/source/source_io/module_dos/cal_pdos_multik.h index a4b194d967b..e327d0d73cd 100644 --- a/source/source_io/module_dos/cal_pdos_multik.h +++ b/source/source_io/module_dos/cal_pdos_multik.h @@ -6,30 +6,25 @@ #include "source_psi/psi.h" // use psi::Psi #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals -#include +#include namespace ModuleIO { // pdos for multi-k point - void cal_pdos( + std::vector cal_pdos( const psi::Psi>* psi, hamilt::Hamilt>* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, - const int nspin0, + const int nspin, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, - const int nlocal, - const int nspin, - const std::string& global_out_dir); + const int nlocal); } diff --git a/source/source_io/module_dos/pdos_orbitals.cpp b/source/source_io/module_dos/pdos_orbitals.cpp new file mode 100644 index 00000000000..86867afbbb5 --- /dev/null +++ b/source/source_io/module_dos/pdos_orbitals.cpp @@ -0,0 +1,49 @@ +#include "pdos_orbitals.h" +#include "source_base/matrix.h" +#include "source_cell/atom_spec.h" + +#include +#include + +std::vector ModuleIO::pdos_orbitals(const Atom& atom) +{ + std::vector orbitals; + for (int l = 0; l <= atom.nwl; ++l) + { + for (int im = 0; im <= 2 * l; ++im) + { + const int m = im % 2 == 0 ? -im / 2 : (im + 1) / 2; + PdosOrbital orbital{l, m, {}}; + for (int j = 0; j < atom.nw; ++j) + { + if (atom.iw2l[j] == l && atom.iw2m[j] == im) + { + orbital.zeta_orbitals.push_back(j); + } + } + if (!orbital.zeta_orbitals.empty()) + { + orbitals.push_back(std::move(orbital)); + } + } + } + return orbitals; +} + +double ModuleIO::PdosOrbital::value(const ModuleBase::matrix& pdos, int first, int energy, bool spinor) const +{ + double sum = 0.0; + for (int j : zeta_orbitals) + { + if (spinor) + { + const int row = first + 2 * j; + sum += pdos(row, energy) + pdos(row + 1, energy); + } + else + { + sum += pdos(first + j, energy); + } + } + return std::abs(sum) < 1.0e-6 ? 0.0 : sum; +} diff --git a/source/source_io/module_dos/pdos_orbitals.h b/source/source_io/module_dos/pdos_orbitals.h new file mode 100644 index 00000000000..00f383fae50 --- /dev/null +++ b/source/source_io/module_dos/pdos_orbitals.h @@ -0,0 +1,25 @@ +#ifndef PDOS_ORBITALS_H +#define PDOS_ORBITALS_H + +#include + +class Atom; +namespace ModuleBase +{ +class matrix; +} + +namespace ModuleIO +{ +struct PdosOrbital +{ + int l; + int m; // physical magnetic quantum number + std::vector zeta_orbitals; + + double value(const ModuleBase::matrix& pdos, int first, int energy, bool spinor) const; +}; + +std::vector pdos_orbitals(const Atom& atom); +} +#endif diff --git a/source/source_io/module_dos/unittests/CMakeLists.txt b/source/source_io/module_dos/unittests/CMakeLists.txt index 525ebce5aab..f63aa7c7f77 100644 --- a/source/source_io/module_dos/unittests/CMakeLists.txt +++ b/source/source_io/module_dos/unittests/CMakeLists.txt @@ -30,6 +30,7 @@ if(ENABLE_MPI) LIBS parameter base device SOURCES test_write_pdos_text.cpp ../write_pdos_text.cpp + ../pdos_orbitals.cpp ../../../source_cell/atom_spec.cpp ../../../source_cell/atom_pseudo.cpp ../../../source_cell/pseudo.cpp @@ -37,3 +38,17 @@ if(ENABLE_MPI) ../../../source_cell/test/support/mock_unitcell.cpp) endif() + +if(ENABLE_LCAO) + addtest( + TARGET MODULE_DOS_write_pdos_npy + LIBS parameter base device + SOURCES test_write_pdos_npy.cpp + ../write_pdos_npy.cpp + ../pdos_orbitals.cpp + ../../../source_cell/atom_spec.cpp + ../../../source_cell/atom_pseudo.cpp + ../../../source_cell/pseudo.cpp + ../../../source_cell/magnetism.cpp + ../../../source_cell/test/support/mock_unitcell.cpp) +endif() diff --git a/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp b/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp new file mode 100644 index 00000000000..47fbd176199 --- /dev/null +++ b/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp @@ -0,0 +1,92 @@ +#include "../write_pdos_npy.h" +#include "source_base/matrix.h" +#include "source_cell/unitcell.h" + +#include +#include +#include +#include +#include + +namespace +{ +class WritePdosNpy : public testing::Test +{ +protected: + UnitCell cell; + std::vector pdos{1}; + std::string prefix; + + void SetUp() override + { + prefix = testing::TempDir() + "/abacus-" + testing::UnitTest::GetInstance()->current_test_info()->name() + "-"; + cell.nat = 1; + cell.ntype = 1; + cell.atoms = new Atom[1]; + cell.set_atom_flag = true; + cell.iat2it = {0}; + cell.atoms[0].label = "Si"; + cell.atoms[0].nw = 2; + cell.atoms[0].nwl = 0; + cell.atoms[0].iw2l = {0, 0}; + cell.atoms[0].iw2m = {0, 0}; + cell.set_iat2iwt_for_test({0}, 1); + pdos.front().create(2, 2); + pdos.front()(0, 0) = 4.25; + pdos.front()(1, 0) = -1.25; + pdos.front()(0, 1) = 1e-8; + pdos.front()(1, 1) = 0; + } + + std::string write(int step, int mode) + { + return ModuleIO::write_pdos_npy(cell, pdos, 1, -1.0, 0.25, prefix, step, mode); + } + + std::string contents(const std::string& path) + { + std::ifstream in(path, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + } + + void TearDown() override + { + std::remove((prefix + "pdos.npy").c_str()); + std::remove((prefix + "pdosg2.npy").c_str()); + } +}; + +TEST_F(WritePdosNpy, FramesAppendOverwriteAndRecoverShortTail) +{ + const auto path = write(0, 1); + const auto first = contents(path); + ASSERT_EQ(first.substr(0, 8), std::string("\x93NUMPY\x01\x00", 8)); + const double expected[] = {3.0, 0.0}; + const auto tail = first.substr(first.size() - sizeof(expected)); + EXPECT_EQ(tail, std::string(reinterpret_cast(expected), sizeof(expected))); + const auto other = write(1, 2); + ASSERT_EQ(other, prefix + "pdosg2.npy"); + const auto second = contents(other); + { + std::ofstream interrupted(path, std::ios::app | std::ios::binary); + interrupted.write(second.data(), second.size() - 1); + } + write(1, 1); + EXPECT_EQ(contents(path), first + second); + write(0, 1); + EXPECT_EQ(contents(path), first); + write(1, 0); + EXPECT_EQ(contents(path), second); +} + +TEST_F(WritePdosNpy, IncompatibleAppendPreservesFile) +{ + const auto path = write(0, 0); + { + std::ofstream existing(path, std::ios::binary); + existing << "unrelated file"; + } + EXPECT_THROW(write(1, 1), std::runtime_error); + EXPECT_EQ(contents(path), "unrelated file"); +} +} diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index e068430f1e1..9cb5eb00692 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -2,6 +2,12 @@ #include "cal_dos.h" #include "cal_pdos_gamma.h" #include "cal_pdos_multik.h" +#include "write_pdos_text.h" +#include "source_base/global_variable.h" +#include "source_io/module_output/write_orb_info.h" +#include "write_pdos_npy.h" +#include "source_base/parallel_common.h" +#include "source_base/tool_quit.h" namespace ModuleIO { @@ -20,6 +26,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, @@ -91,23 +98,40 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) - cal_pdos(psi, - p_ham, - pv, - ucell, - kv, - nspin0, - nbands, - ekb, - emax, - emin, - dos_edelta_ev, - bcoeff, - istep, - out_app_flag, - nlocal, - nspin, - global_out_dir); + const auto pdos = cal_pdos(psi, p_ham, pv, kv, nspin, nbands, ekb, emax, emin, dos_edelta_ev, bcoeff, nlocal); + const bool root = GlobalV::MY_RANK == 0; + if (pdos_format == "npy") + { + std::string error; + if (root) + { + try + { + const std::string path = write_pdos_npy(ucell, pdos, nspin, emin, dos_edelta_ev, + global_out_dir, istep, out_app_flag); + ofs_running << " Wrote projected DOS to " << path << '\n'; + } + catch (const std::exception& e) + { + error = e.what(); + } + } + Parallel_Common::bcast_string(error); + if (!error.empty()) + { + ModuleBase::WARNING_QUIT("write_dos_lcao", error); + } + } + else if (root) + { + const int npoints = pdos.front().nc; + write_pdos_text(ucell, pdos.data(), nspin, nlocal, npoints, emin, dos_edelta_ev, + global_out_dir, istep, out_app_flag); + } + if (root) + { + write_orb_info(&ucell); + } ofs_running << " #DOS CALCULATION ENDS# " << std::endl; @@ -128,6 +152,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, @@ -155,6 +180,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 25e8b6d14a6..40c7351f738 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -28,6 +28,7 @@ namespace ModuleIO const double& dos_edelta_ev, // Delta energy const double& dos_scale, const double& bcoeff, + const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_pdos_npy.cpp b/source/source_io/module_dos/write_pdos_npy.cpp new file mode 100644 index 00000000000..51520259599 --- /dev/null +++ b/source/source_io/module_dos/write_pdos_npy.cpp @@ -0,0 +1,224 @@ +#include "write_pdos_npy.h" +#include "pdos_orbitals.h" +#include "source_base/matrix.h" +#include "source_cell/unitcell.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#else +#include +#endif + +namespace +{ +const char npy_magic[] = "\x93NUMPY\x01\x00"; +const char descriptor[] = "{'descr': [('record_bytes', '& pdos, + int nspin, double emin, double de, int step) +{ + static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "NPY PDOS requires binary64"); + const int ne = pdos.front().nc; + std::vector> by_type(cell.ntype); + size_t width = 1; + for (int it = 0; it < cell.ntype; ++it) + { + by_type[it] = ModuleIO::pdos_orbitals(cell.atoms[it]); + width = std::max(width, cell.atoms[it].label.size()); + } + width = (width + 7) / 8 * 8; // keep the float64 spectrum aligned in every row + size_t norb = 0; + for (int iat = 0; iat < cell.nat; ++iat) + { + norb += by_type[cell.iat2it[iat]].size(); + } + + // One row per (atom, l, m). The array can exceed 2 GiB without making + // the structured dtype itself as large as the whole frame. + const uint16_t one = 1; + const char endian = *reinterpret_cast(&one) == 1 ? '<' : '>'; + std::ostringstream dtype; + dtype.imbue(std::locale::classic()); + dtype << descriptor << "('schema_version','" << endian << "i4'),('ionic_step','" << endian + << "i4'),('nspin','" << endian << "i4'),('atom_index','" << endian << "i4'),('l','" << endian + << "i4'),('m','" << endian << "i4'),('energy_min_eV','" << endian + << "f8'),('energy_step_eV','" << endian << "f8'),('species','|S" << width + << "'),('pdos','" << endian << "f8',(" << pdos.size() << "," << ne + << "))], 'fortran_order': False, 'shape': (" << norb << ",), }"; + std::string header = dtype.str(); + header.append((64 - (10 + header.size() + 1) % 64) % 64, ' '); + header.push_back('\n'); + const unsigned char length[] = {static_cast(header.size() & 255), + static_cast(header.size() >> 8)}; + out.write(npy_magic, 8); + out.write(reinterpret_cast(length), sizeof(length)); + out.write(header.data(), header.size()); + + const uint64_t row_bytes = 8 + 6 * 4 + 2 * 8 + width + 8 * static_cast(ne) * pdos.size(); + if (row_bytes > std::numeric_limits::max()) + { + throw std::runtime_error("one orbital exceeds the NumPy structured dtype size limit"); + } + const uint64_t bytes = norb * row_bytes; + unsigned char frame_size[8]; + for (unsigned int i = 0; i < 8; ++i) + { + frame_size[i] = static_cast((bytes >> (8 * i)) & 255); + } + const double grid[] = {emin, de}; + std::vector spectrum(ne); + const bool spinor = nspin == 4; + for (int iat = 0; iat < cell.nat; ++iat) + { + const int it = cell.iat2it[iat]; + std::string label = cell.atoms[it].label; + label.resize(width, '\0'); + const int first = cell.get_iat2iwt()[iat]; + for (const auto& orbital : by_type[it]) + { + const int32_t attributes[] = {1, step, nspin, iat + 1, orbital.l, orbital.m}; + out.write(reinterpret_cast(frame_size), sizeof(frame_size)); + out.write(reinterpret_cast(attributes), sizeof(attributes)); + out.write(reinterpret_cast(grid), sizeof(grid)); + out.write(label.data(), width); + for (const auto& spin : pdos) + { + for (int n = 0; n < ne; ++n) + { + spectrum[n] = orbital.value(spin, first, n, spinor); + } + out.write(reinterpret_cast(spectrum.data()), spectrum.size() * sizeof(double)); + } + } + } +} + +void truncate_file(const std::string& path, std::streamoff size) +{ +#ifdef _WIN32 + std::FILE* file = std::fopen(path.c_str(), "rb+"); + if (!file) { throw std::runtime_error(std::strerror(errno)); } + const int status = _chsize_s(_fileno(file), size); + std::fclose(file); +#else + const int status = truncate(path.c_str(), size); +#endif + if (status != 0) { throw std::runtime_error("cannot truncate an incomplete NPY record"); } +} + +// Seek over the spectra. A short final record from an interrupted append can be +// discarded without rewriting the complete records, even if each energy grid differs. +std::streamoff prepare_append(const std::string& path) +{ + std::ifstream in(path, std::ios::binary | std::ios::ate); + if (!in) + { + if (errno == ENOENT) { return 0; } + throw std::runtime_error(std::strerror(errno)); + } + const std::streamoff end = in.tellg(); + std::streamoff pos = 0; + while (pos < end) + { + in.seekg(pos); + unsigned char prefix[10] = {}; + in.read(reinterpret_cast(prefix), sizeof(prefix)); + const size_t got = in.gcount(); + if (in.bad() || std::memcmp(prefix, npy_magic, std::min(got, size_t(8))) != 0) + { + throw std::runtime_error("invalid NPY record prefix"); + } + if (got < sizeof(prefix)) { break; } + const int length = prefix[8] + 256 * prefix[9]; + if (length < static_cast(sizeof(descriptor))) { throw std::runtime_error("invalid NPY header length"); } + std::string header(length, '\0'); + in.read(&header[0], length); + const size_t prefix_size = std::min(in.gcount(), sizeof(descriptor) - 1); + if (in.bad() || std::memcmp(header.data(), descriptor, prefix_size) != 0) + { + throw std::runtime_error("incompatible NPY PDOS descriptor"); + } + if (!in) { break; } + unsigned char raw[8]; + in.read(reinterpret_cast(raw), sizeof(raw)); + if (in.bad()) { throw std::runtime_error("error reading NPY record"); } + if (!in) { break; } + uint64_t bytes = 0; + for (unsigned int i = 0; i < 8; ++i) { bytes |= uint64_t(raw[i]) << (8 * i); } + if (bytes < 20) { throw std::runtime_error("invalid NPY payload length"); } + const std::streamoff data_start = pos + 10 + length; + if (bytes > static_cast(end - data_start)) + { + break; + } + pos = data_start + static_cast(bytes); + } + in.close(); + if (pos != end) { truncate_file(path, pos); } + return pos; +} +} + +std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& out_dir, + int istep, int out_app_flag) +{ + const int step = istep < 0 ? 1 : istep + 1; + const bool numbered = out_app_flag == 2 && istep >= 0; + const std::string suffix = numbered ? "g" + std::to_string(step) : ""; + const std::string path = out_dir + "pdos" + suffix + ".npy"; + try + { + const bool append = out_app_flag == 1 && istep > 0; + const std::streamoff previous = append ? prepare_append(path) : 0; + const std::string target = append ? path : path + ".tmp." + std::to_string(std::random_device{}()); + const auto mode = append ? std::ios::app : std::ios::trunc; + std::ofstream out(target, std::ios::binary | mode); + out.exceptions(std::ios::failbit | std::ios::badbit); + try + { + write_frame(out, cell, pdos, nspin, emin, de, step); + out.close(); + if (!append) + { +#ifdef _WIN32 + if (!MoveFileExA(target.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) + { + throw std::runtime_error("cannot replace NPY file (Windows error " + + std::to_string(GetLastError()) + ")"); + } +#else + if (std::rename(target.c_str(), path.c_str()) != 0) + { + throw std::runtime_error(std::strerror(errno)); + } +#endif + } + } + catch (...) + { + out.exceptions(std::ios::goodbit); + if (out.is_open()) { out.close(); } + if (append) { truncate_file(path, previous); } + else { std::remove(target.c_str()); } + throw; + } + } + catch (const std::exception& e) + { + throw std::runtime_error(path + ": " + e.what()); + } + return path; +} diff --git a/source/source_io/module_dos/write_pdos_npy.h b/source/source_io/module_dos/write_pdos_npy.h new file mode 100644 index 00000000000..323d14e2c18 --- /dev/null +++ b/source/source_io/module_dos/write_pdos_npy.h @@ -0,0 +1,19 @@ +#ifndef WRITE_PDOS_NPY_H +#define WRITE_PDOS_NPY_H + +#include +#include + +class UnitCell; +namespace ModuleBase +{ +class matrix; +} + +namespace ModuleIO +{ +std::string write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& out_dir, + int istep, int out_app_flag); +} +#endif diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index c3ded7e75c6..a28f27c4e8d 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -1,12 +1,11 @@ #include "write_pdos_text.h" +#include "pdos_orbitals.h" #include "source_base/global_variable.h" -#include #include #include #include -#include void ModuleIO::write_pdos_text( const UnitCell& ucell, @@ -63,31 +62,8 @@ void ModuleIO::write_pdos_text( const int it = ucell.iat2it[iat]; const Atom* atom = &ucell.atoms[it]; const int s0 = ucell.itiaiw2iwt(it, ia, 0); - const int max_l = atom->nwl; - - // collect all (l, m) for this atom, ordered s,p,d,f - // iw2m stores m as 0..2l (non-negative), so loop m = 0..2*L - struct OrbInfo - { - int l; - int m; // 0..2l - }; - std::vector orb_list; - - for (int L = 0; L <= max_l; ++L) - { - for (int m = 0; m <= 2 * L; ++m) - { - for (int j = 0; j < atom->nw; ++j) - { - if (atom->iw2l[j] == L && atom->iw2m[j] == m) - { - orb_list.push_back({L, m}); - break; - } - } - } - } + const auto orbitals = pdos_orbitals(*atom); + const bool spinor = nspin == 4; for (int n = 0; n < npoints; ++n) { @@ -97,38 +73,9 @@ void ModuleIO::write_pdos_text( << " " << std::setw(3) << iat + 1 << " " << std::setw(4) << ucell.atoms[it].label; - for (size_t io = 0; io < orb_list.size(); ++io) + for (const auto& orbital : orbitals) { - const int L = orb_list[io].l; - const int m = orb_list[io].m; - double pdos_val = 0.0; - - // sum over all zeta for this (l, m) - for (int j = 0; j < atom->nw; ++j) - { - if (atom->iw2l[j] != L || atom->iw2m[j] != m) - { - continue; - } - const int w = ucell.itiaiw2iwt(it, ia, j); - - if (nspin == 4) - { - const int w0 = w - s0; - pdos_val += pdos[0](s0 + 2 * w0, n) + pdos[0](s0 + 2 * w0 + 1, n); - } - else - { - pdos_val += pdos[is](w, n); - } - } - - // zero out negligible values - if (std::abs(pdos_val) < 1e-6) - { - pdos_val = 0.0; - } - + const double pdos_val = orbital.value(pdos[is], s0, n, spinor); ofs << " " << std::setw(8) << std::fixed << std::setprecision(6) << pdos_val; } ofs << std::endl; diff --git a/source/source_io/module_dos/write_pdos_text.h b/source/source_io/module_dos/write_pdos_text.h index 434c6f7ebe9..4d603aae708 100644 --- a/source/source_io/module_dos/write_pdos_text.h +++ b/source/source_io/module_dos/write_pdos_text.h @@ -8,8 +8,8 @@ namespace ModuleIO { /// Write PDOS in plain text long-table format. -/// File name: pdoss{spin}g{geom}.txt (g{geom} omitted when out_app_flag == 1) -/// Columns: energy(eV) atom species l z m pdos(1/eV) +/// Mode 2 adds g{geom} to pdoss{spin}.txt for numbered ionic steps. +/// Rows contain energy (eV), atom, species and one PDOS value per (l,m), summed over zeta. /// For nspin=4, the two spinor components are summed. void write_pdos_text( const UnitCell& ucell, diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index b837b985a85..6aefa6349ec 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -540,6 +540,7 @@ struct Input_para std::string spillage_outdir = "./"; ///< output directory for spillage // ============== #Parameters (12.Postprocess) =========================== + std::string pdos_format = "text"; ///< LCAO projected DOS output format double dos_emin_ev = -15.0; double dos_emax_ev = 15.0; double dos_edelta_ev = 0.03; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 52e88104a6d..6e63aecd031 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -378,6 +378,7 @@ Also controled by out_freq_ion and out_app_flag. item.description = R"(Whether to output the density of states (DOS) and projected density of states (PDOS). For more information, refer to the dos.md. * 0: no output * 1: output the density of states (DOS) and projected density of states (PDOS, LCAO only) + * The PDOS text filenames below apply to pdos_format text. Set pdos_format npy for NumPy output. * With out_app_flag = 0: fixed-name files (`doss{s}.txt`, `pdoss{s}.txt`) are truncated and overwritten at every write. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# ionic step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index cca3d983a65..b021f9bca99 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -9,6 +9,24 @@ void ReadInput::item_postprocess() // NOTE: The order of add_item() calls below determines the parameter order // in the generated documentation (docs/advanced/input_files/input-main.md). // Please preserve this ordering when adding new parameters. + { + Input_Item item("pdos_format"); + item.domain.set_choices({"text", "npy"}); + item.annotation = "LCAO projected DOS file format"; + item.category = "Density of states"; + item.type = "String"; + item.description = "With out_dos 1, select text (pdoss*.txt) or npy (pdos*.npy) for LCAO projected DOS. " + "Total DOS is written as text."; + item.default_value = "text"; + read_sync_string(input.pdos_format); + item.check_value = [](const Input_Item&, const Parameter& para) { + if (para.input.pdos_format == "npy" && para.input.basis_type != "lcao") + { + ModuleBase::WARNING_QUIT("ReadInput", "pdos_format npy requires basis_type lcao"); + } + }; + this->add_item(item); + } { Input_Item item("dos_edelta_ev"); item.annotation = "delta energy for dos"; diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 6c310eeb1c0..642393d54d6 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -350,7 +350,10 @@ def plot(self, fig: Figure, ax: Union[axes.Axes, Sequence[axes.Axes]], efermi: f class PDOS(DOS): - """Parse partial DOS data from the text PDOS files written by ABACUS. + """Parse ABACUS text or NumPy projected DOS. + + A NumPy file stores one structured array per output. The one-based + ``record`` argument selects an array when several were appended. The text format (one file per spin channel) looks like:: @@ -380,9 +383,11 @@ def _col_to_m(l: int, col: int) -> int: return 0 return (col + 1) // 2 if col % 2 == 1 else -(col // 2) - def __init__(self, pdosfile: PathLike = None) -> None: + def __init__(self, pdosfile: PathLike = None, record: int = 1) -> None: self.pdosfile = pdosfile - self._read() + if isinstance(record, bool) or not isinstance(record, (int, np.integer)) or record < 1: + raise ValueError("PDOS record must be a positive integer") + self._read(record) super().__init__(self.nspin) def _find_spin_files(self) -> List[str]: @@ -491,14 +496,75 @@ def _read_one(self, fname: str): return energy, orbitals - def _read(self): + def _read_npy(self, path, record): + """Map only the selected array, skipping earlier records by their NPY headers.""" + from numpy.lib import format + + end = path.stat().st_size + with path.open("rb") as stream: + for _ in range(record): + if stream.tell() == end: + raise ValueError(f"{path} has no PDOS record {record}") + if format.read_magic(stream) != (1, 0): + raise ValueError(f"Unsupported ABACUS PDOS NPY header in {path}") + shape, _, dtype = format.read_array_header_1_0(stream) + if len(shape) != 1 or shape[0] < 1 or dtype.hasobject or not dtype.names: + raise ValueError(f"Expected a nonempty array of PDOS orbitals in {path}") + offset = stream.tell() + size = shape[0] * dtype.itemsize + if size > end - offset: + raise ValueError(f"Incomplete PDOS record in {path}") + stream.seek(size, 1) + + rows = np.memmap(path, mode="r", offset=offset, dtype=dtype, shape=shape) + required = {"schema_version", "ionic_step", "record_bytes", "nspin", "atom_index", + "species", "l", "m", "energy_min_eV", "energy_step_eV", "pdos"} + if not required.issubset(dtype.names) or not np.all(rows["schema_version"] == 1): + raise ValueError(f"Unknown PDOS schema in {path}") + first = rows[0] + values = rows["pdos"] + if (first["nspin"] not in (1, 2, 4) or values.ndim != 3 or values.shape[2] == 0 + or values.shape[1] != (2 if first["nspin"] == 2 else 1) + or values.dtype.kind != "f" or values.dtype.itemsize != 8 + or not np.all(rows["record_bytes"] == size)): + raise ValueError(f"Invalid PDOS dimensions in {path}") + for field in ("nspin", "ionic_step", "energy_min_eV", "energy_step_eV"): + if not np.all(rows[field] == first[field]): + raise ValueError(f"Inconsistent {field} in {path}") + self.nspin = values.shape[1] + self.energy = (first["energy_min_eV"] + np.arange(values.shape[2]) * first["energy_step_eV"])[:, None] + self.orbitals = [ + dict(index=i + 1, atom_index=int(row["atom_index"]), species=row["species"].decode("utf-8"), + l=int(row["l"]), m=int(row["m"]), data=values[i].T) + for i, row in enumerate(rows) + ] + + def _read(self, record): """Read partial DOS data file(s) :params pdosfile: path of a text PDOS file, a spin-up file of a spin-polarized pair, or a path/prefix used to discover the ``pdoss1*``/``pdoss2*`` files. """ - spin_files = self._find_spin_files() + path = Path(self.pdosfile) + if path.suffix == ".npy" and not path.is_dir(): + self._read_npy(path, record) + return + try: + spin_files = self._find_spin_files() + except FileNotFoundError: + prefix = path / "pdos" if path.is_dir() else path + candidates = [prefix.with_name(prefix.name + ".npy")] + numbered = [p for p in prefix.parent.glob(prefix.name + "g*.npy") + if p.stem[len(prefix.name) + 1:].isdigit()] + candidates.extend(sorted(numbered, key=lambda p: int(p.stem[len(prefix.name) + 1:]))) + for candidate in candidates: + if candidate.is_file(): + self._read_npy(candidate, record) + return + raise + if record != 1: + raise ValueError("PDOS record selection requires a .npy file") self.nspin = len(spin_files) energy, orbitals_up = self._read_one(spin_files[0]) diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/main.py b/tools/02_postprocessing/plot-tools/abacus_plot/main.py index 859a49094e2..b3a310ed2b2 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/main.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/main.py @@ -80,6 +80,7 @@ def show_cmdline(cls, args): if args.dos and args.projected: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') + record = text.pop("pdos_record", 1) efermi = text.pop("efermi", 0.0) energy_range = text.pop("energy_range", []) dos_range = text.pop("dos_range", []) @@ -88,6 +89,8 @@ def show_cmdline(cls, args): atom_index = key2int(text.pop("atom_index", None)) species = text.pop("species", None) figsize = text.pop("figsize", (12, 10)) + if not (index or atom_index or species): + fig, ax = plt.subplots(figsize=figsize) if index: fig, ax = plt.subplots( len(index), 1, sharex=True, figsize=figsize) @@ -101,7 +104,7 @@ def show_cmdline(cls, args): len(species) if isinstance(species, dict) else 1, 1, sharex=True, figsize=figsize) prec = text.pop("prec", 0.01) - pdos = PDOS(pdosfile) + pdos = PDOS(pdosfile, record=record) pdos.plot(fig=fig, ax=ax, index=index, atom_index=atom_index, species=species, efermi=efermi, shift=shift, energy_range=energy_range, dos_range=dos_range, prec=prec, **text) dpi = text.pop("dpi", 400) @@ -110,11 +113,12 @@ def show_cmdline(cls, args): if args.dos and args.out: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') + record = text.pop("pdos_record", 1) index = key2int(text.pop("index", None)) atom_index = key2int(text.pop("atom_index", None)) species = text.pop("species", None) outdir = text.pop("outdir", './') - pdos = PDOS(pdosfile) + pdos = PDOS(pdosfile, record=record) pdos.write(index=index, atom_index=atom_index, species=species, outdir=outdir) def main(): diff --git a/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py b/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py new file mode 100644 index 00000000000..d78529f5778 --- /dev/null +++ b/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py @@ -0,0 +1,83 @@ +import tempfile +import unittest +from pathlib import Path + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np + +from abacus_plot.dos import PDOS + + +def frame(nspin, ne, step): + channels = 2 if nspin == 2 else 1 + dtype = [("record_bytes", " Date: Thu, 19 Nov 2026 11:17:26 +0800 Subject: [PATCH 02/15] feat: share NumPy output between total and projected DOS --- docs/advanced/elec_properties/dos.md | 18 +- source/Makefile.Objects | 1 + source/source_io/CMakeLists.txt | 1 + .../source_io/module_ctrl/ctrl_output_pw.cpp | 1 + .../source_io/module_ctrl/ctrl_scf_lcao.cpp | 1 + source/source_io/module_dos/cal_dos.cpp | 53 +++- .../module_dos/unittests/CMakeLists.txt | 4 +- .../module_dos/unittests/test_cal_dos.cpp | 53 ++++ .../unittests/test_write_dos_pw.cpp | 2 + .../source_io/module_dos/write_dos_lcao.cpp | 8 +- source/source_io/module_dos/write_dos_lcao.h | 1 + source/source_io/module_dos/write_dos_pw.cpp | 3 +- source/source_io/module_dos/write_dos_pw.h | 1 + .../source_io/module_dos/write_pdos_npy.cpp | 226 +++--------------- source/source_io/module_output/npy_record.cpp | 172 +++++++++++++ source/source_io/module_output/npy_record.h | 23 ++ .../module_parameter/input_parameter.h | 3 +- .../module_parameter/read_inp_out.cpp | 2 +- .../module_parameter/read_inp_postproc.cpp | 17 +- .../plot-tools/abacus_plot/dos.py | 69 +++--- .../plot-tools/abacus_plot/main.py | 6 +- .../plot-tools/abacus_plot/npy_record.py | 39 +++ .../plot-tools/tests/test_pdos_npy.py | 2 +- .../plot-tools/tests/test_tdos_npy.py | 47 ++++ 24 files changed, 504 insertions(+), 249 deletions(-) create mode 100644 source/source_io/module_output/npy_record.cpp create mode 100644 source/source_io/module_output/npy_record.h create mode 100644 tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py create mode 100644 tools/02_postprocessing/plot-tools/tests/test_tdos_npy.py diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 0e0dff428d7..8ed3839e378 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -98,16 +98,18 @@ The `# istep:` line is only present for geometry-optimization (istep) output. Wi For nspin=2, two files are written (pdoss1* and pdoss2*), one per spin channel. For nspin=4, the two spinor components are summed into a single file. The unit of PDOS is also `(number of states)/(eV * unitcell)`. -### NumPy output for LCAO +### NumPy output -The default `pdos_format text` writes the text files above. To write projected DOS in NumPy format, use +Set `out_spectral_format npy` to write the spectra selected by `out_dos` as NumPy arrays. This includes total DOS for PW and LCAO and projected DOS for LCAO. The default format is `text`. The NPY writer is built into ABACUS. ```text -out_dos 1 -pdos_format npy +out_dos 1 +out_spectral_format npy ``` -This requires only an LCAO build. Total DOS continues to use `doss*.txt`. Each output is a standard, pickle-free NumPy 1.0 structured array with one row for each atom and each `(l,m)` channel present in its basis (all zeta components summed). The `pdos` field holds float64 spectra in 1/eV, with axes `(orbital, spin channel, energy point)` across the array. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. +Each file contains a standard NumPy 1.0 structured array with named fields. Total DOS uses one row per energy point in `doss1.npy`, with a separate `doss2.npy` for collinear spin. The five binary64 fields are `energy_eV`, `dos`, `dos_int`, `dos_smear` and `dos_smear_int`, in the same units as the text columns. `spin_channel` gives the one-based channel. For example, `np.load("doss1.npy")["dos_smear"]` returns the smeared DOS in states/eV per cell. + +LCAO projected DOS uses one row per atom and `(l,m)` channel in `pdos.npy`. Contributions from all zeta components are summed. Across the array, the binary64 `pdos` field has axes `(orbital, spin channel, energy point)` and units of 1/eV. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. With the default spectral format, `pdos_format npy` selects binary PDOS alone. ```python import numpy as np @@ -120,12 +122,12 @@ first_orbital = rows["pdos"][0, 0, :] # first orbital and first spin channel Each row includes the one-based `atom_index`, UTF-8 byte string `species`, `l`, signed `m`, `nspin`, and one-based `ionic_step`. A single-point calculation uses step 1. The fields `schema_version` (1) and `record_bytes` (payload size of the complete array) identify the schema and delimit records for append recovery. -Mode `out_app_flag 0` replaces `pdos.npy`. Mode 1 appends one complete NumPy array per write to that file, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps into `DOS/pdosgN.npy`. +For DOS, mode `out_app_flag 0` replaces the fixed-name file. Mode 1 appends one complete NumPy array per write, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps such as `DOS/doss1g2.npy` and `DOS/pdosg2.npy`. -The plotting and data-export commands both accept the file via `pdosfile`. For an appended file, `pdos_record` selects the one-based record number and defaults to 1. +For `abacus-plot`, use `tdosfile` for total DOS and `pdosfile` for projected DOS. The common JSON option `record` selects a one-based NPY record and defaults to 1. PDOS also accepts the spelling `pdos_record`. ```json -{"pdosfile": "OUT.ABACUS/pdos.npy", "pdos_record": 1, "species": ["Si"]} +{"pdosfile": "OUT.ABACUS/pdos.npy", "record": 1, "species": ["Si"]} ``` Run `abacus-plot -d -p -f config.json` to plot, or `abacus-plot -d -o -f config.json` to export the selected species' curves. diff --git a/source/Makefile.Objects b/source/Makefile.Objects index f8b19e87673..d76a4681485 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -749,6 +749,7 @@ OBJS_IO=module_parameter/input_conv.o\ module_ctrl/ctrl_output_td_pw.o\ module_output/td_conserv_io.o\ module_dos/cal_dos.o\ + module_output/npy_record.o\ module_dos/cal_pdos_gamma.o\ module_dos/cal_pdos_multik.o\ module_dos/write_pdos_text.o\ diff --git a/source/source_io/CMakeLists.txt b/source/source_io/CMakeLists.txt index 972b4652467..55b3d2d0952 100644 --- a/source/source_io/CMakeLists.txt +++ b/source/source_io/CMakeLists.txt @@ -12,6 +12,7 @@ list( module_bessel/bessel_basis.cpp module_output/cal_test.cpp module_dos/cal_dos.cpp + module_output/npy_record.cpp module_dos/cal_ldos.cpp module_ml/cal_mlkedf_desc.cpp module_dos/write_dos_pw.cpp diff --git a/source/source_io/module_ctrl/ctrl_output_pw.cpp b/source/source_io/module_ctrl/ctrl_output_pw.cpp index 435a6412bd4..78b1bef2c9c 100644 --- a/source/source_io/module_ctrl/ctrl_output_pw.cpp +++ b/source/source_io/module_ctrl/ctrl_output_pw.cpp @@ -189,6 +189,7 @@ void ModuleIO::ctrl_scf_pw(const int istep, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, + inp.out_spectral_format, inp.nspin, inp.out_dos, PARAM.globalv.dos_setemax, diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index 74bc1e1622c..458ec2baece 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -168,6 +168,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, + inp.out_spectral_format, inp.pdos_format, out_app_flag, istep, diff --git a/source/source_io/module_dos/cal_dos.cpp b/source/source_io/module_dos/cal_dos.cpp index 4305faa4b98..e45f2af3ff7 100644 --- a/source/source_io/module_dos/cal_dos.cpp +++ b/source/source_io/module_dos/cal_dos.cpp @@ -1,4 +1,6 @@ #include "cal_dos.h" +#include "source_io/module_output/npy_record.h" +#include "source_base/parallel_common.h" #include "source_base/constants.h" #include "source_base/global_function.h" @@ -115,9 +117,11 @@ bool ModuleIO::cal_dos(const int& is, // index for spin std::ofstream ofs_dos; - if (GlobalV::MY_RANK == 0) + const bool npy = fn.size() >= 4 && fn.compare(fn.size() - 4, 4, ".npy") == 0; + const bool append_step = (out_app_flag == 1) && (istep > 0); + const bool root = GlobalV::MY_RANK == 0; + if (root && !npy) { - const bool append_step = (out_app_flag == 1) && (istep > 0); if (append_step) { ofs_dos.open(fn.c_str(), std::ios::app); @@ -152,7 +156,7 @@ bool ModuleIO::cal_dos(const int& is, // index for spin ModuleBase::WARNING("ModuleIO::cal_dos", "npoints <= 0"); return false; } - if (GlobalV::MY_RANK == 0) + if (root && !npy) { ofs_dos << npoints << " # number of points" << std::endl; ofs_dos << std::fixed << std::setprecision(6); @@ -219,8 +223,10 @@ bool ModuleIO::cal_dos(const int& is, // index for spin double sum2 = 0.0; const double dos_thr = 1.0e-12; - if (GlobalV::MY_RANK == 0) + std::string error; + if (root) { + std::vector smear_integral(npy ? npoints : 0); for (int n = 0; n < npoints; ++n) { dos[n] /= static_cast(nkstot); @@ -233,17 +239,50 @@ bool ModuleIO::cal_dos(const int& is, // index for spin } sum2 += dos_smear[n] * de_ev; + if (npy) + { + smear_integral[n] = sum2; + continue; + } ofs_dos << std::setw(13) << ene[n] << " " << std::setw(12) << dos[n] << " " << std::setw(12) << sum_elec[n] << " " << std::setw(14) << dos_smear[n] << " " << std::setw(14) << sum2 << std::endl; } + if (npy) + { + const std::string fields = "('spin_channel','=i8'),('energy_eV','=f8'),('dos','=f8')," + "('dos_int','=f8'),('dos_smear','=f8'),('dos_smear_int','=f8')"; + const int step = std::max(1, istep + 1); + const std::int64_t spin = is + 1; + const size_t row_bytes = sizeof(NpyPrefix) + sizeof(spin) + 5 * sizeof(double); + try + { + write_npy_record(fn, append_step, step, fields, "dos_smear", npoints, row_bytes, + [&](std::ostream& out, const NpyPrefix& prefix) { + for (int n = 0; n < npoints; ++n) + { + const double row[] = {ene[n], dos[n], sum_elec[n], dos_smear[n], smear_integral[n]}; + out.write(prefix.data(), prefix.size()); + out.write(reinterpret_cast(&spin), sizeof(spin)); + out.write(reinterpret_cast(row), sizeof(row)); + } + }); + } + catch (const std::exception& e) { error = e.what(); } + } + else + { + ofs_dos.close(); + } } - - if (GlobalV::MY_RANK == 0) + if (npy) { - ofs_dos.close(); +#ifdef __MPI + Parallel_Common::bcast_string(error); +#endif + if (!error.empty()) { ModuleBase::WARNING_QUIT("cal_dos", error); } } ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Number of bands", nbands); diff --git a/source/source_io/module_dos/unittests/CMakeLists.txt b/source/source_io/module_dos/unittests/CMakeLists.txt index f63aa7c7f77..49ce370083c 100644 --- a/source/source_io/module_dos/unittests/CMakeLists.txt +++ b/source/source_io/module_dos/unittests/CMakeLists.txt @@ -12,7 +12,7 @@ if(ENABLE_MPI) addtest( TARGET MODULE_DOS_cal_dos LIBS parameter base device - SOURCES test_cal_dos.cpp ../cal_dos.cpp) + SOURCES test_cal_dos.cpp ../cal_dos.cpp ../../module_output/npy_record.cpp) addtest( TARGET MODULE_DOS_write_dos_pw @@ -20,6 +20,7 @@ if(ENABLE_MPI) SOURCES test_write_dos_pw.cpp ../write_dos_pw.cpp ../cal_dos.cpp + ../../module_output/npy_record.cpp ../../../source_cell/parallel_kpoints.cpp ../../../source_cell/klist.cpp ../../../source_cell/klist_io.cpp @@ -45,6 +46,7 @@ if(ENABLE_LCAO) LIBS parameter base device SOURCES test_write_pdos_npy.cpp ../write_pdos_npy.cpp + ../../module_output/npy_record.cpp ../pdos_orbitals.cpp ../../../source_cell/atom_spec.cpp ../../../source_cell/atom_pseudo.cpp diff --git a/source/source_io/module_dos/unittests/test_cal_dos.cpp b/source/source_io/module_dos/unittests/test_cal_dos.cpp index 82c99219112..fac5692f296 100644 --- a/source/source_io/module_dos/unittests/test_cal_dos.cpp +++ b/source/source_io/module_dos/unittests/test_cal_dos.cpp @@ -2,6 +2,9 @@ #include "gmock/gmock.h" #include "../cal_dos.h" #include "source_base/global_variable.h" +#include +#include +#include #include #include #ifdef __MPI @@ -27,6 +30,56 @@ class DosTest : public ::testing::Test std::string output; }; +TEST_F(DosTest, NpyStoresFiveColumnsAcrossSteps) +{ + const std::string path = testing::TempDir() + "/abacus-total-dos-steps.npy"; + const std::vector weights{1.0}; + const std::vector spins{0}; + const ModuleBase::matrix eigenvalues(1, 1); + const ModuleBase::matrix occupations(1, 1); + const double sigma = 0.05; + for (int step = 0; step < 2; ++step) + { + ASSERT_TRUE(ModuleIO::cal_dos(0, path, 1.0, 1.0, 0.0, sigma, 1, 1, weights, spins, + 1, eigenvalues, occupations, step, 1, 1)); + } + std::ifstream in(path, std::ios::binary); + for (int step = 1; step <= 2; ++step) + { + unsigned char prefix[10]; + ASSERT_TRUE(in.read(reinterpret_cast(prefix), sizeof(prefix))); + EXPECT_EQ(std::string(reinterpret_cast(prefix), 8), std::string("\x93NUMPY\x01\x00", 8)); + std::string header(prefix[8] + 256 * prefix[9], '\0'); + ASSERT_TRUE(in.read(&header[0], header.size())); + EXPECT_NE(header.find("'dos_smear_int'"), std::string::npos); + EXPECT_NE(header.find("'shape': (2,)"), std::string::npos); + const double peak = 1.0 / (sigma * std::sqrt(2.0 * std::acos(-1.0))); + for (int n = 0; n < 2; ++n) + { + unsigned char bytes[8]; + std::int32_t flags[2]; + std::int64_t spin = 0; + double data[5]; + ASSERT_TRUE(in.read(reinterpret_cast(bytes), sizeof(bytes))); + ASSERT_TRUE(in.read(reinterpret_cast(flags), sizeof(flags))); + ASSERT_TRUE(in.read(reinterpret_cast(&spin), sizeof(spin))); + ASSERT_TRUE(in.read(reinterpret_cast(data), sizeof(data))); + EXPECT_EQ(bytes[0], 128); + EXPECT_EQ(flags[0], 1); + EXPECT_EQ(flags[1], step); + EXPECT_EQ(spin, 1); + EXPECT_DOUBLE_EQ(data[0], n); + EXPECT_DOUBLE_EQ(data[1], n == 0 ? 1.0 : 0.0); + EXPECT_DOUBLE_EQ(data[2], 1.0); + EXPECT_NEAR(data[3], n == 0 ? peak : 0.0, 1e-12); + EXPECT_NEAR(data[4], peak, 1e-12); + } + } + EXPECT_EQ(in.peek(), std::char_traits::eof()); + in.close(); + std::remove(path.c_str()); +} + TEST_F(DosTest,Dos) { //is,fa,de_ev,emax_ev,emin_ev,bcoeff,nks,nkstot,nbands diff --git a/source/source_io/module_dos/unittests/test_write_dos_pw.cpp b/source/source_io/module_dos/unittests/test_write_dos_pw.cpp index 5e719bfe740..12c2887686f 100644 --- a/source/source_io/module_dos/unittests/test_write_dos_pw.cpp +++ b/source/source_io/module_dos/unittests/test_write_dos_pw.cpp @@ -82,6 +82,7 @@ TEST_F(DosPWTest,Dos1) dosp.de_ev, dos_scale, dosp.bcoeff, + "text", nspin, out_dos, dos_setemax, @@ -161,6 +162,7 @@ TEST_F(DosPWTest,Dos2) dosp.de_ev, dos_scale, dosp.bcoeff, + "text", nspin, out_dos, dos_setemax, diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 9cb5eb00692..caf90becc17 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -26,6 +26,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& spectral_format, const std::string& pdos_format, const int out_app_flag, const int istep, @@ -76,7 +77,8 @@ void write_dos_lcao( ss << "g" << istep+1; } - ss << ".txt"; + ss << (spectral_format == "npy" ? ".npy" : ".txt"); + ofs_running << " DOS file: " << ss.str() << '\n'; ModuleIO::cal_dos(is, ss.str(), @@ -100,7 +102,7 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) const auto pdos = cal_pdos(psi, p_ham, pv, kv, nspin, nbands, ekb, emax, emin, dos_edelta_ev, bcoeff, nlocal); const bool root = GlobalV::MY_RANK == 0; - if (pdos_format == "npy") + if (spectral_format == "npy" || pdos_format == "npy") { std::string error; if (root) @@ -152,6 +154,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& spectral_format, const std::string& pdos_format, const int out_app_flag, const int istep, @@ -180,6 +183,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& spectral_format, const std::string& pdos_format, const int out_app_flag, const int istep, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 40c7351f738..0e7c238eaac 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -28,6 +28,7 @@ namespace ModuleIO const double& dos_edelta_ev, // Delta energy const double& dos_scale, const double& bcoeff, + const std::string& spectral_format, const std::string& pdos_format, const int out_app_flag, const int istep, diff --git a/source/source_io/module_dos/write_dos_pw.cpp b/source/source_io/module_dos/write_dos_pw.cpp index 434a39c6f80..9a0c505be74 100644 --- a/source/source_io/module_dos/write_dos_pw.cpp +++ b/source/source_io/module_dos/write_dos_pw.cpp @@ -13,6 +13,7 @@ void ModuleIO::write_dos_pw( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const std::string& spectral_format, const int nspin, const int out_dos, const bool dos_setemax, @@ -61,7 +62,7 @@ void ModuleIO::write_dos_pw( ss << "g" << istep_in+1; } - ss << ".txt"; + ss << (spectral_format == "npy" ? ".npy" : ".txt"); ModuleBase::GlobalFunc::OUT(ofs_running, "DOS file", ss.str()); diff --git a/source/source_io/module_dos/write_dos_pw.h b/source/source_io/module_dos/write_dos_pw.h index 2491c7d303a..e539f2a792e 100644 --- a/source/source_io/module_dos/write_dos_pw.h +++ b/source/source_io/module_dos/write_dos_pw.h @@ -20,6 +20,7 @@ namespace ModuleIO const double &dos_edelta_ev, const double &dos_scale, const double &bcoeff, + const std::string& spectral_format, const int nspin, const int out_dos, const bool dos_setemax, diff --git a/source/source_io/module_dos/write_pdos_npy.cpp b/source/source_io/module_dos/write_pdos_npy.cpp index 51520259599..746d6606fcb 100644 --- a/source/source_io/module_dos/write_pdos_npy.cpp +++ b/source/source_io/module_dos/write_pdos_npy.cpp @@ -2,34 +2,21 @@ #include "pdos_orbitals.h" #include "source_base/matrix.h" #include "source_cell/unitcell.h" +#include "source_io/module_output/npy_record.h" #include -#include -#include -#include -#include -#include -#include #include -#include +#include #include -#include -#ifdef _WIN32 -#include -#include -#else -#include -#endif -namespace -{ -const char npy_magic[] = "\x93NUMPY\x01\x00"; -const char descriptor[] = "{'descr': [('record_bytes', '& pdos, - int nspin, double emin, double de, int step) +std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& out_dir, + int istep, int out_app_flag) { - static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "NPY PDOS requires binary64"); + const int step = istep < 0 ? 1 : istep + 1; + const bool numbered = out_app_flag == 2 && istep >= 0; + const std::string suffix = numbered ? "g" + std::to_string(step) : ""; + const std::string path = out_dir + "pdos" + suffix + ".npy"; const int ne = pdos.front().nc; std::vector> by_type(cell.ntype); size_t width = 1; @@ -45,180 +32,41 @@ void write_frame(std::ostream& out, const UnitCell& cell, const std::vector(&one) == 1 ? '<' : '>'; - std::ostringstream dtype; - dtype.imbue(std::locale::classic()); - dtype << descriptor << "('schema_version','" << endian << "i4'),('ionic_step','" << endian - << "i4'),('nspin','" << endian << "i4'),('atom_index','" << endian << "i4'),('l','" << endian - << "i4'),('m','" << endian << "i4'),('energy_min_eV','" << endian - << "f8'),('energy_step_eV','" << endian << "f8'),('species','|S" << width - << "'),('pdos','" << endian << "f8',(" << pdos.size() << "," << ne - << "))], 'fortran_order': False, 'shape': (" << norb << ",), }"; - std::string header = dtype.str(); - header.append((64 - (10 + header.size() + 1) % 64) % 64, ' '); - header.push_back('\n'); - const unsigned char length[] = {static_cast(header.size() & 255), - static_cast(header.size() >> 8)}; - out.write(npy_magic, 8); - out.write(reinterpret_cast(length), sizeof(length)); - out.write(header.data(), header.size()); - - const uint64_t row_bytes = 8 + 6 * 4 + 2 * 8 + width + 8 * static_cast(ne) * pdos.size(); - if (row_bytes > std::numeric_limits::max()) - { - throw std::runtime_error("one orbital exceeds the NumPy structured dtype size limit"); - } - const uint64_t bytes = norb * row_bytes; - unsigned char frame_size[8]; - for (unsigned int i = 0; i < 8; ++i) - { - frame_size[i] = static_cast((bytes >> (8 * i)) & 255); - } + std::ostringstream fields; + fields.imbue(std::locale::classic()); + fields << "('nspin','=i4'),('atom_index','=i4'),('l','=i4'),('m','=i4')," + << "('energy_min_eV','=f8'),('energy_step_eV','=f8'),('species','|S" << width + << "'),('pdos','=f8',(" << pdos.size() << "," << ne << "))"; + const uint64_t row_bytes = 16 + 4 * 4 + 2 * 8 + width + 8 * static_cast(ne) * pdos.size(); + const bool append = out_app_flag == 1 && istep > 0; const double grid[] = {emin, de}; - std::vector spectrum(ne); const bool spinor = nspin == 4; - for (int iat = 0; iat < cell.nat; ++iat) - { - const int it = cell.iat2it[iat]; - std::string label = cell.atoms[it].label; - label.resize(width, '\0'); - const int first = cell.get_iat2iwt()[iat]; - for (const auto& orbital : by_type[it]) - { - const int32_t attributes[] = {1, step, nspin, iat + 1, orbital.l, orbital.m}; - out.write(reinterpret_cast(frame_size), sizeof(frame_size)); - out.write(reinterpret_cast(attributes), sizeof(attributes)); - out.write(reinterpret_cast(grid), sizeof(grid)); - out.write(label.data(), width); - for (const auto& spin : pdos) - { - for (int n = 0; n < ne; ++n) - { - spectrum[n] = orbital.value(spin, first, n, spinor); - } - out.write(reinterpret_cast(spectrum.data()), spectrum.size() * sizeof(double)); - } - } - } -} - -void truncate_file(const std::string& path, std::streamoff size) -{ -#ifdef _WIN32 - std::FILE* file = std::fopen(path.c_str(), "rb+"); - if (!file) { throw std::runtime_error(std::strerror(errno)); } - const int status = _chsize_s(_fileno(file), size); - std::fclose(file); -#else - const int status = truncate(path.c_str(), size); -#endif - if (status != 0) { throw std::runtime_error("cannot truncate an incomplete NPY record"); } -} - -// Seek over the spectra. A short final record from an interrupted append can be -// discarded without rewriting the complete records, even if each energy grid differs. -std::streamoff prepare_append(const std::string& path) -{ - std::ifstream in(path, std::ios::binary | std::ios::ate); - if (!in) - { - if (errno == ENOENT) { return 0; } - throw std::runtime_error(std::strerror(errno)); - } - const std::streamoff end = in.tellg(); - std::streamoff pos = 0; - while (pos < end) - { - in.seekg(pos); - unsigned char prefix[10] = {}; - in.read(reinterpret_cast(prefix), sizeof(prefix)); - const size_t got = in.gcount(); - if (in.bad() || std::memcmp(prefix, npy_magic, std::min(got, size_t(8))) != 0) - { - throw std::runtime_error("invalid NPY record prefix"); - } - if (got < sizeof(prefix)) { break; } - const int length = prefix[8] + 256 * prefix[9]; - if (length < static_cast(sizeof(descriptor))) { throw std::runtime_error("invalid NPY header length"); } - std::string header(length, '\0'); - in.read(&header[0], length); - const size_t prefix_size = std::min(in.gcount(), sizeof(descriptor) - 1); - if (in.bad() || std::memcmp(header.data(), descriptor, prefix_size) != 0) - { - throw std::runtime_error("incompatible NPY PDOS descriptor"); - } - if (!in) { break; } - unsigned char raw[8]; - in.read(reinterpret_cast(raw), sizeof(raw)); - if (in.bad()) { throw std::runtime_error("error reading NPY record"); } - if (!in) { break; } - uint64_t bytes = 0; - for (unsigned int i = 0; i < 8; ++i) { bytes |= uint64_t(raw[i]) << (8 * i); } - if (bytes < 20) { throw std::runtime_error("invalid NPY payload length"); } - const std::streamoff data_start = pos + 10 + length; - if (bytes > static_cast(end - data_start)) + const std::string descr = fields.str(); + write_npy_record(path, append, step, descr, "pdos", norb, row_bytes, [&](std::ostream& out, const NpyPrefix& prefix) { + std::vector spectrum(ne); + for (int iat = 0; iat < cell.nat; ++iat) { - break; - } - pos = data_start + static_cast(bytes); - } - in.close(); - if (pos != end) { truncate_file(path, pos); } - return pos; -} -} - -std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, - int nspin, double emin, double de, const std::string& out_dir, - int istep, int out_app_flag) -{ - const int step = istep < 0 ? 1 : istep + 1; - const bool numbered = out_app_flag == 2 && istep >= 0; - const std::string suffix = numbered ? "g" + std::to_string(step) : ""; - const std::string path = out_dir + "pdos" + suffix + ".npy"; - try - { - const bool append = out_app_flag == 1 && istep > 0; - const std::streamoff previous = append ? prepare_append(path) : 0; - const std::string target = append ? path : path + ".tmp." + std::to_string(std::random_device{}()); - const auto mode = append ? std::ios::app : std::ios::trunc; - std::ofstream out(target, std::ios::binary | mode); - out.exceptions(std::ios::failbit | std::ios::badbit); - try - { - write_frame(out, cell, pdos, nspin, emin, de, step); - out.close(); - if (!append) + const int it = cell.iat2it[iat]; + std::string label = cell.atoms[it].label; + label.resize(width, '\0'); + const int first = cell.get_iat2iwt()[iat]; + for (const auto& orbital : by_type[it]) { -#ifdef _WIN32 - if (!MoveFileExA(target.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) + const int32_t attributes[] = {nspin, iat + 1, orbital.l, orbital.m}; + out.write(prefix.data(), prefix.size()); + out.write(reinterpret_cast(attributes), sizeof(attributes)); + out.write(reinterpret_cast(grid), sizeof(grid)); + out.write(label.data(), width); + for (const auto& spin : pdos) { - throw std::runtime_error("cannot replace NPY file (Windows error " - + std::to_string(GetLastError()) + ")"); + for (int n = 0; n < ne; ++n) + { + spectrum[n] = orbital.value(spin, first, n, spinor); + } + out.write(reinterpret_cast(spectrum.data()), spectrum.size() * sizeof(double)); } -#else - if (std::rename(target.c_str(), path.c_str()) != 0) - { - throw std::runtime_error(std::strerror(errno)); - } -#endif } } - catch (...) - { - out.exceptions(std::ios::goodbit); - if (out.is_open()) { out.close(); } - if (append) { truncate_file(path, previous); } - else { std::remove(target.c_str()); } - throw; - } - } - catch (const std::exception& e) - { - throw std::runtime_error(path + ": " + e.what()); - } + }); return path; } diff --git a/source/source_io/module_output/npy_record.cpp b/source/source_io/module_output/npy_record.cpp new file mode 100644 index 00000000000..ddfa3ef12b6 --- /dev/null +++ b/source/source_io/module_output/npy_record.cpp @@ -0,0 +1,172 @@ +#include "npy_record.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#else +#include +#endif + +namespace +{ +const char npy_magic[] = "\x93NUMPY\x01\x00"; +const char descriptor[] = "{'descr': [('record_bytes', '(prefix), sizeof(prefix)); + const size_t got = in.gcount(); + if (in.bad() || std::memcmp(prefix, npy_magic, std::min(got, size_t(8))) != 0) + { + throw std::runtime_error("invalid NPY record prefix"); + } + if (got < sizeof(prefix)) { break; } + const int length = prefix[8] + 256 * prefix[9]; + if (length < static_cast(sizeof(descriptor))) { throw std::runtime_error("invalid NPY header length"); } + std::string header(length, '\0'); + in.read(&header[0], length); + const size_t prefix_size = std::min(in.gcount(), sizeof(descriptor) - 1); + if (in.bad() || std::memcmp(header.data(), descriptor, prefix_size) != 0) + { + throw std::runtime_error("incompatible NPY record descriptor"); + } + if (!in) { break; } + if (header.find("('" + identifying_field + "',") == std::string::npos) + { + throw std::runtime_error("unexpected dataset in NPY file"); + } + unsigned char raw[8]; + in.read(reinterpret_cast(raw), sizeof(raw)); + if (in.bad()) { throw std::runtime_error("error reading NPY record"); } + if (!in) { break; } + uint64_t bytes = 0; + for (unsigned int i = 0; i < 8; ++i) { bytes |= uint64_t(raw[i]) << (8 * i); } + if (bytes < sizeof(ModuleIO::NpyPrefix)) { throw std::runtime_error("invalid NPY payload length"); } + const std::streamoff data_start = pos + 10 + length; + if (bytes > static_cast(end - data_start)) + { + break; + } + pos = data_start + static_cast(bytes); + } + in.close(); + if (pos != end) { truncate_file(path, pos); } + return pos; +} +} + +void ModuleIO::write_npy_record(const std::string& path, bool append, int step, + const std::string& fields, const std::string& identifying_field, + std::uint64_t count, std::uint64_t row_bytes, const NpyRows& write_rows) +{ + static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "NPY requires binary64"); + if (count == 0 || row_bytes < 16 || row_bytes > std::numeric_limits::max() + || count > static_cast(std::numeric_limits::max()) / row_bytes) + { + throw std::runtime_error(path + ": NPY record dimensions exceed the structured dtype or file size limit"); + } + const std::uint16_t one = 1; + const char endian = *reinterpret_cast(&one) == 1 ? '<' : '>'; + std::string native_fields = fields; + std::replace(native_fields.begin(), native_fields.end(), '=', endian); + std::ostringstream dtype; + dtype.imbue(std::locale::classic()); + dtype << descriptor << "('schema_version','" << endian << "i4'),('ionic_step','" << endian << "i4')," + << native_fields << "], 'fortran_order': False, 'shape': (" << count << ",), }"; + std::string header = dtype.str(); + header.append((64 - (10 + header.size() + 1) % 64) % 64, ' '); + header.push_back('\n'); + if (header.size() > 65535) { throw std::runtime_error(path + ": NPY v1 header is too long"); } + const unsigned char length[] = {static_cast(header.size() & 255), + static_cast(header.size() >> 8)}; + NpyPrefix prefix; + const uint64_t bytes = count * row_bytes; + for (unsigned int i = 0; i < 8; ++i) { prefix[i] = static_cast((bytes >> (8 * i)) & 255); } + const std::int32_t attributes[] = {1, step}; + std::memcpy(prefix.data() + 8, attributes, sizeof(attributes)); + try + { + const std::streamoff previous = append ? prepare_append(path, identifying_field) : 0; + const std::string target = append ? path : path + ".tmp." + std::to_string(std::random_device{}()); + const auto mode = append ? std::ios::app : std::ios::trunc; + std::ofstream out(target, std::ios::binary | mode); + out.exceptions(std::ios::failbit | std::ios::badbit); + try + { + out.write(npy_magic, 8); + out.write(reinterpret_cast(length), sizeof(length)); + out.write(header.data(), header.size()); + const auto start = out.tellp(); + write_rows(out, prefix); + if (out.tellp() - start != static_cast(bytes)) + { + throw std::runtime_error("NPY payload does not match the declared dimensions"); + } + out.close(); + if (!append) + { +#ifdef _WIN32 + if (!MoveFileExA(target.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) + { + throw std::runtime_error("cannot replace NPY file (Windows error " + + std::to_string(GetLastError()) + ")"); + } +#else + if (std::rename(target.c_str(), path.c_str()) != 0) + { + throw std::runtime_error(std::strerror(errno)); + } +#endif + } + } + catch (...) + { + out.exceptions(std::ios::goodbit); + if (out.is_open()) { out.close(); } + if (append) { truncate_file(path, previous); } + else { std::remove(target.c_str()); } + throw; + } + } + catch (const std::exception& e) + { + throw std::runtime_error(path + ": " + e.what()); + } +} diff --git a/source/source_io/module_output/npy_record.h b/source/source_io/module_output/npy_record.h new file mode 100644 index 00000000000..4d7bb78fc03 --- /dev/null +++ b/source/source_io/module_output/npy_record.h @@ -0,0 +1,23 @@ +#ifndef ABACUS_NPY_RECORD_H +#define ABACUS_NPY_RECORD_H + +#include +#include +#include +#include +#include + +namespace ModuleIO +{ +// Every row starts with the frame's payload size (little endian), schema +// version and one-based ionic step. Remaining numeric fields use native order. +using NpyPrefix = std::array; +using NpyRows = std::function; + +// fields is a comma-separated Python dtype field list. '=' in its numeric +// descriptors is replaced by the writer's explicit byte order. +void write_npy_record(const std::string& path, bool append, int step, + const std::string& fields, const std::string& identifying_field, + std::uint64_t count, std::uint64_t row_bytes, const NpyRows& write_rows); +} +#endif diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 6aefa6349ec..4e5b8b6291b 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -540,7 +540,8 @@ struct Input_para std::string spillage_outdir = "./"; ///< output directory for spillage // ============== #Parameters (12.Postprocess) =========================== - std::string pdos_format = "text"; ///< LCAO projected DOS output format + std::string out_spectral_format = "text"; ///< output format for spectra enabled by out_dos + std::string pdos_format = "text"; ///< compatibility option for binary PDOS alone double dos_emin_ev = -15.0; double dos_emax_ev = 15.0; double dos_edelta_ev = 0.03; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 6e63aecd031..f0930177a24 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -378,7 +378,7 @@ Also controled by out_freq_ion and out_app_flag. item.description = R"(Whether to output the density of states (DOS) and projected density of states (PDOS). For more information, refer to the dos.md. * 0: no output * 1: output the density of states (DOS) and projected density of states (PDOS, LCAO only) - * The PDOS text filenames below apply to pdos_format text. Set pdos_format npy for NumPy output. + * The filenames below describe text output. Set out_spectral_format npy for NumPy DOS files. * With out_app_flag = 0: fixed-name files (`doss{s}.txt`, `pdoss{s}.txt`) are truncated and overwritten at every write. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# ionic step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index b021f9bca99..b08cb00f8fa 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -9,14 +9,27 @@ void ReadInput::item_postprocess() // NOTE: The order of add_item() calls below determines the parameter order // in the generated documentation (docs/advanced/input_files/input-main.md). // Please preserve this ordering when adding new parameters. + { + Input_Item item("out_spectral_format"); + item.domain.set_choices({"text", "npy"}); + item.annotation = "file format for total and projected DOS"; + item.category = "Density of states"; + item.type = "String"; + item.description = "Select text or NumPy NPY for the outputs enabled by out_dos. " + "This covers total DOS for PW and LCAO, and projected DOS for LCAO. " + "NPY stores named binary64 fields and one array per written ionic step."; + item.default_value = "text"; + read_sync_string(input.out_spectral_format); + this->add_item(item); + } { Input_Item item("pdos_format"); item.domain.set_choices({"text", "npy"}); item.annotation = "LCAO projected DOS file format"; item.category = "Density of states"; item.type = "String"; - item.description = "With out_dos 1, select text (pdoss*.txt) or npy (pdos*.npy) for LCAO projected DOS. " - "Total DOS is written as text."; + item.description = "With out_spectral_format text, pdos_format npy selects NumPy for LCAO projected " + "DOS alone. With out_spectral_format npy both total and projected DOS use NumPy."; item.default_value = "text"; read_sync_string(input.pdos_format); item.check_value = [](const Input_Item&, const Parameter& para) { diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 642393d54d6..416c6cc02f0 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -14,6 +14,7 @@ from typing import Dict, List, Sequence, Tuple, Union, Any from matplotlib.figure import Figure from matplotlib import axes +from abacus_plot.npy_record import check_record, read_npy_record from abacus_plot.utils import (energy_minus_efermi, get_angular_momentum_label, get_angular_momentum_name, remove_empty, handle_data, parse_projected_data) @@ -184,9 +185,10 @@ class TDOS(DOS): spinor-summed file, which is handled like nspin=1. """ - def __init__(self, tdosfile: Union[PathLike, Sequence[PathLike]] = None) -> None: + def __init__(self, tdosfile: Union[PathLike, Sequence[PathLike]] = None, record: int = 1) -> None: self.tdosfile = tdosfile - self._read() + check_record(record) + self._read(record) super().__init__(self.nspin) def _find_spin_files(self) -> List[str]: @@ -211,6 +213,10 @@ def _find_spin_files(self) -> List[str]: matches1 = sorted(glob.glob(str(path / "dos1.txt"))) if not matches1 and (path / "dos.txt").is_file(): matches1 = [str(path / "dos.txt")] # legacy PW nspin=1 name + if not matches1: + fixed = path / "doss1.npy" + numbered = [p for p in path.glob("doss1g*.npy") if p.stem[6:].isdigit()] + matches1 = [fixed] if fixed.is_file() else sorted(numbered, key=lambda p: int(p.stem[6:])) if not matches1: raise FileNotFoundError( f"No TDOS file found in directory '{path}'") @@ -238,7 +244,7 @@ def _find_spin_files(self) -> List[str]: # any other file (e.g. legacy TDOS.dat): parse as is return [str(path)] - def _read_one(self, fname: str) -> Dict[str, Any]: + def _read_one(self, fname: str, record: int = 1) -> Dict[str, Any]: """Read one TDOS file; the returned keys map 1:1 to the file columns. Returns a dict with ``energy`` of shape (npoints, 1) and dos/dos_int/ @@ -246,6 +252,22 @@ def _read_one(self, fname: str) -> Dict[str, Any]: channels stored in this file (None where the column is absent, e.g. the legacy 2/3-column formats carry no smeared DOS). """ + if Path(fname).suffix == ".npy": + fields = ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int") + rows = read_npy_record(fname, record, "TDOS", (*fields, "spin_channel")) + for key in fields: + if rows[key].ndim != 1 or rows[key].dtype.kind != "f" or rows[key].dtype.itemsize != 8: + raise ValueError(f"Invalid TDOS column {key} in {fname}") + spin = rows["spin_channel"][0] + if spin not in (1, 2) or not np.all(rows["spin_channel"] == spin): + raise ValueError(f"Invalid TDOS spin channel in {fname}") + data = {key: rows[key][:, None] for key in fields} + data["energy"] = data.pop("energy_eV") + data["spin_channel"] = spin + data["ionic_step"] = rows["ionic_step"][0] + return data + if record != 1: + raise ValueError("TDOS record selection requires a .npy file") rows = [] with open(fname) as f: for line in f: @@ -284,9 +306,14 @@ def _read_one(self, fname: str) -> Dict[str, Any]: raise ValueError(f"Unrecognized TDOS format: {ncols} columns") return out - def _read(self) -> None: + def _read(self, record=1) -> None: spin_files = self._find_spin_files() - parsed = [self._read_one(f) for f in spin_files] + parsed = [self._read_one(f, record) for f in spin_files] + if len(parsed) == 2 and all("spin_channel" in data for data in parsed): + parsed.sort(key=lambda data: data["spin_channel"]) + if ([data["spin_channel"] for data in parsed] != [1, 2] + or parsed[0]["ionic_step"] != parsed[1]["ionic_step"]): + raise ValueError("Mismatched TDOS spin channels or ionic steps") keys = ("dos", "dos_int", "dos_smear", "dos_smear_int") self.energy = parsed[0]["energy"] @@ -385,8 +412,7 @@ def _col_to_m(l: int, col: int) -> int: def __init__(self, pdosfile: PathLike = None, record: int = 1) -> None: self.pdosfile = pdosfile - if isinstance(record, bool) or not isinstance(record, (int, np.integer)) or record < 1: - raise ValueError("PDOS record must be a positive integer") + check_record(record) self._read(record) super().__init__(self.nspin) @@ -497,36 +523,13 @@ def _read_one(self, fname: str): return energy, orbitals def _read_npy(self, path, record): - """Map only the selected array, skipping earlier records by their NPY headers.""" - from numpy.lib import format - - end = path.stat().st_size - with path.open("rb") as stream: - for _ in range(record): - if stream.tell() == end: - raise ValueError(f"{path} has no PDOS record {record}") - if format.read_magic(stream) != (1, 0): - raise ValueError(f"Unsupported ABACUS PDOS NPY header in {path}") - shape, _, dtype = format.read_array_header_1_0(stream) - if len(shape) != 1 or shape[0] < 1 or dtype.hasobject or not dtype.names: - raise ValueError(f"Expected a nonempty array of PDOS orbitals in {path}") - offset = stream.tell() - size = shape[0] * dtype.itemsize - if size > end - offset: - raise ValueError(f"Incomplete PDOS record in {path}") - stream.seek(size, 1) - - rows = np.memmap(path, mode="r", offset=offset, dtype=dtype, shape=shape) - required = {"schema_version", "ionic_step", "record_bytes", "nspin", "atom_index", - "species", "l", "m", "energy_min_eV", "energy_step_eV", "pdos"} - if not required.issubset(dtype.names) or not np.all(rows["schema_version"] == 1): - raise ValueError(f"Unknown PDOS schema in {path}") + fields = {"nspin", "atom_index", "species", "l", "m", "energy_min_eV", "energy_step_eV", "pdos"} + rows = read_npy_record(path, record, "PDOS", fields) first = rows[0] values = rows["pdos"] if (first["nspin"] not in (1, 2, 4) or values.ndim != 3 or values.shape[2] == 0 or values.shape[1] != (2 if first["nspin"] == 2 else 1) - or values.dtype.kind != "f" or values.dtype.itemsize != 8 - or not np.all(rows["record_bytes"] == size)): + or values.dtype.kind != "f" or values.dtype.itemsize != 8): raise ValueError(f"Invalid PDOS dimensions in {path}") for field in ("nspin", "ionic_step", "energy_min_eV", "energy_step_eV"): if not np.all(rows[field] == first[field]): diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/main.py b/tools/02_postprocessing/plot-tools/abacus_plot/main.py index b3a310ed2b2..0fe886869bb 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/main.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/main.py @@ -71,7 +71,7 @@ def show_cmdline(cls, args): fig, ax = plt.subplots(figsize=figsize) prec = text.pop("prec", 0.01) smearing = text.pop("smearing", True) - tdos = TDOS(tdosfile) + tdos = TDOS(tdosfile, record=text.pop("record", 1)) tdos.plot(fig, ax, efermi=efermi, shift=shift, energy_range=energy_range, dos_range=dos_range, prec=prec, smearing=smearing, **text) dpi = text.pop("dpi", 400) @@ -80,7 +80,7 @@ def show_cmdline(cls, args): if args.dos and args.projected: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') - record = text.pop("pdos_record", 1) + record = text.pop("record", text.pop("pdos_record", 1)) efermi = text.pop("efermi", 0.0) energy_range = text.pop("energy_range", []) dos_range = text.pop("dos_range", []) @@ -113,7 +113,7 @@ def show_cmdline(cls, args): if args.dos and args.out: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') - record = text.pop("pdos_record", 1) + record = text.pop("record", text.pop("pdos_record", 1)) index = key2int(text.pop("index", None)) atom_index = key2int(text.pop("atom_index", None)) species = text.pop("species", None) diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py b/tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py new file mode 100644 index 00000000000..0a09e9c727f --- /dev/null +++ b/tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py @@ -0,0 +1,39 @@ +"""Read one ABACUS spectral array from a file of consecutive NPY records.""" +from pathlib import Path + +import numpy as np +from numpy.lib import format + + +def check_record(record): + if isinstance(record, bool) or not isinstance(record, (int, np.integer)) or record < 1: + raise ValueError("record must be a positive integer") + + +def read_npy_record(path, record, kind, fields): + check_record(record) + path = Path(path) + end = path.stat().st_size + with path.open("rb") as stream: + for _ in range(record): + if stream.tell() == end: + raise ValueError(f"{path} has no {kind} record {record}") + if format.read_magic(stream) != (1, 0): + raise ValueError(f"Unsupported ABACUS {kind} NPY header in {path}") + shape, _, dtype = format.read_array_header_1_0(stream) + if len(shape) != 1 or shape[0] < 1 or dtype.hasobject or not dtype.names: + raise ValueError(f"Expected a nonempty array of structured {kind} data in {path}") + required = {"schema_version", "record_bytes", "ionic_step", *fields} + if not required.issubset(dtype.names): + raise ValueError(f"Missing {kind} fields in {path}") + offset = stream.tell() + size = shape[0] * dtype.itemsize + if size > end - offset: + raise ValueError(f"Incomplete {kind} record in {path}") + stream.seek(size, 1) + rows = np.memmap(stream, mode="r", offset=offset, dtype=dtype, shape=shape) + step = rows["ionic_step"] + if (not np.all(rows["schema_version"] == 1) or not np.all(rows["record_bytes"] == size) + or step[0] < 1 or not np.all(step == step[0])): + raise ValueError(f"Invalid {kind} record metadata in {path}") + return rows diff --git a/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py b/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py index d78529f5778..29a6922fa37 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py +++ b/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py @@ -79,5 +79,5 @@ def test_incomplete_record_and_foreign_array(self): with self.assertRaisesRegex(ValueError, "Incomplete PDOS"): PDOS(self.path) np.save(self.path, np.array([1.0])) - with self.assertRaisesRegex(ValueError, "PDOS orbitals"): + with self.assertRaisesRegex(ValueError, "structured PDOS"): PDOS(self.path) diff --git a/tools/02_postprocessing/plot-tools/tests/test_tdos_npy.py b/tools/02_postprocessing/plot-tools/tests/test_tdos_npy.py new file mode 100644 index 00000000000..9ae45871794 --- /dev/null +++ b/tools/02_postprocessing/plot-tools/tests/test_tdos_npy.py @@ -0,0 +1,47 @@ +import tempfile +import unittest +from pathlib import Path + +import numpy as np + +from abacus_plot.dos import TDOS + + +def frame(n, fields, step): + rows = np.zeros(n, dtype=[("record_bytes", " Date: Thu, 19 Nov 2026 11:42:00 +0800 Subject: [PATCH 03/15] refactor: name the DOS format selector out_dos_format --- docs/advanced/elec_properties/dos.md | 8 ++++---- source/source_io/module_ctrl/ctrl_output_pw.cpp | 2 +- source/source_io/module_ctrl/ctrl_scf_lcao.cpp | 2 +- source/source_io/module_dos/write_dos_lcao.cpp | 10 +++++----- source/source_io/module_dos/write_dos_lcao.h | 2 +- source/source_io/module_dos/write_dos_pw.cpp | 4 ++-- source/source_io/module_dos/write_dos_pw.h | 2 +- source/source_io/module_parameter/input_parameter.h | 2 +- source/source_io/module_parameter/read_inp_out.cpp | 2 +- .../source_io/module_parameter/read_inp_postproc.cpp | 8 ++++---- 10 files changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 8ed3839e378..bad166ed243 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -100,16 +100,16 @@ For nspin=2, two files are written (pdoss1* and pdoss2*), one per spin channel. ### NumPy output -Set `out_spectral_format npy` to write the spectra selected by `out_dos` as NumPy arrays. This includes total DOS for PW and LCAO and projected DOS for LCAO. The default format is `text`. The NPY writer is built into ABACUS. +Set `out_dos_format npy` to write the total DOS (PW and LCAO) and projected DOS (LCAO) selected by `out_dos` as NumPy arrays. The default format is `text`. The NPY writer is built into ABACUS. ```text -out_dos 1 -out_spectral_format npy +out_dos 1 +out_dos_format npy ``` Each file contains a standard NumPy 1.0 structured array with named fields. Total DOS uses one row per energy point in `doss1.npy`, with a separate `doss2.npy` for collinear spin. The five binary64 fields are `energy_eV`, `dos`, `dos_int`, `dos_smear` and `dos_smear_int`, in the same units as the text columns. `spin_channel` gives the one-based channel. For example, `np.load("doss1.npy")["dos_smear"]` returns the smeared DOS in states/eV per cell. -LCAO projected DOS uses one row per atom and `(l,m)` channel in `pdos.npy`. Contributions from all zeta components are summed. Across the array, the binary64 `pdos` field has axes `(orbital, spin channel, energy point)` and units of 1/eV. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. With the default spectral format, `pdos_format npy` selects binary PDOS alone. +LCAO projected DOS uses one row per atom and `(l,m)` channel in `pdos.npy`. Contributions from all zeta components are summed. Across the array, the binary64 `pdos` field has axes `(orbital, spin channel, energy point)` and units of 1/eV. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. With `out_dos_format text`, `pdos_format npy` selects binary PDOS alone. ```python import numpy as np diff --git a/source/source_io/module_ctrl/ctrl_output_pw.cpp b/source/source_io/module_ctrl/ctrl_output_pw.cpp index 78b1bef2c9c..72eab2802ba 100644 --- a/source/source_io/module_ctrl/ctrl_output_pw.cpp +++ b/source/source_io/module_ctrl/ctrl_output_pw.cpp @@ -189,7 +189,7 @@ void ModuleIO::ctrl_scf_pw(const int istep, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, - inp.out_spectral_format, + inp.out_dos_format, inp.nspin, inp.out_dos, PARAM.globalv.dos_setemax, diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index 458ec2baece..041f786a9f5 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -168,7 +168,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, - inp.out_spectral_format, + inp.out_dos_format, inp.pdos_format, out_app_flag, istep, diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index caf90becc17..0b4ab890ef3 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -26,7 +26,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& spectral_format, + const std::string& dos_format, const std::string& pdos_format, const int out_app_flag, const int istep, @@ -77,7 +77,7 @@ void write_dos_lcao( ss << "g" << istep+1; } - ss << (spectral_format == "npy" ? ".npy" : ".txt"); + ss << (dos_format == "npy" ? ".npy" : ".txt"); ofs_running << " DOS file: " << ss.str() << '\n'; ModuleIO::cal_dos(is, @@ -102,7 +102,7 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) const auto pdos = cal_pdos(psi, p_ham, pv, kv, nspin, nbands, ekb, emax, emin, dos_edelta_ev, bcoeff, nlocal); const bool root = GlobalV::MY_RANK == 0; - if (spectral_format == "npy" || pdos_format == "npy") + if (dos_format == "npy" || pdos_format == "npy") { std::string error; if (root) @@ -154,7 +154,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& spectral_format, + const std::string& dos_format, const std::string& pdos_format, const int out_app_flag, const int istep, @@ -183,7 +183,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& spectral_format, + const std::string& dos_format, const std::string& pdos_format, const int out_app_flag, const int istep, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 0e7c238eaac..082bf1da8bf 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -28,7 +28,7 @@ namespace ModuleIO const double& dos_edelta_ev, // Delta energy const double& dos_scale, const double& bcoeff, - const std::string& spectral_format, + const std::string& dos_format, const std::string& pdos_format, const int out_app_flag, const int istep, diff --git a/source/source_io/module_dos/write_dos_pw.cpp b/source/source_io/module_dos/write_dos_pw.cpp index 9a0c505be74..36398e9561e 100644 --- a/source/source_io/module_dos/write_dos_pw.cpp +++ b/source/source_io/module_dos/write_dos_pw.cpp @@ -13,7 +13,7 @@ void ModuleIO::write_dos_pw( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& spectral_format, + const std::string& dos_format, const int nspin, const int out_dos, const bool dos_setemax, @@ -62,7 +62,7 @@ void ModuleIO::write_dos_pw( ss << "g" << istep_in+1; } - ss << (spectral_format == "npy" ? ".npy" : ".txt"); + ss << (dos_format == "npy" ? ".npy" : ".txt"); ModuleBase::GlobalFunc::OUT(ofs_running, "DOS file", ss.str()); diff --git a/source/source_io/module_dos/write_dos_pw.h b/source/source_io/module_dos/write_dos_pw.h index e539f2a792e..86338172a41 100644 --- a/source/source_io/module_dos/write_dos_pw.h +++ b/source/source_io/module_dos/write_dos_pw.h @@ -20,7 +20,7 @@ namespace ModuleIO const double &dos_edelta_ev, const double &dos_scale, const double &bcoeff, - const std::string& spectral_format, + const std::string& dos_format, const int nspin, const int out_dos, const bool dos_setemax, diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 4e5b8b6291b..9ead8d0b525 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -540,7 +540,7 @@ struct Input_para std::string spillage_outdir = "./"; ///< output directory for spillage // ============== #Parameters (12.Postprocess) =========================== - std::string out_spectral_format = "text"; ///< output format for spectra enabled by out_dos + std::string out_dos_format = "text"; ///< total and projected DOS file format std::string pdos_format = "text"; ///< compatibility option for binary PDOS alone double dos_emin_ev = -15.0; double dos_emax_ev = 15.0; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index f0930177a24..1308d0ff2f3 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -378,7 +378,7 @@ Also controled by out_freq_ion and out_app_flag. item.description = R"(Whether to output the density of states (DOS) and projected density of states (PDOS). For more information, refer to the dos.md. * 0: no output * 1: output the density of states (DOS) and projected density of states (PDOS, LCAO only) - * The filenames below describe text output. Set out_spectral_format npy for NumPy DOS files. + * The filenames below describe text output. Set out_dos_format npy for NumPy DOS files. * With out_app_flag = 0: fixed-name files (`doss{s}.txt`, `pdoss{s}.txt`) are truncated and overwritten at every write. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# ionic step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index b08cb00f8fa..63c3da2a5ce 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -10,7 +10,7 @@ void ReadInput::item_postprocess() // in the generated documentation (docs/advanced/input_files/input-main.md). // Please preserve this ordering when adding new parameters. { - Input_Item item("out_spectral_format"); + Input_Item item("out_dos_format"); item.domain.set_choices({"text", "npy"}); item.annotation = "file format for total and projected DOS"; item.category = "Density of states"; @@ -19,7 +19,7 @@ void ReadInput::item_postprocess() "This covers total DOS for PW and LCAO, and projected DOS for LCAO. " "NPY stores named binary64 fields and one array per written ionic step."; item.default_value = "text"; - read_sync_string(input.out_spectral_format); + read_sync_string(input.out_dos_format); this->add_item(item); } { @@ -28,8 +28,8 @@ void ReadInput::item_postprocess() item.annotation = "LCAO projected DOS file format"; item.category = "Density of states"; item.type = "String"; - item.description = "With out_spectral_format text, pdos_format npy selects NumPy for LCAO projected " - "DOS alone. With out_spectral_format npy both total and projected DOS use NumPy."; + item.description = "With out_dos_format text, pdos_format npy selects NumPy for LCAO projected " + "DOS alone. With out_dos_format npy both total and projected DOS use NumPy."; item.default_value = "text"; read_sync_string(input.pdos_format); item.check_value = [](const Input_Item&, const Parameter& para) { From 9db8557213bf7e780c8a899c4bb7712da15a589f Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:08:15 +0800 Subject: [PATCH 04/15] refactor: keep NumPy DOS output separate from the text writer --- docs/advanced/elec_properties/dos.md | 4 +- source/Makefile.Objects | 1 - source/source_io/CMakeLists.txt | 1 - .../source_io/module_ctrl/ctrl_scf_lcao.cpp | 1 - .../source_io/module_dos/cal_pdos_gamma.cpp | 18 ++-- source/source_io/module_dos/cal_pdos_gamma.h | 14 ++- .../source_io/module_dos/cal_pdos_multik.cpp | 18 ++-- source/source_io/module_dos/cal_pdos_multik.h | 14 ++- source/source_io/module_dos/pdos_orbitals.cpp | 49 ---------- source/source_io/module_dos/pdos_orbitals.h | 25 ----- .../module_dos/unittests/CMakeLists.txt | 2 - .../unittests/test_write_pdos_npy.cpp | 4 +- .../source_io/module_dos/write_dos_lcao.cpp | 94 +++++++++++-------- source/source_io/module_dos/write_dos_lcao.h | 5 +- .../source_io/module_dos/write_pdos_npy.cpp | 42 +++++---- .../source_io/module_dos/write_pdos_text.cpp | 63 ++++++++++++- source/source_io/module_dos/write_pdos_text.h | 4 +- .../module_parameter/input_parameter.h | 1 - .../module_parameter/read_inp_out.cpp | 1 - .../module_parameter/read_inp_postproc.cpp | 18 ---- .../plot-tools/abacus_plot/dos.py | 38 ++++---- .../plot-tools/abacus_plot/main.py | 4 +- 22 files changed, 212 insertions(+), 209 deletions(-) delete mode 100644 source/source_io/module_dos/pdos_orbitals.cpp delete mode 100644 source/source_io/module_dos/pdos_orbitals.h diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index bad166ed243..b296facbbb5 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -109,7 +109,7 @@ out_dos_format npy Each file contains a standard NumPy 1.0 structured array with named fields. Total DOS uses one row per energy point in `doss1.npy`, with a separate `doss2.npy` for collinear spin. The five binary64 fields are `energy_eV`, `dos`, `dos_int`, `dos_smear` and `dos_smear_int`, in the same units as the text columns. `spin_channel` gives the one-based channel. For example, `np.load("doss1.npy")["dos_smear"]` returns the smeared DOS in states/eV per cell. -LCAO projected DOS uses one row per atom and `(l,m)` channel in `pdos.npy`. Contributions from all zeta components are summed. Across the array, the binary64 `pdos` field has axes `(orbital, spin channel, energy point)` and units of 1/eV. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. With `out_dos_format text`, `pdos_format npy` selects binary PDOS alone. +LCAO projected DOS uses one row per atom and `(l,m)` channel in `pdos.npy`. Contributions from all zeta components are summed. Across the array, the binary64 `pdos` field has axes `(orbital, spin channel, energy point)` and units of 1/eV. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. ```python import numpy as np @@ -124,7 +124,7 @@ Each row includes the one-based `atom_index`, UTF-8 byte string `species`, `l`, For DOS, mode `out_app_flag 0` replaces the fixed-name file. Mode 1 appends one complete NumPy array per write, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps such as `DOS/doss1g2.npy` and `DOS/pdosg2.npy`. -For `abacus-plot`, use `tdosfile` for total DOS and `pdosfile` for projected DOS. The common JSON option `record` selects a one-based NPY record and defaults to 1. PDOS also accepts the spelling `pdos_record`. +For `abacus-plot`, use `tdosfile` for total DOS and `pdosfile` for projected DOS. The common JSON option `record` selects a one-based NPY record and defaults to 1. ```json {"pdosfile": "OUT.ABACUS/pdos.npy", "record": 1, "species": ["Si"]} diff --git a/source/Makefile.Objects b/source/Makefile.Objects index d76a4681485..96b44b97d17 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -753,7 +753,6 @@ OBJS_IO=module_parameter/input_conv.o\ module_dos/cal_pdos_gamma.o\ module_dos/cal_pdos_multik.o\ module_dos/write_pdos_text.o\ - module_dos/pdos_orbitals.o\ module_dos/write_pdos_npy.o\ module_dos/cal_ldos.o\ module_bessel/numerical_descriptor.o\ diff --git a/source/source_io/CMakeLists.txt b/source/source_io/CMakeLists.txt index 55b3d2d0952..1b7156ee9b8 100644 --- a/source/source_io/CMakeLists.txt +++ b/source/source_io/CMakeLists.txt @@ -76,7 +76,6 @@ if(ENABLE_LCAO) module_dos/cal_pdos_gamma.cpp module_dos/cal_pdos_multik.cpp module_dos/write_pdos_text.cpp - module_dos/pdos_orbitals.cpp module_dos/write_pdos_npy.cpp module_output/write_orb_info.cpp module_energy/write_proj_band_lcao.cpp diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index 041f786a9f5..b257e7c8ea8 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -169,7 +169,6 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_scale, inp.dos_sigma, inp.out_dos_format, - inp.pdos_format, out_app_flag, istep, inp.nspin, diff --git a/source/source_io/module_dos/cal_pdos_gamma.cpp b/source/source_io/module_dos/cal_pdos_gamma.cpp index e1b643f1e2f..2a50189cc3f 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.cpp +++ b/source/source_io/module_dos/cal_pdos_gamma.cpp @@ -1,4 +1,5 @@ #include "cal_pdos_gamma.h" +#include "write_dos_lcao.h" #include "source_base/parallel_reduce.h" #include "source_base/module_external/blas_connector.h" #include "source_base/module_external/scalapack_connector.h" @@ -6,24 +7,29 @@ #include "source_lcao/hamilt_lcao.h" -std::vector ModuleIO::cal_pdos( +void ModuleIO::cal_pdos( const psi::Psi* psi, hamilt::Hamilt* p_ham, const Parallel_Orbitals& pv, + const UnitCell& ucell, const K_Vectors& kv, - const int nspin, + const int nspin0, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int nlocal) + const int istep, + const int out_app_flag, + const int nlocal, + const int nspin, + const std::string& global_out_dir, + bool npy) { ModuleBase::TITLE("ModuleIO", "cal_pdos_gamma"); - const int nspin0 = nspin == 2 ? 2 : 1; - assert(nspin == 1 || nspin == 2 || nspin == 4); + assert(nspin0>0); assert(emax>=emin); assert(dos_edelta_ev>0.0); @@ -139,5 +145,5 @@ std::vector ModuleIO::cal_pdos( #endif } // is - return pdos; + write_pdos(ucell, pdos, nspin, nlocal, emin, dos_edelta_ev, global_out_dir, istep, out_app_flag, npy); } diff --git a/source/source_io/module_dos/cal_pdos_gamma.h b/source/source_io/module_dos/cal_pdos_gamma.h index 6457afa7c2c..0583c7dedd8 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.h +++ b/source/source_io/module_dos/cal_pdos_gamma.h @@ -6,24 +6,30 @@ #include "source_psi/psi.h" // use psi::Psi #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals -#include +#include namespace ModuleIO { - std::vector cal_pdos( + void cal_pdos( const psi::Psi* psi, hamilt::Hamilt* p_ham, const Parallel_Orbitals& pv, + const UnitCell& ucell, const K_Vectors& kv, - const int nspin, + const int nspin0, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int nlocal); + const int istep, + const int out_app_flag, + const int nlocal, + const int nspin, + const std::string& global_out_dir, + bool npy); } diff --git a/source/source_io/module_dos/cal_pdos_multik.cpp b/source/source_io/module_dos/cal_pdos_multik.cpp index a582697199d..e7a1274f798 100644 --- a/source/source_io/module_dos/cal_pdos_multik.cpp +++ b/source/source_io/module_dos/cal_pdos_multik.cpp @@ -1,28 +1,34 @@ #include "cal_pdos_multik.h" +#include "write_dos_lcao.h" #include "source_base/parallel_reduce.h" #include "source_base/module_external/blas_connector.h" #include "source_base/module_external/scalapack_connector.h" #include "source_base/global_function.h" #include "source_lcao/hamilt_lcao.h" -std::vector ModuleIO::cal_pdos( +void ModuleIO::cal_pdos( const psi::Psi>* psi, hamilt::Hamilt>* p_ham, const Parallel_Orbitals& pv, + const UnitCell& ucell, const K_Vectors& kv, - const int nspin, + const int nspin0, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int nlocal) + const int istep, + const int out_app_flag, + const int nlocal, + const int nspin, + const std::string& global_out_dir, + bool npy) { ModuleBase::TITLE("ModuleIO", "cal_pdos_multik"); - const int nspin0 = nspin == 2 ? 2 : 1; - assert(nspin == 1 || nspin == 2 || nspin == 4); + assert(nspin0>0); assert(emax>=emin); assert(dos_edelta_ev>0.0); @@ -179,5 +185,5 @@ std::vector ModuleIO::cal_pdos( #endif } // is - return pdos; + write_pdos(ucell, pdos, nspin, nlocal, emin, dos_edelta_ev, global_out_dir, istep, out_app_flag, npy); } diff --git a/source/source_io/module_dos/cal_pdos_multik.h b/source/source_io/module_dos/cal_pdos_multik.h index e327d0d73cd..63f8023983d 100644 --- a/source/source_io/module_dos/cal_pdos_multik.h +++ b/source/source_io/module_dos/cal_pdos_multik.h @@ -6,25 +6,31 @@ #include "source_psi/psi.h" // use psi::Psi #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals -#include +#include namespace ModuleIO { // pdos for multi-k point - std::vector cal_pdos( + void cal_pdos( const psi::Psi>* psi, hamilt::Hamilt>* p_ham, const Parallel_Orbitals& pv, + const UnitCell& ucell, const K_Vectors& kv, - const int nspin, + const int nspin0, const int nbands, const ModuleBase::matrix& ekb, const double& emax, const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int nlocal); + const int istep, + const int out_app_flag, + const int nlocal, + const int nspin, + const std::string& global_out_dir, + bool npy); } diff --git a/source/source_io/module_dos/pdos_orbitals.cpp b/source/source_io/module_dos/pdos_orbitals.cpp deleted file mode 100644 index 86867afbbb5..00000000000 --- a/source/source_io/module_dos/pdos_orbitals.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "pdos_orbitals.h" -#include "source_base/matrix.h" -#include "source_cell/atom_spec.h" - -#include -#include - -std::vector ModuleIO::pdos_orbitals(const Atom& atom) -{ - std::vector orbitals; - for (int l = 0; l <= atom.nwl; ++l) - { - for (int im = 0; im <= 2 * l; ++im) - { - const int m = im % 2 == 0 ? -im / 2 : (im + 1) / 2; - PdosOrbital orbital{l, m, {}}; - for (int j = 0; j < atom.nw; ++j) - { - if (atom.iw2l[j] == l && atom.iw2m[j] == im) - { - orbital.zeta_orbitals.push_back(j); - } - } - if (!orbital.zeta_orbitals.empty()) - { - orbitals.push_back(std::move(orbital)); - } - } - } - return orbitals; -} - -double ModuleIO::PdosOrbital::value(const ModuleBase::matrix& pdos, int first, int energy, bool spinor) const -{ - double sum = 0.0; - for (int j : zeta_orbitals) - { - if (spinor) - { - const int row = first + 2 * j; - sum += pdos(row, energy) + pdos(row + 1, energy); - } - else - { - sum += pdos(first + j, energy); - } - } - return std::abs(sum) < 1.0e-6 ? 0.0 : sum; -} diff --git a/source/source_io/module_dos/pdos_orbitals.h b/source/source_io/module_dos/pdos_orbitals.h deleted file mode 100644 index 00f383fae50..00000000000 --- a/source/source_io/module_dos/pdos_orbitals.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef PDOS_ORBITALS_H -#define PDOS_ORBITALS_H - -#include - -class Atom; -namespace ModuleBase -{ -class matrix; -} - -namespace ModuleIO -{ -struct PdosOrbital -{ - int l; - int m; // physical magnetic quantum number - std::vector zeta_orbitals; - - double value(const ModuleBase::matrix& pdos, int first, int energy, bool spinor) const; -}; - -std::vector pdos_orbitals(const Atom& atom); -} -#endif diff --git a/source/source_io/module_dos/unittests/CMakeLists.txt b/source/source_io/module_dos/unittests/CMakeLists.txt index 49ce370083c..e9e036d32c1 100644 --- a/source/source_io/module_dos/unittests/CMakeLists.txt +++ b/source/source_io/module_dos/unittests/CMakeLists.txt @@ -31,7 +31,6 @@ if(ENABLE_MPI) LIBS parameter base device SOURCES test_write_pdos_text.cpp ../write_pdos_text.cpp - ../pdos_orbitals.cpp ../../../source_cell/atom_spec.cpp ../../../source_cell/atom_pseudo.cpp ../../../source_cell/pseudo.cpp @@ -47,7 +46,6 @@ if(ENABLE_LCAO) SOURCES test_write_pdos_npy.cpp ../write_pdos_npy.cpp ../../module_output/npy_record.cpp - ../pdos_orbitals.cpp ../../../source_cell/atom_spec.cpp ../../../source_cell/atom_pseudo.cpp ../../../source_cell/pseudo.cpp diff --git a/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp b/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp index 47fbd176199..5105fd54ec4 100644 --- a/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp +++ b/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp @@ -28,8 +28,8 @@ class WritePdosNpy : public testing::Test cell.atoms[0].label = "Si"; cell.atoms[0].nw = 2; cell.atoms[0].nwl = 0; - cell.atoms[0].iw2l = {0, 0}; - cell.atoms[0].iw2m = {0, 0}; + cell.atoms[0].l_nchi = {2}; + cell.atoms[0].set_index(); cell.set_iat2iwt_for_test({0}, 1); pdos.front().create(2, 2); pdos.front()(0, 0) = 4.25; diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 0b4ab890ef3..5bc0165a35e 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -2,16 +2,46 @@ #include "cal_dos.h" #include "cal_pdos_gamma.h" #include "cal_pdos_multik.h" +#include "write_pdos_npy.h" #include "write_pdos_text.h" #include "source_base/global_variable.h" -#include "source_io/module_output/write_orb_info.h" -#include "write_pdos_npy.h" #include "source_base/parallel_common.h" #include "source_base/tool_quit.h" +#include "source_io/module_output/write_orb_info.h" namespace ModuleIO { +void write_pdos(const UnitCell& ucell, const std::vector& pdos, int nspin, int nlocal, + double emin, double de, const std::string& out_dir, int istep, int out_app_flag, bool npy) +{ + std::string error; + if (GlobalV::MY_RANK == 0) + { + if (npy) + { + try + { + const auto path = write_pdos_npy(ucell, pdos, nspin, emin, de, out_dir, istep, out_app_flag); + GlobalV::ofs_running << " Wrote projected DOS to " << path << '\n'; + } + catch (const std::exception& e) { error = e.what(); } + } + else + { + write_pdos_text(ucell, pdos.data(), nspin, nlocal, pdos.front().nc, emin, de, out_dir, istep, out_app_flag); + } + if (error.empty()) { write_orb_info(&ucell); } + } + if (npy) + { +#ifdef __MPI + Parallel_Common::bcast_string(error); +#endif + if (!error.empty()) { ModuleBase::WARNING_QUIT("write_pdos", error); } + } +} + template void write_dos_lcao( const psi::Psi* psi, @@ -27,7 +57,6 @@ void write_dos_lcao( const double& dos_scale, const double& bcoeff, const std::string& dos_format, - const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, @@ -43,6 +72,7 @@ void write_dos_lcao( { ModuleBase::TITLE("ModuleIO", "write_dos_lcao"); + const bool npy = dos_format == "npy"; const int nspin0 = (nspin == 2) ? 2 : 1; double emax = 0.0; @@ -77,8 +107,8 @@ void write_dos_lcao( ss << "g" << istep+1; } - ss << (dos_format == "npy" ? ".npy" : ".txt"); - ofs_running << " DOS file: " << ss.str() << '\n'; + ss << (npy ? ".npy" : ".txt"); + if (npy) { ofs_running << " DOS file: " << ss.str() << '\n'; } ModuleIO::cal_dos(is, ss.str(), @@ -100,40 +130,24 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) - const auto pdos = cal_pdos(psi, p_ham, pv, kv, nspin, nbands, ekb, emax, emin, dos_edelta_ev, bcoeff, nlocal); - const bool root = GlobalV::MY_RANK == 0; - if (dos_format == "npy" || pdos_format == "npy") - { - std::string error; - if (root) - { - try - { - const std::string path = write_pdos_npy(ucell, pdos, nspin, emin, dos_edelta_ev, - global_out_dir, istep, out_app_flag); - ofs_running << " Wrote projected DOS to " << path << '\n'; - } - catch (const std::exception& e) - { - error = e.what(); - } - } - Parallel_Common::bcast_string(error); - if (!error.empty()) - { - ModuleBase::WARNING_QUIT("write_dos_lcao", error); - } - } - else if (root) - { - const int npoints = pdos.front().nc; - write_pdos_text(ucell, pdos.data(), nspin, nlocal, npoints, emin, dos_edelta_ev, - global_out_dir, istep, out_app_flag); - } - if (root) - { - write_orb_info(&ucell); - } + cal_pdos(psi, + p_ham, + pv, + ucell, + kv, + nspin0, + nbands, + ekb, + emax, + emin, + dos_edelta_ev, + bcoeff, + istep, + out_app_flag, + nlocal, + nspin, + global_out_dir, + npy); ofs_running << " #DOS CALCULATION ENDS# " << std::endl; @@ -155,7 +169,6 @@ template void write_dos_lcao( const double& dos_scale, const double& bcoeff, const std::string& dos_format, - const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, @@ -184,7 +197,6 @@ template void write_dos_lcao( const double& dos_scale, const double& bcoeff, const std::string& dos_format, - const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 082bf1da8bf..2ca2c1f4009 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -7,10 +7,14 @@ #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals #include "source_estate/fp_energy.h" // use elecstate::Efermi +#include namespace ModuleIO { + void write_pdos(const UnitCell& ucell, const std::vector& pdos, int nspin, int nlocal, + double emin, double de, const std::string& out_dir, int istep, int out_app_flag, bool npy); + /// @brief calculate density of states(DOS), /// partial density of states(PDOS), /// and mulliken charge for LCAO base @@ -29,7 +33,6 @@ namespace ModuleIO const double& dos_scale, const double& bcoeff, const std::string& dos_format, - const std::string& pdos_format, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_pdos_npy.cpp b/source/source_io/module_dos/write_pdos_npy.cpp index 746d6606fcb..0a80371975d 100644 --- a/source/source_io/module_dos/write_pdos_npy.cpp +++ b/source/source_io/module_dos/write_pdos_npy.cpp @@ -1,10 +1,10 @@ #include "write_pdos_npy.h" -#include "pdos_orbitals.h" #include "source_base/matrix.h" #include "source_cell/unitcell.h" #include "source_io/module_output/npy_record.h" #include +#include #include #include #include @@ -18,19 +18,15 @@ std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector> by_type(cell.ntype); size_t width = 1; - for (int it = 0; it < cell.ntype; ++it) - { - by_type[it] = ModuleIO::pdos_orbitals(cell.atoms[it]); - width = std::max(width, cell.atoms[it].label.size()); - } - width = (width + 7) / 8 * 8; // keep the float64 spectrum aligned in every row size_t norb = 0; for (int iat = 0; iat < cell.nat; ++iat) { - norb += by_type[cell.iat2it[iat]].size(); + const Atom& atom = cell.atoms[cell.iat2it[iat]]; + width = std::max(width, atom.label.size()); + norb += std::count(atom.iw2n.begin(), atom.iw2n.end(), 0); } + width = (width + 7) / 8 * 8; // align the binary64 spectrum in every row std::ostringstream fields; fields.imbue(std::locale::classic()); @@ -40,28 +36,42 @@ std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector(ne) * pdos.size(); const bool append = out_app_flag == 1 && istep > 0; const double grid[] = {emin, de}; - const bool spinor = nspin == 4; + const int npol = nspin == 4 ? 2 : 1; const std::string descr = fields.str(); write_npy_record(path, append, step, descr, "pdos", norb, row_bytes, [&](std::ostream& out, const NpyPrefix& prefix) { std::vector spectrum(ne); for (int iat = 0; iat < cell.nat; ++iat) { - const int it = cell.iat2it[iat]; - std::string label = cell.atoms[it].label; + const Atom& atom = cell.atoms[cell.iat2it[iat]]; + std::string label = atom.label; label.resize(width, '\0'); const int first = cell.get_iat2iwt()[iat]; - for (const auto& orbital : by_type[it]) + // Atom::set_index orders orbitals by l, then zeta, then real-harmonic column. + for (int iw = 0; iw < atom.nw; ++iw) { - const int32_t attributes[] = {nspin, iat + 1, orbital.l, orbital.m}; + if (atom.iw2n[iw] != 0) { continue; } + const int l = atom.iw2l[iw]; + const int col = atom.iw2m[iw]; + const int m = col % 2 == 0 ? -col / 2 : (col + 1) / 2; + const int32_t attributes[] = {nspin, iat + 1, l, m}; out.write(prefix.data(), prefix.size()); out.write(reinterpret_cast(attributes), sizeof(attributes)); out.write(reinterpret_cast(grid), sizeof(grid)); out.write(label.data(), width); for (const auto& spin : pdos) { - for (int n = 0; n < ne; ++n) + std::fill(spectrum.begin(), spectrum.end(), 0.0); + for (int zeta = 0; zeta < atom.l_nchi[l]; ++zeta) + { + const int row = first + npol * (iw + zeta * (2 * l + 1)); + for (int n = 0; n < ne; ++n) + { + spectrum[n] += npol == 2 ? spin(row, n) + spin(row + 1, n) : spin(row, n); + } + } + for (double& value : spectrum) { - spectrum[n] = orbital.value(spin, first, n, spinor); + if (std::abs(value) < 1e-6) { value = 0.0; } } out.write(reinterpret_cast(spectrum.data()), spectrum.size() * sizeof(double)); } diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index a28f27c4e8d..c3ded7e75c6 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -1,11 +1,12 @@ #include "write_pdos_text.h" -#include "pdos_orbitals.h" #include "source_base/global_variable.h" +#include #include #include #include +#include void ModuleIO::write_pdos_text( const UnitCell& ucell, @@ -62,8 +63,31 @@ void ModuleIO::write_pdos_text( const int it = ucell.iat2it[iat]; const Atom* atom = &ucell.atoms[it]; const int s0 = ucell.itiaiw2iwt(it, ia, 0); - const auto orbitals = pdos_orbitals(*atom); - const bool spinor = nspin == 4; + const int max_l = atom->nwl; + + // collect all (l, m) for this atom, ordered s,p,d,f + // iw2m stores m as 0..2l (non-negative), so loop m = 0..2*L + struct OrbInfo + { + int l; + int m; // 0..2l + }; + std::vector orb_list; + + for (int L = 0; L <= max_l; ++L) + { + for (int m = 0; m <= 2 * L; ++m) + { + for (int j = 0; j < atom->nw; ++j) + { + if (atom->iw2l[j] == L && atom->iw2m[j] == m) + { + orb_list.push_back({L, m}); + break; + } + } + } + } for (int n = 0; n < npoints; ++n) { @@ -73,9 +97,38 @@ void ModuleIO::write_pdos_text( << " " << std::setw(3) << iat + 1 << " " << std::setw(4) << ucell.atoms[it].label; - for (const auto& orbital : orbitals) + for (size_t io = 0; io < orb_list.size(); ++io) { - const double pdos_val = orbital.value(pdos[is], s0, n, spinor); + const int L = orb_list[io].l; + const int m = orb_list[io].m; + double pdos_val = 0.0; + + // sum over all zeta for this (l, m) + for (int j = 0; j < atom->nw; ++j) + { + if (atom->iw2l[j] != L || atom->iw2m[j] != m) + { + continue; + } + const int w = ucell.itiaiw2iwt(it, ia, j); + + if (nspin == 4) + { + const int w0 = w - s0; + pdos_val += pdos[0](s0 + 2 * w0, n) + pdos[0](s0 + 2 * w0 + 1, n); + } + else + { + pdos_val += pdos[is](w, n); + } + } + + // zero out negligible values + if (std::abs(pdos_val) < 1e-6) + { + pdos_val = 0.0; + } + ofs << " " << std::setw(8) << std::fixed << std::setprecision(6) << pdos_val; } ofs << std::endl; diff --git a/source/source_io/module_dos/write_pdos_text.h b/source/source_io/module_dos/write_pdos_text.h index 4d603aae708..434c6f7ebe9 100644 --- a/source/source_io/module_dos/write_pdos_text.h +++ b/source/source_io/module_dos/write_pdos_text.h @@ -8,8 +8,8 @@ namespace ModuleIO { /// Write PDOS in plain text long-table format. -/// Mode 2 adds g{geom} to pdoss{spin}.txt for numbered ionic steps. -/// Rows contain energy (eV), atom, species and one PDOS value per (l,m), summed over zeta. +/// File name: pdoss{spin}g{geom}.txt (g{geom} omitted when out_app_flag == 1) +/// Columns: energy(eV) atom species l z m pdos(1/eV) /// For nspin=4, the two spinor components are summed. void write_pdos_text( const UnitCell& ucell, diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 9ead8d0b525..4fa5a41aae6 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -541,7 +541,6 @@ struct Input_para // ============== #Parameters (12.Postprocess) =========================== std::string out_dos_format = "text"; ///< total and projected DOS file format - std::string pdos_format = "text"; ///< compatibility option for binary PDOS alone double dos_emin_ev = -15.0; double dos_emax_ev = 15.0; double dos_edelta_ev = 0.03; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 1308d0ff2f3..52e88104a6d 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -378,7 +378,6 @@ Also controled by out_freq_ion and out_app_flag. item.description = R"(Whether to output the density of states (DOS) and projected density of states (PDOS). For more information, refer to the dos.md. * 0: no output * 1: output the density of states (DOS) and projected density of states (PDOS, LCAO only) - * The filenames below describe text output. Set out_dos_format npy for NumPy DOS files. * With out_app_flag = 0: fixed-name files (`doss{s}.txt`, `pdoss{s}.txt`) are truncated and overwritten at every write. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# ionic step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index 63c3da2a5ce..89a63f47866 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -22,24 +22,6 @@ void ReadInput::item_postprocess() read_sync_string(input.out_dos_format); this->add_item(item); } - { - Input_Item item("pdos_format"); - item.domain.set_choices({"text", "npy"}); - item.annotation = "LCAO projected DOS file format"; - item.category = "Density of states"; - item.type = "String"; - item.description = "With out_dos_format text, pdos_format npy selects NumPy for LCAO projected " - "DOS alone. With out_dos_format npy both total and projected DOS use NumPy."; - item.default_value = "text"; - read_sync_string(input.pdos_format); - item.check_value = [](const Input_Item&, const Parameter& para) { - if (para.input.pdos_format == "npy" && para.input.basis_type != "lcao") - { - ModuleBase::WARNING_QUIT("ReadInput", "pdos_format npy requires basis_type lcao"); - } - }; - this->add_item(item); - } { Input_Item item("dos_edelta_ev"); item.annotation = "delta energy for dos"; diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 416c6cc02f0..356e08afc82 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -20,6 +20,16 @@ get_angular_momentum_name, remove_empty, handle_data, parse_projected_data) +def _npy_files(prefix): + """Find the fixed DOS file, or numbered steps in ionic-step order.""" + fixed = prefix.with_name(prefix.name + ".npy") + if fixed.is_file(): + return [fixed] + start = len(prefix.name) + 1 + numbered = (p for p in prefix.parent.glob(prefix.name + "g*.npy") if p.stem[start:].isdigit()) + return sorted(numbered, key=lambda p: int(p.stem[start:])) + + class DOS: """Parse DOS data""" @@ -214,9 +224,7 @@ def _find_spin_files(self) -> List[str]: if not matches1 and (path / "dos.txt").is_file(): matches1 = [str(path / "dos.txt")] # legacy PW nspin=1 name if not matches1: - fixed = path / "doss1.npy" - numbered = [p for p in path.glob("doss1g*.npy") if p.stem[6:].isdigit()] - matches1 = [fixed] if fixed.is_file() else sorted(numbered, key=lambda p: int(p.stem[6:])) + matches1 = _npy_files(path / "doss1") if not matches1: raise FileNotFoundError( f"No TDOS file found in directory '{path}'") @@ -422,6 +430,8 @@ def _find_spin_files(self) -> List[str]: Returns a list with one (nspin=1) or two (nspin=2) file paths. """ path = Path(self.pdosfile) + if path.suffix == ".npy" and not path.is_dir(): + return [str(path)] if path.is_file(): name = path.name if name.startswith("pdoss"): @@ -450,6 +460,9 @@ def _find_spin_files(self) -> List[str]: if matches: candidates.append(matches[0]) elif spin == 1: + binary = _npy_files(Path(prefix)) + if binary: + return [str(binary[0])] raise FileNotFoundError( f"No text PDOS file matching '{pattern}'") return candidates @@ -549,23 +562,10 @@ def _read(self, record): spin-polarized pair, or a path/prefix used to discover the ``pdoss1*``/``pdoss2*`` files. """ - path = Path(self.pdosfile) - if path.suffix == ".npy" and not path.is_dir(): - self._read_npy(path, record) + spin_files = self._find_spin_files() + if Path(spin_files[0]).suffix == ".npy": + self._read_npy(spin_files[0], record) return - try: - spin_files = self._find_spin_files() - except FileNotFoundError: - prefix = path / "pdos" if path.is_dir() else path - candidates = [prefix.with_name(prefix.name + ".npy")] - numbered = [p for p in prefix.parent.glob(prefix.name + "g*.npy") - if p.stem[len(prefix.name) + 1:].isdigit()] - candidates.extend(sorted(numbered, key=lambda p: int(p.stem[len(prefix.name) + 1:]))) - for candidate in candidates: - if candidate.is_file(): - self._read_npy(candidate, record) - return - raise if record != 1: raise ValueError("PDOS record selection requires a .npy file") self.nspin = len(spin_files) diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/main.py b/tools/02_postprocessing/plot-tools/abacus_plot/main.py index 0fe886869bb..b01a6aa3c9e 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/main.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/main.py @@ -80,7 +80,7 @@ def show_cmdline(cls, args): if args.dos and args.projected: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') - record = text.pop("record", text.pop("pdos_record", 1)) + record = text.pop("record", 1) efermi = text.pop("efermi", 0.0) energy_range = text.pop("energy_range", []) dos_range = text.pop("dos_range", []) @@ -113,7 +113,7 @@ def show_cmdline(cls, args): if args.dos and args.out: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') - record = text.pop("record", text.pop("pdos_record", 1)) + record = text.pop("record", 1) index = key2int(text.pop("index", None)) atom_index = key2int(text.pop("atom_index", None)) species = text.pop("species", None) From abaab224f8df6109e924f94fc899b595e1d3b450 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:16:25 +0800 Subject: [PATCH 05/15] Share PDOS orbital sums and simplify NumPy output --- docs/advanced/elec_properties/dos.md | 4 +- source/Makefile.Objects | 2 +- source/source_io/CMakeLists.txt | 2 +- source/source_io/module_dos/cal_dos.cpp | 72 +++---- .../module_dos/unittests/CMakeLists.txt | 18 +- .../unittests/test_write_pdos_npy.cpp | 92 --------- .../unittests/test_write_pdos_text.cpp | 54 ++++++ .../source_io/module_dos/write_dos_lcao.cpp | 2 +- source/source_io/module_dos/write_pdos.cpp | 96 +++++++++ source/source_io/module_dos/write_pdos.h | 22 +++ .../source_io/module_dos/write_pdos_npy.cpp | 82 -------- source/source_io/module_dos/write_pdos_npy.h | 19 -- .../source_io/module_dos/write_pdos_text.cpp | 67 +------ source/source_io/module_output/npy_record.cpp | 183 +++++------------- source/source_io/module_output/npy_record.h | 16 +- .../plot-tools/abacus_plot/dos.py | 43 +++- .../plot-tools/abacus_plot/npy_record.py | 39 ---- .../{test_pdos_npy.py => test_dos_npy.py} | 57 ++++-- .../plot-tools/tests/test_tdos_npy.py | 47 ----- 19 files changed, 351 insertions(+), 566 deletions(-) delete mode 100644 source/source_io/module_dos/unittests/test_write_pdos_npy.cpp create mode 100644 source/source_io/module_dos/write_pdos.cpp create mode 100644 source/source_io/module_dos/write_pdos.h delete mode 100644 source/source_io/module_dos/write_pdos_npy.cpp delete mode 100644 source/source_io/module_dos/write_pdos_npy.h delete mode 100644 tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py rename tools/02_postprocessing/plot-tools/tests/{test_pdos_npy.py => test_dos_npy.py} (59%) delete mode 100644 tools/02_postprocessing/plot-tools/tests/test_tdos_npy.py diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index b296facbbb5..8305d10f50a 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -120,9 +120,9 @@ energy = first["energy_min_eV"] + np.arange(rows["pdos"].shape[-1]) * first["ene first_orbital = rows["pdos"][0, 0, :] # first orbital and first spin channel ``` -Each row includes the one-based `atom_index`, UTF-8 byte string `species`, `l`, signed `m`, `nspin`, and one-based `ionic_step`. A single-point calculation uses step 1. The fields `schema_version` (1) and `record_bytes` (payload size of the complete array) identify the schema and delimit records for append recovery. +Each row includes the one-based `atom_index`, UTF-8 byte string `species`, `l`, signed `m`, `nspin`, and one-based `ionic_step`. A single-point calculation uses step 1. The fields `schema_version` (1) and `record_bytes` (payload size of the complete array) identify the schema and record boundaries. Appending to a damaged final record reports an error and leaves the existing records in place. -For DOS, mode `out_app_flag 0` replaces the fixed-name file. Mode 1 appends one complete NumPy array per write, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps such as `DOS/doss1g2.npy` and `DOS/pdosg2.npy`. +For DOS, mode `out_app_flag 0` truncates the fixed-name file before writing. An interruption can leave an incomplete final array. Mode 1 appends one complete NumPy array per write, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps such as `DOS/doss1g2.npy` and `DOS/pdosg2.npy`. For `abacus-plot`, use `tdosfile` for total DOS and `pdosfile` for projected DOS. The common JSON option `record` selects a one-based NPY record and defaults to 1. diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 96b44b97d17..c8cb0832706 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -753,7 +753,7 @@ OBJS_IO=module_parameter/input_conv.o\ module_dos/cal_pdos_gamma.o\ module_dos/cal_pdos_multik.o\ module_dos/write_pdos_text.o\ - module_dos/write_pdos_npy.o\ + module_dos/write_pdos.o\ module_dos/cal_ldos.o\ module_bessel/numerical_descriptor.o\ module_bessel/numerical_basis.o\ diff --git a/source/source_io/CMakeLists.txt b/source/source_io/CMakeLists.txt index 1b7156ee9b8..661e8cab841 100644 --- a/source/source_io/CMakeLists.txt +++ b/source/source_io/CMakeLists.txt @@ -76,7 +76,7 @@ if(ENABLE_LCAO) module_dos/cal_pdos_gamma.cpp module_dos/cal_pdos_multik.cpp module_dos/write_pdos_text.cpp - module_dos/write_pdos_npy.cpp + module_dos/write_pdos.cpp module_output/write_orb_info.cpp module_energy/write_proj_band_lcao.cpp module_chgpot/get_pchg_lcao.cpp diff --git a/source/source_io/module_dos/cal_dos.cpp b/source/source_io/module_dos/cal_dos.cpp index e45f2af3ff7..c7aae693e89 100644 --- a/source/source_io/module_dos/cal_dos.cpp +++ b/source/source_io/module_dos/cal_dos.cpp @@ -176,7 +176,6 @@ bool ModuleIO::cal_dos(const int& is, // index for spin std::vector dos(npoints, 0.0); std::vector ene(npoints, 0.0); std::vector dos_smear(npoints, 0.0); - std::vector sum_elec(npoints, 0.0); const double b = std::sqrt(2.0) * bcoeff; const double gauss_norm = std::sqrt(ModuleBase::PI) * b; @@ -226,56 +225,43 @@ bool ModuleIO::cal_dos(const int& is, // index for spin std::string error; if (root) { - std::vector smear_integral(npy ? npoints : 0); - for (int n = 0; n < npoints; ++n) + try { - dos[n] /= static_cast(nkstot); - sum += dos[n]; - sum_elec[n] = sum; - - if (dos_smear[n] < dos_thr) - { - dos_smear[n] = 0.0; - } - sum2 += dos_smear[n] * de_ev; - + std::array prefix; + const std::int64_t spin = is + 1; if (npy) { - smear_integral[n] = sum2; - continue; + const std::string fields = "('spin_channel','=i8'),('energy_eV','=f8'),('dos','=f8')," + "('dos_int','=f8'),('dos_smear','=f8'),('dos_smear_int','=f8')"; + const int step = std::max(1, istep + 1); + const size_t row_bytes = prefix.size() + sizeof(spin) + 5 * sizeof(double); + prefix = open_npy_record(ofs_dos, fn, append_step, step, fields, "dos_smear", npoints, row_bytes); } - ofs_dos << std::setw(13) << ene[n] - << " " << std::setw(12) << dos[n] - << " " << std::setw(12) << sum_elec[n] - << " " << std::setw(14) << dos_smear[n] - << " " << std::setw(14) << sum2 << std::endl; - } - if (npy) - { - const std::string fields = "('spin_channel','=i8'),('energy_eV','=f8'),('dos','=f8')," - "('dos_int','=f8'),('dos_smear','=f8'),('dos_smear_int','=f8')"; - const int step = std::max(1, istep + 1); - const std::int64_t spin = is + 1; - const size_t row_bytes = sizeof(NpyPrefix) + sizeof(spin) + 5 * sizeof(double); - try + for (int n = 0; n < npoints; ++n) { - write_npy_record(fn, append_step, step, fields, "dos_smear", npoints, row_bytes, - [&](std::ostream& out, const NpyPrefix& prefix) { - for (int n = 0; n < npoints; ++n) - { - const double row[] = {ene[n], dos[n], sum_elec[n], dos_smear[n], smear_integral[n]}; - out.write(prefix.data(), prefix.size()); - out.write(reinterpret_cast(&spin), sizeof(spin)); - out.write(reinterpret_cast(row), sizeof(row)); - } - }); + dos[n] /= static_cast(nkstot); + sum += dos[n]; + if (dos_smear[n] < dos_thr) { dos_smear[n] = 0.0; } + sum2 += dos_smear[n] * de_ev; + if (npy) + { + const double row[] = {ene[n], dos[n], sum, dos_smear[n], sum2}; + ofs_dos.write(prefix.data(), prefix.size()); + ofs_dos.write(reinterpret_cast(&spin), sizeof(spin)); + ofs_dos.write(reinterpret_cast(row), sizeof(row)); + } + else + { + ofs_dos << std::setw(13) << ene[n] + << " " << std::setw(12) << dos[n] + << " " << std::setw(12) << sum + << " " << std::setw(14) << dos_smear[n] + << " " << std::setw(14) << sum2 << std::endl; + } } - catch (const std::exception& e) { error = e.what(); } - } - else - { ofs_dos.close(); } + catch (const std::exception& e) { error = e.what(); } } if (npy) { diff --git a/source/source_io/module_dos/unittests/CMakeLists.txt b/source/source_io/module_dos/unittests/CMakeLists.txt index e9e036d32c1..e9f0e25a886 100644 --- a/source/source_io/module_dos/unittests/CMakeLists.txt +++ b/source/source_io/module_dos/unittests/CMakeLists.txt @@ -26,25 +26,15 @@ if(ENABLE_MPI) ../../../source_cell/klist_io.cpp ../../../source_cell/reciprocal_grid.cpp) +endif() + +if(ENABLE_MPI OR ENABLE_LCAO) addtest( TARGET MODULE_DOS_write_pdos_text LIBS parameter base device SOURCES test_write_pdos_text.cpp ../write_pdos_text.cpp - ../../../source_cell/atom_spec.cpp - ../../../source_cell/atom_pseudo.cpp - ../../../source_cell/pseudo.cpp - ../../../source_cell/magnetism.cpp - ../../../source_cell/test/support/mock_unitcell.cpp) - -endif() - -if(ENABLE_LCAO) - addtest( - TARGET MODULE_DOS_write_pdos_npy - LIBS parameter base device - SOURCES test_write_pdos_npy.cpp - ../write_pdos_npy.cpp + ../write_pdos.cpp ../../module_output/npy_record.cpp ../../../source_cell/atom_spec.cpp ../../../source_cell/atom_pseudo.cpp diff --git a/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp b/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp deleted file mode 100644 index 5105fd54ec4..00000000000 --- a/source/source_io/module_dos/unittests/test_write_pdos_npy.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "../write_pdos_npy.h" -#include "source_base/matrix.h" -#include "source_cell/unitcell.h" - -#include -#include -#include -#include -#include - -namespace -{ -class WritePdosNpy : public testing::Test -{ -protected: - UnitCell cell; - std::vector pdos{1}; - std::string prefix; - - void SetUp() override - { - prefix = testing::TempDir() + "/abacus-" + testing::UnitTest::GetInstance()->current_test_info()->name() + "-"; - cell.nat = 1; - cell.ntype = 1; - cell.atoms = new Atom[1]; - cell.set_atom_flag = true; - cell.iat2it = {0}; - cell.atoms[0].label = "Si"; - cell.atoms[0].nw = 2; - cell.atoms[0].nwl = 0; - cell.atoms[0].l_nchi = {2}; - cell.atoms[0].set_index(); - cell.set_iat2iwt_for_test({0}, 1); - pdos.front().create(2, 2); - pdos.front()(0, 0) = 4.25; - pdos.front()(1, 0) = -1.25; - pdos.front()(0, 1) = 1e-8; - pdos.front()(1, 1) = 0; - } - - std::string write(int step, int mode) - { - return ModuleIO::write_pdos_npy(cell, pdos, 1, -1.0, 0.25, prefix, step, mode); - } - - std::string contents(const std::string& path) - { - std::ifstream in(path, std::ios::binary); - return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); - } - - void TearDown() override - { - std::remove((prefix + "pdos.npy").c_str()); - std::remove((prefix + "pdosg2.npy").c_str()); - } -}; - -TEST_F(WritePdosNpy, FramesAppendOverwriteAndRecoverShortTail) -{ - const auto path = write(0, 1); - const auto first = contents(path); - ASSERT_EQ(first.substr(0, 8), std::string("\x93NUMPY\x01\x00", 8)); - const double expected[] = {3.0, 0.0}; - const auto tail = first.substr(first.size() - sizeof(expected)); - EXPECT_EQ(tail, std::string(reinterpret_cast(expected), sizeof(expected))); - const auto other = write(1, 2); - ASSERT_EQ(other, prefix + "pdosg2.npy"); - const auto second = contents(other); - { - std::ofstream interrupted(path, std::ios::app | std::ios::binary); - interrupted.write(second.data(), second.size() - 1); - } - write(1, 1); - EXPECT_EQ(contents(path), first + second); - write(0, 1); - EXPECT_EQ(contents(path), first); - write(1, 0); - EXPECT_EQ(contents(path), second); -} - -TEST_F(WritePdosNpy, IncompatibleAppendPreservesFile) -{ - const auto path = write(0, 0); - { - std::ofstream existing(path, std::ios::binary); - existing << "unrelated file"; - } - EXPECT_THROW(write(1, 1), std::runtime_error); - EXPECT_EQ(contents(path), "unrelated file"); -} -} diff --git a/source/source_io/module_dos/unittests/test_write_pdos_text.cpp b/source/source_io/module_dos/unittests/test_write_pdos_text.cpp index add0fa08007..67fc7cb711b 100644 --- a/source/source_io/module_dos/unittests/test_write_pdos_text.cpp +++ b/source/source_io/module_dos/unittests/test_write_pdos_text.cpp @@ -1,10 +1,13 @@ +#include #include +#include #include #include #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "../write_pdos.h" #include "../write_pdos_text.h" #include "source_base/global_variable.h" #include "source_cell/unitcell.h" @@ -242,3 +245,54 @@ TEST_F(WritePdosTextTest, Mode2PerStepFile) GlobalV::ofs_running.close(); remove("test_write_pdos_text.log"); } + +TEST_F(WritePdosTextTest, NpyAppendOverwriteAndNumberedSteps) +{ + Atom& atom = ucell->atoms[0]; + atom.nw = 2; + atom.nwl = 0; + atom.l_nchi = {2}; + atom.set_index(); + std::vector data(1); + data[0].create(2, 2); + data[0](0, 0) = 4.25; + data[0](1, 0) = -1.25; + data[0](0, 1) = 1e-8; + + const std::string prefix = testing::TempDir() + "/abacus-pdos-frame-"; + auto write = [&](int step, int mode) { + return ModuleIO::write_pdos_npy(*ucell, data, 1, -1.0, 0.25, prefix, step, mode); + }; + auto bytes = [](const std::string& path) { + std::ifstream in(path, std::ios::binary); + std::ostringstream buffer; + buffer << in.rdbuf(); + return buffer.str(); + }; + const auto path = write(0, 1); + const auto first = bytes(path); + const double expected[] = {3.0, 0.0}; + ASSERT_GE(first.size(), sizeof(expected)); + EXPECT_EQ(first.substr(first.size() - sizeof(expected)), + std::string(reinterpret_cast(expected), sizeof(expected))); + const auto numbered = write(1, 2); + EXPECT_EQ(numbered, prefix + "pdosg2.npy"); + const auto second = bytes(numbered); + write(1, 1); + EXPECT_EQ(bytes(path), first + second); + write(1, 0); + EXPECT_EQ(bytes(path), second); + write(0, 1); + EXPECT_EQ(bytes(path), first); + + // An incomplete next step must be left untouched on a subsequent append. + const auto partial = second.substr(0, second.size() - 1); + std::ofstream(path, std::ios::binary | std::ios::app).write(partial.data(), partial.size()); + EXPECT_THROW(write(2, 1), std::runtime_error); + EXPECT_EQ(bytes(path), first + partial); + std::ofstream(path, std::ios::binary) << "foreign data"; + EXPECT_THROW(write(2, 1), std::runtime_error); + EXPECT_EQ(bytes(path), "foreign data"); + std::remove(path.c_str()); + std::remove(numbered.c_str()); +} diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 5bc0165a35e..9fac698e4af 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -2,7 +2,7 @@ #include "cal_dos.h" #include "cal_pdos_gamma.h" #include "cal_pdos_multik.h" -#include "write_pdos_npy.h" +#include "write_pdos.h" #include "write_pdos_text.h" #include "source_base/global_variable.h" #include "source_base/parallel_common.h" diff --git a/source/source_io/module_dos/write_pdos.cpp b/source/source_io/module_dos/write_pdos.cpp new file mode 100644 index 00000000000..f22d2d80f0a --- /dev/null +++ b/source/source_io/module_dos/write_pdos.cpp @@ -0,0 +1,96 @@ +#include "write_pdos.h" +#include "source_base/matrix.h" +#include "source_cell/unitcell.h" +#include "source_io/module_output/npy_record.h" + +#include +#include +#include +#include +#include + +ModuleIO::PdosBlock ModuleIO::atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdos, + int spins, bool spinor) +{ + const Atom& atom = cell.atoms[cell.iat2it[iat]]; + const int ne = pdos[0].nc; + const int first = cell.get_iat2iwt()[iat]; + const int npol = spinor ? 2 : 1; + PdosBlock block; + for (int iw = 0; iw < atom.nw; ++iw) + { + auto& channel = block[{atom.iw2l[iw], atom.iw2m[iw]}]; + if (channel.empty()) { channel.resize(static_cast(spins) * ne); } + const int row = first + npol * iw; + for (int is = 0; is < spins; ++is) + { + double* values = channel.data() + static_cast(is) * ne; + for (int n = 0; n < ne; ++n) + { + values[n] += spinor ? pdos[is](row, n) + pdos[is](row + 1, n) : pdos[is](row, n); + } + } + } + for (auto& channel : block) + { + for (double& value : channel.second) + { + if (std::abs(value) < 1e-6) { value = 0.0; } + } + } + return block; +} + +std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& out_dir, + int istep, int out_app_flag) +{ + const int step = std::max(1, istep + 1); + const bool numbered = out_app_flag == 2 && istep >= 0; + const std::string suffix = numbered ? "g" + std::to_string(step) : ""; + const std::string path = out_dir + "pdos" + suffix + ".npy"; + const int ne = pdos.front().nc; + size_t width = 1; + size_t count = 0; + for (int it = 0; it < cell.ntype; ++it) + { + const Atom& atom = cell.atoms[it]; + width = std::max(width, atom.label.size()); + for (int l = 0; l <= atom.nwl; ++l) + { + if (atom.l_nchi[l] > 0) { count += static_cast(atom.na) * (2 * l + 1); } + } + } + width = (width + 7) / 8 * 8; + std::ostringstream fields; + fields.imbue(std::locale::classic()); + fields << "('nspin','=i4'),('atom_index','=i4'),('l','=i4'),('m','=i4')," + << "('energy_min_eV','=f8'),('energy_step_eV','=f8'),('species','|S" << width + << "'),('pdos','=f8',(" << pdos.size() << "," << ne << "))"; + const std::uint64_t row_bytes = 48 + width + sizeof(double) * static_cast(ne) * pdos.size(); + const bool append = out_app_flag == 1 && istep > 0; + const std::string descr = fields.str(); + std::ofstream out; + const auto prefix = open_npy_record(out, path, append, step, descr, "pdos", count, row_bytes); + const double grid[] = {emin, de}; + const bool spinor = nspin == 4; + for (int iat = 0; iat < cell.nat; ++iat) + { + std::string label = cell.atoms[cell.iat2it[iat]].label; + label.resize(width, '\0'); + const auto channels = atom_pdos(cell, iat, pdos.data(), pdos.size(), spinor); + for (const auto& channel : channels) + { + const int col = channel.first.second; + const int m = col % 2 == 0 ? -col / 2 : (col + 1) / 2; + const std::int32_t attrs[] = {nspin, iat + 1, channel.first.first, m}; + out.write(prefix.data(), prefix.size()); + out.write(reinterpret_cast(attrs), sizeof(attrs)); + out.write(reinterpret_cast(grid), sizeof(grid)); + out.write(label.data(), label.size()); + out.write(reinterpret_cast(channel.second.data()), channel.second.size() * sizeof(double)); + } + } + out.close(); + return path; +} diff --git a/source/source_io/module_dos/write_pdos.h b/source/source_io/module_dos/write_pdos.h new file mode 100644 index 00000000000..55653a71dd2 --- /dev/null +++ b/source/source_io/module_dos/write_pdos.h @@ -0,0 +1,22 @@ +#ifndef WRITE_PDOS_H +#define WRITE_PDOS_H + +#include +#include +#include +#include + +class UnitCell; +namespace ModuleBase { class matrix; } + +namespace ModuleIO +{ +// Each (l, real-harmonic column) maps to the zeta sum, ordered by spin and energy. +using PdosBlock = std::map, std::vector>; +PdosBlock atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdos, int spins, bool spinor); + +std::string write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& out_dir, + int istep, int out_app_flag); +} +#endif diff --git a/source/source_io/module_dos/write_pdos_npy.cpp b/source/source_io/module_dos/write_pdos_npy.cpp deleted file mode 100644 index 0a80371975d..00000000000 --- a/source/source_io/module_dos/write_pdos_npy.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "write_pdos_npy.h" -#include "source_base/matrix.h" -#include "source_cell/unitcell.h" -#include "source_io/module_output/npy_record.h" - -#include -#include -#include -#include -#include - -std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, - int nspin, double emin, double de, const std::string& out_dir, - int istep, int out_app_flag) -{ - const int step = istep < 0 ? 1 : istep + 1; - const bool numbered = out_app_flag == 2 && istep >= 0; - const std::string suffix = numbered ? "g" + std::to_string(step) : ""; - const std::string path = out_dir + "pdos" + suffix + ".npy"; - const int ne = pdos.front().nc; - size_t width = 1; - size_t norb = 0; - for (int iat = 0; iat < cell.nat; ++iat) - { - const Atom& atom = cell.atoms[cell.iat2it[iat]]; - width = std::max(width, atom.label.size()); - norb += std::count(atom.iw2n.begin(), atom.iw2n.end(), 0); - } - width = (width + 7) / 8 * 8; // align the binary64 spectrum in every row - - std::ostringstream fields; - fields.imbue(std::locale::classic()); - fields << "('nspin','=i4'),('atom_index','=i4'),('l','=i4'),('m','=i4')," - << "('energy_min_eV','=f8'),('energy_step_eV','=f8'),('species','|S" << width - << "'),('pdos','=f8',(" << pdos.size() << "," << ne << "))"; - const uint64_t row_bytes = 16 + 4 * 4 + 2 * 8 + width + 8 * static_cast(ne) * pdos.size(); - const bool append = out_app_flag == 1 && istep > 0; - const double grid[] = {emin, de}; - const int npol = nspin == 4 ? 2 : 1; - const std::string descr = fields.str(); - write_npy_record(path, append, step, descr, "pdos", norb, row_bytes, [&](std::ostream& out, const NpyPrefix& prefix) { - std::vector spectrum(ne); - for (int iat = 0; iat < cell.nat; ++iat) - { - const Atom& atom = cell.atoms[cell.iat2it[iat]]; - std::string label = atom.label; - label.resize(width, '\0'); - const int first = cell.get_iat2iwt()[iat]; - // Atom::set_index orders orbitals by l, then zeta, then real-harmonic column. - for (int iw = 0; iw < atom.nw; ++iw) - { - if (atom.iw2n[iw] != 0) { continue; } - const int l = atom.iw2l[iw]; - const int col = atom.iw2m[iw]; - const int m = col % 2 == 0 ? -col / 2 : (col + 1) / 2; - const int32_t attributes[] = {nspin, iat + 1, l, m}; - out.write(prefix.data(), prefix.size()); - out.write(reinterpret_cast(attributes), sizeof(attributes)); - out.write(reinterpret_cast(grid), sizeof(grid)); - out.write(label.data(), width); - for (const auto& spin : pdos) - { - std::fill(spectrum.begin(), spectrum.end(), 0.0); - for (int zeta = 0; zeta < atom.l_nchi[l]; ++zeta) - { - const int row = first + npol * (iw + zeta * (2 * l + 1)); - for (int n = 0; n < ne; ++n) - { - spectrum[n] += npol == 2 ? spin(row, n) + spin(row + 1, n) : spin(row, n); - } - } - for (double& value : spectrum) - { - if (std::abs(value) < 1e-6) { value = 0.0; } - } - out.write(reinterpret_cast(spectrum.data()), spectrum.size() * sizeof(double)); - } - } - } - }); - return path; -} diff --git a/source/source_io/module_dos/write_pdos_npy.h b/source/source_io/module_dos/write_pdos_npy.h deleted file mode 100644 index 323d14e2c18..00000000000 --- a/source/source_io/module_dos/write_pdos_npy.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef WRITE_PDOS_NPY_H -#define WRITE_PDOS_NPY_H - -#include -#include - -class UnitCell; -namespace ModuleBase -{ -class matrix; -} - -namespace ModuleIO -{ -std::string write_pdos_npy(const UnitCell& cell, const std::vector& pdos, - int nspin, double emin, double de, const std::string& out_dir, - int istep, int out_app_flag); -} -#endif diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index c3ded7e75c6..4b524876c2c 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -1,12 +1,11 @@ #include "write_pdos_text.h" +#include "write_pdos.h" #include "source_base/global_variable.h" -#include #include #include #include -#include void ModuleIO::write_pdos_text( const UnitCell& ucell, @@ -59,35 +58,9 @@ void ModuleIO::write_pdos_text( for (int iat = 0; iat < ucell.nat; ++iat) { - const int ia = ucell.iat2ia[iat]; const int it = ucell.iat2it[iat]; - const Atom* atom = &ucell.atoms[it]; - const int s0 = ucell.itiaiw2iwt(it, ia, 0); - const int max_l = atom->nwl; - - // collect all (l, m) for this atom, ordered s,p,d,f - // iw2m stores m as 0..2l (non-negative), so loop m = 0..2*L - struct OrbInfo - { - int l; - int m; // 0..2l - }; - std::vector orb_list; - - for (int L = 0; L <= max_l; ++L) - { - for (int m = 0; m <= 2 * L; ++m) - { - for (int j = 0; j < atom->nw; ++j) - { - if (atom->iw2l[j] == L && atom->iw2m[j] == m) - { - orb_list.push_back({L, m}); - break; - } - } - } - } + const bool spinor = nspin == 4; + const auto channels = atom_pdos(ucell, iat, pdos + is, 1, spinor); for (int n = 0; n < npoints; ++n) { @@ -97,39 +70,9 @@ void ModuleIO::write_pdos_text( << " " << std::setw(3) << iat + 1 << " " << std::setw(4) << ucell.atoms[it].label; - for (size_t io = 0; io < orb_list.size(); ++io) + for (const auto& channel : channels) { - const int L = orb_list[io].l; - const int m = orb_list[io].m; - double pdos_val = 0.0; - - // sum over all zeta for this (l, m) - for (int j = 0; j < atom->nw; ++j) - { - if (atom->iw2l[j] != L || atom->iw2m[j] != m) - { - continue; - } - const int w = ucell.itiaiw2iwt(it, ia, j); - - if (nspin == 4) - { - const int w0 = w - s0; - pdos_val += pdos[0](s0 + 2 * w0, n) + pdos[0](s0 + 2 * w0 + 1, n); - } - else - { - pdos_val += pdos[is](w, n); - } - } - - // zero out negligible values - if (std::abs(pdos_val) < 1e-6) - { - pdos_val = 0.0; - } - - ofs << " " << std::setw(8) << std::fixed << std::setprecision(6) << pdos_val; + ofs << " " << std::setw(8) << std::fixed << std::setprecision(6) << channel.second[n]; } ofs << std::endl; } diff --git a/source/source_io/module_output/npy_record.cpp b/source/source_io/module_output/npy_record.cpp index ddfa3ef12b6..44a97169e51 100644 --- a/source/source_io/module_output/npy_record.cpp +++ b/source/source_io/module_output/npy_record.cpp @@ -2,171 +2,88 @@ #include #include -#include #include #include #include -#include -#include -#include #include -#ifdef _WIN32 -#include -#include -#else -#include -#endif namespace { -const char npy_magic[] = "\x93NUMPY\x01\x00"; -const char descriptor[] = "{'descr': [('record_bytes', '(prefix), sizeof(prefix)); - const size_t got = in.gcount(); - if (in.bad() || std::memcmp(prefix, npy_magic, std::min(got, size_t(8))) != 0) + unsigned char tag[10]; + in.read(reinterpret_cast(tag), sizeof(tag)); + const int length = tag[8] + 256 * tag[9]; + if (std::memcmp(tag, magic, 8) != 0 || length < static_cast(descriptor.size())) { - throw std::runtime_error("invalid NPY record prefix"); + throw std::runtime_error("invalid NPY header"); } - if (got < sizeof(prefix)) { break; } - const int length = prefix[8] + 256 * prefix[9]; - if (length < static_cast(sizeof(descriptor))) { throw std::runtime_error("invalid NPY header length"); } std::string header(length, '\0'); in.read(&header[0], length); - const size_t prefix_size = std::min(in.gcount(), sizeof(descriptor) - 1); - if (in.bad() || std::memcmp(header.data(), descriptor, prefix_size) != 0) + if (header.compare(0, descriptor.size(), descriptor) != 0 + || header.find(std::string("('") + field + "',") == std::string::npos) { - throw std::runtime_error("incompatible NPY record descriptor"); + throw std::runtime_error("incompatible DOS array"); } - if (!in) { break; } - if (header.find("('" + identifying_field + "',") == std::string::npos) + const std::streamoff start = in.tellg(); + unsigned char size[8]; + in.read(reinterpret_cast(size), sizeof(size)); + std::uint64_t bytes = 0; + for (int i = 7; i >= 0; --i) { bytes = (bytes << 8) | size[i]; } + if (bytes < 16 || bytes > static_cast(end - start)) { - throw std::runtime_error("unexpected dataset in NPY file"); + throw std::runtime_error("incomplete DOS array"); } - unsigned char raw[8]; - in.read(reinterpret_cast(raw), sizeof(raw)); - if (in.bad()) { throw std::runtime_error("error reading NPY record"); } - if (!in) { break; } - uint64_t bytes = 0; - for (unsigned int i = 0; i < 8; ++i) { bytes |= uint64_t(raw[i]) << (8 * i); } - if (bytes < sizeof(ModuleIO::NpyPrefix)) { throw std::runtime_error("invalid NPY payload length"); } - const std::streamoff data_start = pos + 10 + length; - if (bytes > static_cast(end - data_start)) - { - break; - } - pos = data_start + static_cast(bytes); + in.seekg(start + static_cast(bytes)); } - in.close(); - if (pos != end) { truncate_file(path, pos); } - return pos; } } -void ModuleIO::write_npy_record(const std::string& path, bool append, int step, - const std::string& fields, const std::string& identifying_field, - std::uint64_t count, std::uint64_t row_bytes, const NpyRows& write_rows) +std::array ModuleIO::open_npy_record(std::ofstream& out, const std::string& path, bool append, int step, + const std::string& fields, const char* field, std::uint64_t count, + std::uint64_t row_bytes) { static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "NPY requires binary64"); - if (count == 0 || row_bytes < 16 || row_bytes > std::numeric_limits::max() - || count > static_cast(std::numeric_limits::max()) / row_bytes) + if (count == 0 || row_bytes < 16 || row_bytes > std::numeric_limits::max() + || count > static_cast(std::numeric_limits::max()) / row_bytes) { - throw std::runtime_error(path + ": NPY record dimensions exceed the structured dtype or file size limit"); + throw std::runtime_error(path + ": unsupported DOS array dimensions"); } const std::uint16_t one = 1; const char endian = *reinterpret_cast(&one) == 1 ? '<' : '>'; - std::string native_fields = fields; - std::replace(native_fields.begin(), native_fields.end(), '=', endian); - std::ostringstream dtype; - dtype.imbue(std::locale::classic()); - dtype << descriptor << "('schema_version','" << endian << "i4'),('ionic_step','" << endian << "i4')," - << native_fields << "], 'fortran_order': False, 'shape': (" << count << ",), }"; - std::string header = dtype.str(); - header.append((64 - (10 + header.size() + 1) % 64) % 64, ' '); - header.push_back('\n'); + std::string header = descriptor + "('schema_version','=i4'),('ionic_step','=i4')," + fields + + "], 'fortran_order': False, 'shape': (" + std::to_string(count) + ",), }"; + std::replace(header.begin(), header.end(), '=', endian); + header.append((64 - (11 + header.size()) % 64) % 64, ' '); + header += '\n'; if (header.size() > 65535) { throw std::runtime_error(path + ": NPY v1 header is too long"); } - const unsigned char length[] = {static_cast(header.size() & 255), - static_cast(header.size() >> 8)}; - NpyPrefix prefix; - const uint64_t bytes = count * row_bytes; - for (unsigned int i = 0; i < 8; ++i) { prefix[i] = static_cast((bytes >> (8 * i)) & 255); } - const std::int32_t attributes[] = {1, step}; - std::memcpy(prefix.data() + 8, attributes, sizeof(attributes)); + const unsigned char length[] = {static_cast(header.size()), static_cast(header.size() >> 8)}; try { - const std::streamoff previous = append ? prepare_append(path, identifying_field) : 0; - const std::string target = append ? path : path + ".tmp." + std::to_string(std::random_device{}()); - const auto mode = append ? std::ios::app : std::ios::trunc; - std::ofstream out(target, std::ios::binary | mode); - out.exceptions(std::ios::failbit | std::ios::badbit); - try - { - out.write(npy_magic, 8); - out.write(reinterpret_cast(length), sizeof(length)); - out.write(header.data(), header.size()); - const auto start = out.tellp(); - write_rows(out, prefix); - if (out.tellp() - start != static_cast(bytes)) - { - throw std::runtime_error("NPY payload does not match the declared dimensions"); - } - out.close(); - if (!append) - { -#ifdef _WIN32 - if (!MoveFileExA(target.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) - { - throw std::runtime_error("cannot replace NPY file (Windows error " - + std::to_string(GetLastError()) + ")"); - } -#else - if (std::rename(target.c_str(), path.c_str()) != 0) - { - throw std::runtime_error(std::strerror(errno)); - } -#endif - } - } - catch (...) - { - out.exceptions(std::ios::goodbit); - if (out.is_open()) { out.close(); } - if (append) { truncate_file(path, previous); } - else { std::remove(target.c_str()); } - throw; - } - } - catch (const std::exception& e) - { - throw std::runtime_error(path + ": " + e.what()); + if (append) { check_append(path, field); } + out.exceptions(std::ios::badbit | std::ios::failbit); + out.open(path, std::ios::binary | (append ? std::ios::app : std::ios::trunc)); + out.write(magic, 8); + out.write(reinterpret_cast(length), sizeof(length)); + out.write(header.data(), header.size()); } + catch (const std::exception& e) { throw std::runtime_error(path + ": " + e.what()); } + + std::array prefix; + const std::uint64_t bytes = count * row_bytes; + for (int i = 0; i < 8; ++i) { prefix[i] = static_cast(bytes >> (8 * i)); } + const std::int32_t attributes[] = {1, step}; + std::memcpy(prefix.data() + 8, attributes, sizeof(attributes)); + return prefix; } diff --git a/source/source_io/module_output/npy_record.h b/source/source_io/module_output/npy_record.h index 4d7bb78fc03..c88f590d6f0 100644 --- a/source/source_io/module_output/npy_record.h +++ b/source/source_io/module_output/npy_record.h @@ -3,21 +3,15 @@ #include #include -#include #include #include namespace ModuleIO { -// Every row starts with the frame's payload size (little endian), schema -// version and one-based ionic step. Remaining numeric fields use native order. -using NpyPrefix = std::array; -using NpyRows = std::function; - -// fields is a comma-separated Python dtype field list. '=' in its numeric -// descriptors is replaced by the writer's explicit byte order. -void write_npy_record(const std::string& path, bool append, int step, - const std::string& fields, const std::string& identifying_field, - std::uint64_t count, std::uint64_t row_bytes, const NpyRows& write_rows); +// Opens a DOS array and writes its NPY v1 header. Each row starts with the +// returned payload length, schema version and one-based ionic step. +std::array open_npy_record(std::ofstream& out, const std::string& path, bool append, int step, + const std::string& fields, const char* field, std::uint64_t count, + std::uint64_t row_bytes); } #endif diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 356e08afc82..551800d98bf 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -14,12 +14,45 @@ from typing import Dict, List, Sequence, Tuple, Union, Any from matplotlib.figure import Figure from matplotlib import axes -from abacus_plot.npy_record import check_record, read_npy_record +from numpy.lib import format as npy_format from abacus_plot.utils import (energy_minus_efermi, get_angular_momentum_label, get_angular_momentum_name, remove_empty, handle_data, parse_projected_data) +def _check_record(record): + if isinstance(record, bool) or not isinstance(record, (int, np.integer)) or record < 1: + raise ValueError("record must be a positive integer") + + +def _read_npy_record(path, record, kind, fields): + path = Path(path) + end = path.stat().st_size + with path.open("rb") as stream: + for _ in range(record): + if stream.tell() == end: + raise ValueError(f"{path} has no {kind} record {record}") + if npy_format.read_magic(stream) != (1, 0): + raise ValueError(f"Unsupported ABACUS {kind} NPY header in {path}") + shape, _, dtype = npy_format.read_array_header_1_0(stream) + if len(shape) != 1 or shape[0] < 1 or dtype.hasobject or not dtype.names: + raise ValueError(f"Expected a nonempty array of structured {kind} data in {path}") + required = {"schema_version", "record_bytes", "ionic_step", *fields} + if not required.issubset(dtype.names): + raise ValueError(f"Missing {kind} fields in {path}") + offset = stream.tell() + size = shape[0] * dtype.itemsize + if size > end - offset: + raise ValueError(f"Incomplete {kind} record in {path}") + stream.seek(size, 1) + rows = np.memmap(stream, mode="r", offset=offset, dtype=dtype, shape=shape) + step = rows["ionic_step"] + if (not np.all(rows["schema_version"] == 1) or not np.all(rows["record_bytes"] == size) + or step[0] < 1 or not np.all(step == step[0])): + raise ValueError(f"Invalid {kind} record metadata in {path}") + return rows + + def _npy_files(prefix): """Find the fixed DOS file, or numbered steps in ionic-step order.""" fixed = prefix.with_name(prefix.name + ".npy") @@ -197,7 +230,7 @@ class TDOS(DOS): def __init__(self, tdosfile: Union[PathLike, Sequence[PathLike]] = None, record: int = 1) -> None: self.tdosfile = tdosfile - check_record(record) + _check_record(record) self._read(record) super().__init__(self.nspin) @@ -262,7 +295,7 @@ def _read_one(self, fname: str, record: int = 1) -> Dict[str, Any]: """ if Path(fname).suffix == ".npy": fields = ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int") - rows = read_npy_record(fname, record, "TDOS", (*fields, "spin_channel")) + rows = _read_npy_record(fname, record, "TDOS", (*fields, "spin_channel")) for key in fields: if rows[key].ndim != 1 or rows[key].dtype.kind != "f" or rows[key].dtype.itemsize != 8: raise ValueError(f"Invalid TDOS column {key} in {fname}") @@ -420,7 +453,7 @@ def _col_to_m(l: int, col: int) -> int: def __init__(self, pdosfile: PathLike = None, record: int = 1) -> None: self.pdosfile = pdosfile - check_record(record) + _check_record(record) self._read(record) super().__init__(self.nspin) @@ -537,7 +570,7 @@ def _read_one(self, fname: str): def _read_npy(self, path, record): fields = {"nspin", "atom_index", "species", "l", "m", "energy_min_eV", "energy_step_eV", "pdos"} - rows = read_npy_record(path, record, "PDOS", fields) + rows = _read_npy_record(path, record, "PDOS", fields) first = rows[0] values = rows["pdos"] if (first["nspin"] not in (1, 2, 4) or values.ndim != 3 or values.shape[2] == 0 diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py b/tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py deleted file mode 100644 index 0a09e9c727f..00000000000 --- a/tools/02_postprocessing/plot-tools/abacus_plot/npy_record.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Read one ABACUS spectral array from a file of consecutive NPY records.""" -from pathlib import Path - -import numpy as np -from numpy.lib import format - - -def check_record(record): - if isinstance(record, bool) or not isinstance(record, (int, np.integer)) or record < 1: - raise ValueError("record must be a positive integer") - - -def read_npy_record(path, record, kind, fields): - check_record(record) - path = Path(path) - end = path.stat().st_size - with path.open("rb") as stream: - for _ in range(record): - if stream.tell() == end: - raise ValueError(f"{path} has no {kind} record {record}") - if format.read_magic(stream) != (1, 0): - raise ValueError(f"Unsupported ABACUS {kind} NPY header in {path}") - shape, _, dtype = format.read_array_header_1_0(stream) - if len(shape) != 1 or shape[0] < 1 or dtype.hasobject or not dtype.names: - raise ValueError(f"Expected a nonempty array of structured {kind} data in {path}") - required = {"schema_version", "record_bytes", "ionic_step", *fields} - if not required.issubset(dtype.names): - raise ValueError(f"Missing {kind} fields in {path}") - offset = stream.tell() - size = shape[0] * dtype.itemsize - if size > end - offset: - raise ValueError(f"Incomplete {kind} record in {path}") - stream.seek(size, 1) - rows = np.memmap(stream, mode="r", offset=offset, dtype=dtype, shape=shape) - step = rows["ionic_step"] - if (not np.all(rows["schema_version"] == 1) or not np.all(rows["record_bytes"] == size) - or step[0] < 1 or not np.all(step == step[0])): - raise ValueError(f"Invalid {kind} record metadata in {path}") - return rows diff --git a/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py b/tools/02_postprocessing/plot-tools/tests/test_dos_npy.py similarity index 59% rename from tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py rename to tools/02_postprocessing/plot-tools/tests/test_dos_npy.py index 29a6922fa37..4ae2d858a64 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_pdos_npy.py +++ b/tools/02_postprocessing/plot-tools/tests/test_dos_npy.py @@ -7,20 +7,25 @@ import matplotlib.pyplot as plt import numpy as np -from abacus_plot.dos import PDOS +from abacus_plot.dos import PDOS, TDOS -def frame(nspin, ne, step): - channels = 2 if nspin == 2 else 1 - dtype = [("record_bytes", " Date: Thu, 19 Nov 2026 16:23:43 +0800 Subject: [PATCH 06/15] Limit NumPy output to single-point LCAO projected DOS --- docs/advanced/elec_properties/dos.md | 38 ++--- source/Makefile.Objects | 2 - source/source_io/CMakeLists.txt | 2 - .../source_io/module_ctrl/ctrl_output_pw.cpp | 1 - .../source_io/module_ctrl/ctrl_scf_lcao.cpp | 3 +- source/source_io/module_dos/cal_dos.cpp | 69 +++------- .../source_io/module_dos/cal_pdos_gamma.cpp | 12 +- source/source_io/module_dos/cal_pdos_gamma.h | 11 +- .../source_io/module_dos/cal_pdos_multik.cpp | 12 +- source/source_io/module_dos/cal_pdos_multik.h | 11 +- .../module_dos/unittests/CMakeLists.txt | 9 +- .../module_dos/unittests/test_cal_dos.cpp | 53 ------- .../unittests/test_write_dos_pw.cpp | 2 - .../unittests/test_write_pdos_text.cpp | 84 ++++------- .../source_io/module_dos/write_dos_lcao.cpp | 82 +++++------ source/source_io/module_dos/write_dos_lcao.h | 6 +- source/source_io/module_dos/write_dos_pw.cpp | 3 +- source/source_io/module_dos/write_dos_pw.h | 1 - source/source_io/module_dos/write_pdos.cpp | 96 ------------- source/source_io/module_dos/write_pdos.h | 22 --- .../source_io/module_dos/write_pdos_text.cpp | 109 ++++++++++++++- source/source_io/module_dos/write_pdos_text.h | 5 + source/source_io/module_output/npy_record.cpp | 89 ------------ source/source_io/module_output/npy_record.h | 17 --- .../module_parameter/input_parameter.h | 2 +- .../module_parameter/read_inp_postproc.cpp | 20 ++- .../plot-tools/abacus_plot/dos.py | 130 ++++-------------- .../plot-tools/abacus_plot/main.py | 10 +- .../plot-tools/tests/test_dos.py | 21 ++- .../plot-tools/tests/test_dos_npy.py | 112 --------------- 30 files changed, 295 insertions(+), 739 deletions(-) delete mode 100644 source/source_io/module_dos/write_pdos.cpp delete mode 100644 source/source_io/module_dos/write_pdos.h delete mode 100644 source/source_io/module_output/npy_record.cpp delete mode 100644 source/source_io/module_output/npy_record.h delete mode 100644 tools/02_postprocessing/plot-tools/tests/test_dos_npy.py diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 8305d10f50a..2fc50c978d0 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -98,36 +98,20 @@ The `# istep:` line is only present for geometry-optimization (istep) output. Wi For nspin=2, two files are written (pdoss1* and pdoss2*), one per spin channel. For nspin=4, the two spinor components are summed into a single file. The unit of PDOS is also `(number of states)/(eV * unitcell)`. -### NumPy output - -Set `out_dos_format npy` to write the total DOS (PW and LCAO) and projected DOS (LCAO) selected by `out_dos` as NumPy arrays. The default format is `text`. The NPY writer is built into ABACUS. - -```text -out_dos 1 -out_dos_format npy -``` - -Each file contains a standard NumPy 1.0 structured array with named fields. Total DOS uses one row per energy point in `doss1.npy`, with a separate `doss2.npy` for collinear spin. The five binary64 fields are `energy_eV`, `dos`, `dos_int`, `dos_smear` and `dos_smear_int`, in the same units as the text columns. `spin_channel` gives the one-based channel. For example, `np.load("doss1.npy")["dos_smear"]` returns the smeared DOS in states/eV per cell. - -LCAO projected DOS uses one row per atom and `(l,m)` channel in `pdos.npy`. Contributions from all zeta components are summed. Across the array, the binary64 `pdos` field has axes `(orbital, spin channel, energy point)` and units of 1/eV. There are two spin channels for `nspin=2` and one for `nspin=1` or `4`. The latter includes both spinor components. Both output formats apply the same small-value threshold. +For a single-point LCAO SCF or NSCF calculation, set `out_dos 1` and +`pdos_format npy` to write `pdos.npy`. The default is `pdos_format text`. +Total DOS still goes to `doss{spin}.txt`. Set `pdosfile` to the path of +`pdos.npy` in the `abacus-plot -d -p` configuration, or open it with NumPy: ```python import numpy as np -rows = np.load("OUT.ABACUS/pdos.npy", allow_pickle=False, mmap_mode="r") -first = rows[0] -energy = first["energy_min_eV"] + np.arange(rows["pdos"].shape[-1]) * first["energy_step_eV"] -first_orbital = rows["pdos"][0, 0, :] # first orbital and first spin channel -``` - -Each row includes the one-based `atom_index`, UTF-8 byte string `species`, `l`, signed `m`, `nspin`, and one-based `ionic_step`. A single-point calculation uses step 1. The fields `schema_version` (1) and `record_bytes` (payload size of the complete array) identify the schema and record boundaries. Appending to a damaged final record reports an error and leaves the existing records in place. - -For DOS, mode `out_app_flag 0` truncates the fixed-name file before writing. An interruption can leave an incomplete final array. Mode 1 appends one complete NumPy array per write, with the first ionic step starting a fresh file. Each array can have a different energy grid. `np.load(path)` opens the first record. To read consecutive records, open the file once in `"rb"` mode and call `np.load(stream, allow_pickle=False)` for each one. Mode 2 writes numbered steps such as `DOS/doss1g2.npy` and `DOS/pdosg2.npy`. - -For `abacus-plot`, use `tdosfile` for total DOS and `pdosfile` for projected DOS. The common JSON option `record` selects a one-based NPY record and defaults to 1. - -```json -{"pdosfile": "OUT.ABACUS/pdos.npy", "record": 1, "species": ["Si"]} +rows = np.load("pdos.npy", mmap_mode="r") +spectrum = rows["pdos"][0] # (spin channel, energy point), in 1/eV +energy_eV = rows["energy_min_eV"][0] + np.arange(spectrum.shape[1]) * rows["energy_step_eV"][0] ``` -Run `abacus-plot -d -p -f config.json` to plot, or `abacus-plot -d -o -f config.json` to export the selected species' curves. +Each row identifies one channel by `atom_index` (one-based), `species`, `l` +and signed `m`. `nspin` is the input spin mode. Modes 1 and 4 store one +spectrum per row, and mode 2 stores spin-up and spin-down. The array uses +binary64 and the same zeta sums and zero threshold as text. diff --git a/source/Makefile.Objects b/source/Makefile.Objects index c8cb0832706..5ca197fb512 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -749,11 +749,9 @@ OBJS_IO=module_parameter/input_conv.o\ module_ctrl/ctrl_output_td_pw.o\ module_output/td_conserv_io.o\ module_dos/cal_dos.o\ - module_output/npy_record.o\ module_dos/cal_pdos_gamma.o\ module_dos/cal_pdos_multik.o\ module_dos/write_pdos_text.o\ - module_dos/write_pdos.o\ module_dos/cal_ldos.o\ module_bessel/numerical_descriptor.o\ module_bessel/numerical_basis.o\ diff --git a/source/source_io/CMakeLists.txt b/source/source_io/CMakeLists.txt index 661e8cab841..01696065995 100644 --- a/source/source_io/CMakeLists.txt +++ b/source/source_io/CMakeLists.txt @@ -12,7 +12,6 @@ list( module_bessel/bessel_basis.cpp module_output/cal_test.cpp module_dos/cal_dos.cpp - module_output/npy_record.cpp module_dos/cal_ldos.cpp module_ml/cal_mlkedf_desc.cpp module_dos/write_dos_pw.cpp @@ -76,7 +75,6 @@ if(ENABLE_LCAO) module_dos/cal_pdos_gamma.cpp module_dos/cal_pdos_multik.cpp module_dos/write_pdos_text.cpp - module_dos/write_pdos.cpp module_output/write_orb_info.cpp module_energy/write_proj_band_lcao.cpp module_chgpot/get_pchg_lcao.cpp diff --git a/source/source_io/module_ctrl/ctrl_output_pw.cpp b/source/source_io/module_ctrl/ctrl_output_pw.cpp index 72eab2802ba..435a6412bd4 100644 --- a/source/source_io/module_ctrl/ctrl_output_pw.cpp +++ b/source/source_io/module_ctrl/ctrl_output_pw.cpp @@ -189,7 +189,6 @@ void ModuleIO::ctrl_scf_pw(const int istep, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, - inp.out_dos_format, inp.nspin, inp.out_dos, PARAM.globalv.dos_setemax, diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index b257e7c8ea8..fcf0264b91f 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -156,6 +156,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, const std::string global_dos_dir = PARAM.globalv.global_dos_dir; // Mode-2 DOS/ subdirectory is created lazily at write time. ModuleBase::ensure_directory(global_dos_dir); + const bool pdos_npy = inp.pdos_format == "npy"; ModuleIO::write_dos_lcao(psi, p_hamilt, pv, @@ -168,7 +169,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, - inp.out_dos_format, + pdos_npy, out_app_flag, istep, inp.nspin, diff --git a/source/source_io/module_dos/cal_dos.cpp b/source/source_io/module_dos/cal_dos.cpp index c7aae693e89..4305faa4b98 100644 --- a/source/source_io/module_dos/cal_dos.cpp +++ b/source/source_io/module_dos/cal_dos.cpp @@ -1,6 +1,4 @@ #include "cal_dos.h" -#include "source_io/module_output/npy_record.h" -#include "source_base/parallel_common.h" #include "source_base/constants.h" #include "source_base/global_function.h" @@ -117,11 +115,9 @@ bool ModuleIO::cal_dos(const int& is, // index for spin std::ofstream ofs_dos; - const bool npy = fn.size() >= 4 && fn.compare(fn.size() - 4, 4, ".npy") == 0; - const bool append_step = (out_app_flag == 1) && (istep > 0); - const bool root = GlobalV::MY_RANK == 0; - if (root && !npy) + if (GlobalV::MY_RANK == 0) { + const bool append_step = (out_app_flag == 1) && (istep > 0); if (append_step) { ofs_dos.open(fn.c_str(), std::ios::app); @@ -156,7 +152,7 @@ bool ModuleIO::cal_dos(const int& is, // index for spin ModuleBase::WARNING("ModuleIO::cal_dos", "npoints <= 0"); return false; } - if (root && !npy) + if (GlobalV::MY_RANK == 0) { ofs_dos << npoints << " # number of points" << std::endl; ofs_dos << std::fixed << std::setprecision(6); @@ -176,6 +172,7 @@ bool ModuleIO::cal_dos(const int& is, // index for spin std::vector dos(npoints, 0.0); std::vector ene(npoints, 0.0); std::vector dos_smear(npoints, 0.0); + std::vector sum_elec(npoints, 0.0); const double b = std::sqrt(2.0) * bcoeff; const double gauss_norm = std::sqrt(ModuleBase::PI) * b; @@ -222,53 +219,31 @@ bool ModuleIO::cal_dos(const int& is, // index for spin double sum2 = 0.0; const double dos_thr = 1.0e-12; - std::string error; - if (root) + if (GlobalV::MY_RANK == 0) { - try + for (int n = 0; n < npoints; ++n) { - std::array prefix; - const std::int64_t spin = is + 1; - if (npy) + dos[n] /= static_cast(nkstot); + sum += dos[n]; + sum_elec[n] = sum; + + if (dos_smear[n] < dos_thr) { - const std::string fields = "('spin_channel','=i8'),('energy_eV','=f8'),('dos','=f8')," - "('dos_int','=f8'),('dos_smear','=f8'),('dos_smear_int','=f8')"; - const int step = std::max(1, istep + 1); - const size_t row_bytes = prefix.size() + sizeof(spin) + 5 * sizeof(double); - prefix = open_npy_record(ofs_dos, fn, append_step, step, fields, "dos_smear", npoints, row_bytes); + dos_smear[n] = 0.0; } - for (int n = 0; n < npoints; ++n) - { - dos[n] /= static_cast(nkstot); - sum += dos[n]; - if (dos_smear[n] < dos_thr) { dos_smear[n] = 0.0; } - sum2 += dos_smear[n] * de_ev; - if (npy) - { - const double row[] = {ene[n], dos[n], sum, dos_smear[n], sum2}; - ofs_dos.write(prefix.data(), prefix.size()); - ofs_dos.write(reinterpret_cast(&spin), sizeof(spin)); - ofs_dos.write(reinterpret_cast(row), sizeof(row)); - } - else - { - ofs_dos << std::setw(13) << ene[n] - << " " << std::setw(12) << dos[n] - << " " << std::setw(12) << sum - << " " << std::setw(14) << dos_smear[n] - << " " << std::setw(14) << sum2 << std::endl; - } - } - ofs_dos.close(); + sum2 += dos_smear[n] * de_ev; + + ofs_dos << std::setw(13) << ene[n] + << " " << std::setw(12) << dos[n] + << " " << std::setw(12) << sum_elec[n] + << " " << std::setw(14) << dos_smear[n] + << " " << std::setw(14) << sum2 << std::endl; } - catch (const std::exception& e) { error = e.what(); } } - if (npy) + + if (GlobalV::MY_RANK == 0) { -#ifdef __MPI - Parallel_Common::bcast_string(error); -#endif - if (!error.empty()) { ModuleBase::WARNING_QUIT("cal_dos", error); } + ofs_dos.close(); } ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Number of bands", nbands); diff --git a/source/source_io/module_dos/cal_pdos_gamma.cpp b/source/source_io/module_dos/cal_pdos_gamma.cpp index 2a50189cc3f..f36b2365bb9 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.cpp +++ b/source/source_io/module_dos/cal_pdos_gamma.cpp @@ -1,5 +1,4 @@ #include "cal_pdos_gamma.h" -#include "write_dos_lcao.h" #include "source_base/parallel_reduce.h" #include "source_base/module_external/blas_connector.h" #include "source_base/module_external/scalapack_connector.h" @@ -7,11 +6,10 @@ #include "source_lcao/hamilt_lcao.h" -void ModuleIO::cal_pdos( +std::vector ModuleIO::cal_pdos( const psi::Psi* psi, hamilt::Hamilt* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, const int nspin0, const int nbands, @@ -20,12 +18,8 @@ void ModuleIO::cal_pdos( const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, const int nlocal, - const int nspin, - const std::string& global_out_dir, - bool npy) + const int nspin) { ModuleBase::TITLE("ModuleIO", "cal_pdos_gamma"); @@ -145,5 +139,5 @@ void ModuleIO::cal_pdos( #endif } // is - write_pdos(ucell, pdos, nspin, nlocal, emin, dos_edelta_ev, global_out_dir, istep, out_app_flag, npy); + return pdos; } diff --git a/source/source_io/module_dos/cal_pdos_gamma.h b/source/source_io/module_dos/cal_pdos_gamma.h index 0583c7dedd8..f4ad52cf393 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.h +++ b/source/source_io/module_dos/cal_pdos_gamma.h @@ -6,16 +6,15 @@ #include "source_psi/psi.h" // use psi::Psi #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals -#include +#include namespace ModuleIO { - void cal_pdos( + std::vector cal_pdos( const psi::Psi* psi, hamilt::Hamilt* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, const int nspin0, const int nbands, @@ -24,12 +23,8 @@ namespace ModuleIO const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, const int nlocal, - const int nspin, - const std::string& global_out_dir, - bool npy); + const int nspin); } diff --git a/source/source_io/module_dos/cal_pdos_multik.cpp b/source/source_io/module_dos/cal_pdos_multik.cpp index e7a1274f798..7d3a2b4e65f 100644 --- a/source/source_io/module_dos/cal_pdos_multik.cpp +++ b/source/source_io/module_dos/cal_pdos_multik.cpp @@ -1,16 +1,14 @@ #include "cal_pdos_multik.h" -#include "write_dos_lcao.h" #include "source_base/parallel_reduce.h" #include "source_base/module_external/blas_connector.h" #include "source_base/module_external/scalapack_connector.h" #include "source_base/global_function.h" #include "source_lcao/hamilt_lcao.h" -void ModuleIO::cal_pdos( +std::vector ModuleIO::cal_pdos( const psi::Psi>* psi, hamilt::Hamilt>* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, const int nspin0, const int nbands, @@ -19,12 +17,8 @@ void ModuleIO::cal_pdos( const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, const int nlocal, - const int nspin, - const std::string& global_out_dir, - bool npy) + const int nspin) { ModuleBase::TITLE("ModuleIO", "cal_pdos_multik"); @@ -185,5 +179,5 @@ void ModuleIO::cal_pdos( #endif } // is - write_pdos(ucell, pdos, nspin, nlocal, emin, dos_edelta_ev, global_out_dir, istep, out_app_flag, npy); + return pdos; } diff --git a/source/source_io/module_dos/cal_pdos_multik.h b/source/source_io/module_dos/cal_pdos_multik.h index 63f8023983d..417c682bd7b 100644 --- a/source/source_io/module_dos/cal_pdos_multik.h +++ b/source/source_io/module_dos/cal_pdos_multik.h @@ -6,17 +6,16 @@ #include "source_psi/psi.h" // use psi::Psi #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals -#include +#include namespace ModuleIO { // pdos for multi-k point - void cal_pdos( + std::vector cal_pdos( const psi::Psi>* psi, hamilt::Hamilt>* p_ham, const Parallel_Orbitals& pv, - const UnitCell& ucell, const K_Vectors& kv, const int nspin0, const int nbands, @@ -25,12 +24,8 @@ namespace ModuleIO const double& emin, const double& dos_edelta_ev, const double& bcoeff, - const int istep, - const int out_app_flag, const int nlocal, - const int nspin, - const std::string& global_out_dir, - bool npy); + const int nspin); } diff --git a/source/source_io/module_dos/unittests/CMakeLists.txt b/source/source_io/module_dos/unittests/CMakeLists.txt index e9f0e25a886..525ebce5aab 100644 --- a/source/source_io/module_dos/unittests/CMakeLists.txt +++ b/source/source_io/module_dos/unittests/CMakeLists.txt @@ -12,7 +12,7 @@ if(ENABLE_MPI) addtest( TARGET MODULE_DOS_cal_dos LIBS parameter base device - SOURCES test_cal_dos.cpp ../cal_dos.cpp ../../module_output/npy_record.cpp) + SOURCES test_cal_dos.cpp ../cal_dos.cpp) addtest( TARGET MODULE_DOS_write_dos_pw @@ -20,25 +20,20 @@ if(ENABLE_MPI) SOURCES test_write_dos_pw.cpp ../write_dos_pw.cpp ../cal_dos.cpp - ../../module_output/npy_record.cpp ../../../source_cell/parallel_kpoints.cpp ../../../source_cell/klist.cpp ../../../source_cell/klist_io.cpp ../../../source_cell/reciprocal_grid.cpp) -endif() - -if(ENABLE_MPI OR ENABLE_LCAO) addtest( TARGET MODULE_DOS_write_pdos_text LIBS parameter base device SOURCES test_write_pdos_text.cpp ../write_pdos_text.cpp - ../write_pdos.cpp - ../../module_output/npy_record.cpp ../../../source_cell/atom_spec.cpp ../../../source_cell/atom_pseudo.cpp ../../../source_cell/pseudo.cpp ../../../source_cell/magnetism.cpp ../../../source_cell/test/support/mock_unitcell.cpp) + endif() diff --git a/source/source_io/module_dos/unittests/test_cal_dos.cpp b/source/source_io/module_dos/unittests/test_cal_dos.cpp index fac5692f296..82c99219112 100644 --- a/source/source_io/module_dos/unittests/test_cal_dos.cpp +++ b/source/source_io/module_dos/unittests/test_cal_dos.cpp @@ -2,9 +2,6 @@ #include "gmock/gmock.h" #include "../cal_dos.h" #include "source_base/global_variable.h" -#include -#include -#include #include #include #ifdef __MPI @@ -30,56 +27,6 @@ class DosTest : public ::testing::Test std::string output; }; -TEST_F(DosTest, NpyStoresFiveColumnsAcrossSteps) -{ - const std::string path = testing::TempDir() + "/abacus-total-dos-steps.npy"; - const std::vector weights{1.0}; - const std::vector spins{0}; - const ModuleBase::matrix eigenvalues(1, 1); - const ModuleBase::matrix occupations(1, 1); - const double sigma = 0.05; - for (int step = 0; step < 2; ++step) - { - ASSERT_TRUE(ModuleIO::cal_dos(0, path, 1.0, 1.0, 0.0, sigma, 1, 1, weights, spins, - 1, eigenvalues, occupations, step, 1, 1)); - } - std::ifstream in(path, std::ios::binary); - for (int step = 1; step <= 2; ++step) - { - unsigned char prefix[10]; - ASSERT_TRUE(in.read(reinterpret_cast(prefix), sizeof(prefix))); - EXPECT_EQ(std::string(reinterpret_cast(prefix), 8), std::string("\x93NUMPY\x01\x00", 8)); - std::string header(prefix[8] + 256 * prefix[9], '\0'); - ASSERT_TRUE(in.read(&header[0], header.size())); - EXPECT_NE(header.find("'dos_smear_int'"), std::string::npos); - EXPECT_NE(header.find("'shape': (2,)"), std::string::npos); - const double peak = 1.0 / (sigma * std::sqrt(2.0 * std::acos(-1.0))); - for (int n = 0; n < 2; ++n) - { - unsigned char bytes[8]; - std::int32_t flags[2]; - std::int64_t spin = 0; - double data[5]; - ASSERT_TRUE(in.read(reinterpret_cast(bytes), sizeof(bytes))); - ASSERT_TRUE(in.read(reinterpret_cast(flags), sizeof(flags))); - ASSERT_TRUE(in.read(reinterpret_cast(&spin), sizeof(spin))); - ASSERT_TRUE(in.read(reinterpret_cast(data), sizeof(data))); - EXPECT_EQ(bytes[0], 128); - EXPECT_EQ(flags[0], 1); - EXPECT_EQ(flags[1], step); - EXPECT_EQ(spin, 1); - EXPECT_DOUBLE_EQ(data[0], n); - EXPECT_DOUBLE_EQ(data[1], n == 0 ? 1.0 : 0.0); - EXPECT_DOUBLE_EQ(data[2], 1.0); - EXPECT_NEAR(data[3], n == 0 ? peak : 0.0, 1e-12); - EXPECT_NEAR(data[4], peak, 1e-12); - } - } - EXPECT_EQ(in.peek(), std::char_traits::eof()); - in.close(); - std::remove(path.c_str()); -} - TEST_F(DosTest,Dos) { //is,fa,de_ev,emax_ev,emin_ev,bcoeff,nks,nkstot,nbands diff --git a/source/source_io/module_dos/unittests/test_write_dos_pw.cpp b/source/source_io/module_dos/unittests/test_write_dos_pw.cpp index 12c2887686f..5e719bfe740 100644 --- a/source/source_io/module_dos/unittests/test_write_dos_pw.cpp +++ b/source/source_io/module_dos/unittests/test_write_dos_pw.cpp @@ -82,7 +82,6 @@ TEST_F(DosPWTest,Dos1) dosp.de_ev, dos_scale, dosp.bcoeff, - "text", nspin, out_dos, dos_setemax, @@ -162,7 +161,6 @@ TEST_F(DosPWTest,Dos2) dosp.de_ev, dos_scale, dosp.bcoeff, - "text", nspin, out_dos, dos_setemax, diff --git a/source/source_io/module_dos/unittests/test_write_pdos_text.cpp b/source/source_io/module_dos/unittests/test_write_pdos_text.cpp index 67fc7cb711b..5d7b09cb0cc 100644 --- a/source/source_io/module_dos/unittests/test_write_pdos_text.cpp +++ b/source/source_io/module_dos/unittests/test_write_pdos_text.cpp @@ -1,13 +1,10 @@ -#include #include -#include #include #include #include "gmock/gmock.h" #include "gtest/gtest.h" -#include "../write_pdos.h" #include "../write_pdos_text.h" #include "source_base/global_variable.h" #include "source_cell/unitcell.h" @@ -182,6 +179,36 @@ TEST_F(WritePdosTextTest, SpinPolarized) remove("test_write_pdos_text.log"); } +TEST_F(WritePdosTextTest, NpySumsZetasAndSpinorsBeforeThreshold) +{ + Atom& atom = ucell->atoms[0]; + atom.nwl = 0; + atom.nw = 2; + atom.l_nchi = {2}; + atom.iw2l = {0, 0}; + atom.iw2m = {0, 0}; + ucell->set_iat2iwt_for_test({0}, 2); + std::vector pdos(1); + pdos[0].create(4, 3, true); + for (int iw = 0; iw < 4; ++iw) + { + pdos[0](iw, 0) = iw + 1; + pdos[0](iw, 1) = 0.3e-6; + pdos[0](iw, 2) = 0.1e-6; + } + const std::string path = testing::TempDir() + "abacus_pdos_spinor.npy"; + ModuleIO::write_pdos_npy(*ucell, pdos, 4, -1.0, 0.5, path); + std::ifstream file(path, std::ios::binary); + // The single (atom, l, m) record ends in a spin-summed binary64 spectrum. + double spectrum[3]; + file.seekg(-static_cast(sizeof(spectrum)), std::ios::end); + ASSERT_TRUE(file.read(reinterpret_cast(spectrum), sizeof(spectrum))); + EXPECT_DOUBLE_EQ(spectrum[0], 10.0); + EXPECT_DOUBLE_EQ(spectrum[1], 1.2e-6); + EXPECT_DOUBLE_EQ(spectrum[2], 0.0); + std::remove(path.c_str()); +} + // --------------------------------------------------------------------------- // out_app_flag = 1: fixed-name files, successive calls append records. // --------------------------------------------------------------------------- @@ -245,54 +272,3 @@ TEST_F(WritePdosTextTest, Mode2PerStepFile) GlobalV::ofs_running.close(); remove("test_write_pdos_text.log"); } - -TEST_F(WritePdosTextTest, NpyAppendOverwriteAndNumberedSteps) -{ - Atom& atom = ucell->atoms[0]; - atom.nw = 2; - atom.nwl = 0; - atom.l_nchi = {2}; - atom.set_index(); - std::vector data(1); - data[0].create(2, 2); - data[0](0, 0) = 4.25; - data[0](1, 0) = -1.25; - data[0](0, 1) = 1e-8; - - const std::string prefix = testing::TempDir() + "/abacus-pdos-frame-"; - auto write = [&](int step, int mode) { - return ModuleIO::write_pdos_npy(*ucell, data, 1, -1.0, 0.25, prefix, step, mode); - }; - auto bytes = [](const std::string& path) { - std::ifstream in(path, std::ios::binary); - std::ostringstream buffer; - buffer << in.rdbuf(); - return buffer.str(); - }; - const auto path = write(0, 1); - const auto first = bytes(path); - const double expected[] = {3.0, 0.0}; - ASSERT_GE(first.size(), sizeof(expected)); - EXPECT_EQ(first.substr(first.size() - sizeof(expected)), - std::string(reinterpret_cast(expected), sizeof(expected))); - const auto numbered = write(1, 2); - EXPECT_EQ(numbered, prefix + "pdosg2.npy"); - const auto second = bytes(numbered); - write(1, 1); - EXPECT_EQ(bytes(path), first + second); - write(1, 0); - EXPECT_EQ(bytes(path), second); - write(0, 1); - EXPECT_EQ(bytes(path), first); - - // An incomplete next step must be left untouched on a subsequent append. - const auto partial = second.substr(0, second.size() - 1); - std::ofstream(path, std::ios::binary | std::ios::app).write(partial.data(), partial.size()); - EXPECT_THROW(write(2, 1), std::runtime_error); - EXPECT_EQ(bytes(path), first + partial); - std::ofstream(path, std::ios::binary) << "foreign data"; - EXPECT_THROW(write(2, 1), std::runtime_error); - EXPECT_EQ(bytes(path), "foreign data"); - std::remove(path.c_str()); - std::remove(numbered.c_str()); -} diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 9fac698e4af..752118fc0f9 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -2,45 +2,17 @@ #include "cal_dos.h" #include "cal_pdos_gamma.h" #include "cal_pdos_multik.h" -#include "write_pdos.h" #include "write_pdos_text.h" #include "source_base/global_variable.h" #include "source_base/parallel_common.h" #include "source_base/tool_quit.h" #include "source_io/module_output/write_orb_info.h" -namespace ModuleIO -{ +#include +#include -void write_pdos(const UnitCell& ucell, const std::vector& pdos, int nspin, int nlocal, - double emin, double de, const std::string& out_dir, int istep, int out_app_flag, bool npy) +namespace ModuleIO { - std::string error; - if (GlobalV::MY_RANK == 0) - { - if (npy) - { - try - { - const auto path = write_pdos_npy(ucell, pdos, nspin, emin, de, out_dir, istep, out_app_flag); - GlobalV::ofs_running << " Wrote projected DOS to " << path << '\n'; - } - catch (const std::exception& e) { error = e.what(); } - } - else - { - write_pdos_text(ucell, pdos.data(), nspin, nlocal, pdos.front().nc, emin, de, out_dir, istep, out_app_flag); - } - if (error.empty()) { write_orb_info(&ucell); } - } - if (npy) - { -#ifdef __MPI - Parallel_Common::bcast_string(error); -#endif - if (!error.empty()) { ModuleBase::WARNING_QUIT("write_pdos", error); } - } -} template void write_dos_lcao( @@ -56,7 +28,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& dos_format, + const bool pdos_npy, const int out_app_flag, const int istep, const int nspin, @@ -72,7 +44,6 @@ void write_dos_lcao( { ModuleBase::TITLE("ModuleIO", "write_dos_lcao"); - const bool npy = dos_format == "npy"; const int nspin0 = (nspin == 2) ? 2 : 1; double emax = 0.0; @@ -107,8 +78,7 @@ void write_dos_lcao( ss << "g" << istep+1; } - ss << (npy ? ".npy" : ".txt"); - if (npy) { ofs_running << " DOS file: " << ss.str() << '\n'; } + ss << ".txt"; ModuleIO::cal_dos(is, ss.str(), @@ -130,10 +100,9 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) - cal_pdos(psi, + const auto pdos = cal_pdos(psi, p_ham, pv, - ucell, kv, nspin0, nbands, @@ -142,12 +111,37 @@ void write_dos_lcao( emin, dos_edelta_ev, bcoeff, - istep, - out_app_flag, nlocal, - nspin, - global_out_dir, - npy); + nspin); + + std::string error; + if (GlobalV::MY_RANK == 0) + { + if (pdos_npy) + { + const std::string path = global_out_dir + "pdos.npy"; + try + { + write_pdos_npy(ucell, pdos, nspin, emin, dos_edelta_ev, path); + ofs_running << " Wrote projected DOS to " << path << '\n'; + } + catch (const std::exception& e) + { + error = path + ": " + e.what(); + } + } + else + { + write_pdos_text(ucell, pdos.data(), nspin, nlocal, pdos.front().nc, + emin, dos_edelta_ev, global_out_dir, istep, out_app_flag); + } + if (error.empty()) { write_orb_info(&ucell); } + } + if (pdos_npy) + { + Parallel_Common::bcast_string(error); + if (!error.empty()) { ModuleBase::WARNING_QUIT("write_dos_lcao", error); } + } ofs_running << " #DOS CALCULATION ENDS# " << std::endl; @@ -168,7 +162,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& dos_format, + const bool pdos_npy, const int out_app_flag, const int istep, const int nspin, @@ -196,7 +190,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& dos_format, + const bool pdos_npy, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 2ca2c1f4009..6b26a258b25 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -7,14 +7,10 @@ #include "source_hamilt/hamilt.h" // use hamilt::Hamilt #include "source_basis/module_ao/parallel_orbitals.h" // use Parallel_Orbitals #include "source_estate/fp_energy.h" // use elecstate::Efermi -#include namespace ModuleIO { - void write_pdos(const UnitCell& ucell, const std::vector& pdos, int nspin, int nlocal, - double emin, double de, const std::string& out_dir, int istep, int out_app_flag, bool npy); - /// @brief calculate density of states(DOS), /// partial density of states(PDOS), /// and mulliken charge for LCAO base @@ -32,7 +28,7 @@ namespace ModuleIO const double& dos_edelta_ev, // Delta energy const double& dos_scale, const double& bcoeff, - const std::string& dos_format, + const bool pdos_npy, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_dos_pw.cpp b/source/source_io/module_dos/write_dos_pw.cpp index 36398e9561e..434a39c6f80 100644 --- a/source/source_io/module_dos/write_dos_pw.cpp +++ b/source/source_io/module_dos/write_dos_pw.cpp @@ -13,7 +13,6 @@ void ModuleIO::write_dos_pw( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const std::string& dos_format, const int nspin, const int out_dos, const bool dos_setemax, @@ -62,7 +61,7 @@ void ModuleIO::write_dos_pw( ss << "g" << istep_in+1; } - ss << (dos_format == "npy" ? ".npy" : ".txt"); + ss << ".txt"; ModuleBase::GlobalFunc::OUT(ofs_running, "DOS file", ss.str()); diff --git a/source/source_io/module_dos/write_dos_pw.h b/source/source_io/module_dos/write_dos_pw.h index 86338172a41..2491c7d303a 100644 --- a/source/source_io/module_dos/write_dos_pw.h +++ b/source/source_io/module_dos/write_dos_pw.h @@ -20,7 +20,6 @@ namespace ModuleIO const double &dos_edelta_ev, const double &dos_scale, const double &bcoeff, - const std::string& dos_format, const int nspin, const int out_dos, const bool dos_setemax, diff --git a/source/source_io/module_dos/write_pdos.cpp b/source/source_io/module_dos/write_pdos.cpp deleted file mode 100644 index f22d2d80f0a..00000000000 --- a/source/source_io/module_dos/write_pdos.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include "write_pdos.h" -#include "source_base/matrix.h" -#include "source_cell/unitcell.h" -#include "source_io/module_output/npy_record.h" - -#include -#include -#include -#include -#include - -ModuleIO::PdosBlock ModuleIO::atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdos, - int spins, bool spinor) -{ - const Atom& atom = cell.atoms[cell.iat2it[iat]]; - const int ne = pdos[0].nc; - const int first = cell.get_iat2iwt()[iat]; - const int npol = spinor ? 2 : 1; - PdosBlock block; - for (int iw = 0; iw < atom.nw; ++iw) - { - auto& channel = block[{atom.iw2l[iw], atom.iw2m[iw]}]; - if (channel.empty()) { channel.resize(static_cast(spins) * ne); } - const int row = first + npol * iw; - for (int is = 0; is < spins; ++is) - { - double* values = channel.data() + static_cast(is) * ne; - for (int n = 0; n < ne; ++n) - { - values[n] += spinor ? pdos[is](row, n) + pdos[is](row + 1, n) : pdos[is](row, n); - } - } - } - for (auto& channel : block) - { - for (double& value : channel.second) - { - if (std::abs(value) < 1e-6) { value = 0.0; } - } - } - return block; -} - -std::string ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, - int nspin, double emin, double de, const std::string& out_dir, - int istep, int out_app_flag) -{ - const int step = std::max(1, istep + 1); - const bool numbered = out_app_flag == 2 && istep >= 0; - const std::string suffix = numbered ? "g" + std::to_string(step) : ""; - const std::string path = out_dir + "pdos" + suffix + ".npy"; - const int ne = pdos.front().nc; - size_t width = 1; - size_t count = 0; - for (int it = 0; it < cell.ntype; ++it) - { - const Atom& atom = cell.atoms[it]; - width = std::max(width, atom.label.size()); - for (int l = 0; l <= atom.nwl; ++l) - { - if (atom.l_nchi[l] > 0) { count += static_cast(atom.na) * (2 * l + 1); } - } - } - width = (width + 7) / 8 * 8; - std::ostringstream fields; - fields.imbue(std::locale::classic()); - fields << "('nspin','=i4'),('atom_index','=i4'),('l','=i4'),('m','=i4')," - << "('energy_min_eV','=f8'),('energy_step_eV','=f8'),('species','|S" << width - << "'),('pdos','=f8',(" << pdos.size() << "," << ne << "))"; - const std::uint64_t row_bytes = 48 + width + sizeof(double) * static_cast(ne) * pdos.size(); - const bool append = out_app_flag == 1 && istep > 0; - const std::string descr = fields.str(); - std::ofstream out; - const auto prefix = open_npy_record(out, path, append, step, descr, "pdos", count, row_bytes); - const double grid[] = {emin, de}; - const bool spinor = nspin == 4; - for (int iat = 0; iat < cell.nat; ++iat) - { - std::string label = cell.atoms[cell.iat2it[iat]].label; - label.resize(width, '\0'); - const auto channels = atom_pdos(cell, iat, pdos.data(), pdos.size(), spinor); - for (const auto& channel : channels) - { - const int col = channel.first.second; - const int m = col % 2 == 0 ? -col / 2 : (col + 1) / 2; - const std::int32_t attrs[] = {nspin, iat + 1, channel.first.first, m}; - out.write(prefix.data(), prefix.size()); - out.write(reinterpret_cast(attrs), sizeof(attrs)); - out.write(reinterpret_cast(grid), sizeof(grid)); - out.write(label.data(), label.size()); - out.write(reinterpret_cast(channel.second.data()), channel.second.size() * sizeof(double)); - } - } - out.close(); - return path; -} diff --git a/source/source_io/module_dos/write_pdos.h b/source/source_io/module_dos/write_pdos.h deleted file mode 100644 index 55653a71dd2..00000000000 --- a/source/source_io/module_dos/write_pdos.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef WRITE_PDOS_H -#define WRITE_PDOS_H - -#include -#include -#include -#include - -class UnitCell; -namespace ModuleBase { class matrix; } - -namespace ModuleIO -{ -// Each (l, real-harmonic column) maps to the zeta sum, ordered by spin and energy. -using PdosBlock = std::map, std::vector>; -PdosBlock atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdos, int spins, bool spinor); - -std::string write_pdos_npy(const UnitCell& cell, const std::vector& pdos, - int nspin, double emin, double de, const std::string& out_dir, - int istep, int out_app_flag); -} -#endif diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index 4b524876c2c..f1677b70bd3 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -1,11 +1,54 @@ #include "write_pdos_text.h" -#include "write_pdos.h" #include "source_base/global_variable.h" +#include +#include +#include #include #include +#include +#include +#include #include +#include + +namespace +{ +// Each (l, real-harmonic column) contains the zeta sum in spin-major order. +using PdosBlock = std::map, std::vector>; +PdosBlock atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdos, + int spins, bool spinor) +{ + const Atom& atom = cell.atoms[cell.iat2it[iat]]; + const int ne = pdos[0].nc; + const int first = cell.get_iat2iwt()[iat]; + const int npol = spinor ? 2 : 1; + PdosBlock block; + for (int iw = 0; iw < atom.nw; ++iw) + { + auto& channel = block[{atom.iw2l[iw], atom.iw2m[iw]}]; + if (channel.empty()) { channel.resize(static_cast(spins) * ne); } + const int row = first + npol * iw; + for (int is = 0; is < spins; ++is) + { + double* values = channel.data() + static_cast(is) * ne; + for (int n = 0; n < ne; ++n) + { + values[n] += spinor ? pdos[is](row, n) + pdos[is](row + 1, n) : pdos[is](row, n); + } + } + } + for (auto& channel : block) + { + for (double& value : channel.second) + { + if (std::abs(value) < 1e-6) { value = 0.0; } + } + } + return block; +} +} void ModuleIO::write_pdos_text( const UnitCell& ucell, @@ -81,3 +124,67 @@ void ModuleIO::write_pdos_text( ofs.close(); } } + +void ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& path) +{ + const int ne = pdos.front().nc; + size_t width = 1; + size_t count = 0; + for (int it = 0; it < cell.ntype; ++it) + { + const Atom& atom = cell.atoms[it]; + width = std::max(width, atom.label.size()); + for (int l = 0; l <= atom.nwl; ++l) + { + if (atom.l_nchi[l] > 0) { count += static_cast(atom.na) * (2 * l + 1); } + } + } + width = (width + 7) / 8 * 8; + std::ostringstream fields; + fields.imbue(std::locale::classic()); + fields << "('nspin','=i4'),('atom_index','=i4'),('l','=i4'),('m','=i4')," + << "('energy_min_eV','=f8'),('energy_step_eV','=f8'),('species','|S" << width + << "'),('pdos','=f8',(" << pdos.size() << "," << ne << "))"; + // NPY v1 stores a little-endian header length and an explicit byte order for the payload. + static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "PDOS requires binary64"); + const std::uint16_t one = 1; + const char endian = *reinterpret_cast(&one) ? '<' : '>'; + std::string header = "{'descr': [" + fields.str() + "], 'fortran_order': False, 'shape': (" + + std::to_string(count) + ",), }"; + std::replace(header.begin(), header.end(), '=', endian); + header.append((64 - (11 + header.size()) % 64) % 64, ' '); + header += '\n'; + const std::uint64_t row_bytes = 32 + width + sizeof(double) * static_cast(ne) * pdos.size(); + if (header.size() > 65535 || row_bytes > std::numeric_limits::max()) + { + throw std::runtime_error("PDOS array exceeds NumPy v1 dtype limits"); + } + const unsigned char length[] = {static_cast(header.size()), + static_cast(header.size() >> 8)}; + std::ofstream out; + out.exceptions(std::ios::badbit | std::ios::failbit); + out.open(path, std::ios::binary | std::ios::trunc); + out.write("\x93NUMPY\x01\x00", 8); + out.write(reinterpret_cast(length), sizeof(length)); + out.write(header.data(), header.size()); + const double grid[] = {emin, de}; + const bool spinor = nspin == 4; + for (int iat = 0; iat < cell.nat; ++iat) + { + std::string label = cell.atoms[cell.iat2it[iat]].label; + label.resize(width, '\0'); + const auto channels = atom_pdos(cell, iat, pdos.data(), pdos.size(), spinor); + for (const auto& channel : channels) + { + const int col = channel.first.second; + const int m = col % 2 == 0 ? -col / 2 : (col + 1) / 2; + const std::int32_t attrs[] = {nspin, iat + 1, channel.first.first, m}; + out.write(reinterpret_cast(attrs), sizeof(attrs)); + out.write(reinterpret_cast(grid), sizeof(grid)); + out.write(label.data(), label.size()); + out.write(reinterpret_cast(channel.second.data()), channel.second.size() * sizeof(double)); + } + } + out.close(); +} diff --git a/source/source_io/module_dos/write_pdos_text.h b/source/source_io/module_dos/write_pdos_text.h index 434c6f7ebe9..90589e14fd3 100644 --- a/source/source_io/module_dos/write_pdos_text.h +++ b/source/source_io/module_dos/write_pdos_text.h @@ -3,6 +3,7 @@ #include "source_base/matrix.h" #include "source_cell/unitcell.h" +#include namespace ModuleIO { @@ -23,6 +24,10 @@ void write_pdos_text( const int istep, const int out_app_flag); +/// Write one NPY array of atom- and orbital-projected spin spectra. +void write_pdos_npy(const UnitCell& cell, const std::vector& pdos, + int nspin, double emin, double de, const std::string& path); + } #endif diff --git a/source/source_io/module_output/npy_record.cpp b/source/source_io/module_output/npy_record.cpp deleted file mode 100644 index 44a97169e51..00000000000 --- a/source/source_io/module_output/npy_record.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "npy_record.h" - -#include -#include -#include -#include -#include -#include - -namespace -{ -const char magic[] = "\x93NUMPY\x01\x00"; -const std::string descriptor = "{'descr': [('record_bytes', '(tag), sizeof(tag)); - const int length = tag[8] + 256 * tag[9]; - if (std::memcmp(tag, magic, 8) != 0 || length < static_cast(descriptor.size())) - { - throw std::runtime_error("invalid NPY header"); - } - std::string header(length, '\0'); - in.read(&header[0], length); - if (header.compare(0, descriptor.size(), descriptor) != 0 - || header.find(std::string("('") + field + "',") == std::string::npos) - { - throw std::runtime_error("incompatible DOS array"); - } - const std::streamoff start = in.tellg(); - unsigned char size[8]; - in.read(reinterpret_cast(size), sizeof(size)); - std::uint64_t bytes = 0; - for (int i = 7; i >= 0; --i) { bytes = (bytes << 8) | size[i]; } - if (bytes < 16 || bytes > static_cast(end - start)) - { - throw std::runtime_error("incomplete DOS array"); - } - in.seekg(start + static_cast(bytes)); - } -} -} - -std::array ModuleIO::open_npy_record(std::ofstream& out, const std::string& path, bool append, int step, - const std::string& fields, const char* field, std::uint64_t count, - std::uint64_t row_bytes) -{ - static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "NPY requires binary64"); - if (count == 0 || row_bytes < 16 || row_bytes > std::numeric_limits::max() - || count > static_cast(std::numeric_limits::max()) / row_bytes) - { - throw std::runtime_error(path + ": unsupported DOS array dimensions"); - } - const std::uint16_t one = 1; - const char endian = *reinterpret_cast(&one) == 1 ? '<' : '>'; - std::string header = descriptor + "('schema_version','=i4'),('ionic_step','=i4')," + fields - + "], 'fortran_order': False, 'shape': (" + std::to_string(count) + ",), }"; - std::replace(header.begin(), header.end(), '=', endian); - header.append((64 - (11 + header.size()) % 64) % 64, ' '); - header += '\n'; - if (header.size() > 65535) { throw std::runtime_error(path + ": NPY v1 header is too long"); } - const unsigned char length[] = {static_cast(header.size()), static_cast(header.size() >> 8)}; - try - { - if (append) { check_append(path, field); } - out.exceptions(std::ios::badbit | std::ios::failbit); - out.open(path, std::ios::binary | (append ? std::ios::app : std::ios::trunc)); - out.write(magic, 8); - out.write(reinterpret_cast(length), sizeof(length)); - out.write(header.data(), header.size()); - } - catch (const std::exception& e) { throw std::runtime_error(path + ": " + e.what()); } - - std::array prefix; - const std::uint64_t bytes = count * row_bytes; - for (int i = 0; i < 8; ++i) { prefix[i] = static_cast(bytes >> (8 * i)); } - const std::int32_t attributes[] = {1, step}; - std::memcpy(prefix.data() + 8, attributes, sizeof(attributes)); - return prefix; -} diff --git a/source/source_io/module_output/npy_record.h b/source/source_io/module_output/npy_record.h deleted file mode 100644 index c88f590d6f0..00000000000 --- a/source/source_io/module_output/npy_record.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef ABACUS_NPY_RECORD_H -#define ABACUS_NPY_RECORD_H - -#include -#include -#include -#include - -namespace ModuleIO -{ -// Opens a DOS array and writes its NPY v1 header. Each row starts with the -// returned payload length, schema version and one-based ionic step. -std::array open_npy_record(std::ofstream& out, const std::string& path, bool append, int step, - const std::string& fields, const char* field, std::uint64_t count, - std::uint64_t row_bytes); -} -#endif diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 4fa5a41aae6..2f85b1f4f6b 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -540,7 +540,7 @@ struct Input_para std::string spillage_outdir = "./"; ///< output directory for spillage // ============== #Parameters (12.Postprocess) =========================== - std::string out_dos_format = "text"; ///< total and projected DOS file format + std::string pdos_format = "text"; ///< LCAO projected DOS file format double dos_emin_ev = -15.0; double dos_emax_ev = 15.0; double dos_edelta_ev = 0.03; diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index 89a63f47866..1812ed42a35 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -10,16 +10,24 @@ void ReadInput::item_postprocess() // in the generated documentation (docs/advanced/input_files/input-main.md). // Please preserve this ordering when adding new parameters. { - Input_Item item("out_dos_format"); + Input_Item item("pdos_format"); item.domain.set_choices({"text", "npy"}); - item.annotation = "file format for total and projected DOS"; + item.annotation = "file format for LCAO projected DOS"; item.category = "Density of states"; item.type = "String"; - item.description = "Select text or NumPy NPY for the outputs enabled by out_dos. " - "This covers total DOS for PW and LCAO, and projected DOS for LCAO. " - "NPY stores named binary64 fields and one array per written ionic step."; + item.description = "With out_dos = 1, select per-spin text files or a single pdos.npy " + "for projected DOS. NumPy output is available for single-point LCAO SCF and NSCF."; item.default_value = "text"; - read_sync_string(input.out_dos_format); + read_sync_string(input.pdos_format); + item.check_value = [](const Input_Item&, const Parameter& para) { + const auto& in = para.input; + if (in.out_dos && in.pdos_format == "npy" + && (in.basis_type != "lcao" || in.esolver_type != "ksdft" + || (in.calculation != "scf" && in.calculation != "nscf"))) + { + ModuleBase::WARNING_QUIT("ReadInput", "pdos_format npy requires a single-point LCAO KSDFT SCF or NSCF calculation."); + } + }; this->add_item(item); } { diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 551800d98bf..9019276d45d 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -14,55 +14,11 @@ from typing import Dict, List, Sequence, Tuple, Union, Any from matplotlib.figure import Figure from matplotlib import axes -from numpy.lib import format as npy_format from abacus_plot.utils import (energy_minus_efermi, get_angular_momentum_label, get_angular_momentum_name, remove_empty, handle_data, parse_projected_data) -def _check_record(record): - if isinstance(record, bool) or not isinstance(record, (int, np.integer)) or record < 1: - raise ValueError("record must be a positive integer") - - -def _read_npy_record(path, record, kind, fields): - path = Path(path) - end = path.stat().st_size - with path.open("rb") as stream: - for _ in range(record): - if stream.tell() == end: - raise ValueError(f"{path} has no {kind} record {record}") - if npy_format.read_magic(stream) != (1, 0): - raise ValueError(f"Unsupported ABACUS {kind} NPY header in {path}") - shape, _, dtype = npy_format.read_array_header_1_0(stream) - if len(shape) != 1 or shape[0] < 1 or dtype.hasobject or not dtype.names: - raise ValueError(f"Expected a nonempty array of structured {kind} data in {path}") - required = {"schema_version", "record_bytes", "ionic_step", *fields} - if not required.issubset(dtype.names): - raise ValueError(f"Missing {kind} fields in {path}") - offset = stream.tell() - size = shape[0] * dtype.itemsize - if size > end - offset: - raise ValueError(f"Incomplete {kind} record in {path}") - stream.seek(size, 1) - rows = np.memmap(stream, mode="r", offset=offset, dtype=dtype, shape=shape) - step = rows["ionic_step"] - if (not np.all(rows["schema_version"] == 1) or not np.all(rows["record_bytes"] == size) - or step[0] < 1 or not np.all(step == step[0])): - raise ValueError(f"Invalid {kind} record metadata in {path}") - return rows - - -def _npy_files(prefix): - """Find the fixed DOS file, or numbered steps in ionic-step order.""" - fixed = prefix.with_name(prefix.name + ".npy") - if fixed.is_file(): - return [fixed] - start = len(prefix.name) + 1 - numbered = (p for p in prefix.parent.glob(prefix.name + "g*.npy") if p.stem[start:].isdigit()) - return sorted(numbered, key=lambda p: int(p.stem[start:])) - - class DOS: """Parse DOS data""" @@ -228,10 +184,9 @@ class TDOS(DOS): spinor-summed file, which is handled like nspin=1. """ - def __init__(self, tdosfile: Union[PathLike, Sequence[PathLike]] = None, record: int = 1) -> None: + def __init__(self, tdosfile: Union[PathLike, Sequence[PathLike]] = None) -> None: self.tdosfile = tdosfile - _check_record(record) - self._read(record) + self._read() super().__init__(self.nspin) def _find_spin_files(self) -> List[str]: @@ -256,8 +211,6 @@ def _find_spin_files(self) -> List[str]: matches1 = sorted(glob.glob(str(path / "dos1.txt"))) if not matches1 and (path / "dos.txt").is_file(): matches1 = [str(path / "dos.txt")] # legacy PW nspin=1 name - if not matches1: - matches1 = _npy_files(path / "doss1") if not matches1: raise FileNotFoundError( f"No TDOS file found in directory '{path}'") @@ -285,7 +238,7 @@ def _find_spin_files(self) -> List[str]: # any other file (e.g. legacy TDOS.dat): parse as is return [str(path)] - def _read_one(self, fname: str, record: int = 1) -> Dict[str, Any]: + def _read_one(self, fname: str) -> Dict[str, Any]: """Read one TDOS file; the returned keys map 1:1 to the file columns. Returns a dict with ``energy`` of shape (npoints, 1) and dos/dos_int/ @@ -293,22 +246,6 @@ def _read_one(self, fname: str, record: int = 1) -> Dict[str, Any]: channels stored in this file (None where the column is absent, e.g. the legacy 2/3-column formats carry no smeared DOS). """ - if Path(fname).suffix == ".npy": - fields = ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int") - rows = _read_npy_record(fname, record, "TDOS", (*fields, "spin_channel")) - for key in fields: - if rows[key].ndim != 1 or rows[key].dtype.kind != "f" or rows[key].dtype.itemsize != 8: - raise ValueError(f"Invalid TDOS column {key} in {fname}") - spin = rows["spin_channel"][0] - if spin not in (1, 2) or not np.all(rows["spin_channel"] == spin): - raise ValueError(f"Invalid TDOS spin channel in {fname}") - data = {key: rows[key][:, None] for key in fields} - data["energy"] = data.pop("energy_eV") - data["spin_channel"] = spin - data["ionic_step"] = rows["ionic_step"][0] - return data - if record != 1: - raise ValueError("TDOS record selection requires a .npy file") rows = [] with open(fname) as f: for line in f: @@ -347,14 +284,9 @@ def _read_one(self, fname: str, record: int = 1) -> Dict[str, Any]: raise ValueError(f"Unrecognized TDOS format: {ncols} columns") return out - def _read(self, record=1) -> None: + def _read(self) -> None: spin_files = self._find_spin_files() - parsed = [self._read_one(f, record) for f in spin_files] - if len(parsed) == 2 and all("spin_channel" in data for data in parsed): - parsed.sort(key=lambda data: data["spin_channel"]) - if ([data["spin_channel"] for data in parsed] != [1, 2] - or parsed[0]["ionic_step"] != parsed[1]["ionic_step"]): - raise ValueError("Mismatched TDOS spin channels or ionic steps") + parsed = [self._read_one(f) for f in spin_files] keys = ("dos", "dos_int", "dos_smear", "dos_smear_int") self.energy = parsed[0]["energy"] @@ -418,10 +350,7 @@ def plot(self, fig: Figure, ax: Union[axes.Axes, Sequence[axes.Axes]], efermi: f class PDOS(DOS): - """Parse ABACUS text or NumPy projected DOS. - - A NumPy file stores one structured array per output. The one-based - ``record`` argument selects an array when several were appended. + """Parse projected DOS from ABACUS text files or a single pdos.npy. The text format (one file per spin channel) looks like:: @@ -451,10 +380,9 @@ def _col_to_m(l: int, col: int) -> int: return 0 return (col + 1) // 2 if col % 2 == 1 else -(col // 2) - def __init__(self, pdosfile: PathLike = None, record: int = 1) -> None: + def __init__(self, pdosfile: PathLike = None) -> None: self.pdosfile = pdosfile - _check_record(record) - self._read(record) + self._read() super().__init__(self.nspin) def _find_spin_files(self) -> List[str]: @@ -463,8 +391,6 @@ def _find_spin_files(self) -> List[str]: Returns a list with one (nspin=1) or two (nspin=2) file paths. """ path = Path(self.pdosfile) - if path.suffix == ".npy" and not path.is_dir(): - return [str(path)] if path.is_file(): name = path.name if name.startswith("pdoss"): @@ -493,9 +419,8 @@ def _find_spin_files(self) -> List[str]: if matches: candidates.append(matches[0]) elif spin == 1: - binary = _npy_files(Path(prefix)) - if binary: - return [str(binary[0])] + if path.is_dir() and (path / "pdos.npy").is_file(): + return [str(path / "pdos.npy")] raise FileNotFoundError( f"No text PDOS file matching '{pattern}'") return candidates @@ -568,27 +493,24 @@ def _read_one(self, fname: str): return energy, orbitals - def _read_npy(self, path, record): - fields = {"nspin", "atom_index", "species", "l", "m", "energy_min_eV", "energy_step_eV", "pdos"} - rows = _read_npy_record(path, record, "PDOS", fields) - first = rows[0] + def _read_npy(self, path): + rows = np.load(path, mmap_mode="r", allow_pickle=False) + fields = {"nspin", "atom_index", "l", "m", "species", "energy_min_eV", "energy_step_eV", "pdos"} + if rows.ndim != 1 or not rows.size or not fields.issubset(rows.dtype.names or ()): + raise ValueError(f"Expected an ABACUS PDOS array in {path}") + self.nspin = int(rows["nspin"][0]) values = rows["pdos"] - if (first["nspin"] not in (1, 2, 4) or values.ndim != 3 or values.shape[2] == 0 - or values.shape[1] != (2 if first["nspin"] == 2 else 1) - or values.dtype.kind != "f" or values.dtype.itemsize != 8): - raise ValueError(f"Invalid PDOS dimensions in {path}") - for field in ("nspin", "ionic_step", "energy_min_eV", "energy_step_eV"): - if not np.all(rows[field] == first[field]): - raise ValueError(f"Inconsistent {field} in {path}") - self.nspin = values.shape[1] - self.energy = (first["energy_min_eV"] + np.arange(values.shape[2]) * first["energy_step_eV"])[:, None] + if self.nspin not in (1, 2, 4) or values.ndim != 3 or values.shape[1] != (2 if self.nspin == 2 else 1): + raise ValueError(f"Invalid PDOS spin dimensions in {path}") + grid = rows["energy_min_eV"][0] + np.arange(values.shape[2]) * rows["energy_step_eV"][0] + self.energy = grid[:, None] self.orbitals = [ - dict(index=i + 1, atom_index=int(row["atom_index"]), species=row["species"].decode("utf-8"), - l=int(row["l"]), m=int(row["m"]), data=values[i].T) - for i, row in enumerate(rows) + dict(index=i, atom_index=int(row["atom_index"]), species=row["species"].decode(), + l=int(row["l"]), m=int(row["m"]), data=row["pdos"].T) + for i, row in enumerate(rows, 1) ] - def _read(self, record): + def _read(self): """Read partial DOS data file(s) :params pdosfile: path of a text PDOS file, a spin-up file of a @@ -597,10 +519,8 @@ def _read(self, record): """ spin_files = self._find_spin_files() if Path(spin_files[0]).suffix == ".npy": - self._read_npy(spin_files[0], record) + self._read_npy(spin_files[0]) return - if record != 1: - raise ValueError("PDOS record selection requires a .npy file") self.nspin = len(spin_files) energy, orbitals_up = self._read_one(spin_files[0]) diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/main.py b/tools/02_postprocessing/plot-tools/abacus_plot/main.py index b01a6aa3c9e..859a49094e2 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/main.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/main.py @@ -71,7 +71,7 @@ def show_cmdline(cls, args): fig, ax = plt.subplots(figsize=figsize) prec = text.pop("prec", 0.01) smearing = text.pop("smearing", True) - tdos = TDOS(tdosfile, record=text.pop("record", 1)) + tdos = TDOS(tdosfile) tdos.plot(fig, ax, efermi=efermi, shift=shift, energy_range=energy_range, dos_range=dos_range, prec=prec, smearing=smearing, **text) dpi = text.pop("dpi", 400) @@ -80,7 +80,6 @@ def show_cmdline(cls, args): if args.dos and args.projected: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') - record = text.pop("record", 1) efermi = text.pop("efermi", 0.0) energy_range = text.pop("energy_range", []) dos_range = text.pop("dos_range", []) @@ -89,8 +88,6 @@ def show_cmdline(cls, args): atom_index = key2int(text.pop("atom_index", None)) species = text.pop("species", None) figsize = text.pop("figsize", (12, 10)) - if not (index or atom_index or species): - fig, ax = plt.subplots(figsize=figsize) if index: fig, ax = plt.subplots( len(index), 1, sharex=True, figsize=figsize) @@ -104,7 +101,7 @@ def show_cmdline(cls, args): len(species) if isinstance(species, dict) else 1, 1, sharex=True, figsize=figsize) prec = text.pop("prec", 0.01) - pdos = PDOS(pdosfile, record=record) + pdos = PDOS(pdosfile) pdos.plot(fig=fig, ax=ax, index=index, atom_index=atom_index, species=species, efermi=efermi, shift=shift, energy_range=energy_range, dos_range=dos_range, prec=prec, **text) dpi = text.pop("dpi", 400) @@ -113,12 +110,11 @@ def show_cmdline(cls, args): if args.dos and args.out: text = read_json(args.file) pdosfile = text.pop("pdosfile", '') - record = text.pop("record", 1) index = key2int(text.pop("index", None)) atom_index = key2int(text.pop("atom_index", None)) species = text.pop("species", None) outdir = text.pop("outdir", './') - pdos = PDOS(pdosfile, record=record) + pdos = PDOS(pdosfile) pdos.write(index=index, atom_index=atom_index, species=species, outdir=outdir) def main(): diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos.py b/tools/02_postprocessing/plot-tools/tests/test_dos.py index db1107c7cc1..bd8cbfc954e 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_dos.py +++ b/tools/02_postprocessing/plot-tools/tests/test_dos.py @@ -11,7 +11,7 @@ import matplotlib.pyplot as plt import numpy as np -from abacus_plot.dos import DOSPlot, TDOS +from abacus_plot.dos import DOSPlot, PDOS, TDOS class TDOSTest(unittest.TestCase): @@ -126,5 +126,24 @@ def test_plain_axes_and_missing_subplot_apis(self): self.assertEqual(ax.get_xlabel(), "Energy(eV)") +class PDOSNumPyTest(unittest.TestCase): + def test_spin_channels_and_energy_grid(self): + values = np.array([[1., 2., 3.], [4., 5., 6.]]) + dtype = [("nspin", "i4"), ("atom_index", "i4"), ("l", "i4"), ("m", "i4"), + ("energy_min_eV", "f8"), ("energy_step_eV", "f8"), ("species", "S8"), + ("pdos", "f8", values.shape)] + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "pdos.npy" + np.save(path, np.array([(2, 3, 1, -1, -1., .5, b"Fe", values)], dtype=dtype)) + for source in (path, path.parent): + result = PDOS(source) + self.assertEqual(result.nspin, 2) + np.testing.assert_array_equal(result.energy[:, 0], [-1., -.5, 0.]) + orbital, = result.orbitals + self.assertEqual((orbital["index"], orbital["atom_index"], orbital["species"], + orbital["l"], orbital["m"]), (1, 3, "Fe", 1, -1)) + np.testing.assert_array_equal(orbital["data"], values.T) + + if __name__ == "__main__": unittest.main() diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos_npy.py b/tools/02_postprocessing/plot-tools/tests/test_dos_npy.py deleted file mode 100644 index 4ae2d858a64..00000000000 --- a/tools/02_postprocessing/plot-tools/tests/test_dos_npy.py +++ /dev/null @@ -1,112 +0,0 @@ -import tempfile -import unittest -from pathlib import Path - -import matplotlib -matplotlib.use("Agg") -import matplotlib.pyplot as plt -import numpy as np - -from abacus_plot.dos import PDOS, TDOS - - -def frame(n, fields, step): - rows = np.zeros(n, dtype=[("record_bytes", " Date: Thu, 19 Nov 2026 21:56:10 +0800 Subject: [PATCH 07/15] Handle ambiguous PDOS directories and test native NumPy output --- docs/advanced/elec_properties/dos.md | 5 +- .../module_dos/unittests/CMakeLists.txt | 9 ++++ .../module_dos/unittests/test_pdos_npy.py | 47 +++++++++++++++++++ .../unittests/test_write_pdos_text.cpp | 26 +++++----- .../source_io/module_dos/write_pdos_text.cpp | 6 ++- .../unittests/test_read_input_parallel.cpp | 40 ++++++++++++++++ .../plot-tools/abacus_plot/dos.py | 6 ++- .../plot-tools/tests/test_dos.py | 7 +++ 8 files changed, 129 insertions(+), 17 deletions(-) create mode 100644 source/source_io/module_dos/unittests/test_pdos_npy.py diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 2fc50c978d0..fa367b75a71 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -100,8 +100,9 @@ For nspin=2, two files are written (pdoss1* and pdoss2*), one per spin channel. For a single-point LCAO SCF or NSCF calculation, set `out_dos 1` and `pdos_format npy` to write `pdos.npy`. The default is `pdos_format text`. -Total DOS still goes to `doss{spin}.txt`. Set `pdosfile` to the path of -`pdos.npy` in the `abacus-plot -d -p` configuration, or open it with NumPy: +Total DOS still goes to `doss{spin}.txt`. If the output directory contains +both formats, set `pdosfile` to the desired file in the `abacus-plot -d -p` +configuration. You can also open the binary file with NumPy: ```python import numpy as np diff --git a/source/source_io/module_dos/unittests/CMakeLists.txt b/source/source_io/module_dos/unittests/CMakeLists.txt index 525ebce5aab..614e9060ba1 100644 --- a/source/source_io/module_dos/unittests/CMakeLists.txt +++ b/source/source_io/module_dos/unittests/CMakeLists.txt @@ -36,4 +36,13 @@ if(ENABLE_MPI) ../../../source_cell/magnetism.cpp ../../../source_cell/test/support/mock_unitcell.cpp) + find_package(Python3 QUIET COMPONENTS Interpreter) + if(Python3_Interpreter_FOUND) + add_test( + NAME MODULE_DOS_pdos_npy_roundtrip + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/test_pdos_npy.py" + "$") + set_tests_properties(MODULE_DOS_pdos_npy_roundtrip PROPERTIES SKIP_RETURN_CODE 77) + endif() + endif() diff --git a/source/source_io/module_dos/unittests/test_pdos_npy.py b/source/source_io/module_dos/unittests/test_pdos_npy.py new file mode 100644 index 00000000000..6c3e1e63c11 --- /dev/null +++ b/source/source_io/module_dos/unittests/test_pdos_npy.py @@ -0,0 +1,47 @@ +"""Read the spectrum from the native PDOS writer with NumPy.""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main(writer_test): + try: + import numpy as np + except ModuleNotFoundError as exc: + if exc.name != "numpy": + raise + print("NumPy is required for the PDOS round-trip test") + return 77 + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "pdos.npy" + subprocess.run([writer_test, "--gtest_filter=WritePdosTextTest.NpySumsZetasAndSpinorsBeforeThreshold"], + env=dict(os.environ, ABACUS_TEST_PDOS_NPY=str(path)), check=True) + with path.open("rb") as stream: + rows = np.load(stream, allow_pickle=False) + assert not stream.read(1), "NPY record count leaves trailing data" + + assert rows.shape == (4,) + assert rows.dtype.names == ("nspin", "atom_index", "l", "m", "energy_min_eV", "energy_step_eV", "species", "pdos") + for field in ("nspin", "atom_index", "l", "m"): + assert rows[field].dtype == np.int32 + for field in ("energy_min_eV", "energy_step_eV", "pdos"): + assert rows[field].dtype == np.float64 + np.testing.assert_array_equal(rows["nspin"], 4) + np.testing.assert_array_equal(rows["atom_index"], 1) + np.testing.assert_array_equal(rows["species"], b"Si") + np.testing.assert_array_equal(rows["l"], [0, 1, 1, 1]) + np.testing.assert_array_equal(rows["m"], [0, 0, 1, -1]) + np.testing.assert_array_equal(rows["energy_min_eV"], -1.0) + np.testing.assert_array_equal(rows["energy_step_eV"], 0.5) + assert rows["pdos"].shape == (4, 1, 3) + expected = [[3., 0., 0.], [26., 1.2e-6, 0.], [34., 1.2e-6, 0.], [42., 1.2e-6, 0.]] + np.testing.assert_allclose(rows["pdos"][:, 0], expected, rtol=1e-15, atol=0.) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1])) diff --git a/source/source_io/module_dos/unittests/test_write_pdos_text.cpp b/source/source_io/module_dos/unittests/test_write_pdos_text.cpp index 5d7b09cb0cc..59a77594f5c 100644 --- a/source/source_io/module_dos/unittests/test_write_pdos_text.cpp +++ b/source/source_io/module_dos/unittests/test_write_pdos_text.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -182,31 +183,34 @@ TEST_F(WritePdosTextTest, SpinPolarized) TEST_F(WritePdosTextTest, NpySumsZetasAndSpinorsBeforeThreshold) { Atom& atom = ucell->atoms[0]; - atom.nwl = 0; - atom.nw = 2; - atom.l_nchi = {2}; - atom.iw2l = {0, 0}; - atom.iw2m = {0, 0}; + atom.nwl = 1; + atom.nw = 7; + atom.l_nchi = {1, 2}; + atom.iw2l = {0, 1, 1, 1, 1, 1, 1}; + atom.iw2m = {0, 0, 1, 2, 0, 1, 2}; ucell->set_iat2iwt_for_test({0}, 2); std::vector pdos(1); - pdos[0].create(4, 3, true); - for (int iw = 0; iw < 4; ++iw) + const int nrows = 2 * atom.nw; + pdos[0].create(nrows, 3, true); + for (int iw = 0; iw < nrows; ++iw) { pdos[0](iw, 0) = iw + 1; pdos[0](iw, 1) = 0.3e-6; pdos[0](iw, 2) = 0.1e-6; } - const std::string path = testing::TempDir() + "abacus_pdos_spinor.npy"; + const char* fixture_path = std::getenv("ABACUS_TEST_PDOS_NPY"); + const std::string path = fixture_path ? fixture_path : testing::TempDir() + "abacus_pdos_spinor.npy"; ModuleIO::write_pdos_npy(*ucell, pdos, 4, -1.0, 0.5, path); std::ifstream file(path, std::ios::binary); - // The single (atom, l, m) record ends in a spin-summed binary64 spectrum. + // The last p channel combines both zetas and both spinor components. double spectrum[3]; file.seekg(-static_cast(sizeof(spectrum)), std::ios::end); ASSERT_TRUE(file.read(reinterpret_cast(spectrum), sizeof(spectrum))); - EXPECT_DOUBLE_EQ(spectrum[0], 10.0); + EXPECT_DOUBLE_EQ(spectrum[0], 42.0); EXPECT_DOUBLE_EQ(spectrum[1], 1.2e-6); EXPECT_DOUBLE_EQ(spectrum[2], 0.0); - std::remove(path.c_str()); + file.close(); + if (!fixture_path) { std::remove(path.c_str()); } } // --------------------------------------------------------------------------- diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index f1677b70bd3..fb510b01398 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -103,7 +103,8 @@ void ModuleIO::write_pdos_text( { const int it = ucell.iat2it[iat]; const bool spinor = nspin == 4; - const auto channels = atom_pdos(ucell, iat, pdos + is, 1, spinor); + const auto* spin_pdos = pdos + is; + const auto channels = atom_pdos(ucell, iat, spin_pdos, 1, spinor); for (int n = 0; n < npoints; ++n) { @@ -183,7 +184,8 @@ void ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector(attrs), sizeof(attrs)); out.write(reinterpret_cast(grid), sizeof(grid)); out.write(label.data(), label.size()); - out.write(reinterpret_cast(channel.second.data()), channel.second.size() * sizeof(double)); + const auto spectrum_bytes = channel.second.size() * sizeof(double); + out.write(reinterpret_cast(channel.second.data()), spectrum_bytes); } } out.close(); diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index a0d83c31c1f..adfb4ca9a49 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -68,6 +68,7 @@ TEST_F(InputParaTest, ParaRead) EXPECT_EQ(param.inp.npart_sto, 1); EXPECT_FALSE(param.inp.cal_cond); EXPECT_EQ(param.inp.dos_nche, 100); + EXPECT_EQ(param.inp.pdos_format, "text"); EXPECT_DOUBLE_EQ(param.inp.cond_che_thr, 1e-8); EXPECT_DOUBLE_EQ(param.inp.cond_dw, 0.1); EXPECT_DOUBLE_EQ(param.inp.cond_wcut, 10); @@ -778,6 +779,45 @@ TEST_F(InputParaTest, RemovedElpaZSolverIsRejected) EXPECT_EXIT(item.check_value(item, param), testing::ExitedWithCode(1), ""); } +TEST_F(InputParaTest, PdosFormat) +{ + ModuleIO::ReadInput reader(0); + const auto& entries = reader.get_input_lists(); + std::map items(entries.begin(), entries.end()); + Parameter param; + auto set = [&](const std::string& key, const std::string& value) { + auto& item = items.at(key); + item.str_values = {value}; + item.read_value(item, param); + }; + const auto& format = items.at("pdos_format"); + EXPECT_FALSE(format.domain.validate_explicit("pdos_format", {"invalid"}).empty()); + for (const auto* token : {"text", "npy"}) + { + EXPECT_TRUE(format.domain.validate_explicit("pdos_format", {token}).empty()); + } + + set("basis_type", "lcao"); + set("pdos_format", "npy"); + ASSERT_EQ(param.inp.pdos_format, "npy"); + set("out_dos", "1"); + for (const auto* calculation : {"scf", "nscf"}) + { + set("calculation", calculation); + format.check_value(format, param); + } + set("calculation", "md"); + EXPECT_EXIT(format.check_value(format, param), testing::ExitedWithCode(1), ""); + set("calculation", "scf"); + set("esolver_type", "lr"); + EXPECT_EXIT(format.check_value(format, param), testing::ExitedWithCode(1), ""); + set("esolver_type", "ksdft"); + set("basis_type", "pw"); + EXPECT_EXIT(format.check_value(format, param), testing::ExitedWithCode(1), ""); + set("out_dos", "0"); + format.check_value(format, param); +} + TEST_F(InputParaTest, OpticalGaugeCanDisableSpectrum) { diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 9019276d45d..5431a83f8d2 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -391,6 +391,10 @@ def _find_spin_files(self) -> List[str]: Returns a list with one (nspin=1) or two (nspin=2) file paths. """ path = Path(self.pdosfile) + if path.is_dir() and (path / "pdos.npy").is_file(): + if any(path.glob("pdoss[12]*.txt")): + raise ValueError(f"Both text PDOS and pdos.npy found in {path}. Pass a specific PDOS file.") + return [str(path / "pdos.npy")] if path.is_file(): name = path.name if name.startswith("pdoss"): @@ -419,8 +423,6 @@ def _find_spin_files(self) -> List[str]: if matches: candidates.append(matches[0]) elif spin == 1: - if path.is_dir() and (path / "pdos.npy").is_file(): - return [str(path / "pdos.npy")] raise FileNotFoundError( f"No text PDOS file matching '{pattern}'") return candidates diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos.py b/tools/02_postprocessing/plot-tools/tests/test_dos.py index bd8cbfc954e..025ade4a463 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_dos.py +++ b/tools/02_postprocessing/plot-tools/tests/test_dos.py @@ -144,6 +144,13 @@ def test_spin_channels_and_energy_grid(self): orbital["l"], orbital["m"]), (1, 3, "Fe", 1, -1)) np.testing.assert_array_equal(orbital["data"], values.T) + text = path.parent / "pdoss1.txt" + text.write_text("0.0 1 Fe 9.0\n") + with self.assertRaisesRegex(ValueError, "Pass a specific PDOS file"): + PDOS(path.parent) + np.testing.assert_array_equal(PDOS(path).orbitals[0]["data"], values.T) + self.assertEqual(PDOS(text).orbitals[0]["data"].item(), 9.) + if __name__ == "__main__": unittest.main() From 3f17fd770af1df3c26c941cbf2fb8b6cff9e1442 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:40:03 +0800 Subject: [PATCH 08/15] Exercise spin-polarized NPY PDOS in Autotest and validate record metadata --- tests/03_NAO_multik/scf_out_dos_spin2/INPUT | 4 +++ .../scf_out_dos_spin2/pdos.ref.json | 12 +++++++ .../validation_tools/check_pdos_npy.py | 36 +++++++++++++++++++ .../integrate/validation_tools/props_basic.sh | 3 ++ .../plot-tools/abacus_plot/dos.py | 9 ++++- .../plot-tools/tests/test_dos.py | 28 +++++++++++++-- 6 files changed, 89 insertions(+), 3 deletions(-) create mode 100644 tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json create mode 100644 tests/integrate/validation_tools/check_pdos_npy.py diff --git a/tests/03_NAO_multik/scf_out_dos_spin2/INPUT b/tests/03_NAO_multik/scf_out_dos_spin2/INPUT index acebda90702..27f7ce18a82 100644 --- a/tests/03_NAO_multik/scf_out_dos_spin2/INPUT +++ b/tests/03_NAO_multik/scf_out_dos_spin2/INPUT @@ -28,3 +28,7 @@ mixing_beta 0.4 mixing_beta_mag 0.4 out_dos 1 +pdos_format npy +dos_emin_ev -60 +dos_emax_ev 30 +dos_edelta_ev 0.0625 diff --git a/tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json b/tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json new file mode 100644 index 00000000000..0884042332b --- /dev/null +++ b/tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json @@ -0,0 +1,12 @@ +{ + "records": 32, + "nspin": 2, + "npoints": 1441, + "energy_min_eV": -60.0, + "energy_step_eV": 0.0625, + "samples": [ + {"atom_index": 1, "species": "Fe", "l": 0, "m": 0, "energy_index": 137, "pdos": [0.406277, 2.817491]}, + {"atom_index": 2, "species": "Fe", "l": 1, "m": -1, "energy_index": 381, "pdos": [0.025894, 0.000000]}, + {"atom_index": 2, "species": "Fe", "l": 2, "m": 0, "energy_index": 1261, "pdos": [0.370396, 1.864192]} + ] +} diff --git a/tests/integrate/validation_tools/check_pdos_npy.py b/tests/integrate/validation_tools/check_pdos_npy.py new file mode 100644 index 00000000000..faabd7b0117 --- /dev/null +++ b/tests/integrate/validation_tools/check_pdos_npy.py @@ -0,0 +1,36 @@ +"""Check an ABACUS PDOS array against selected channels from reference text output.""" + +import json +import sys + +import numpy as np + + +def check_pdos(path, reference): + with open(reference) as stream: + ref = json.load(stream) + rows = np.load(path, mmap_mode="r", allow_pickle=False) + spins = 2 if ref["nspin"] == 2 else 1 + species_dtype = rows.dtype["species"] + assert species_dtype.kind == "S", species_dtype + expected_dtype = np.dtype([ + ("nspin", "i4"), ("atom_index", "i4"), ("l", "i4"), ("m", "i4"), + ("energy_min_eV", "f8"), ("energy_step_eV", "f8"), ("species", species_dtype), + ("pdos", "f8", (spins, ref["npoints"])), + ]) + np.testing.assert_equal(rows.dtype, expected_dtype) + np.testing.assert_equal(rows.shape, (ref["records"],)) + for field in ("nspin", "energy_min_eV", "energy_step_eV"): + np.testing.assert_array_equal(rows[field], ref[field], err_msg=field) + + for sample in ref["samples"]: + match = ((rows["atom_index"] == sample["atom_index"]) + & (rows["l"] == sample["l"]) & (rows["m"] == sample["m"])) + orbital, = rows[match] + np.testing.assert_equal(orbital["species"], sample["species"].encode()) + values = orbital["pdos"][:, sample["energy_index"]] + np.testing.assert_allclose(values, sample["pdos"], rtol=1e-3, atol=5e-5, err_msg=str(sample)) + + +if __name__ == "__main__": + check_pdos(*sys.argv[1:]) diff --git a/tests/integrate/validation_tools/props_basic.sh b/tests/integrate/validation_tools/props_basic.sh index 25529af50cc..dc539c8ca61 100644 --- a/tests/integrate/validation_tools/props_basic.sh +++ b/tests/integrate/validation_tools/props_basic.sh @@ -123,6 +123,9 @@ run_basic_props() { total_dos=$(cat OUT.autotest/dos*.txt | awk 'END {print}' | awk '{print $3}') echo "totaldosref $total_dos" >>$props_result_file fi + if [ -f pdos.ref.json ]; then + python3 "$PROPS_TOOLS_DIR/check_pdos_npy.py" OUT.autotest/pdos.npy pdos.ref.json + fi #------------------------------- # Onsager coefficiency diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 5431a83f8d2..5de357f8f9b 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -500,11 +500,18 @@ def _read_npy(self, path): fields = {"nspin", "atom_index", "l", "m", "species", "energy_min_eV", "energy_step_eV", "pdos"} if rows.ndim != 1 or not rows.size or not fields.issubset(rows.dtype.names or ()): raise ValueError(f"Expected an ABACUS PDOS array in {path}") + for field in ("nspin", "energy_min_eV", "energy_step_eV"): + if not np.all(rows[field] == rows[field][0]): + raise ValueError(f"Inconsistent {field} across PDOS records in {path}") self.nspin = int(rows["nspin"][0]) values = rows["pdos"] if self.nspin not in (1, 2, 4) or values.ndim != 3 or values.shape[1] != (2 if self.nspin == 2 else 1): raise ValueError(f"Invalid PDOS spin dimensions in {path}") - grid = rows["energy_min_eV"][0] + np.arange(values.shape[2]) * rows["energy_step_eV"][0] + emin = rows["energy_min_eV"][0] + step = rows["energy_step_eV"][0] + if not np.isfinite(emin) or not np.isfinite(step) or step <= 0: + raise ValueError(f"Invalid PDOS energy grid in {path}: expected finite energies and a positive step") + grid = emin + np.arange(values.shape[2]) * step self.energy = grid[:, None] self.orbitals = [ dict(index=i, atom_index=int(row["atom_index"]), species=row["species"].decode(), diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos.py b/tools/02_postprocessing/plot-tools/tests/test_dos.py index 025ade4a463..4e3514c92d2 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_dos.py +++ b/tools/02_postprocessing/plot-tools/tests/test_dos.py @@ -127,14 +127,20 @@ def test_plain_axes_and_missing_subplot_apis(self): class PDOSNumPyTest(unittest.TestCase): - def test_spin_channels_and_energy_grid(self): + @staticmethod + def spin_record(): values = np.array([[1., 2., 3.], [4., 5., 6.]]) dtype = [("nspin", "i4"), ("atom_index", "i4"), ("l", "i4"), ("m", "i4"), ("energy_min_eV", "f8"), ("energy_step_eV", "f8"), ("species", "S8"), ("pdos", "f8", values.shape)] + return np.array([(2, 3, 1, -1, -1., .5, b"Fe", values)], dtype=dtype) + + def test_spin_channels_and_energy_grid(self): + record = self.spin_record() + values = record["pdos"][0] with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "pdos.npy" - np.save(path, np.array([(2, 3, 1, -1, -1., .5, b"Fe", values)], dtype=dtype)) + np.save(path, record) for source in (path, path.parent): result = PDOS(source) self.assertEqual(result.nspin, 2) @@ -151,6 +157,24 @@ def test_spin_channels_and_energy_grid(self): np.testing.assert_array_equal(PDOS(path).orbitals[0]["data"], values.T) self.assertEqual(PDOS(text).orbitals[0]["data"].item(), 9.) + def test_invalid_record_metadata(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "pdos.npy" + for field, values, message in ( + ("nspin", [2, 1], "nspin"), + ("energy_min_eV", [-1., 0.], "energy_min_eV"), + ("energy_step_eV", [.5, .25], "energy_step_eV"), + ("energy_step_eV", [0., 0.], "positive step"), + ("energy_step_eV", [-.5, -.5], "positive step"), + ("energy_step_eV", [np.inf, np.inf], "finite"), + ): + with self.subTest(field=field, values=values): + rows = np.repeat(self.spin_record(), 2) + rows[field] = values + np.save(path, rows) + with self.assertRaisesRegex(ValueError, message): + PDOS(path) + if __name__ == "__main__": unittest.main() From 1fa2f23db875055c3c7521a20f932b3178d8bf61 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:43:49 +0800 Subject: [PATCH 09/15] Propagate PDOS validation failures to Autotest --- .../integrate/validation_tools/props_basic.sh | 2 +- .../validation_tools/test_props_basic.py | 26 ++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tests/integrate/validation_tools/props_basic.sh b/tests/integrate/validation_tools/props_basic.sh index dc539c8ca61..a654e808bc7 100644 --- a/tests/integrate/validation_tools/props_basic.sh +++ b/tests/integrate/validation_tools/props_basic.sh @@ -124,7 +124,7 @@ run_basic_props() { echo "totaldosref $total_dos" >>$props_result_file fi if [ -f pdos.ref.json ]; then - python3 "$PROPS_TOOLS_DIR/check_pdos_npy.py" OUT.autotest/pdos.npy pdos.ref.json + python3 "$PROPS_TOOLS_DIR/check_pdos_npy.py" OUT.autotest/pdos.npy pdos.ref.json || return 1 fi #------------------------------- diff --git a/tests/integrate/validation_tools/test_props_basic.py b/tests/integrate/validation_tools/test_props_basic.py index 4014869afe3..4f93681adf2 100644 --- a/tests/integrate/validation_tools/test_props_basic.py +++ b/tests/integrate/validation_tools/test_props_basic.py @@ -1,5 +1,6 @@ -"""Regression checks for MD force collection and its shell entry points.""" +"""Regression checks for basic property collection and its shell entry points.""" +from importlib.util import find_spec import os from pathlib import Path import shutil @@ -123,5 +124,28 @@ def test_reference_generation_preserves_existing_reference(self): self.assertFalse((case / "result.ref.new").exists()) +class PdosCollectionTest(unittest.TestCase): + @unittest.skipUnless(find_spec("numpy"), "PDOS validation requires NumPy") + def test_missing_or_corrupt_pdos_fails_through_shell_entry(self): + fixture = INTEGRATE.parent / "03_NAO_multik/scf_out_dos_spin2" + with tempfile.TemporaryDirectory() as scratch: + case = Path(scratch) + shutil.copy(fixture / "INPUT", case) + shutil.copy(fixture / "pdos.ref.json", case) + out = case / "OUT.autotest" + out.mkdir() + (out / "running_scf.log").write_text(" TOTAL ATOM NUMBER = 2\nETOT_ -1.0\n", encoding="utf-8") + (out / "doss1.txt").write_text("0.0 0.0 20.0\n", encoding="utf-8") + + for contents, error in ((None, "FileNotFoundError"), (b"invalid NPY", "ValueError")): + with self.subTest(error=error): + if contents is not None: + (out / "pdos.npy").write_bytes(contents) + result = subprocess.run(["bash", "-e", str(TOOLS / "catch_properties.sh"), "result.out"], + cwd=case, capture_output=True, text=True) + self.assertIn(error, result.stderr) + self.assertNotEqual(result.returncode, 0, result.stderr) + + if __name__ == "__main__": unittest.main() From c31189abdca57292ba770f4a51a788dd296693e3 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:58:40 +0800 Subject: [PATCH 10/15] Select NumPy total and projected LCAO DOS with out_dos 2 --- docs/advanced/elec_properties/dos.md | 23 +++++-- .../source_io/module_ctrl/ctrl_scf_lcao.cpp | 4 +- source/source_io/module_dos/cal_dos.cpp | 28 ++++++--- source/source_io/module_dos/dos_npy_header.h | 36 +++++++++++ .../source_io/module_dos/write_dos_lcao.cpp | 27 +++++--- source/source_io/module_dos/write_dos_lcao.h | 2 +- .../source_io/module_dos/write_pdos_text.cpp | 18 +----- .../module_parameter/input_parameter.h | 1 - .../module_parameter/read_inp_out.cpp | 12 ++-- .../module_parameter/read_inp_postproc.cpp | 21 ------- .../unittests/test_read_input_parallel.cpp | 28 ++++----- tests/03_NAO_multik/scf_out_dos_spin2/INPUT | 3 +- .../{pdos.ref.json => dos.ref.json} | 4 ++ .../validation_tools/check_dos_npy.py | 62 +++++++++++++++++++ .../validation_tools/check_pdos_npy.py | 36 ----------- .../integrate/validation_tools/props_basic.sh | 7 ++- .../validation_tools/test_props_basic.py | 3 +- .../plot-tools/abacus_plot/dos.py | 34 +++++----- .../plot-tools/tests/test_dos.py | 17 +++++ 19 files changed, 222 insertions(+), 144 deletions(-) create mode 100644 source/source_io/module_dos/dos_npy_header.h rename tests/03_NAO_multik/scf_out_dos_spin2/{pdos.ref.json => dos.ref.json} (66%) create mode 100644 tests/integrate/validation_tools/check_dos_npy.py delete mode 100644 tests/integrate/validation_tools/check_pdos_npy.py diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index cf9d1f33a75..208dc02c3ca 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -98,21 +98,32 @@ The `# Ionic_Step` line is only present for geometry-optimization (istep) output For nspin=2, two files are written (pdoss1* and pdoss2*), one per spin channel. For nspin=4, the two spinor components are summed into a single file. The unit of PDOS is also `(number of states)/(eV * unitcell)`. -For a single-point LCAO SCF or NSCF calculation, set `out_dos 1` and -`pdos_format npy` to write `pdos.npy`. The default is `pdos_format text`. -Total DOS still goes to `doss{spin}.txt`. If the output directory contains -both formats, set `pdosfile` to the desired file in the `abacus-plot -d -p` -configuration. You can also open the binary file with NumPy: +### NumPy output + +For a single-point LCAO KSDFT SCF or NSCF calculation, set `out_dos 2` +to write both total and projected DOS as NumPy arrays. Use `out_dos 1` +for text output or `out_dos 0` (the default) to disable DOS output. +Older releases used `out_dos 2` to request text PDOS. + +Total DOS uses one record per energy point in `doss1.npy`, plus `doss2.npy` +for spin-polarized calculations (`nspin=2`). Its five binary64 fields are +`energy_eV`, `dos`, `dos_int`, `dos_smear` and `dos_smear_int`, in the +same order and units as the text columns. Projected DOS is in `pdos.npy`. +With `out_app_flag 2`, these files are in the `DOS/` output subdirectory. +For plotting, set `tdosfile` or `pdosfile` in the `abacus-plot` config. +Use an explicit file path when the directory contains both formats. ```python import numpy as np +total = np.load("doss1.npy", mmap_mode="r") +dos_per_eV = total["dos_smear"] rows = np.load("pdos.npy", mmap_mode="r") spectrum = rows["pdos"][0] # (spin channel, energy point), in 1/eV energy_eV = rows["energy_min_eV"][0] + np.arange(spectrum.shape[1]) * rows["energy_step_eV"][0] ``` -Each row identifies one channel by `atom_index` (one-based), `species`, `l` +Each PDOS row identifies one channel by `atom_index` (one-based), `species`, `l` and signed `m`. `nspin` is the input spin mode. Modes 1 and 4 store one spectrum per row, and mode 2 stores spin-up and spin-down. The array uses binary64 and the same zeta sums and zero threshold as text. diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index f9bf78974f8..6ee9724a471 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -174,7 +174,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, const std::string global_dos_dir = PARAM.globalv.global_dos_dir; // Mode-2 DOS/ subdirectory is created lazily at write time. ModuleBase::ensure_directory(global_dos_dir); - const bool pdos_npy = inp.pdos_format == "npy"; + const bool dos_npy = inp.out_dos == 2; ModuleIO::write_dos_lcao(psi, p_hamilt, pv, @@ -187,7 +187,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, - pdos_npy, + dos_npy, out_app_flag, istep, inp.nspin, diff --git a/source/source_io/module_dos/cal_dos.cpp b/source/source_io/module_dos/cal_dos.cpp index 9dd73cd2582..b3fb4191516 100644 --- a/source/source_io/module_dos/cal_dos.cpp +++ b/source/source_io/module_dos/cal_dos.cpp @@ -1,4 +1,5 @@ #include "cal_dos.h" +#include "dos_npy_header.h" #include "source_base/constants.h" #include "source_base/global_function.h" @@ -115,8 +116,9 @@ bool ModuleIO::cal_dos(const int& is, // index for spin ModuleBase::TITLE("ModuleIO", "cal_dos"); std::ofstream ofs_dos; - - if (GlobalV::MY_RANK == 0) + const bool npy = fn.size() >= 4 && fn.compare(fn.size() - 4, 4, ".npy") == 0; + const bool root = GlobalV::MY_RANK == 0; + if (root && !npy) { const std::string time_stamp = ModuleIO::local_timestamp(); const int istep_one_based = istep + 1; @@ -155,7 +157,13 @@ bool ModuleIO::cal_dos(const int& is, // index for spin ModuleBase::WARNING("ModuleIO::cal_dos", "npoints <= 0"); return false; } - if (GlobalV::MY_RANK == 0) + if (root && npy) + { + ofs_dos.open(fn, std::ios::binary | std::ios::trunc); + write_dos_npy_header(ofs_dos, "('energy_eV','=f8'),('dos','=f8'),('dos_int','=f8')," + "('dos_smear','=f8'),('dos_smear_int','=f8')", npoints); + } + else if (root) { ofs_dos << npoints << " # number of points" << std::endl; ofs_dos << std::fixed << std::setprecision(6); @@ -222,7 +230,7 @@ bool ModuleIO::cal_dos(const int& is, // index for spin double sum2 = 0.0; const double dos_thr = 1.0e-12; - if (GlobalV::MY_RANK == 0) + if (root) { for (int n = 0; n < npoints; ++n) { @@ -236,21 +244,23 @@ bool ModuleIO::cal_dos(const int& is, // index for spin } sum2 += dos_smear[n] * de_ev; + if (npy) + { + const double row[] = {ene[n], dos[n], sum_elec[n], dos_smear[n], sum2}; + ofs_dos.write(reinterpret_cast(row), sizeof(row)); + continue; + } ofs_dos << std::setw(13) << ene[n] << " " << std::setw(12) << dos[n] << " " << std::setw(12) << sum_elec[n] << " " << std::setw(14) << dos_smear[n] << " " << std::setw(14) << sum2 << std::endl; } - } - - if (GlobalV::MY_RANK == 0) - { ofs_dos.close(); } ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Number of bands", nbands); ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Total electronic states from DOS", sum); - return true; + return !npy || !root || ofs_dos.good(); } diff --git a/source/source_io/module_dos/dos_npy_header.h b/source/source_io/module_dos/dos_npy_header.h new file mode 100644 index 00000000000..6d3cbf48a0c --- /dev/null +++ b/source/source_io/module_dos/dos_npy_header.h @@ -0,0 +1,36 @@ +#ifndef MODULE_IO_DOS_NPY_HEADER_H +#define MODULE_IO_DOS_NPY_HEADER_H + +#include +#include +#include +#include +#include + +namespace ModuleIO +{ +/// Write the NPY v1 header for a one-dimensional array of structured records. +inline void write_dos_npy_header(std::ostream& out, const std::string& fields, std::size_t count) +{ + static_assert(sizeof(double) == 8 && std::numeric_limits::is_iec559, "DOS requires binary64"); + const std::uint16_t one = 1; + const char endian = *reinterpret_cast(&one) ? '<' : '>'; + std::string header = "{'descr': [" + fields + "], 'fortran_order': False, 'shape': (" + + std::to_string(count) + ",), }"; + std::replace(header.begin(), header.end(), '=', endian); + header.append((64 - (11 + header.size()) % 64) % 64, ' '); + header += '\n'; + if (header.size() > std::numeric_limits::max()) + { + out.setstate(std::ios::failbit); + return; + } + const unsigned char length[] = {static_cast(header.size()), + static_cast(header.size() >> 8)}; + out.write("\x93NUMPY\x01\x00", 8); + out.write(reinterpret_cast(length), sizeof(length)); + out.write(header.data(), header.size()); +} +} + +#endif diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 81c8ff30dae..f97d6ca1667 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -28,7 +28,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const bool pdos_npy, + const bool dos_npy, const int out_app_flag, const int istep, const int nspin, @@ -71,16 +71,15 @@ void write_dos_lcao( ss << global_out_dir << "doss" << is + 1; - // Modes 0 and 1 reuse the fixed name (mode 0 overwrites, mode 1 appends - // a new DOS block per written step); only mode 2 keeps the g{N} suffix. - if(istep>=0 && out_app_flag==2) + // Only per-step text output carries the g{N} suffix. + if (!dos_npy && istep >= 0 && out_app_flag == 2) { ss << "g" << istep+1; } - ss << ".txt"; + ss << (dos_npy ? ".npy" : ".txt"); - ModuleIO::cal_dos(is, + bool written = ModuleIO::cal_dos(is, ss.str(), dos_edelta_ev, emax, @@ -97,6 +96,14 @@ void write_dos_lcao( out_app_flag, bndpar); + if (dos_npy) + { + Parallel_Common::bcast_bool(written); + if (!written) + { + ModuleBase::WARNING_QUIT("write_dos_lcao", "Failed to write " + ss.str()); + } + } if (GlobalV::MY_RANK == 0) { ModuleIO::write_notice(ofs_running, "DOS", is, nspin, ss.str()); @@ -122,7 +129,7 @@ void write_dos_lcao( std::string error; if (GlobalV::MY_RANK == 0) { - if (pdos_npy) + if (dos_npy) { const std::string path = global_out_dir + "pdos.npy"; try @@ -141,7 +148,7 @@ void write_dos_lcao( emin, dos_edelta_ev, global_out_dir, istep, out_app_flag, ofs_running); } } - if (pdos_npy) + if (dos_npy) { Parallel_Common::bcast_string(error); if (!error.empty()) { ModuleBase::WARNING_QUIT("write_dos_lcao", error); } @@ -166,7 +173,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const bool pdos_npy, + const bool dos_npy, const int out_app_flag, const int istep, const int nspin, @@ -194,7 +201,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const bool pdos_npy, + const bool dos_npy, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 6b26a258b25..213dd6cf36a 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -28,7 +28,7 @@ namespace ModuleIO const double& dos_edelta_ev, // Delta energy const double& dos_scale, const double& bcoeff, - const bool pdos_npy, + const bool dos_npy, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index 276344e97b9..1ec222de01b 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -1,4 +1,5 @@ #include "write_pdos_text.h" +#include "dos_npy_header.h" #include "source_base/global_variable.h" #include "source_io/module_output/provenance_header.h" @@ -154,28 +155,15 @@ void ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector::is_iec559, "PDOS requires binary64"); - const std::uint16_t one = 1; - const char endian = *reinterpret_cast(&one) ? '<' : '>'; - std::string header = "{'descr': [" + fields.str() + "], 'fortran_order': False, 'shape': (" - + std::to_string(count) + ",), }"; - std::replace(header.begin(), header.end(), '=', endian); - header.append((64 - (11 + header.size()) % 64) % 64, ' '); - header += '\n'; const std::uint64_t row_bytes = 32 + width + sizeof(double) * static_cast(ne) * pdos.size(); - if (header.size() > 65535 || row_bytes > std::numeric_limits::max()) + if (row_bytes > std::numeric_limits::max()) { throw std::runtime_error("PDOS array exceeds NumPy v1 dtype limits"); } - const unsigned char length[] = {static_cast(header.size()), - static_cast(header.size() >> 8)}; std::ofstream out; out.exceptions(std::ios::badbit | std::ios::failbit); out.open(path, std::ios::binary | std::ios::trunc); - out.write("\x93NUMPY\x01\x00", 8); - out.write(reinterpret_cast(length), sizeof(length)); - out.write(header.data(), header.size()); + write_dos_npy_header(out, fields.str(), count); const double grid[] = {emin, de}; const bool spinor = nspin == 4; for (int iat = 0; iat < cell.nat; ++iat) diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index f646003d298..351c79f73c7 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -540,7 +540,6 @@ struct Input_para std::string spillage_outdir = "./"; ///< output directory for spillage // ============== #Parameters (12.Postprocess) =========================== - std::string pdos_format = "text"; ///< LCAO projected DOS file format double dos_emin_ev = -15.0; double dos_emax_ev = 15.0; double dos_edelta_ev = 0.03; diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 5b66f054b10..11867fd9277 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -381,22 +381,24 @@ Also controled by out_freq_ion and out_app_flag. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# Ionic_Step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). * nspin=1 or 4: one spin channel (`s1`). nspin=2: two channels (`s1`, `s2`). PW and LCAO use the same naming. -Note: values 2 and 3 are no longer supported. Setting out_dos to 2 or 3 will raise an error.)"; +* 2: write total DOS (`doss1.npy` and, for nspin=2, `doss2.npy`) and projected DOS (`pdos.npy`) as NumPy arrays for a single-point LCAO KSDFT SCF or NSCF calculation. Older versions used 2 to request text PDOS; use 1 for text. +* 3: Fermi surface output has been removed.)"; item.default_value = "0"; item.unit = ""; read_sync_int(input.out_dos); item.reset_value = [](const Input_Item& item, Parameter& para) { - if (para.input.calculation == "get_wf" || para.input.calculation == "get_pchg") + if (para.input.out_dos != 2 && (para.input.calculation == "get_wf" || para.input.calculation == "get_pchg")) { para.input.out_dos = 0; } }; item.check_value = [](const Input_Item& item, const Parameter& para) { - if (para.input.out_dos == 2) + const auto& in = para.input; + if (in.out_dos == 2 && (in.basis_type != "lcao" || in.esolver_type != "ksdft" + || (in.calculation != "scf" && in.calculation != "nscf"))) { ModuleBase::WARNING_QUIT("ReadInput", - "out_dos = 2 has been deprecated. " - "PDOS is now written automatically with out_dos = 1."); + "out_dos = 2 requires a single-point LCAO KSDFT SCF or NSCF calculation."); } if (para.input.out_dos == 3) { diff --git a/source/source_io/module_parameter/read_inp_postproc.cpp b/source/source_io/module_parameter/read_inp_postproc.cpp index cae218e2166..a9acc3c4d0a 100644 --- a/source/source_io/module_parameter/read_inp_postproc.cpp +++ b/source/source_io/module_parameter/read_inp_postproc.cpp @@ -9,27 +9,6 @@ void ReadInput::item_postprocess() // NOTE: The order of add_item() calls below determines the parameter order // in the generated documentation (docs/advanced/input_files/input-main.md). // Please preserve this ordering when adding new parameters. - { - Input_Item item("pdos_format"); - item.domain.set_choices({"text", "npy"}); - item.annotation = "file format for LCAO projected DOS"; - item.category = "Density of states"; - item.type = "String"; - item.description = "With out_dos = 1, select per-spin text files or a single pdos.npy " - "for projected DOS. NumPy output is available for single-point LCAO SCF and NSCF."; - item.default_value = "text"; - read_sync_string(input.pdos_format); - item.check_value = [](const Input_Item&, const Parameter& para) { - const auto& in = para.input; - if (in.out_dos && in.pdos_format == "npy" - && (in.basis_type != "lcao" || in.esolver_type != "ksdft" - || (in.calculation != "scf" && in.calculation != "nscf"))) - { - ModuleBase::WARNING_QUIT("ReadInput", "pdos_format npy requires a single-point LCAO KSDFT SCF or NSCF calculation."); - } - }; - this->add_item(item); - } { Input_Item item("dos_edelta_ev"); item.annotation = "delta energy for dos"; diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 721132cb561..faf97886536 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -68,7 +68,6 @@ TEST_F(InputParaTest, ParaRead) EXPECT_EQ(param.inp.npart_sto, 1); EXPECT_FALSE(param.inp.cal_cond); EXPECT_EQ(param.inp.dos_nche, 100); - EXPECT_EQ(param.inp.pdos_format, "text"); EXPECT_DOUBLE_EQ(param.inp.cond_che_thr, 1e-8); EXPECT_DOUBLE_EQ(param.inp.cond_dw, 0.1); EXPECT_DOUBLE_EQ(param.inp.cond_wcut, 10); @@ -779,7 +778,7 @@ TEST_F(InputParaTest, RemovedElpaZSolverIsRejected) EXPECT_EXIT(item.check_value(item, param), testing::ExitedWithCode(1), ""); } -TEST_F(InputParaTest, PdosFormat) +TEST_F(InputParaTest, OutDosNpy) { ModuleIO::ReadInput reader(0); const auto& entries = reader.get_input_lists(); @@ -790,32 +789,27 @@ TEST_F(InputParaTest, PdosFormat) item.str_values = {value}; item.read_value(item, param); }; - const auto& format = items.at("pdos_format"); - EXPECT_FALSE(format.domain.validate_explicit("pdos_format", {"invalid"}).empty()); - for (const auto* token : {"text", "npy"}) - { - EXPECT_TRUE(format.domain.validate_explicit("pdos_format", {token}).empty()); - } + const auto& output = items.at("out_dos"); + EXPECT_EQ(param.inp.out_dos, 0); set("basis_type", "lcao"); - set("pdos_format", "npy"); - ASSERT_EQ(param.inp.pdos_format, "npy"); - set("out_dos", "1"); + set("out_dos", "2"); + ASSERT_EQ(param.inp.out_dos, 2); for (const auto* calculation : {"scf", "nscf"}) { set("calculation", calculation); - format.check_value(format, param); + output.check_value(output, param); } set("calculation", "md"); - EXPECT_EXIT(format.check_value(format, param), testing::ExitedWithCode(1), ""); + EXPECT_EXIT(output.check_value(output, param), testing::ExitedWithCode(1), ""); set("calculation", "scf"); set("esolver_type", "lr"); - EXPECT_EXIT(format.check_value(format, param), testing::ExitedWithCode(1), ""); + EXPECT_EXIT(output.check_value(output, param), testing::ExitedWithCode(1), ""); set("esolver_type", "ksdft"); set("basis_type", "pw"); - EXPECT_EXIT(format.check_value(format, param), testing::ExitedWithCode(1), ""); - set("out_dos", "0"); - format.check_value(format, param); + EXPECT_EXIT(output.check_value(output, param), testing::ExitedWithCode(1), ""); + set("out_dos", "1"); + output.check_value(output, param); } diff --git a/tests/03_NAO_multik/scf_out_dos_spin2/INPUT b/tests/03_NAO_multik/scf_out_dos_spin2/INPUT index 27f7ce18a82..ad815adc1c9 100644 --- a/tests/03_NAO_multik/scf_out_dos_spin2/INPUT +++ b/tests/03_NAO_multik/scf_out_dos_spin2/INPUT @@ -27,8 +27,7 @@ mixing_type broyden mixing_beta 0.4 mixing_beta_mag 0.4 -out_dos 1 -pdos_format npy +out_dos 2 dos_emin_ev -60 dos_emax_ev 30 dos_edelta_ev 0.0625 diff --git a/tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json b/tests/03_NAO_multik/scf_out_dos_spin2/dos.ref.json similarity index 66% rename from tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json rename to tests/03_NAO_multik/scf_out_dos_spin2/dos.ref.json index 0884042332b..4db9ba6f0f8 100644 --- a/tests/03_NAO_multik/scf_out_dos_spin2/pdos.ref.json +++ b/tests/03_NAO_multik/scf_out_dos_spin2/dos.ref.json @@ -4,6 +4,10 @@ "npoints": 1441, "energy_min_eV": -60.0, "energy_step_eV": 0.0625, + "total_samples": [ + {"energy_index": 381, "spins": [[2.0, 7.5, 15.127818, 6.624421], [0.0, 2.0, 0.0, 2.0]]}, + {"energy_index": 1261, "spins": [[0.0, 19.0, 8.825885, 18.832640], [0.5, 17.0, 5.439418, 16.741209]]} + ], "samples": [ {"atom_index": 1, "species": "Fe", "l": 0, "m": 0, "energy_index": 137, "pdos": [0.406277, 2.817491]}, {"atom_index": 2, "species": "Fe", "l": 1, "m": -1, "energy_index": 381, "pdos": [0.025894, 0.000000]}, diff --git a/tests/integrate/validation_tools/check_dos_npy.py b/tests/integrate/validation_tools/check_dos_npy.py new file mode 100644 index 00000000000..b3d76ede430 --- /dev/null +++ b/tests/integrate/validation_tools/check_dos_npy.py @@ -0,0 +1,62 @@ +"""Collect the integrated DOS and check LCAO spectra against a text reference.""" + +import json +from pathlib import Path +import sys + +import numpy as np + + +def check_pdos(path, ref): + rows = np.load(path, mmap_mode="r", allow_pickle=False) + spins = 2 if ref["nspin"] == 2 else 1 + species_dtype = rows.dtype["species"] + assert species_dtype.kind == "S", species_dtype + expected_dtype = np.dtype([ + ("nspin", "i4"), ("atom_index", "i4"), ("l", "i4"), ("m", "i4"), + ("energy_min_eV", "f8"), ("energy_step_eV", "f8"), ("species", species_dtype), + ("pdos", "f8", (spins, ref["npoints"])), + ]) + np.testing.assert_equal(rows.dtype, expected_dtype) + np.testing.assert_equal(rows.shape, (ref["records"],)) + for field in ("nspin", "energy_min_eV", "energy_step_eV"): + np.testing.assert_array_equal(rows[field], ref[field], err_msg=field) + + for sample in ref["samples"]: + match = ((rows["atom_index"] == sample["atom_index"]) + & (rows["l"] == sample["l"]) & (rows["m"] == sample["m"])) + orbital, = rows[match] + np.testing.assert_equal(orbital["species"], sample["species"].encode()) + values = orbital["pdos"][:, sample["energy_index"]] + np.testing.assert_allclose(values, sample["pdos"], rtol=1e-3, atol=5e-5, err_msg=str(sample)) + + +def collect_dos(directory, nspin, reference): + ref = None + if reference.is_file(): + ref = json.loads(reference.read_text()) + np.testing.assert_equal(nspin, ref["nspin"]) + check_pdos(directory / "pdos.npy", ref) + + fields = ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int") + dtype = np.dtype([(field, "f8") for field in fields]) + spins = 2 if nspin == 2 else 1 + for spin in range(spins): + rows = np.load(directory / f"doss{spin + 1}.npy", mmap_mode="r", allow_pickle=False) + np.testing.assert_equal(rows.dtype, dtype) + if rows.ndim != 1 or not rows.size: + raise ValueError("Expected one total DOS record per energy point") + if ref: + grid = ref["energy_min_eV"] + np.arange(ref["npoints"]) * ref["energy_step_eV"] + np.testing.assert_allclose(rows["energy_eV"], grid, atol=5e-7, rtol=0) + for sample in ref["total_samples"]: + row = rows[sample["energy_index"]] + np.testing.assert_allclose([row[name] for name in fields[1:]], + sample["spins"][spin], rtol=1e-3, atol=5e-5) + # The text collector takes the last bin from the last spin file. + return rows["dos_int"][-1] + + +if __name__ == "__main__": + value = collect_dos(Path(sys.argv[1]), int(sys.argv[2]), Path(sys.argv[3])) + print(f"totaldosref {value}") diff --git a/tests/integrate/validation_tools/check_pdos_npy.py b/tests/integrate/validation_tools/check_pdos_npy.py deleted file mode 100644 index faabd7b0117..00000000000 --- a/tests/integrate/validation_tools/check_pdos_npy.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Check an ABACUS PDOS array against selected channels from reference text output.""" - -import json -import sys - -import numpy as np - - -def check_pdos(path, reference): - with open(reference) as stream: - ref = json.load(stream) - rows = np.load(path, mmap_mode="r", allow_pickle=False) - spins = 2 if ref["nspin"] == 2 else 1 - species_dtype = rows.dtype["species"] - assert species_dtype.kind == "S", species_dtype - expected_dtype = np.dtype([ - ("nspin", "i4"), ("atom_index", "i4"), ("l", "i4"), ("m", "i4"), - ("energy_min_eV", "f8"), ("energy_step_eV", "f8"), ("species", species_dtype), - ("pdos", "f8", (spins, ref["npoints"])), - ]) - np.testing.assert_equal(rows.dtype, expected_dtype) - np.testing.assert_equal(rows.shape, (ref["records"],)) - for field in ("nspin", "energy_min_eV", "energy_step_eV"): - np.testing.assert_array_equal(rows[field], ref[field], err_msg=field) - - for sample in ref["samples"]: - match = ((rows["atom_index"] == sample["atom_index"]) - & (rows["l"] == sample["l"]) & (rows["m"] == sample["m"])) - orbital, = rows[match] - np.testing.assert_equal(orbital["species"], sample["species"].encode()) - values = orbital["pdos"][:, sample["energy_index"]] - np.testing.assert_allclose(values, sample["pdos"], rtol=1e-3, atol=5e-5, err_msg=str(sample)) - - -if __name__ == "__main__": - check_pdos(*sys.argv[1:]) diff --git a/tests/integrate/validation_tools/props_basic.sh b/tests/integrate/validation_tools/props_basic.sh index a654e808bc7..9171e728eca 100644 --- a/tests/integrate/validation_tools/props_basic.sh +++ b/tests/integrate/validation_tools/props_basic.sh @@ -122,9 +122,10 @@ run_basic_props() { if ! test -z "$has_dos" && [ $has_dos == 1 ]; then total_dos=$(cat OUT.autotest/dos*.txt | awk 'END {print}' | awk '{print $3}') echo "totaldosref $total_dos" >>$props_result_file - fi - if [ -f pdos.ref.json ]; then - python3 "$PROPS_TOOLS_DIR/check_pdos_npy.py" OUT.autotest/pdos.npy pdos.ref.json || return 1 + elif [ "$has_dos" = 2 ]; then + local dos_dir=OUT.autotest + if [ "$out_app_flag" = 2 ]; then dos_dir+=/DOS; fi + python3 "$PROPS_TOOLS_DIR/check_dos_npy.py" "$dos_dir" "${nspin:-1}" dos.ref.json >> "$props_result_file" || return 1 fi #------------------------------- diff --git a/tests/integrate/validation_tools/test_props_basic.py b/tests/integrate/validation_tools/test_props_basic.py index 4f93681adf2..51cbd1a15f9 100644 --- a/tests/integrate/validation_tools/test_props_basic.py +++ b/tests/integrate/validation_tools/test_props_basic.py @@ -131,11 +131,10 @@ def test_missing_or_corrupt_pdos_fails_through_shell_entry(self): with tempfile.TemporaryDirectory() as scratch: case = Path(scratch) shutil.copy(fixture / "INPUT", case) - shutil.copy(fixture / "pdos.ref.json", case) + shutil.copy(fixture / "dos.ref.json", case) out = case / "OUT.autotest" out.mkdir() (out / "running_scf.log").write_text(" TOTAL ATOM NUMBER = 2\nETOT_ -1.0\n", encoding="utf-8") - (out / "doss1.txt").write_text("0.0 0.0 20.0\n", encoding="utf-8") for contents, error in ((None, "FileNotFoundError"), (b"invalid NPY", "ValueError")): with self.subTest(error=error): diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 5de357f8f9b..436ec7a8628 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -176,8 +176,8 @@ class TDOS(DOS): """Parse total DOS data ``tdosfile`` may be a single TDOS file, a list of one or two per-spin - files, or a directory containing them. ABACUS writes one 5-column text - file per spin channel (``doss1*``/``doss2*``; legacy PW names + files, or a directory containing them. ABACUS writes one five-column + text or NPY file per spin channel (``doss1*``/``doss2*``; legacy PW names ``dos1.txt``/``dos2.txt``). A single spin-channel file is paired with its counterpart when present, searching in both directions, so passing either spin file works. For nspin=4 ABACUS writes a single @@ -198,6 +198,8 @@ def _find_spin_files(self) -> List[str]: f"tdosfile accepts 1 or 2 files, got {len(files)}") # canonicalize spin order: the spin-1 channel always comes first if len(files) == 2: + if (Path(files[0]).suffix == ".npy") != (Path(files[1]).suffix == ".npy"): + raise ValueError("Both TDOS spin files must have the same format") first, second = Path(files[0]).name, Path(files[1]).name if ("doss2" in first or "dos2" in first) and \ ("doss1" in second or "dos1" in second): @@ -211,21 +213,15 @@ def _find_spin_files(self) -> List[str]: matches1 = sorted(glob.glob(str(path / "dos1.txt"))) if not matches1 and (path / "dos.txt").is_file(): matches1 = [str(path / "dos.txt")] # legacy PW nspin=1 name + binary = path / "doss1.npy" + if binary.is_file(): + if matches1: + raise ValueError(f"Both text and NPY TDOS found in '{path}'. Pass a specific TDOS file.") + matches1 = [str(binary)] if not matches1: raise FileNotFoundError( f"No TDOS file found in directory '{path}'") - spin1 = Path(matches1[0]) - candidates = [str(spin1)] - # pair with the spin-2 file carrying the same name suffix, e.g. - # doss1g1.txt -> doss2g1.txt, so different geometry steps are - # never mixed - for one, two in (("doss1", "doss2"), ("dos1", "dos2")): - if one in spin1.name: - spin2 = spin1.parent / spin1.name.replace(one, two) - if spin2.is_file(): - candidates.append(str(spin2)) - break - return candidates + path = Path(matches1[0]) if path.is_file(): name = path.name @@ -246,6 +242,16 @@ def _read_one(self, fname: str) -> Dict[str, Any]: channels stored in this file (None where the column is absent, e.g. the legacy 2/3-column formats carry no smeared DOS). """ + if Path(fname).suffix == ".npy": + rows = np.load(fname, mmap_mode="r", allow_pickle=False) + names = ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int") + if (rows.ndim != 1 or not rows.size or rows.dtype.names != names + or any(rows[name].dtype.kind != "f" or rows[name].dtype.itemsize != 8 for name in names)): + raise ValueError(f"Invalid TDOS NPY array: {fname}") + data = {name: rows[name][:, None] for name in names[1:]} + data["energy"] = rows["energy_eV"][:, None] + return data + rows = [] with open(fname) as f: for line in f: diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos.py b/tools/02_postprocessing/plot-tools/tests/test_dos.py index 4e3514c92d2..f71facea118 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_dos.py +++ b/tools/02_postprocessing/plot-tools/tests/test_dos.py @@ -113,6 +113,23 @@ def test_spin_grids_require_equal_shape_and_absolute_agreement(self): down = self.write_spin("doss2g1.txt", other, 7.) self.assertEqual(TDOS([up, down]).nspin, 2) + def test_numpy_spin_files_and_text_agree(self): + dtype = [(key, "f8") for key in ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int")] + for spin in (1, 2): + text = self.write_spin(f"doss{spin}.txt", self.energy, spin) + values = np.loadtxt(text, skiprows=2) + np.save(text.with_suffix(".npy"), np.array([tuple(row) for row in values], dtype=dtype)) + reference = TDOS(text) + with self.assertRaisesRegex(ValueError, "Pass a specific TDOS file"): + TDOS(self.root) + for path in self.root.glob("*.txt"): + path.unlink() + for source in (self.root, self.root / "doss2.npy"): + result = TDOS(source) + self.assertEqual(result.nspin, 2) + for name in ("energy", "dos", "dos_int", "dos_smear", "dos_smear_int"): + np.testing.assert_array_equal(getattr(result, name), getattr(reference, name)) + def test_plain_axes_and_missing_subplot_apis(self): fig = plt.figure() plain = fig.add_axes([0.1, 0.1, 0.8, 0.8]) From 96a8d85834db556e183b0f9cc9cd31a511e530ad Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:53:22 +0800 Subject: [PATCH 11/15] Store all total DOS spin channels in dos.npy --- docs/advanced/elec_properties/dos.md | 12 +-- source/source_io/module_dos/cal_dos.cpp | 25 +++--- source/source_io/module_dos/cal_dos.h | 9 ++- .../module_dos/unittests/test_cal_dos.cpp | 14 ++-- .../source_io/module_dos/write_dos_lcao.cpp | 76 ++++++++++++++----- source/source_io/module_dos/write_dos_pw.cpp | 3 +- .../module_parameter/read_inp_out.cpp | 2 +- .../validation_tools/check_dos_npy.py | 31 ++++---- .../plot-tools/abacus_plot/dos.py | 24 +++--- .../plot-tools/tests/test_dos.py | 30 ++++++++ 10 files changed, 149 insertions(+), 77 deletions(-) diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 208dc02c3ca..a989e64b60b 100644 --- a/docs/advanced/elec_properties/dos.md +++ b/docs/advanced/elec_properties/dos.md @@ -105,10 +105,12 @@ to write both total and projected DOS as NumPy arrays. Use `out_dos 1` for text output or `out_dos 0` (the default) to disable DOS output. Older releases used `out_dos 2` to request text PDOS. -Total DOS uses one record per energy point in `doss1.npy`, plus `doss2.npy` -for spin-polarized calculations (`nspin=2`). Its five binary64 fields are -`energy_eV`, `dos`, `dos_int`, `dos_smear` and `dos_smear_int`, in the -same order and units as the text columns. Projected DOS is in `pdos.npy`. +Total DOS is in `dos.npy`, with one record per energy point. The shared +`energy_eV` field has shape `(npoints,)`. The four spectrum fields, +`dos`, `dos_int`, `dos_smear` and `dos_smear_int`, each have shape +`(npoints, 2)` for `nspin=2` (spin up, then spin down) or `(npoints, 1)` +for `nspin=1` or `4`. All five fields use binary64 and the same units as +the text columns. Projected DOS is in `pdos.npy`. With `out_app_flag 2`, these files are in the `DOS/` output subdirectory. For plotting, set `tdosfile` or `pdosfile` in the `abacus-plot` config. Use an explicit file path when the directory contains both formats. @@ -116,7 +118,7 @@ Use an explicit file path when the directory contains both formats. ```python import numpy as np -total = np.load("doss1.npy", mmap_mode="r") +total = np.load("dos.npy", mmap_mode="r") dos_per_eV = total["dos_smear"] rows = np.load("pdos.npy", mmap_mode="r") spectrum = rows["pdos"][0] # (spin channel, energy point), in 1/eV diff --git a/source/source_io/module_dos/cal_dos.cpp b/source/source_io/module_dos/cal_dos.cpp index b3fb4191516..1676752d013 100644 --- a/source/source_io/module_dos/cal_dos.cpp +++ b/source/source_io/module_dos/cal_dos.cpp @@ -1,5 +1,4 @@ #include "cal_dos.h" -#include "dos_npy_header.h" #include "source_base/constants.h" #include "source_base/global_function.h" @@ -111,14 +110,14 @@ bool ModuleIO::cal_dos(const int& is, // index for spin const ModuleBase::matrix& wg, // weight of k-points and bands const int istep, // ionic step const int out_app_flag, - const int bndpar) + const int bndpar, + DosSpectrum* spectrum) { ModuleBase::TITLE("ModuleIO", "cal_dos"); std::ofstream ofs_dos; - const bool npy = fn.size() >= 4 && fn.compare(fn.size() - 4, 4, ".npy") == 0; const bool root = GlobalV::MY_RANK == 0; - if (root && !npy) + if (root && !spectrum) { const std::string time_stamp = ModuleIO::local_timestamp(); const int istep_one_based = istep + 1; @@ -157,13 +156,7 @@ bool ModuleIO::cal_dos(const int& is, // index for spin ModuleBase::WARNING("ModuleIO::cal_dos", "npoints <= 0"); return false; } - if (root && npy) - { - ofs_dos.open(fn, std::ios::binary | std::ios::trunc); - write_dos_npy_header(ofs_dos, "('energy_eV','=f8'),('dos','=f8'),('dos_int','=f8')," - "('dos_smear','=f8'),('dos_smear_int','=f8')", npoints); - } - else if (root) + if (root && !spectrum) { ofs_dos << npoints << " # number of points" << std::endl; ofs_dos << std::fixed << std::setprecision(6); @@ -232,6 +225,7 @@ bool ModuleIO::cal_dos(const int& is, // index for spin if (root) { + if (spectrum) { spectrum->resize(npoints); } for (int n = 0; n < npoints; ++n) { dos[n] /= static_cast(nkstot); @@ -244,10 +238,9 @@ bool ModuleIO::cal_dos(const int& is, // index for spin } sum2 += dos_smear[n] * de_ev; - if (npy) + if (spectrum) { - const double row[] = {ene[n], dos[n], sum_elec[n], dos_smear[n], sum2}; - ofs_dos.write(reinterpret_cast(row), sizeof(row)); + (*spectrum)[n] = {ene[n], dos[n], sum_elec[n], dos_smear[n], sum2}; continue; } ofs_dos << std::setw(13) << ene[n] @@ -256,11 +249,11 @@ bool ModuleIO::cal_dos(const int& is, // index for spin << " " << std::setw(14) << dos_smear[n] << " " << std::setw(14) << sum2 << std::endl; } - ofs_dos.close(); + if (!spectrum) { ofs_dos.close(); } } ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Number of bands", nbands); ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Total electronic states from DOS", sum); - return !npy || !root || ofs_dos.good(); + return true; } diff --git a/source/source_io/module_dos/cal_dos.h b/source/source_io/module_dos/cal_dos.h index e8f305b685b..caf829d344e 100644 --- a/source/source_io/module_dos/cal_dos.h +++ b/source/source_io/module_dos/cal_dos.h @@ -1,13 +1,17 @@ #ifndef DOS_H #define DOS_H -#include +#include +#include #include "source_base/matrix.h" #include "source_estate/fp_energy.h" namespace ModuleIO { + // Per-energy rows in text column order for one spin channel. + using DosSpectrum = std::vector>; + void prepare_dos(std::ofstream& ofs_running, const elecstate::Efermi &energy_fermi, const ModuleBase::matrix& ekb, @@ -38,7 +42,8 @@ namespace ModuleIO const ModuleBase::matrix &wg, //weight of (kpoint,bands)) const int istep_in, // ionic_step const int out_app_flag, // 0: no append, 1: append, 2: subdirectory - const int bndpar); // number of band parallel groups + const int bndpar, // number of band parallel groups + DosSpectrum* spectrum); // collect rank-zero rows for NPY output when supplied } diff --git a/source/source_io/module_dos/unittests/test_cal_dos.cpp b/source/source_io/module_dos/unittests/test_cal_dos.cpp index c32e9cbc27f..38fb3f599fb 100644 --- a/source/source_io/module_dos/unittests/test_cal_dos.cpp +++ b/source/source_io/module_dos/unittests/test_cal_dos.cpp @@ -54,7 +54,7 @@ TEST_F(DosTest,Dos) dosp.wg, istep, out_app_flag, - bndpar); + bndpar, nullptr); #ifdef __MPI if(GlobalV::MY_RANK==0) @@ -153,7 +153,7 @@ TEST_F(DosTest,DosW1) dosp.wg, istep, out_app_flag, - bndpar)); + bndpar, nullptr)); GlobalV::ofs_warning.close(); #ifdef __MPI if(GlobalV::MY_RANK==0) @@ -200,7 +200,7 @@ TEST_F(DosTest,DosW2) dosp.wg, istep, out_app_flag, - bndpar)); + bndpar, nullptr)); GlobalV::ofs_warning.close(); #ifdef __MPI @@ -238,12 +238,12 @@ TEST_F(DosTest, Mode1Appends) ModuleIO::cal_dos(dosp.is, dosp.fa, dosp.de_ev, dosp.emax_ev, dosp.emin_ev, dosp.bcoeff, dosp.nks, dosp.nkstot, dosp.wk, dosp.isk, dosp.nbands, dosp.ekb, dosp.wg, - /*istep=*/0, out_app_flag, bndpar); + /*istep=*/0, out_app_flag, bndpar, nullptr); // Second call: istep=1 -> "# Ionic_Step 2", appended. ModuleIO::cal_dos(dosp.is, dosp.fa, dosp.de_ev, dosp.emax_ev, dosp.emin_ev, dosp.bcoeff, dosp.nks, dosp.nkstot, dosp.wk, dosp.isk, dosp.nbands, dosp.ekb, dosp.wg, - /*istep=*/1, out_app_flag, bndpar); + /*istep=*/1, out_app_flag, bndpar, nullptr); #ifdef __MPI if (GlobalV::MY_RANK == 0) @@ -280,11 +280,11 @@ TEST_F(DosTest, Mode2Overwrites) ModuleIO::cal_dos(dosp.is, dosp.fa, dosp.de_ev, dosp.emax_ev, dosp.emin_ev, dosp.bcoeff, dosp.nks, dosp.nkstot, dosp.wk, dosp.isk, dosp.nbands, dosp.ekb, dosp.wg, - /*istep=*/0, out_app_flag, bndpar); + /*istep=*/0, out_app_flag, bndpar, nullptr); ModuleIO::cal_dos(dosp.is, dosp.fa, dosp.de_ev, dosp.emax_ev, dosp.emin_ev, dosp.bcoeff, dosp.nks, dosp.nkstot, dosp.wk, dosp.isk, dosp.nbands, dosp.ekb, dosp.wg, - /*istep=*/1, out_app_flag, bndpar); + /*istep=*/1, out_app_flag, bndpar, nullptr); #ifdef __MPI if (GlobalV::MY_RANK == 0) diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index f97d6ca1667..831ab775a2e 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -2,6 +2,7 @@ #include "cal_dos.h" #include "cal_pdos_gamma.h" #include "cal_pdos_multik.h" +#include "dos_npy_header.h" #include "write_pdos_text.h" #include "source_base/global_variable.h" #include "source_base/parallel_common.h" @@ -9,11 +10,49 @@ #include "source_io/module_output/write_notice.h" #include +#include #include namespace ModuleIO { +namespace +{ +void write_dos_npy(const std::string& path, const std::vector& spectra) +{ + const auto npoints = spectra.front().size(); + const auto spins = spectra.size(); + const std::string field_type = "','=f8',(" + std::to_string(spins) + ",))"; + std::string fields = "('energy_eV','=f8')"; + for (const char* name : {"dos", "dos_int", "dos_smear", "dos_smear_int"}) + { + fields += std::string(",('") + name + field_type; + } + + std::ofstream out; + out.exceptions(std::ios::badbit | std::ios::failbit); + out.open(path, std::ios::binary | std::ios::trunc); + write_dos_npy_header(out, fields, npoints); + // One shared energy, followed by all spin channels of each quantity. + const auto record_width = 1 + 4 * spins; + std::vector record(record_width); + const auto bytes = record.size() * sizeof(double); + for (std::size_t n = 0; n < npoints; ++n) + { + record[0] = spectra.front()[n][0]; + for (std::size_t field = 0; field < 4; ++field) + { + for (std::size_t is = 0; is < spins; ++is) + { + record[1 + field * spins + is] = spectra[is][n][1 + field]; + } + } + out.write(reinterpret_cast(record.data()), bytes); + } + out.close(); +} +} + template void write_dos_lcao( const psi::Psi* psi, @@ -64,22 +103,19 @@ void write_dos_lcao( dos_emin_ev, two_fermi); - // output the DOS file. + const int buffered_spins = dos_npy ? nspin0 : 0; + std::vector total_dos(buffered_spins); for (int is = 0; is < nspin0; ++is) { std::stringstream ss; - - ss << global_out_dir << "doss" << is + 1; - - // Only per-step text output carries the g{N} suffix. - if (!dos_npy && istep >= 0 && out_app_flag == 2) + if (!dos_npy) { - ss << "g" << istep+1; + ss << global_out_dir << "doss" << is + 1; + if (istep >= 0 && out_app_flag == 2) { ss << "g" << istep + 1; } + ss << ".txt"; } - - ss << (dos_npy ? ".npy" : ".txt"); - - bool written = ModuleIO::cal_dos(is, + DosSpectrum* spectrum = dos_npy ? &total_dos[is] : nullptr; + const bool calculated = ModuleIO::cal_dos(is, ss.str(), dos_edelta_ev, emax, @@ -94,17 +130,14 @@ void write_dos_lcao( wg, istep, out_app_flag, - bndpar); + bndpar, + spectrum); - if (dos_npy) + if (dos_npy && !calculated) { - Parallel_Common::bcast_bool(written); - if (!written) - { - ModuleBase::WARNING_QUIT("write_dos_lcao", "Failed to write " + ss.str()); - } + ModuleBase::WARNING_QUIT("write_dos_lcao", "Cannot calculate total DOS for dos.npy"); } - if (GlobalV::MY_RANK == 0) + if (!dos_npy && GlobalV::MY_RANK == 0) { ModuleIO::write_notice(ofs_running, "DOS", is, nspin, ss.str()); } @@ -131,9 +164,12 @@ void write_dos_lcao( { if (dos_npy) { - const std::string path = global_out_dir + "pdos.npy"; + std::string path = global_out_dir + "dos.npy"; try { + write_dos_npy(path, total_dos); + ModuleIO::write_notice(ofs_running, "DOS", path); + path = global_out_dir + "pdos.npy"; write_pdos_npy(ucell, pdos, nspin, emin, dos_edelta_ev, path); ModuleIO::write_notice(ofs_running, "PDOS", path); } diff --git a/source/source_io/module_dos/write_dos_pw.cpp b/source/source_io/module_dos/write_dos_pw.cpp index 434a39c6f80..6bd62811c2a 100644 --- a/source/source_io/module_dos/write_dos_pw.cpp +++ b/source/source_io/module_dos/write_dos_pw.cpp @@ -80,7 +80,8 @@ void ModuleIO::write_dos_pw( wg, istep_in, out_app_flag, - bndpar); + bndpar, + nullptr); } diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 11867fd9277..7357feed280 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -381,7 +381,7 @@ Also controled by out_freq_ion and out_app_flag. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# Ionic_Step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). * nspin=1 or 4: one spin channel (`s1`). nspin=2: two channels (`s1`, `s2`). PW and LCAO use the same naming. -* 2: write total DOS (`doss1.npy` and, for nspin=2, `doss2.npy`) and projected DOS (`pdos.npy`) as NumPy arrays for a single-point LCAO KSDFT SCF or NSCF calculation. Older versions used 2 to request text PDOS; use 1 for text. +* 2: write total DOS (`dos.npy`) and projected DOS (`pdos.npy`) as NumPy arrays for a single-point LCAO KSDFT SCF or NSCF calculation. Both spin channels for nspin=2 share the same files. Older versions used 2 to request text PDOS; use 1 for text. * 3: Fermi surface output has been removed.)"; item.default_value = "0"; item.unit = ""; diff --git a/tests/integrate/validation_tools/check_dos_npy.py b/tests/integrate/validation_tools/check_dos_npy.py index b3d76ede430..4d0e22962a4 100644 --- a/tests/integrate/validation_tools/check_dos_npy.py +++ b/tests/integrate/validation_tools/check_dos_npy.py @@ -38,23 +38,22 @@ def collect_dos(directory, nspin, reference): np.testing.assert_equal(nspin, ref["nspin"]) check_pdos(directory / "pdos.npy", ref) - fields = ("energy_eV", "dos", "dos_int", "dos_smear", "dos_smear_int") - dtype = np.dtype([(field, "f8") for field in fields]) + fields = ("dos", "dos_int", "dos_smear", "dos_smear_int") spins = 2 if nspin == 2 else 1 - for spin in range(spins): - rows = np.load(directory / f"doss{spin + 1}.npy", mmap_mode="r", allow_pickle=False) - np.testing.assert_equal(rows.dtype, dtype) - if rows.ndim != 1 or not rows.size: - raise ValueError("Expected one total DOS record per energy point") - if ref: - grid = ref["energy_min_eV"] + np.arange(ref["npoints"]) * ref["energy_step_eV"] - np.testing.assert_allclose(rows["energy_eV"], grid, atol=5e-7, rtol=0) - for sample in ref["total_samples"]: - row = rows[sample["energy_index"]] - np.testing.assert_allclose([row[name] for name in fields[1:]], - sample["spins"][spin], rtol=1e-3, atol=5e-5) - # The text collector takes the last bin from the last spin file. - return rows["dos_int"][-1] + dtype = np.dtype([("energy_eV", "f8")] + [(name, "f8", (spins,)) for name in fields]) + rows = np.load(directory / "dos.npy", mmap_mode="r", allow_pickle=False) + np.testing.assert_equal(rows.dtype, dtype) + if rows.ndim != 1 or not rows.size: + raise ValueError("Expected one total DOS record per energy point") + if ref: + grid = ref["energy_min_eV"] + np.arange(ref["npoints"]) * ref["energy_step_eV"] + np.testing.assert_allclose(rows["energy_eV"], grid, atol=5e-7, rtol=0) + for sample in ref["total_samples"]: + row = rows[sample["energy_index"]] + values = np.column_stack([row[name] for name in fields]) + np.testing.assert_allclose(values, sample["spins"], rtol=1e-3, atol=5e-5) + # Match the last bin and last spin used by the text collector. + return rows["dos_int"][-1, -1] if __name__ == "__main__": diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 436ec7a8628..887dfa34d7e 100644 --- a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py +++ b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py @@ -176,9 +176,10 @@ class TDOS(DOS): """Parse total DOS data ``tdosfile`` may be a single TDOS file, a list of one or two per-spin - files, or a directory containing them. ABACUS writes one five-column - text or NPY file per spin channel (``doss1*``/``doss2*``; legacy PW names - ``dos1.txt``/``dos2.txt``). A single spin-channel file is paired with + files, or a directory containing them. ABACUS writes all spin channels + in ``dos.npy`` or one five-column text file per spin channel + (``doss1*``/``doss2*``; legacy PW names ``dos1.txt``/``dos2.txt``). + A single spin-channel file is paired with its counterpart when present, searching in both directions, so passing either spin file works. For nspin=4 ABACUS writes a single spinor-summed file, which is handled like nspin=1. @@ -213,11 +214,11 @@ def _find_spin_files(self) -> List[str]: matches1 = sorted(glob.glob(str(path / "dos1.txt"))) if not matches1 and (path / "dos.txt").is_file(): matches1 = [str(path / "dos.txt")] # legacy PW nspin=1 name - binary = path / "doss1.npy" - if binary.is_file(): - if matches1: - raise ValueError(f"Both text and NPY TDOS found in '{path}'. Pass a specific TDOS file.") - matches1 = [str(binary)] + binary = [path / name for name in ("dos.npy", "doss1.npy") if (path / name).is_file()] + if binary: + if matches1 or len(binary) > 1: + raise ValueError(f"Multiple TDOS formats found in '{path}'. Pass a specific TDOS file.") + matches1 = [str(binary[0])] if not matches1: raise FileNotFoundError( f"No TDOS file found in directory '{path}'") @@ -248,7 +249,12 @@ def _read_one(self, fname: str) -> Dict[str, Any]: if (rows.ndim != 1 or not rows.size or rows.dtype.names != names or any(rows[name].dtype.kind != "f" or rows[name].dtype.itemsize != 8 for name in names)): raise ValueError(f"Invalid TDOS NPY array: {fname}") - data = {name: rows[name][:, None] for name in names[1:]} + spin_shape = rows["dos"].shape[1:] + # Older per-spin NPY files have scalar spectrum fields. + if (rows["energy_eV"].ndim != 1 or spin_shape not in ((), (1,), (2,)) + or any(rows[name].shape[1:] != spin_shape for name in names[1:])): + raise ValueError(f"Invalid TDOS spin dimensions: {fname}") + data = {name: rows[name].reshape(rows.size, -1) for name in names[1:]} data["energy"] = rows["energy_eV"][:, None] return data diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos.py b/tools/02_postprocessing/plot-tools/tests/test_dos.py index f71facea118..62ea6e50e0f 100644 --- a/tools/02_postprocessing/plot-tools/tests/test_dos.py +++ b/tools/02_postprocessing/plot-tools/tests/test_dos.py @@ -130,6 +130,36 @@ def test_numpy_spin_files_and_text_agree(self): for name in ("energy", "dos", "dos_int", "dos_smear", "dos_smear_int"): np.testing.assert_array_equal(getattr(result, name), getattr(reference, name)) + def test_combined_numpy_spectra_match_text(self): + fields = ("dos", "dos_int", "dos_smear", "dos_smear_int") + path = self.root / "dos.npy" + for spins in (1, 2): + with self.subTest(spins=spins): + text = self.write_spin(f"doss{spins}.txt", self.energy, spins) + reference = TDOS(text) + dtype = [("energy_eV", "f8")] + [(field, "f8", (spins,)) for field in fields] + rows = np.empty(len(self.energy), dtype=dtype) + rows["energy_eV"] = self.energy + for field in fields: + rows[field] = getattr(reference, field) + np.save(path, rows) + with self.assertRaisesRegex(ValueError, "Pass a specific TDOS file"): + TDOS(self.root) + result = TDOS(path) + self.assertEqual(result.nspin, spins) + for field in ("energy", *fields): + np.testing.assert_array_equal(getattr(result, field), getattr(reference, field)) + for text in self.root.glob("*.txt"): + text.unlink() + np.testing.assert_array_equal(TDOS(self.root).dos_smear, rows["dos_smear"]) + + def test_combined_numpy_rejects_inconsistent_spins(self): + dtype = [("energy_eV", "f8"), ("dos", "f8", (2,)), ("dos_int", "f8", (1,)), + ("dos_smear", "f8", (2,)), ("dos_smear_int", "f8", (2,))] + np.save(self.root / "dos.npy", np.zeros(3, dtype=dtype)) + with self.assertRaisesRegex(ValueError, "spin dimensions"): + TDOS(self.root) + def test_plain_axes_and_missing_subplot_apis(self): fig = plt.figure() plain = fig.add_axes([0.1, 0.1, 0.8, 0.8]) From c3af378bcff16c1e71d1795b9ed51c24e797f1b9 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:20:55 +0800 Subject: [PATCH 12/15] docs: clarify precision and write costs for out_dos 2 --- source/source_io/module_parameter/read_inp_out.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 7357feed280..3e364648634 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -381,7 +381,10 @@ Also controled by out_freq_ion and out_app_flag. * With out_app_flag = 1: the same fixed-name files are reused; the first written step truncates them and later steps append one record per step (prefixed with a `# Ionic_Step N` header, one-based). * With out_app_flag = 2: per-step files are named `doss{s}g{geom}.txt` and `pdoss{s}g{geom}.txt` where `{geom}` is the one-based geometry index (e.g. `doss1g3.txt` for the third ionic step). * nspin=1 or 4: one spin channel (`s1`). nspin=2: two channels (`s1`, `s2`). PW and LCAO use the same naming. -* 2: write total DOS (`dos.npy`) and projected DOS (`pdos.npy`) as NumPy arrays for a single-point LCAO KSDFT SCF or NSCF calculation. Both spin channels for nspin=2 share the same files. Older versions used 2 to request text PDOS; use 1 for text. +* 2: write total DOS (`dos.npy`) and projected DOS (`pdos.npy`) as NumPy arrays for a single-point LCAO KSDFT SCF or NSCF calculation. Both spin channels for nspin=2 share the same files. + NumPy output preserves double-precision (`float64`) spectral values, while text output rounds them to six decimal places. + For large PDOS datasets, NumPy output can also reduce write time and file size. + If an older input uses `out_dos 2` for text PDOS, change it to `out_dos 1` to keep text output. * 3: Fermi surface output has been removed.)"; item.default_value = "0"; item.unit = ""; From 6fc82ea7fd532003f529db9c326f29958dc7cb33 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:00:30 +0800 Subject: [PATCH 13/15] refactor: pass out_dos directly to the LCAO DOS writer --- .../source_io/module_ctrl/ctrl_scf_lcao.cpp | 3 +- .../source_io/module_dos/write_dos_lcao.cpp | 29 ++++++++++++------- source/source_io/module_dos/write_dos_lcao.h | 2 +- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp index 6ee9724a471..a1818598c29 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -174,7 +174,6 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, const std::string global_dos_dir = PARAM.globalv.global_dos_dir; // Mode-2 DOS/ subdirectory is created lazily at write time. ModuleBase::ensure_directory(global_dos_dir); - const bool dos_npy = inp.out_dos == 2; ModuleIO::write_dos_lcao(psi, p_hamilt, pv, @@ -187,7 +186,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, - dos_npy, + inp.out_dos, out_app_flag, istep, inp.nspin, diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 831ab775a2e..4a8f18405be 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -67,7 +67,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const bool dos_npy, + const int out_dos, const int out_app_flag, const int istep, const int nspin, @@ -103,18 +103,25 @@ void write_dos_lcao( dos_emin_ev, two_fermi); - const int buffered_spins = dos_npy ? nspin0 : 0; - std::vector total_dos(buffered_spins); + std::vector total_dos; + if (out_dos == 2) + { + total_dos.resize(nspin0); + } for (int is = 0; is < nspin0; ++is) { std::stringstream ss; - if (!dos_npy) + DosSpectrum* spectrum = nullptr; + if (out_dos == 2) + { + spectrum = &total_dos[is]; + } + else { ss << global_out_dir << "doss" << is + 1; if (istep >= 0 && out_app_flag == 2) { ss << "g" << istep + 1; } ss << ".txt"; } - DosSpectrum* spectrum = dos_npy ? &total_dos[is] : nullptr; const bool calculated = ModuleIO::cal_dos(is, ss.str(), dos_edelta_ev, @@ -133,11 +140,11 @@ void write_dos_lcao( bndpar, spectrum); - if (dos_npy && !calculated) + if (out_dos == 2 && !calculated) { ModuleBase::WARNING_QUIT("write_dos_lcao", "Cannot calculate total DOS for dos.npy"); } - if (!dos_npy && GlobalV::MY_RANK == 0) + if (out_dos != 2 && GlobalV::MY_RANK == 0) { ModuleIO::write_notice(ofs_running, "DOS", is, nspin, ss.str()); } @@ -162,7 +169,7 @@ void write_dos_lcao( std::string error; if (GlobalV::MY_RANK == 0) { - if (dos_npy) + if (out_dos == 2) { std::string path = global_out_dir + "dos.npy"; try @@ -184,7 +191,7 @@ void write_dos_lcao( emin, dos_edelta_ev, global_out_dir, istep, out_app_flag, ofs_running); } } - if (dos_npy) + if (out_dos == 2) { Parallel_Common::bcast_string(error); if (!error.empty()) { ModuleBase::WARNING_QUIT("write_dos_lcao", error); } @@ -209,7 +216,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const bool dos_npy, + const int out_dos, const int out_app_flag, const int istep, const int nspin, @@ -237,7 +244,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, - const bool dos_npy, + const int out_dos, const int out_app_flag, const int istep, const int nspin, diff --git a/source/source_io/module_dos/write_dos_lcao.h b/source/source_io/module_dos/write_dos_lcao.h index 213dd6cf36a..468cb109ae3 100644 --- a/source/source_io/module_dos/write_dos_lcao.h +++ b/source/source_io/module_dos/write_dos_lcao.h @@ -28,7 +28,7 @@ namespace ModuleIO const double& dos_edelta_ev, // Delta energy const double& dos_scale, const double& bcoeff, - const bool dos_npy, + const int out_dos, const int out_app_flag, const int istep, const int nspin, From f885ee79fc3fb5f4f10026e6cfab2feb6207a34b Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:58:46 +0800 Subject: [PATCH 14/15] test: cover in-memory capture of total DOS --- .../module_dos/unittests/test_cal_dos.cpp | 37 +++++++++++++++++++ .../source_io/module_dos/write_dos_lcao.cpp | 3 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/source/source_io/module_dos/unittests/test_cal_dos.cpp b/source/source_io/module_dos/unittests/test_cal_dos.cpp index 38fb3f599fb..c3e6c5151a8 100644 --- a/source/source_io/module_dos/unittests/test_cal_dos.cpp +++ b/source/source_io/module_dos/unittests/test_cal_dos.cpp @@ -1,9 +1,13 @@ #include "gtest/gtest.h" #include "gmock/gmock.h" #include "../cal_dos.h" +#include "source_base/constants.h" #include "source_base/global_variable.h" +#include +#include #include #include +#include #ifdef __MPI #include "mpi.h" #endif @@ -124,6 +128,39 @@ TEST_F(DosTest,Dos) +TEST_F(DosTest, CapturesSpectrumWithoutTextOutput) +{ + const auto pid = getpid(); + const std::string text_path = testing::TempDir() + "abacus_cal_dos_capture_" + std::to_string(pid) + ".txt"; + const double step = 0.5; + const double sigma = 0.5; + ModuleBase::matrix eigenvalues(1, 1); + eigenvalues(0, 0) = 0.0; + ModuleBase::matrix occupations(1, 1); + occupations(0, 0) = 1.0; + ModuleIO::DosSpectrum spectrum; + const bool calculated = ModuleIO::cal_dos(0, text_path, step, 0.5, 0.0, sigma, + 1, 1, {1.0}, {0}, 1, eigenvalues, occupations, + /*istep=*/-1, /*out_app_flag=*/0, /*bndpar=*/1, &spectrum); + ASSERT_TRUE(calculated); + const std::ifstream text_output(text_path); + EXPECT_FALSE(text_output.is_open()); + + // One state at 0 eV, sampled at the Gaussian peak and one sigma above it. + const double peak = 1.0 / (sigma * std::sqrt(ModuleBase::TWO_PI)); + const double shoulder = peak * std::exp(-0.5); + const ModuleIO::DosSpectrum expected = { + {0.0, 1.0, 1.0, peak, step * peak}, + {0.5, 0.0, 1.0, shoulder, step * (peak + shoulder)} + }; + ASSERT_EQ(spectrum.size(), expected.size()); + const auto near = testing::DoubleNear(1e-12); + for (size_t row = 0; row < expected.size(); ++row) + { + EXPECT_THAT(spectrum[row], testing::Pointwise(near, expected[row])) << "row " << row; + } +} + TEST_F(DosTest,DosW1) { //is,fa,de_ev,emax_ev,emin_ev,bcoeff,nks,nkstot,nbands diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 4a8f18405be..2adc41cc9ee 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -30,7 +30,8 @@ void write_dos_npy(const std::string& path, const std::vector& spec } std::ofstream out; - out.exceptions(std::ios::badbit | std::ios::failbit); + const auto exception_mask = std::ios::badbit | std::ios::failbit; + out.exceptions(exception_mask); out.open(path, std::ios::binary | std::ios::trunc); write_dos_npy_header(out, fields, npoints); // One shared energy, followed by all spin channels of each quantity. From 0787f37d8c3707a1fbb878f5b530f93ea82f19b3 Mon Sep 17 00:00:00 2001 From: Jiacheng Xu <13862180016@163.com> Date: Tue, 24 Nov 2026 10:14:27 +0800 Subject: [PATCH 15/15] refactor: use explicit types in LCAO DOS output and tests --- .../module_dos/unittests/test_cal_dos.cpp | 8 +++++--- source/source_io/module_dos/write_dos_lcao.cpp | 12 ++++++------ source/source_io/module_dos/write_pdos_text.cpp | 16 ++++++++-------- .../source_io/module_parameter/read_inp_out.cpp | 2 +- .../unittests/test_read_input_parallel.cpp | 11 ++++++----- 5 files changed, 26 insertions(+), 23 deletions(-) diff --git a/source/source_io/module_dos/unittests/test_cal_dos.cpp b/source/source_io/module_dos/unittests/test_cal_dos.cpp index c3e6c5151a8..795774ed8ac 100644 --- a/source/source_io/module_dos/unittests/test_cal_dos.cpp +++ b/source/source_io/module_dos/unittests/test_cal_dos.cpp @@ -130,7 +130,7 @@ TEST_F(DosTest,Dos) TEST_F(DosTest, CapturesSpectrumWithoutTextOutput) { - const auto pid = getpid(); + const pid_t pid = getpid(); const std::string text_path = testing::TempDir() + "abacus_cal_dos_capture_" + std::to_string(pid) + ".txt"; const double step = 0.5; const double sigma = 0.5; @@ -154,10 +154,12 @@ TEST_F(DosTest, CapturesSpectrumWithoutTextOutput) {0.5, 0.0, 1.0, shoulder, step * (peak + shoulder)} }; ASSERT_EQ(spectrum.size(), expected.size()); - const auto near = testing::DoubleNear(1e-12); for (size_t row = 0; row < expected.size(); ++row) { - EXPECT_THAT(spectrum[row], testing::Pointwise(near, expected[row])) << "row " << row; + for (std::size_t col = 0; col < expected[row].size(); ++col) + { + EXPECT_NEAR(spectrum[row][col], expected[row][col], 1e-12) << "row " << row << ", column " << col; + } } } diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index 2adc41cc9ee..b63c9e73b63 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -20,8 +20,8 @@ namespace { void write_dos_npy(const std::string& path, const std::vector& spectra) { - const auto npoints = spectra.front().size(); - const auto spins = spectra.size(); + const std::size_t npoints = spectra.front().size(); + const std::size_t spins = spectra.size(); const std::string field_type = "','=f8',(" + std::to_string(spins) + ",))"; std::string fields = "('energy_eV','=f8')"; for (const char* name : {"dos", "dos_int", "dos_smear", "dos_smear_int"}) @@ -30,14 +30,14 @@ void write_dos_npy(const std::string& path, const std::vector& spec } std::ofstream out; - const auto exception_mask = std::ios::badbit | std::ios::failbit; + const std::ios_base::iostate exception_mask = std::ios::badbit | std::ios::failbit; out.exceptions(exception_mask); out.open(path, std::ios::binary | std::ios::trunc); write_dos_npy_header(out, fields, npoints); // One shared energy, followed by all spin channels of each quantity. - const auto record_width = 1 + 4 * spins; + const std::size_t record_width = 1 + 4 * spins; std::vector record(record_width); - const auto bytes = record.size() * sizeof(double); + const std::size_t bytes = record.size() * sizeof(double); for (std::size_t n = 0; n < npoints; ++n) { record[0] = spectra.front()[n][0]; @@ -153,7 +153,7 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) - const auto pdos = cal_pdos(psi, + const std::vector pdos = cal_pdos(psi, p_ham, pv, kv, diff --git a/source/source_io/module_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index 1ec222de01b..ab99418ee44 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -30,7 +30,7 @@ PdosBlock atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdo PdosBlock block; for (int iw = 0; iw < atom.nw; ++iw) { - auto& channel = block[{atom.iw2l[iw], atom.iw2m[iw]}]; + std::vector& channel = block[{atom.iw2l[iw], atom.iw2m[iw]}]; if (channel.empty()) { channel.resize(static_cast(spins) * ne); } const int row = first + npol * iw; for (int is = 0; is < spins; ++is) @@ -42,7 +42,7 @@ PdosBlock atom_pdos(const UnitCell& cell, int iat, const ModuleBase::matrix* pdo } } } - for (auto& channel : block) + for (PdosBlock::value_type& channel : block) { for (double& value : channel.second) { @@ -109,8 +109,8 @@ void ModuleIO::write_pdos_text( { const int it = ucell.iat2it[iat]; const bool spinor = nspin == 4; - const auto* spin_pdos = pdos + is; - const auto channels = atom_pdos(ucell, iat, spin_pdos, 1, spinor); + const ModuleBase::matrix* spin_pdos = pdos + is; + const PdosBlock channels = atom_pdos(ucell, iat, spin_pdos, 1, spinor); for (int n = 0; n < npoints; ++n) { @@ -120,7 +120,7 @@ void ModuleIO::write_pdos_text( << " " << std::setw(3) << iat + 1 << " " << std::setw(4) << ucell.atoms[it].label; - for (const auto& channel : channels) + for (const PdosBlock::value_type& channel : channels) { ofs << " " << std::setw(8) << std::fixed << std::setprecision(6) << channel.second[n]; } @@ -170,8 +170,8 @@ void ModuleIO::write_pdos_npy(const UnitCell& cell, const std::vector(attrs), sizeof(attrs)); out.write(reinterpret_cast(grid), sizeof(grid)); out.write(label.data(), label.size()); - const auto spectrum_bytes = channel.second.size() * sizeof(double); + const std::size_t spectrum_bytes = channel.second.size() * sizeof(double); out.write(reinterpret_cast(channel.second.data()), spectrum_bytes); } } diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 3e364648634..77d4f7373b8 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -396,7 +396,7 @@ Also controled by out_freq_ion and out_app_flag. } }; item.check_value = [](const Input_Item& item, const Parameter& para) { - const auto& in = para.input; + const Input_para& in = para.input; if (in.out_dos == 2 && (in.basis_type != "lcao" || in.esolver_type != "ksdft" || (in.calculation != "scf" && in.calculation != "nscf"))) { diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index faf97886536..bff1993149b 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -781,21 +781,22 @@ TEST_F(InputParaTest, RemovedElpaZSolverIsRejected) TEST_F(InputParaTest, OutDosNpy) { ModuleIO::ReadInput reader(0); - const auto& entries = reader.get_input_lists(); + const std::vector>& entries = reader.get_input_lists(); std::map items(entries.begin(), entries.end()); Parameter param; - auto set = [&](const std::string& key, const std::string& value) { - auto& item = items.at(key); + std::function set = [&](const std::string& key, + const std::string& value) { + ModuleIO::Input_Item& item = items.at(key); item.str_values = {value}; item.read_value(item, param); }; - const auto& output = items.at("out_dos"); + const ModuleIO::Input_Item& output = items.at("out_dos"); EXPECT_EQ(param.inp.out_dos, 0); set("basis_type", "lcao"); set("out_dos", "2"); ASSERT_EQ(param.inp.out_dos, 2); - for (const auto* calculation : {"scf", "nscf"}) + for (const char* calculation : {"scf", "nscf"}) { set("calculation", calculation); output.check_value(output, param);