diff --git a/docs/advanced/elec_properties/dos.md b/docs/advanced/elec_properties/dos.md index 8c854caaf2c..a989e64b60b 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 `# Ionic_Step` 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 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 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. + +```python +import numpy as np + +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 +energy_eV = rows["energy_min_eV"][0] + np.arange(spectrum.shape[1]) * rows["energy_step_eV"][0] +``` + +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 88384faf792..a1818598c29 100644 --- a/source/source_io/module_ctrl/ctrl_scf_lcao.cpp +++ b/source/source_io/module_ctrl/ctrl_scf_lcao.cpp @@ -186,6 +186,7 @@ void ModuleIO::ctrl_scf_lcao(UnitCell& ucell, inp.dos_edelta_ev, inp.dos_scale, inp.dos_sigma, + inp.out_dos, 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..1676752d013 100644 --- a/source/source_io/module_dos/cal_dos.cpp +++ b/source/source_io/module_dos/cal_dos.cpp @@ -110,13 +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; - - if (GlobalV::MY_RANK == 0) + const bool root = GlobalV::MY_RANK == 0; + if (root && !spectrum) { const std::string time_stamp = ModuleIO::local_timestamp(); const int istep_one_based = istep + 1; @@ -155,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 && !spectrum) { ofs_dos << npoints << " # number of points" << std::endl; ofs_dos << std::fixed << std::setprecision(6); @@ -222,8 +223,9 @@ 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) { + if (spectrum) { spectrum->resize(npoints); } for (int n = 0; n < npoints; ++n) { dos[n] /= static_cast(nkstot); @@ -236,17 +238,18 @@ bool ModuleIO::cal_dos(const int& is, // index for spin } sum2 += dos_smear[n] * de_ev; + if (spectrum) + { + (*spectrum)[n] = {ene[n], dos[n], sum_elec[n], dos_smear[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 (GlobalV::MY_RANK == 0) - { - ofs_dos.close(); + if (!spectrum) { ofs_dos.close(); } } ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Number of bands", nbands); 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/cal_pdos_gamma.cpp b/source/source_io/module_dos/cal_pdos_gamma.cpp index 6404fbe0173..f36b2365bb9 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.cpp +++ b/source/source_io/module_dos/cal_pdos_gamma.cpp @@ -1,19 +1,15 @@ #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_notice.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, @@ -22,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, - std::ofstream& ofs_running) + const int nspin) { ModuleBase::TITLE("ModuleIO", "cal_pdos_gamma"); @@ -147,9 +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, ofs_running); - } + 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 c48fdd347e2..f4ad52cf393 100644 --- a/source/source_io/module_dos/cal_pdos_gamma.h +++ b/source/source_io/module_dos/cal_pdos_gamma.h @@ -6,17 +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 +#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, @@ -25,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, - std::ofstream& ofs_running); + 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 6246c36c409..7d3a2b4e65f 100644 --- a/source/source_io/module_dos/cal_pdos_multik.cpp +++ b/source/source_io/module_dos/cal_pdos_multik.cpp @@ -1,18 +1,14 @@ #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_notice.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 nbands, @@ -21,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, - std::ofstream& ofs_running) + const int nspin) { ModuleBase::TITLE("ModuleIO", "cal_pdos_multik"); @@ -187,9 +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, ofs_running); - } + 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 f28a5cce6e6..417c682bd7b 100644 --- a/source/source_io/module_dos/cal_pdos_multik.h +++ b/source/source_io/module_dos/cal_pdos_multik.h @@ -6,18 +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 +#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, @@ -26,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, - std::ofstream& ofs_running); + const int nspin); } 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/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_cal_dos.cpp b/source/source_io/module_dos/unittests/test_cal_dos.cpp index c32e9cbc27f..795774ed8ac 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 @@ -54,7 +58,7 @@ TEST_F(DosTest,Dos) dosp.wg, istep, out_app_flag, - bndpar); + bndpar, nullptr); #ifdef __MPI if(GlobalV::MY_RANK==0) @@ -124,6 +128,41 @@ TEST_F(DosTest,Dos) +TEST_F(DosTest, CapturesSpectrumWithoutTextOutput) +{ + 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; + 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()); + for (size_t row = 0; row < expected.size(); ++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; + } + } +} + TEST_F(DosTest,DosW1) { //is,fa,de_ev,emax_ev,emin_ev,bcoeff,nks,nkstot,nbands @@ -153,7 +192,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 +239,7 @@ TEST_F(DosTest,DosW2) dosp.wg, istep, out_app_flag, - bndpar)); + bndpar, nullptr)); GlobalV::ofs_warning.close(); #ifdef __MPI @@ -238,12 +277,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 +319,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/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 6baccffb0f6..a505bbfd754 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 @@ -181,6 +182,39 @@ TEST_F(WritePdosTextTest, SpinPolarized) remove("test_write_pdos_text.log"); } +TEST_F(WritePdosTextTest, NpySumsZetasAndSpinorsBeforeThreshold) +{ + Atom& atom = ucell->atoms[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); + 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 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 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], 42.0); + EXPECT_DOUBLE_EQ(spectrum[1], 1.2e-6); + EXPECT_DOUBLE_EQ(spectrum[2], 0.0); + file.close(); + if (!fixture_path) { std::remove(path.c_str()); } +} + // --------------------------------------------------------------------------- // out_app_flag = 1: fixed-name files, successive calls append records. // --------------------------------------------------------------------------- diff --git a/source/source_io/module_dos/write_dos_lcao.cpp b/source/source_io/module_dos/write_dos_lcao.cpp index f4eaf987da7..b63c9e73b63 100644 --- a/source/source_io/module_dos/write_dos_lcao.cpp +++ b/source/source_io/module_dos/write_dos_lcao.cpp @@ -2,12 +2,58 @@ #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" +#include "source_base/tool_quit.h" #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 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"}) + { + fields += std::string(",('") + name + field_type; + } + + std::ofstream out; + 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 std::size_t record_width = 1 + 4 * spins; + std::vector record(record_width); + const std::size_t 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, @@ -22,6 +68,7 @@ void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const int out_dos, const int out_app_flag, const int istep, const int nspin, @@ -57,23 +104,26 @@ void write_dos_lcao( dos_emin_ev, two_fermi); - // output the DOS file. + std::vector total_dos; + if (out_dos == 2) + { + total_dos.resize(nspin0); + } for (int is = 0; is < nspin0; ++is) { std::stringstream ss; - - 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) + DosSpectrum* spectrum = nullptr; + if (out_dos == 2) { - ss << "g" << istep+1; + spectrum = &total_dos[is]; } - - ss << ".txt"; - - ModuleIO::cal_dos(is, + else + { + ss << global_out_dir << "doss" << is + 1; + if (istep >= 0 && out_app_flag == 2) { ss << "g" << istep + 1; } + ss << ".txt"; + } + const bool calculated = ModuleIO::cal_dos(is, ss.str(), dos_edelta_ev, emax, @@ -88,9 +138,14 @@ void write_dos_lcao( wg, istep, out_app_flag, - bndpar); + bndpar, + spectrum); - if (GlobalV::MY_RANK == 0) + if (out_dos == 2 && !calculated) + { + ModuleBase::WARNING_QUIT("write_dos_lcao", "Cannot calculate total DOS for dos.npy"); + } + if (out_dos != 2 && GlobalV::MY_RANK == 0) { ModuleIO::write_notice(ofs_running, "DOS", is, nspin, ss.str()); } @@ -98,10 +153,9 @@ void write_dos_lcao( // out_dos >= 1: always compute PDOS alongside DOS (LCAO only) - cal_pdos(psi, + const std::vector pdos = cal_pdos(psi, p_ham, pv, - ucell, kv, nspin0, nbands, @@ -110,12 +164,39 @@ void write_dos_lcao( emin, dos_edelta_ev, bcoeff, - istep, - out_app_flag, nlocal, - nspin, - global_out_dir, - ofs_running); + nspin); + + std::string error; + if (GlobalV::MY_RANK == 0) + { + if (out_dos == 2) + { + 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); + } + 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, ofs_running); + } + } + if (out_dos == 2) + { + Parallel_Common::bcast_string(error); + if (!error.empty()) { ModuleBase::WARNING_QUIT("write_dos_lcao", error); } + } ofs_running << " #DOS CALCULATION ENDS#" << std::endl; @@ -136,6 +217,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + const int out_dos, const int out_app_flag, const int istep, const int nspin, @@ -163,6 +245,7 @@ template void write_dos_lcao( const double& dos_edelta_ev, const double& dos_scale, const double& bcoeff, + 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 25e8b6d14a6..468cb109ae3 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 int out_dos, 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 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_dos/write_pdos_text.cpp b/source/source_io/module_dos/write_pdos_text.cpp index f931f94fd0e..ab99418ee44 100644 --- a/source/source_io/module_dos/write_pdos_text.cpp +++ b/source/source_io/module_dos/write_pdos_text.cpp @@ -1,14 +1,57 @@ #include "write_pdos_text.h" +#include "dos_npy_header.h" #include "source_base/global_variable.h" #include "source_io/module_output/provenance_header.h" #include "source_io/module_output/write_notice.h" +#include #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) + { + 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) + { + 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 (PdosBlock::value_type& 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, @@ -64,35 +107,10 @@ 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 ModuleBase::matrix* spin_pdos = pdos + is; + const PdosBlock channels = atom_pdos(ucell, iat, spin_pdos, 1, spinor); for (int n = 0; n < npoints; ++n) { @@ -102,39 +120,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 PdosBlock::value_type& 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; } @@ -145,3 +133,55 @@ void ModuleIO::write_pdos_text( ModuleIO::write_notice(ofs_running, "PDOS", is, nspin, ss.str()); } } + +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 << "))"; + const std::uint64_t row_bytes = 32 + width + sizeof(double) * static_cast(ne) * pdos.size(); + if (row_bytes > std::numeric_limits::max()) + { + throw std::runtime_error("PDOS array exceeds NumPy v1 dtype limits"); + } + 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.str(), count); + 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 PdosBlock channels = atom_pdos(cell, iat, pdos.data(), pdos.size(), spinor); + for (const PdosBlock::value_type& 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()); + const std::size_t spectrum_bytes = channel.second.size() * sizeof(double); + out.write(reinterpret_cast(channel.second.data()), spectrum_bytes); + } + } + 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 8f20b5061c3..6119a58f681 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 #include @@ -26,6 +27,10 @@ void write_pdos_text( const int out_app_flag, std::ofstream& ofs_running); +/// 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_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 5b66f054b10..77d4f7373b8 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -381,22 +381,27 @@ 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 (`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 = ""; 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 Input_para& 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/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 252df3cc8fa..bff1993149b 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -778,6 +778,41 @@ TEST_F(InputParaTest, RemovedElpaZSolverIsRejected) EXPECT_EXIT(item.check_value(item, param), testing::ExitedWithCode(1), ""); } +TEST_F(InputParaTest, OutDosNpy) +{ + ModuleIO::ReadInput reader(0); + const std::vector>& entries = reader.get_input_lists(); + std::map items(entries.begin(), entries.end()); + Parameter param; + 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 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 char* calculation : {"scf", "nscf"}) + { + set("calculation", calculation); + output.check_value(output, param); + } + set("calculation", "md"); + EXPECT_EXIT(output.check_value(output, param), testing::ExitedWithCode(1), ""); + set("calculation", "scf"); + set("esolver_type", "lr"); + EXPECT_EXIT(output.check_value(output, param), testing::ExitedWithCode(1), ""); + set("esolver_type", "ksdft"); + set("basis_type", "pw"); + EXPECT_EXIT(output.check_value(output, param), testing::ExitedWithCode(1), ""); + set("out_dos", "1"); + output.check_value(output, param); +} + TEST_F(InputParaTest, OpticalGaugeCanDisableSpectrum) { diff --git a/tests/03_NAO_multik/scf_out_dos_spin2/INPUT b/tests/03_NAO_multik/scf_out_dos_spin2/INPUT index acebda90702..ad815adc1c9 100644 --- a/tests/03_NAO_multik/scf_out_dos_spin2/INPUT +++ b/tests/03_NAO_multik/scf_out_dos_spin2/INPUT @@ -27,4 +27,7 @@ mixing_type broyden mixing_beta 0.4 mixing_beta_mag 0.4 -out_dos 1 +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/dos.ref.json b/tests/03_NAO_multik/scf_out_dos_spin2/dos.ref.json new file mode 100644 index 00000000000..4db9ba6f0f8 --- /dev/null +++ b/tests/03_NAO_multik/scf_out_dos_spin2/dos.ref.json @@ -0,0 +1,16 @@ +{ + "records": 32, + "nspin": 2, + "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]}, + {"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_dos_npy.py b/tests/integrate/validation_tools/check_dos_npy.py new file mode 100644 index 00000000000..4d0e22962a4 --- /dev/null +++ b/tests/integrate/validation_tools/check_dos_npy.py @@ -0,0 +1,61 @@ +"""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 = ("dos", "dos_int", "dos_smear", "dos_smear_int") + spins = 2 if nspin == 2 else 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__": + 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/props_basic.sh b/tests/integrate/validation_tools/props_basic.sh index 25529af50cc..9171e728eca 100644 --- a/tests/integrate/validation_tools/props_basic.sh +++ b/tests/integrate/validation_tools/props_basic.sh @@ -122,6 +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 + 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 4014869afe3..51cbd1a15f9 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,27 @@ 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 / "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") + + 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() diff --git a/tools/02_postprocessing/plot-tools/abacus_plot/dos.py b/tools/02_postprocessing/plot-tools/abacus_plot/dos.py index 6c310eeb1c0..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 5-column text - 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. @@ -198,6 +199,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 +214,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 / 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}'") - 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 +243,21 @@ 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}") + 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 + rows = [] with open(fname) as f: for line in f: @@ -350,7 +362,7 @@ 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 projected DOS from ABACUS text files or a single pdos.npy. The text format (one file per spin channel) looks like:: @@ -391,6 +403,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"): @@ -491,6 +507,30 @@ def _read_one(self, fname: str): return energy, orbitals + 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}") + 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}") + 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(), + l=int(row["l"]), m=int(row["m"]), data=row["pdos"].T) + for i, row in enumerate(rows, 1) + ] + def _read(self): """Read partial DOS data file(s) @@ -499,6 +539,9 @@ def _read(self): ``pdoss1*``/``pdoss2*`` files. """ spin_files = self._find_spin_files() + if Path(spin_files[0]).suffix == ".npy": + self._read_npy(spin_files[0]) + return self.nspin = len(spin_files) energy, orbitals_up = self._read_one(spin_files[0]) diff --git a/tools/02_postprocessing/plot-tools/tests/test_dos.py b/tools/02_postprocessing/plot-tools/tests/test_dos.py index db1107c7cc1..62ea6e50e0f 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): @@ -113,6 +113,53 @@ 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_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]) @@ -126,5 +173,55 @@ def test_plain_axes_and_missing_subplot_apis(self): self.assertEqual(ax.get_xlabel(), "Energy(eV)") +class PDOSNumPyTest(unittest.TestCase): + @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, record) + 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) + + 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.) + + 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()