From 24f602a16ff5ab9ec6d29ba21cd9ec2ad5319953 Mon Sep 17 00:00:00 2001 From: maki49 <1579492865@qq.com> Date: Thu, 19 Nov 2026 21:43:17 -0500 Subject: [PATCH 1/6] feat(lr): add full-Hamiltonian optical commutator velocity Reuse the real-time AO velocity, position integrals and LR transition projection. Read H(R) and S(R) from text CSR for standalone LR and use the in-memory KS blocks for ks-lr. Cover the opt-in gauge with a multik Si absorption regression and check the fixed-orbital SRCH result against an independent Fourier reconstruction. (cherry picked from commit caed480b98c9221af07f3c452451c745550e9dfd) --- docs/advanced/elec_properties/hs_matrix.md | 16 ++ source/source_esolver/esolver_lr_init.cpp | 2 +- .../source_esolver/esolver_lr_lcao_tddft.cpp | 47 ++++- .../module_hcontainer/read_hcontainer.cpp | 9 +- source/source_hamilt/module_xc/exx_info.cpp | 11 +- .../module_xc/general_exx_info.h | 11 + .../source_io/module_current/td_current_io.h | 16 +- .../module_current/td_current_io_comm.cpp | 183 +++++++++-------- .../module_parameter/read_inp_out.cpp | 2 + .../module_parameter/read_inp_tddft.cpp | 71 ++++++- .../unittests/test_read_input_parallel.cpp | 60 +++++- source/source_lcao/module_lr/init_helpers.cpp | 2 +- source/source_lcao/module_lr/lr_spectrum.cpp | 4 +- source/source_lcao/module_lr/lr_spectrum.h | 9 +- .../module_lr/utils/spectrum_mo.cpp | 193 +++++++++++++----- .../source_lcao/module_lr/utils/spectrum_mo.h | 17 ++ tests/08_RI/CASES_CPU.txt | 1 + .../08_RI/lr_tddft_velocity_commutator/INPUT | 36 ++++ tests/08_RI/lr_tddft_velocity_commutator/KPT | 4 + tests/08_RI/lr_tddft_velocity_commutator/STRU | 21 ++ .../absorption.dat.ref | 101 +++++++++ .../lr_tddft_velocity_commutator/result.ref | 6 + tests/integrate/validation_tools/props_ml.sh | 4 + 23 files changed, 649 insertions(+), 177 deletions(-) create mode 100644 tests/08_RI/lr_tddft_velocity_commutator/INPUT create mode 100644 tests/08_RI/lr_tddft_velocity_commutator/KPT create mode 100644 tests/08_RI/lr_tddft_velocity_commutator/STRU create mode 100644 tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref create mode 100644 tests/08_RI/lr_tddft_velocity_commutator/result.ref diff --git a/docs/advanced/elec_properties/hs_matrix.md b/docs/advanced/elec_properties/hs_matrix.md index 4a800b0b305..c6d46ac53c7 100644 --- a/docs/advanced/elec_properties/hs_matrix.md +++ b/docs/advanced/elec_properties/hs_matrix.md @@ -93,6 +93,22 @@ In gamma-only mode, every generated file reports one Bravais lattice vector and # representation: gamma-only folded matrix; stored R-space contributions are summed into R = (0, 0, 0) ``` +### Using the matrices for LR-TDDFT absorption + +The full-Hamiltonian [velocity commutator](../input_files/input-main.md#abs_gauge) is available for MPI LCAO LR-TDDFT with `gamma_only 0`. If the ground-state functional uses exact exchange, LR-TDDFT selects it when `abs_gauge` is omitted. With `ks-lr`, the ground-state solver supplies the matrices in memory. + +For standalone `lr`, add the following to the SCF or NSCF input that supplies the orbitals: + +```text +gamma_only 0 +out_hsr 1 12 +out_app_flag 0 +``` + +Place `hrs1_nao.csr` and `sr_nao.csr` in the LR `read_file_dir` alongside the matching wavefunctions. For `nspin 2`, also place `hrs2_nao.csr` there. ABACUS calculates the position integrals internally. The single `nspin 1` Hamiltonian block is used at its original scale, with spin degeneracy included in the singlet transition amplitude. + +For local and semilocal functionals without exact exchange, use `abs_gauge velocity`. Its direct momentum and nonlocal pseudopotential integrals avoid the additional finite-AO projection used to form the full commutator. + ### Native Binary CSR Format Set `out_hsr 2` to write the same H(R) and S(R) matrix sets with a `.dat` suffix. For example, an `nspin = 2` calculation writes `hrs1_nao.dat`, `hrs2_nao.dat`, and `sr_nao.dat`. When `out_app_flag` is 2, the one-based ionic step is included before `_nao`, for example `hrs1g1_nao.dat` and `srg1_nao.dat`. diff --git a/source/source_esolver/esolver_lr_init.cpp b/source/source_esolver/esolver_lr_init.cpp index 41223492a13..5925a7b6ce4 100644 --- a/source/source_esolver/esolver_lr_init.cpp +++ b/source/source_esolver/esolver_lr_init.cpp @@ -376,7 +376,7 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell /// read orbitals and build the interpolation table two_center_bundle_own_.build_orb(ucell.ntype, ucell.orbital_fn.data(), inp.orbital_dir); - LCAO_Orbitals orb; + LCAO_Orbitals& orb = this->orb_; two_center_bundle_own_.to_LCAO_Orbitals( orb, inp.lcao_ecut, inp.lcao_dk, inp.lcao_dr, inp.lcao_rmax, inp.out_element_info, inp.cal_force); orb_cutoff_ = orb.cutoffs(); diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index 67cb43729e7..c418cab7134 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr_lcao_tddft.cpp @@ -1,6 +1,7 @@ // LR execution flow and final spectrum/density output. #include "esolver_lr_lcao_tddft.h" #include "source_hamilt/module_xc/xc_functional.h" +#include "source_lcao/hamilt_lcao.h" #include "source_lcao/module_lr/hamilt_ulr.h" #include "source_lcao/module_lr/hsolver_lrtd.h" #include "source_lcao/module_lr/lr_density.h" @@ -282,14 +283,50 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) const std::string gauge = LR_Util::tolower(this->inp_->abs_gauge); const bool calculate_spectrum = gauge != "none"; const std::vector spatial_weights = LR_Util::spatial_k_weights(this->kv.wk, nspin); - // cal spectrum - if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") + const bool use_velocity = gauge == "velocity" || gauge == "velocity_commutator"; + const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; + if (gauge == "velocity") { - const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; this->velocity_mo = LR_Util::cal_velocity_mo( *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->paraC_, this->kv, *this->psi_ks, this->nk, nspin_tmp, this->nbasis, this->nocc, this->nvirt); } + if (gauge == "velocity_commutator") + { + std::vector*> hr; + hamilt::HContainer overlap(&this->paraMat_); + hamilt::HContainer hr_up(&this->paraMat_); + hamilt::HContainer hr_down(&this->paraMat_); + const hamilt::HContainer* sr = &overlap; + const LCAO_Orbitals& orbitals = this->ks_ ? this->ks_->orb_ : this->orb_; + if (this->ks_) + { + auto* hamilt = static_cast*>(this->ks_->p_hamilt); + const auto spin_blocks = hamilt->getHR_vector(); + hr.assign(spin_blocks.begin(), spin_blocks.end()); + sr = hamilt->getSR(); + } + else + { + const std::string overlap_path = this->in_dir + "sr_nao.csr"; + const std::string up_path = this->in_dir + "hrs1_nao.csr"; + LR_Util::read_velocity_matrix_R(overlap, overlap_path, ucell, this->nbasis, this->my_rank_, + this->ofs_running_); + LR_Util::read_velocity_matrix_R(hr_up, up_path, ucell, this->nbasis, this->my_rank_, + this->ofs_running_); + hr.push_back(&hr_up); + if (nspin_tmp == 2) + { + const std::string down_path = this->in_dir + "hrs2_nao.csr"; + LR_Util::read_velocity_matrix_R(hr_down, down_path, ucell, this->nbasis, this->my_rank_, + this->ofs_running_); + hr.push_back(&hr_down); + } + } + this->velocity_mo = LR_Util::cal_commutator_velocity_mo( + ucell, this->gd(), orbitals, this->paraMat_, this->paraC_, this->kv, *this->psi_ks, + this->nk, nspin_tmp, this->nocc, this->nvirt, this->inp_->cal_force, *sr, hr); + } std::vector freq; if (calculate_spectrum) { @@ -322,8 +359,8 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, this->kv, spatial_weights, this->gd(), this->orb_cutoff_, this->tcb(), this->paraX_, this->paraC_, this->paraMat_, &this->pelec->ekb.c[is * nstates], this->eig_ks.c, this->X[is].template data(), nstates, openshell, - LR_Util::tolower(this->inp_->abs_gauge), this->my_rank_, this->out_dir); - if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") + gauge, this->my_rank_, this->out_dir); + if (use_velocity) { spectrum.set_vmo(this->velocity_mo.data()); } diff --git a/source/source_hamilt/module_hcontainer/read_hcontainer.cpp b/source/source_hamilt/module_hcontainer/read_hcontainer.cpp index 4ca22e466ff..b64f1a7b5d5 100644 --- a/source/source_hamilt/module_hcontainer/read_hcontainer.cpp +++ b/source/source_hamilt/module_hcontainer/read_hcontainer.cpp @@ -2,6 +2,7 @@ #include "source_base/module_out/sparse_matrix.h" #include "source_base/module_out/csr_reader.h" +#include "source_base/tool_quit.h" #include "hcontainer_funcs.h" #include "transfer.h" @@ -55,8 +56,12 @@ void Read_HContainer::read() { #endif ModuleIO::csrFileReader csr(this->_filename); - int step = csr.getStep(); - int matrix_dimension = csr.getMatrixDimension(); + const int matrix_dimension = csr.getMatrixDimension(); + if (matrix_dimension != this->_nlocal) + { + ModuleBase::WARNING_QUIT("Read_HContainer::read", + "Matrix dimension in " + this->_filename + " does not match the number of basis functions."); + } int r_number = csr.getNumberOfR(); //construct serial hcontainer firstly diff --git a/source/source_hamilt/module_xc/exx_info.cpp b/source/source_hamilt/module_xc/exx_info.cpp index aea194e4979..79c542cc259 100644 --- a/source/source_hamilt/module_xc/exx_info.cpp +++ b/source/source_hamilt/module_xc/exx_info.cpp @@ -26,16 +26,7 @@ bool init_general_exx_info(General_Exx_Info& info, const Input_para& inp) dft_functional_lower.begin(), tolower); bool generate_opt_orb = false; - if (dft_functional_lower == "hf" - || dft_functional_lower == "pbe0" || dft_functional_lower == "b3lyp" || dft_functional_lower == "hse" - || dft_functional_lower == "scan0" - || dft_functional_lower == "muller" || dft_functional_lower == "power" - || dft_functional_lower == "cwp22" || dft_functional_lower == "wp22" - || dft_functional_lower == "lc_pbe" - || dft_functional_lower == "lc_wpbe" - || dft_functional_lower == "lrc_wpbe" - || dft_functional_lower == "lrc_wpbeh" - || dft_functional_lower == "cam_pbeh") + if (xc_uses_exact_exchange(dft_functional_lower)) { info.cal_exx = true; diff --git a/source/source_hamilt/module_xc/general_exx_info.h b/source/source_hamilt/module_xc/general_exx_info.h index 8d678299c59..b1b58490365 100644 --- a/source/source_hamilt/module_xc/general_exx_info.h +++ b/source/source_hamilt/module_xc/general_exx_info.h @@ -4,6 +4,17 @@ #include "coulomb_config.h" #include +#include + +/// Identify functionals that assemble a nonlocal Fock term. The name is lowercase. +inline bool xc_uses_exact_exchange(const std::string& functional) +{ + return functional == "hf" || functional == "pbe0" || functional == "b3lyp" + || functional == "hse" || functional == "scan0" || functional == "muller" + || functional == "power" || functional == "cwp22" || functional == "wp22" + || functional == "lc_pbe" || functional == "lc_wpbe" || functional == "lrc_wpbe" + || functional == "lrc_wpbeh" || functional == "cam_pbeh"; +} /// General EXX configuration, independent of basis type. /// Contains the fields needed by both PW and LCAO EXX calculations. diff --git a/source/source_io/module_current/td_current_io.h b/source/source_io/module_current/td_current_io.h index e0f85638c6d..09f7728aaac 100644 --- a/source/source_io/module_current/td_current_io.h +++ b/source/source_io/module_current/td_current_io.h @@ -57,12 +57,11 @@ void write_current( const Exx_NAO>& exx_nao, const Exx_Info& exx_info ); -void set_rR_from_hR(const UnitCell& ucell, +void set_position_matrix_R(const UnitCell& ucell, const Grid_Driver& GridD, const LCAO_Orbitals& orb, const Parallel_Orbitals* pv, Position_op& r_calculator, - const hamilt::HContainer>* hR, ModuleBase::Vector3*>& rR); template void sum_HR( @@ -87,15 +86,16 @@ void init_from_adj(const UnitCell& ucell, ModuleBase::Vector3*>& rR); template void init_from_hR(const hamilt::HContainer* hR, hamilt::HContainer* aimR); -template +/// Compute i[H,r] in the nonorthogonal AO basis, in Ry*Bohr. +/// A null TD context uses field-free Bloch folds. Use one H(R) block per spin. +template void cal_velocity_basis_k(const UnitCell& ucell, - TD_info* td_p, - const LCAO_Orbitals& orb, - const Parallel_Orbitals* pv, + const TD_info* td_p, + const Parallel_Blkcyclic& layout, const K_Vectors& kv, const ModuleBase::Vector3*>& rR, - const hamilt::HContainer& sR, - const std::vector>*>& spin_hR, + const hamilt::HContainer& sR, + const std::vector*>& hr_spin, std::vector*>>& velocity_basis_k); void cal_velocity_matrix(const psi::Psi>* psi, diff --git a/source/source_io/module_current/td_current_io_comm.cpp b/source/source_io/module_current/td_current_io_comm.cpp index 059dd69aa2f..b5f5b290cd3 100644 --- a/source/source_io/module_current/td_current_io_comm.cpp +++ b/source/source_io/module_current/td_current_io_comm.cpp @@ -105,16 +105,15 @@ void ModuleIO::init_from_adj(const UnitCell& ucell, ModuleBase::timer::end("ModuleIO", "init_from_adj"); } -void ModuleIO::set_rR_from_hR(const UnitCell& ucell, +void ModuleIO::set_position_matrix_R(const UnitCell& ucell, const Grid_Driver& GridD, const LCAO_Orbitals& orb, const Parallel_Orbitals* pv, Position_op& r_calculator, - const hamilt::HContainer>* hR, ModuleBase::Vector3*>& rR) { - ModuleBase::TITLE("ModuleIO", "set_rR_from_hR"); - ModuleBase::timer::start("ModuleIO", "set_rR_from_hR"); + ModuleBase::TITLE("ModuleIO", "set_position_matrix_R"); + ModuleBase::timer::start("ModuleIO", "set_position_matrix_R"); // init std::vector adjs_all; @@ -182,8 +181,7 @@ void ModuleIO::set_rR_from_hR(const UnitCell& ucell, } } } - ModuleBase::timer::end("ModuleIO", "set_rR_from_hR"); - ModuleBase::TITLE("ModuleIO", "set_rR_from_sR"); + ModuleBase::timer::end("ModuleIO", "set_position_matrix_R"); } template void ModuleIO::sum_HR(const UnitCell& ucell, @@ -249,23 +247,21 @@ void ModuleIO::add_HR(const hamilt::HContainer* hR, hamilt::HContainer +template void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, - TD_info* td_p, - const LCAO_Orbitals& orb, - const Parallel_Orbitals* pv, + const TD_info* td_p, + const Parallel_Blkcyclic& layout, const K_Vectors& kv, const ModuleBase::Vector3*>& rR, - const hamilt::HContainer& sR, - const std::vector>*>& spin_hR, + const hamilt::HContainer& sR, + const std::vector*>& hr_spin, std::vector*>>& velocity_basis_k) { ModuleBase::TITLE("ModuleIO", "cal_velocity_basis_k"); ModuleBase::timer::start("ModuleIO", "cal_velocity_basis_k"); #ifdef __MPI - const int nlocal = PARAM.globalv.nlocal; + const int nlocal = layout.nrglb(); + const bool hybrid_gauge = td_p && td_p->field().gauge() == 2; const char N_char = 'N'; const std::complex one_imag = ModuleBase::IMAG_UNIT; const std::complex neg_one_imag = ModuleBase::NEG_IMAG_UNIT; @@ -273,25 +269,36 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, const std::complex neg_one_real = ModuleBase::NEG_ONE; const std::complex zero_complex = ModuleBase::ZERO; - std::complex* hk = new std::complex[pv->para_2d().size()]; - std::complex* sk = new std::complex[pv->para_2d().size()]; - std::complex* partial_hk = new std::complex[pv->para_2d().size()]; - std::complex* partial_sk = new std::complex[pv->para_2d().size()]; - std::complex* rk = new std::complex[pv->para_2d().size()]; - std::complex* h_is = new std::complex[pv->para_2d().size()]; - std::complex* h_is_r = new std::complex[pv->para_2d().size()]; - std::complex* r_is = new std::complex[pv->para_2d().size()]; - std::complex* r_is_h = new std::complex[pv->para_2d().size()]; - std::complex* h_is_ps = new std::complex[pv->para_2d().size()]; + std::vector> hk_storage(layout.size()); + std::complex* const hk = hk_storage.data(); + std::vector> sk_storage(layout.size()); + std::complex* const sk = sk_storage.data(); + std::vector> partial_hk_storage(layout.size()); + std::complex* const partial_hk = partial_hk_storage.data(); + std::vector> partial_sk_storage(layout.size()); + std::complex* const partial_sk = partial_sk_storage.data(); + std::vector> rk_storage(layout.size()); + std::complex* const rk = rk_storage.data(); + std::vector> h_is_storage(layout.size()); + std::complex* const h_is = h_is_storage.data(); + std::vector> h_is_r_storage(layout.size()); + std::complex* const h_is_r = h_is_r_storage.data(); + std::vector> r_is_storage(layout.size()); + std::complex* const r_is = r_is_storage.data(); + std::vector> r_is_h_storage(layout.size()); + std::complex* const r_is_h = r_is_h_storage.data(); + std::vector> h_is_ps_storage(layout.size()); + std::complex* const h_is_ps = h_is_ps_storage.data(); for (size_t ik = 0; ik != kv.get_nks(); ++ik) { - const hamilt::HContainer>& hR = *spin_hR[kv.isk[ik]]; + const int spin = hr_spin.size() == 1 ? 0 : kv.isk[ik]; + const hamilt::HContainer& hR = *hr_spin[spin]; // set H(k), S(k) // 1.1 set H(k) - ModuleBase::GlobalFunc::ZEROS(hk, pv->para_2d().size()); - const int nrow = pv->para_2d().nrloc(); - if (td_p->field().gauge() == 2) + ModuleBase::GlobalFunc::ZEROS(hk, layout.size()); + const int nrow = layout.nrloc(); + if (hybrid_gauge) { module_rt::folding_HR_td(hR, hk, kv.kvec_d[ik], td_p->endpoint_A(), td_p->get_phase_hybrid(), nrow, 1); } @@ -300,8 +307,8 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, hamilt::folding_HR(hR, hk, kv.kvec_d[ik], nrow, 1); } // 1.2 set S(k) - ModuleBase::GlobalFunc::ZEROS(sk, pv->para_2d().size()); - if (td_p->field().gauge() == 2) + ModuleBase::GlobalFunc::ZEROS(sk, layout.size()); + if (hybrid_gauge) { module_rt::folding_HR_td(sR, sk, kv.kvec_d[ik], td_p->endpoint_A(), td_p->get_phase_hybrid(), nrow, 1); } @@ -310,40 +317,50 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, hamilt::folding_HR(sR, sk, kv.kvec_d[ik], nrow, 1); } // 2. set inverse S(k) -> sk will be changed to sk_inv - int* ipiv = new int[pv->para_2d().size()]; + std::vector ipiv(layout.nrloc() + layout.nb()); int info = 0; // 2.1 compute ipiv - ScalapackConnector::getrf(nlocal, nlocal, sk, 1, 1, pv->para_2d().desc(), ipiv, &info); + ScalapackConnector::getrf(nlocal, nlocal, sk, 1, 1, layout.desc(), ipiv.data(), &info); + if (info != 0) + { + ModuleBase::WARNING_QUIT("cal_velocity_basis_k", "Could not factor the AO overlap S(k)."); + } int lwork = -1; - int liwotk = -1; + int liwork = -1; std::vector> work(1, 0); std::vector iwork(1, 0); // 2.2 compute work - ScalapackConnector::getri(nlocal, sk, 1, 1, pv->para_2d().desc(), ipiv, work.data(), &lwork, iwork.data(), &liwotk, &info); + ScalapackConnector::getri(nlocal, sk, 1, 1, layout.desc(), ipiv.data(), work.data(), &lwork, iwork.data(), &liwork, &info); + if (info != 0) + { + ModuleBase::WARNING_QUIT("cal_velocity_basis_k", "Could not query the AO overlap inverse workspace."); + } lwork = work[0].real(); work.resize(lwork, 0); - liwotk = iwork[0]; - iwork.resize(liwotk, 0); + liwork = iwork[0]; + iwork.resize(liwork, 0); // 2.3 compute inverse matrix of Sk ScalapackConnector::getri(nlocal, sk, // return sk^-1 1, 1, - pv->para_2d().desc(), - ipiv, + layout.desc(), + ipiv.data(), work.data(), &lwork, iwork.data(), - &liwotk, + &liwork, &info); - delete[] ipiv; - assert(0 == info); + if (info != 0) + { + ModuleBase::WARNING_QUIT("cal_velocity_basis_k", "Could not invert the AO overlap S(k)."); + } for (size_t i_alpha = 0; i_alpha != 3; ++i_alpha) { // 3. set partial_H(k), partial_S(k) and r(k) // 3.1 set partial_H(k) - ModuleBase::GlobalFunc::ZEROS(partial_hk, pv->para_2d().size()); - if (td_p->field().gauge() == 2) + ModuleBase::GlobalFunc::ZEROS(partial_hk, layout.size()); + if (hybrid_gauge) { module_rt::folding_partial_HR_td(ucell, hR, @@ -360,8 +377,8 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, module_rt::folding_partial_HR(ucell, hR, partial_hk, kv.kvec_d[ik], i_alpha, nrow, 1); } // 3.2 set partial S(k) - ModuleBase::GlobalFunc::ZEROS(partial_sk, pv->para_2d().size()); - if (td_p->field().gauge() == 2) + ModuleBase::GlobalFunc::ZEROS(partial_sk, layout.size()); + if (hybrid_gauge) { module_rt::folding_partial_HR_td(ucell, sR, @@ -378,9 +395,8 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, module_rt::folding_partial_HR(ucell, sR, partial_sk, kv.kvec_d[ik], i_alpha, nrow, 1); } // 3.3 set r(k) - ModuleBase::GlobalFunc::ZEROS(rk, pv->para_2d().size()); - // folding_rR(rR[i_alpha], partial_sk, rk, pv, kv.kvec_d[ik], nrow, 1); - if (td_p->field().gauge() == 2) + ModuleBase::GlobalFunc::ZEROS(rk, layout.size()); + if (hybrid_gauge) { module_rt::folding_HR_td(*rR[i_alpha], rk, kv.kvec_d[ik], td_p->endpoint_A(), td_p->get_phase_hybrid(), nrow, 1); } @@ -391,7 +407,7 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, // 4. calculate <\vu,k|v_a|\mu,k> = partial_Hk + IMAG_UNIT * (Hk * Sk_inv * rk) - IMAG_UNIT * (rk * Sk_inv * // Hk) - Hk * Sk_inv * partial_Sk // 4.1.1 Hk * Sk_inv (note 2.) - ModuleBase::GlobalFunc::ZEROS(h_is, pv->para_2d().size()); + ModuleBase::GlobalFunc::ZEROS(h_is, layout.size()); ScalapackConnector::gemm(N_char, N_char, nlocal, @@ -401,18 +417,18 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, hk, 1, 1, - pv->para_2d().desc(), + layout.desc(), sk, 1, 1, - pv->para_2d().desc(), + layout.desc(), zero_complex, h_is, 1, 1, - pv->para_2d().desc()); + layout.desc()); // 4.1.2 (Hk * Sk_inv) * rk - ModuleBase::GlobalFunc::ZEROS(h_is_r, pv->para_2d().size()); + ModuleBase::GlobalFunc::ZEROS(h_is_r, layout.size()); ScalapackConnector::gemm(N_char, N_char, nlocal, @@ -422,18 +438,18 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, h_is, 1, 1, - pv->para_2d().desc(), + layout.desc(), rk, 1, 1, - pv->para_2d().desc(), + layout.desc(), zero_complex, h_is_r, 1, 1, - pv->para_2d().desc()); + layout.desc()); // 4.2.1 rk * Sk_inv (note 2.) - ModuleBase::GlobalFunc::ZEROS(r_is, pv->para_2d().size()); + ModuleBase::GlobalFunc::ZEROS(r_is, layout.size()); ScalapackConnector::gemm(N_char, N_char, nlocal, @@ -443,18 +459,18 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, rk, 1, 1, - pv->para_2d().desc(), + layout.desc(), sk, 1, 1, - pv->para_2d().desc(), + layout.desc(), zero_complex, r_is, 1, 1, - pv->para_2d().desc()); + layout.desc()); // 4.2.2 (rk * Sk_inv) * Hk - ModuleBase::GlobalFunc::ZEROS(r_is_h, pv->para_2d().size()); + ModuleBase::GlobalFunc::ZEROS(r_is_h, layout.size()); ScalapackConnector::gemm(N_char, N_char, nlocal, @@ -464,18 +480,18 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, r_is, 1, 1, - pv->para_2d().desc(), + layout.desc(), hk, 1, 1, - pv->para_2d().desc(), + layout.desc(), zero_complex, r_is_h, 1, 1, - pv->para_2d().desc()); + layout.desc()); // 4.3.1 (Hk * Sk_inv) * partial_Sk - ModuleBase::GlobalFunc::ZEROS(h_is_ps, pv->para_2d().size()); + ModuleBase::GlobalFunc::ZEROS(h_is_ps, layout.size()); ScalapackConnector::gemm(N_char, N_char, nlocal, @@ -485,41 +501,36 @@ void ModuleIO::cal_velocity_basis_k(const UnitCell& ucell, h_is, 1, 1, - pv->para_2d().desc(), + layout.desc(), partial_sk, 1, 1, - pv->para_2d().desc(), + layout.desc(), zero_complex, h_is_ps, 1, 1, - pv->para_2d().desc()); + layout.desc()); // 4.4 h_is_r will be changed to partial_Hk + IMAG_UNIT * (Hk * Sk_inv * rk) - ScalapackConnector::geadd('N', nlocal, nlocal, one_real, partial_hk, 1, 1, pv->para_2d().desc(), one_imag, h_is_r, 1, 1, pv->para_2d().desc()); + ScalapackConnector::geadd('N', nlocal, nlocal, one_real, partial_hk, 1, 1, layout.desc(), one_imag, h_is_r, 1, 1, layout.desc()); // 4.5 r_is_h will be changed to h_is_r - IMAG_UNIT * (rk * Sk_inv * Hk) - ScalapackConnector::geadd('N', nlocal, nlocal, one_real, h_is_r, 1, 1, pv->para_2d().desc(), neg_one_imag, r_is_h, 1, 1, pv->para_2d().desc()); + ScalapackConnector::geadd('N', nlocal, nlocal, one_real, h_is_r, 1, 1, layout.desc(), neg_one_imag, r_is_h, 1, 1, layout.desc()); // 4.6 h_is_ps will be changed to r_is_h - Hk * Sk_inv * partial_Sk - ScalapackConnector::geadd('N', nlocal, nlocal, one_real, r_is_h, 1, 1, pv->para_2d().desc(), neg_one_real, h_is_ps, 1, 1, pv->para_2d().desc()); + ScalapackConnector::geadd('N', nlocal, nlocal, one_real, r_is_h, 1, 1, layout.desc(), neg_one_real, h_is_ps, 1, 1, layout.desc()); // 5. copy h_is_ps to velocity_basis_k[ik][i_alpha] - BlasConnector::copy(pv->para_2d().size(), h_is_ps, 1, velocity_basis_k[ik][i_alpha], 1); + BlasConnector::copy(layout.size(), h_is_ps, 1, velocity_basis_k[ik][i_alpha], 1); } } - delete[] hk; - delete[] sk; - delete[] partial_hk; - delete[] partial_sk; - delete[] rk; - delete[] h_is; - delete[] h_is_r; - delete[] r_is; - delete[] r_is_h; - delete[] h_is_ps; #endif //__MPI ModuleBase::timer::end("ModuleIO", "cal_velocity_basis_k"); } +template void ModuleIO::cal_velocity_basis_k( + const UnitCell&, const TD_info*, const Parallel_Blkcyclic&, const K_Vectors&, + const ModuleBase::Vector3*>&, const hamilt::HContainer&, + const std::vector*>&, std::vector*>>&); + void ModuleIO::cal_velocity_matrix(const psi::Psi>* psi, const Parallel_Orbitals* pv, const K_Vectors& kv, @@ -645,9 +656,9 @@ void ModuleIO::cal_current_comm_k(const UnitCell& ucell, } } // set rR - set_rR_from_hR(ucell, GridD, orb, pv, td_p->r_calculator, spin_hR.front(), rR); - // set velocity_basis_k - cal_velocity_basis_k(ucell, td_p, orb, pv, kv, rR, sR, spin_hR, velocity_basis_k); + set_position_matrix_R(ucell, GridD, orb, pv, td_p->r_calculator, rR); + const auto& layout = pv->para_2d(); + cal_velocity_basis_k(ucell, td_p, layout, kv, rR, sR, spin_hR, velocity_basis_k); // set velocity_k cal_velocity_matrix(psi, pv, kv, velocity_basis_k, velocity_k); diff --git a/source/source_io/module_parameter/read_inp_out.cpp b/source/source_io/module_parameter/read_inp_out.cpp index 5b66f054b10..71b76d37734 100644 --- a/source/source_io/module_parameter/read_inp_out.cpp +++ b/source/source_io/module_parameter/read_inp_out.cpp @@ -680,6 +680,8 @@ When out_app_flag is 2, g followed by the one-based ionic-step index is inserted For multi-k calculations, the output contains the individual real-space blocks stored for the Bravais lattice vectors R. For gamma-only calculations, the internal real-space contributions are folded into a single R = (0, 0, 0) block. This folded result cannot recover the original R-resolved contributions or interpolate arbitrary k points. Terms added only while constructing H(k) are not guaranteed to be present. +Standalone LCAO LR-TDDFT with [abs_gauge](#abs_gauge) set to `velocity_commutator` reads the text CSR matrices from this output. For example, use `out_hsr 1 12`, `out_app_flag 0`, and `gamma_only 0` in the SCF or NSCF run supplying the wavefunctions. Copy `hrs1_nao.csr` and `sr_nao.csr` to `read_file_dir` for LR, with `hrs2_nao.csr` for `nspin 2`. With `nspin 1`, `hrs1_nao.csr` stores the common one-electron Hamiltonian block at its original scale. + For binary output, each file uses the same basename as text output with a .dat suffix. Every native record starts with a five-int versioned header: the magic 0x48535242, the format version (currently 2), the one-based ionic step, the matrix dimension, and the number of R blocks. Files written before this versioned header was introduced (v3.11.0-beta9/beta10 stored a zero-based step, and development builds after that stored a one-based step without any version marker) cannot be interpreted from their content alone, so readers must not assume the current layout for old .dat files. Each R block contains three int coordinates, an int nonzero count, native double values (real/imaginary double pairs for complex matrices), int column indices, and long long row pointers. Native integer representation and byte order are used. When out_app_flag is 0, the fixed file is truncated and overwritten at every write; when out_app_flag is 1, the first ionic step truncates the file and later steps append complete records. [NOTE] In the 3.10-LTS version, the file names are data-HR-sparse_SPIN0.csr and data-SR-sparse_SPIN0.csr, etc.)"; diff --git a/source/source_io/module_parameter/read_inp_tddft.cpp b/source/source_io/module_parameter/read_inp_tddft.cpp index 8a7d8f28274..b854864108b 100644 --- a/source/source_io/module_parameter/read_inp_tddft.cpp +++ b/source/source_io/module_parameter/read_inp_tddft.cpp @@ -1,5 +1,6 @@ #include "source_base/constants.h" #include "source_base/tool_quit.h" +#include "source_hamilt/module_xc/general_exx_info.h" #include "read_input.h" #include "read_input_tool.h" @@ -7,6 +8,7 @@ #include #include #include +#include #include namespace ModuleIO @@ -1422,19 +1424,72 @@ Ignored outside `calculation = relax`.)"; } { Input_Item item("abs_gauge"); - item.annotation = "optical gauge: length, velocity, or none to skip the spectrum"; + item.annotation = "optical gauge for transition dipoles and absorption"; item.category = "Linear Response TDDFT"; item.type = "String"; - item.description = "Optical gauge for LR-TDDFT/BSE: length or velocity. Set none to skip transition dipoles, oscillator strengths, transition analysis and absorption spectra, while retaining excitation energies, requested charge output, and LR forces or relaxation."; - item.default_value = "velocity"; + item.description = R"(Optical gauge for LR-TDDFT and BSE. + +* `velocity`: integrate the momentum and nonlocal pseudopotential commutator directly. Recommended for local and semilocal functionals without exact exchange, since direct integration avoids inserting a finite AO resolution of the identity between the operators. For HSE and other functionals with exact exchange, this omits the commutator of the nonlocal Fock operator with position. +* `velocity_commutator`: build the velocity from the full ground-state Hamiltonian in the nonorthogonal AO basis, including the Fock commutator when exact exchange is present. Available for MPI LCAO LR-TDDFT with [gamma_only](#gamma_only) set to `0`. +* `length`: use position matrix elements. +* `none`: skip transition dipoles, oscillator strengths, transition analysis and absorption spectra. Excitation energies, requested charge output, and LR forces or relaxation are still available. + +If this keyword is omitted, supported LR-TDDFT calculations whose ground-state [dft_functional](#dft_functional) includes exact exchange automatically select `velocity_commutator`. BSE, gamma-only and non-MPI builds use the `velocity` default. Explicit selections take precedence over the automatic selection. + +With `esolver_type ks-lr`, the commutator uses the ground-state matrices already in memory. For standalone `esolver_type lr`, enable text CSR with [out_hsr](#out_hsr) set to `1` in the SCF or NSCF calculation supplying the orbitals. For example, `out_hsr 1 12` uses 12-digit precision. Use [out_app_flag](#out_app_flag) set to `0` to write one frame with the standard filenames. Use `gamma_only 0` there as well. Place the text CSR files `hrs1_nao.csr` and `sr_nao.csr` in [read_file_dir](#read_file_dir) alongside the wavefunctions. Add `hrs2_nao.csr` for `nspin 2`. Use matrices from the same geometry, basis, spin setting and Hamiltonian as the wavefunctions. ABACUS computes the position integrals internally. + +For `nspin 1`, ABACUS uses the single Hamiltonian block as written. Spin degeneracy enters the singlet transition amplitude through a factor of $\sqrt{2}$.)"; + item.default_value = "velocity (velocity_commutator for supported LR-TDDFT with exact exchange)"; item.unit = ""; + item.domain.set_choices({"length", "velocity", "velocity_commutator", "none"}); read_sync_string(input.abs_gauge); - item.check_value = [](const Input_Item& item, const Parameter& para) - { - const std::vector gauges = {"length", "velocity", "none"}; - if (std::find(gauges.begin(), gauges.end(), para.input.abs_gauge) == gauges.end()) + const auto supports_commutator = [](const Input_para& input) { +#ifdef __MPI + const bool is_lr = input.esolver_type == "lr" || input.esolver_type == "ks-lr"; + return is_lr && input.xc_kernel != "bse" && input.basis_type == "lcao" && !input.gamma_only; +#else + (void)input; + return false; +#endif + }; + item.reset_value = [supports_commutator](const Input_Item& item, Parameter& para) { + if (!item.is_read() && supports_commutator(para.input)) + { + std::string functional = para.input.dft_functional; + std::transform(functional.begin(), functional.end(), functional.begin(), + [](unsigned char c) { return std::tolower(c); }); + if (xc_uses_exact_exchange(functional)) + { + para.input.abs_gauge = "velocity_commutator"; + } + } + }; + item.check_value = [supports_commutator](const Input_Item&, const Parameter& para) { + if (para.inp.abs_gauge != "velocity_commutator") + { + return; + } + if (!supports_commutator(para.inp)) { - ModuleBase::WARNING_QUIT("ReadInput", "abs_gauge must be length, velocity or none"); + ModuleBase::WARNING_QUIT("ReadInput", + "abs_gauge velocity_commutator requires MPI LCAO LR-TDDFT with gamma_only 0."); + } + if (para.inp.esolver_type == "lr") + { + const std::vector files = para.inp.nspin == 2 + ? std::vector{"hrs1_nao.csr", "sr_nao.csr", "hrs2_nao.csr"} + : std::vector{"hrs1_nao.csr", "sr_nao.csr"}; + for (const auto& file : files) + { + const std::string path = para.globalv.global_readin_dir + file; + if (!std::ifstream(path)) + { + ModuleBase::WARNING_QUIT("ReadInput", + "abs_gauge velocity_commutator requires " + path + + ". Export matching text CSR matrices with out_hsr 1 " + "in the SCF or NSCF calculation, or select abs_gauge velocity explicitly."); + } + } } }; this->add_item(item); diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 252df3cc8fa..b1566ccd232 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -796,7 +796,61 @@ TEST_F(InputParaTest, OpticalGaugeCanDisableSpectrum) item.check_value(item, param); EXPECT_EQ(param.inp.abs_gauge, gauge); } - item.str_values = {"invalid"}; - item.read_value(item, param); - EXPECT_EXIT(item.check_value(item, param), testing::ExitedWithCode(1), ""); + const auto error = item.domain.validate_explicit(item.label, {"invalid"}); + EXPECT_FALSE(error.empty()); +} + +TEST_F(InputParaTest, OpticalGaugeDefaultsToCommutatorForGroundStateExactExchange) +{ + ModuleIO::ReadInput reader(0); + const auto& list = reader.get_input_lists(); + const std::map items(list.begin(), list.end()); + auto item = items.at("abs_gauge"); + const auto set = [&items](Parameter& parameter, const std::string& label, const std::string& value) { + auto option = items.at(label); + option.str_values = {value}; + option.read_value(option, parameter); + }; + for (const std::string functional : {"HSE", "cam_pbeh", "hf", "pbe0", "wp22"}) + { + Parameter parameter; + set(parameter, "basis_type", "lcao"); + set(parameter, "esolver_type", "ks-lr"); + set(parameter, "dft_functional", functional); + set(parameter, "xc_kernel", "rpa"); + item.reset_value(item, parameter); + EXPECT_EQ(parameter.inp.abs_gauge, "velocity_commutator") << functional; + item.check_value(item, parameter); + } + + Parameter parameter; + set(parameter, "basis_type", "lcao"); + set(parameter, "esolver_type", "ks-lr"); + set(parameter, "dft_functional", "pbe"); + set(parameter, "xc_kernel", "hse"); + item.reset_value(item, parameter); + EXPECT_EQ(parameter.inp.abs_gauge, "velocity"); + + set(parameter, "dft_functional", "hse"); + set(parameter, "xc_kernel", "hse"); + set(parameter, "gamma_only", "1"); + item.reset_value(item, parameter); + EXPECT_EQ(parameter.inp.abs_gauge, "velocity"); + + set(parameter, "gamma_only", "0"); + set(parameter, "esolver_type", "lr"); + set(parameter, "xc_kernel", "bse"); + item.reset_value(item, parameter); + EXPECT_EQ(parameter.inp.abs_gauge, "velocity"); + + set(parameter, "esolver_type", "ks-lr"); + set(parameter, "dft_functional", "hse"); + set(parameter, "xc_kernel", "hse"); + for (const std::string gauge : {"velocity", "length", "none"}) + { + item.str_values = {gauge}; + item.read_value(item, parameter); + item.reset_value(item, parameter); + EXPECT_EQ(parameter.inp.abs_gauge, gauge); + } } diff --git a/source/source_lcao/module_lr/init_helpers.cpp b/source/source_lcao/module_lr/init_helpers.cpp index fbcc89f5ecb..a1537600669 100644 --- a/source/source_lcao/module_lr/init_helpers.cpp +++ b/source/source_lcao/module_lr/init_helpers.cpp @@ -43,7 +43,7 @@ void check_lr_parameters(const Input_para& input, const std::string& xc_kernel, // functional or a hybrid, both of which `LR_Util` enumerates. Listing the names a third // time here is what used to make a newly supported hybrid fail at input parsing. const std::set kernel_less = { "rpa", "bse" }; - const std::set abs_gauge = { "velocity", "length", "none" }; + const std::set abs_gauge = { "velocity", "velocity_commutator", "length", "none" }; if (lr_solvers.find(input.lr_solver) == lr_solvers.end()) { throw std::invalid_argument("ESolver_LR: unknown type of lr_solver"); } diff --git a/source/source_lcao/module_lr/lr_spectrum.cpp b/source/source_lcao/module_lr/lr_spectrum.cpp index 380b466d74c..945d19757f1 100644 --- a/source/source_lcao/module_lr/lr_spectrum.cpp +++ b/source/source_lcao/module_lr/lr_spectrum.cpp @@ -219,7 +219,7 @@ void LR::LR_Spectrum::transition_analysis(const std::string& spintype) std::ofstream ofs; std::ofstream ofs_k; const int nbands = nocc[0] + nvirt[0]; - const bool use_td_weight = (this->vmo_ptr != nullptr && LR_Util::tolower(this->gauge) == "velocity"); + const bool use_td_weight = (this->vmo_ptr != nullptr); if (this->my_rank == 0) { ofs.open(this->out_dir + "trans_analysis_" + spintype + ".dat"); @@ -248,7 +248,7 @@ void LR::LR_Spectrum::transition_analysis(const std::string& spintype) ofs_k << "# weight2(k) = sum_{state,spin,direction,occ,virt} |td * X|^2 + |td *Y|^2, where td index as (spin,dir,k,occ,virt).\n"; if (!use_td_weight) { - ofs_k << "# NOTE: td-weighted statistics require abs_gauge velocity and a valid velocity_mo pointer.\n"; + ofs_k << "# NOTE: td-weighted statistics require optical velocity matrix elements.\n"; } else { ofs_k << "# \n"; } diff --git a/source/source_lcao/module_lr/lr_spectrum.h b/source/source_lcao/module_lr/lr_spectrum.h index 28845d12186..8a553d8ace2 100644 --- a/source/source_lcao/module_lr/lr_spectrum.h +++ b/source/source_lcao/module_lr/lr_spectrum.h @@ -38,7 +38,14 @@ namespace LR void set_full(bool tag) { this->is_full = tag; }; void cal_spectrum(){ std::cout << "Calculating transition dipole moments in " << this->gauge << " gauge." << std::endl; - this->gauge == "velocity" ? this->cal_transition_dipoles_velocity(this->eig_ks) : this->cal_transition_dipoles_length(); + if (this->gauge == "velocity" || this->gauge == "velocity_commutator") + { + this->cal_transition_dipoles_velocity(this->eig_ks); + } + else + { + this->cal_transition_dipoles_length(); + } this->oscillator_strength(); } /// @brief calculate the optical absorption spectrum with $Im[1/[(w+i\eta)^2-\Omega_S^2]]$ diff --git a/source/source_lcao/module_lr/utils/spectrum_mo.cpp b/source/source_lcao/module_lr/utils/spectrum_mo.cpp index 969452f92e2..57833ff7806 100644 --- a/source/source_lcao/module_lr/utils/spectrum_mo.cpp +++ b/source/source_lcao/module_lr/utils/spectrum_mo.cpp @@ -6,6 +6,8 @@ #include "source_basis/module_ao/elem_basis_idx_orb.h" #include "source_basis/module_nao/two_center_bundle.h" #include "source_cell/klist.h" +#include "source_hamilt/module_hcontainer/read_hcontainer.h" +#include "source_io/module_current/td_current_io.h" #include "source_io/module_parameter/parameter.h" #include "source_hamilt/module_hcontainer/hcontainer_funcs.h" #include "source_lcao/module_lr/ao_to_mo_transformer/ao_to_mo.h" @@ -14,46 +16,20 @@ #include "source_lcao/module_rt/velocity_op.h" #include "source_psi/psi.h" +#include +#include + namespace LR_Util { -template -std::vector> cal_velocity_mo(const UnitCell& ucell, - const Grid_Driver& gd, - const TwoCenterBundle& two_center_bundle, - const Parallel_Orbitals& pmat,/*nbasis×nbasis*/ - const Parallel_Blkcyclic& pc,/*nbasis×nbands*/ - const K_Vectors& kv, - const psi::Psi& psi_ks, - const int nk, - const int nspin_tmp, - const int nbasis, - const std::vector nocc, - const std::vector nvirt) +namespace +{ +template +std::vector> project_velocity_mo(const Parallel_Orbitals& pmat, + const Parallel_Blkcyclic& pc, const K_Vectors& kv, const psi::Psi& psi_ks, + const int nk, const int nspin_tmp, const int nbasis, const std::vector& nocc, + const std::vector& nvirt, const BuildVelocity& build_velocity) { - ModuleBase::TITLE("LR_Util", "cal_velocity_mo"); const std::complex unit_factor(1.0); - ModuleBase::timer::start("LR_Util", "cal_velocity_mo"); - std::cout<<"Calculating velocity matrix in KS presentation..."<> vR(&ucell, - &gd, - basis, - pmat.para_2d(), - orb, - two_center_bundle.overlap_orb.get()); - vR.calculate_grad_term(); // $<\mu, 0|-i∇r|\nu, R>$ - vR.calculate_vcomm_r(); // $<\mu, 0|i[Vnl, r]|\nu, R>$ - int nks = kv.get_nks(); // include spin assert(nks == nk * nspin_tmp); assert(psi_ks.get_nk() == nks); @@ -87,19 +63,8 @@ std::vector> cal_velocity_mo(const UnitCell& ucell, std::vector vk(nks, LR_Util::newTensor>({ pmat.para_2d().ncloc(), pmat.para_2d().nrloc() })); for (int id = 0; id < 3; ++id) { - for (auto& v : vk) v.zero(); - + build_velocity(id, vk); std::vector> v_mo(nks * pmo.size(), 0.0); - - for (int is = 0; is < nspin_tmp; ++is) - { - assert(KS_num == nocc[is] + nvirt[is]); - - for (int ik = is*nk; ik < (is+1)*nk; ++ik) - { - hamilt::folding_HR(*vR.get_current_term_pointer(id), vk[ik].data>(), kv.kvec_d[ik], pmat.para_2d().nrloc(), 1/*column-major*/); - } - } #ifdef __MPI LR::ao_to_mo_pblas(vk, pmat.para_2d(), c_psi_ks, pc, nbasis, nocc[0], nvirt[0], pmo, v_mo.data(), @@ -133,11 +98,139 @@ std::vector> cal_velocity_mo(const UnitCell& ucell, const MPI_Comm velocity_comm = pmo.comm(); Parallel_Common::reduce_data(velocity_mo.data(), velocity_size, velocity_comm); #endif - ModuleBase::GlobalFunc::DONE(GlobalV::ofs_running, "Finish velocity matrix in KS presentation."); - ModuleBase::timer::end("LR_Util", "cal_velocity_mo"); return velocity_mo; } +} // namespace + +template +std::vector> cal_velocity_mo(const UnitCell& ucell, + const Grid_Driver& gd, + const TwoCenterBundle& two_center_bundle, + const Parallel_Orbitals& pmat,/*nbasis×nbasis*/ + const Parallel_Blkcyclic& pc,/*nbasis×nbands*/ + const K_Vectors& kv, + const psi::Psi& psi_ks, + const int nk, + const int nspin_tmp, + const int nbasis, + const std::vector nocc, + const std::vector nvirt) +{ + ModuleBase::timer::start("LR_Util", "cal_velocity_mo"); + LCAO_Orbitals orb; + const auto& inp = PARAM.inp; + two_center_bundle.to_LCAO_Orbitals(orb, inp.lcao_ecut, inp.lcao_dk, inp.lcao_dr, inp.lcao_rmax, + inp.out_element_info, inp.cal_force); + + const ModuleBase::Element_Basis_Index::Range range = + ModuleBase::Element_Basis_Index::construct_range(orb); + const ModuleBase::Element_Basis_Index::IndexLNM hierarchy = + ModuleBase::Element_Basis_Index::construct_index(range); + const BasisFlattenedIndexing basis(hierarchy, ucell.iat2it, ucell.get_npol()); + Velocity_op> vR(&ucell, + &gd, + basis, + pmat.para_2d(), + orb, + two_center_bundle.overlap_orb.get()); + vR.calculate_grad_term(); // $<\mu, 0|-i∇r|\nu, R>$ + vR.calculate_vcomm_r(); // $<\mu, 0|i[Vnl, r]|\nu, R>$ + + auto build_velocity = [&](int direction, std::vector& vk) + { + const auto* velocity_r = vR.get_current_term_pointer(direction); + for (int ik = 0; ik < kv.get_nks(); ++ik) + { + vk[ik].zero(); + hamilt::folding_HR(*velocity_r, vk[ik].data>(), + kv.kvec_d[ik], pmat.para_2d().nrloc(), 1); + } + }; + auto velocity = project_velocity_mo(pmat, pc, kv, psi_ks, nk, nspin_tmp, nbasis, nocc, nvirt, build_velocity); + ModuleBase::timer::end("LR_Util", "cal_velocity_mo"); + return velocity; +} + +template +std::vector> cal_commutator_velocity_mo( + const UnitCell& ucell, const Grid_Driver& gd, const LCAO_Orbitals& orb, + const Parallel_Orbitals& pmat, const Parallel_Blkcyclic& pc, const K_Vectors& kv, + const psi::Psi& psi_ks, const int nk, const int nspin, + const std::vector& nocc, const std::vector& nvirt, const bool cal_force, + const hamilt::HContainer& sr, + const std::vector*>& hr) +{ + ModuleBase::timer::start("LR_Util", "cal_commutator_velocity_mo"); + const auto& layout = pmat.para_2d(); + const int nbasis = layout.nrglb(); + Position_op position_integrals; + position_integrals.init(ucell, layout, orb, cal_force, nbasis); + hamilt::HContainer x(&pmat); + hamilt::HContainer y(&pmat); + hamilt::HContainer z(&pmat); + ModuleBase::Vector3*> rR(&x, &y, &z); + ModuleIO::set_position_matrix_R(ucell, gd, orb, &pmat, position_integrals, rR); + + std::array, 3> velocity_ao; + std::vector*>> blocks(kv.get_nks()); + for (int direction = 0; direction < 3; ++direction) + { + auto& matrices = velocity_ao[direction]; + matrices.resize(kv.get_nks()); + for (int ik = 0; ik < kv.get_nks(); ++ik) + { + matrices[ik] = LR_Util::newTensor>({layout.ncloc(), layout.nrloc()}); + blocks[ik][direction] = matrices[ik].data>(); + } + } + ModuleIO::cal_velocity_basis_k(ucell, nullptr, layout, kv, rR, sr, hr, blocks); + auto build_velocity = [&](int direction, std::vector& vk) + { + vk.swap(velocity_ao[direction]); + // H(R) is in Ry, while LR contracts velocities and KS gaps in Hartree atomic units. + for (auto& matrix : vk) + { + auto* values = matrix.data>(); + for (std::size_t i = 0; i < layout.size(); ++i) + { + values[i] /= ModuleBase::e2; + } + } + velocity_ao[direction].clear(); + }; + auto velocity = project_velocity_mo(pmat, pc, kv, psi_ks, nk, nspin, nbasis, nocc, nvirt, build_velocity); + ModuleBase::timer::end("LR_Util", "cal_commutator_velocity_mo"); + return velocity; +} + +void read_velocity_matrix_R(hamilt::HContainer& matrix, const std::string& path, + const UnitCell& ucell, const int nbasis, const int rank, std::ostream& log) +{ + if (rank == 0) + { + std::ifstream file(path); + if (!file) + { + ModuleBase::WARNING_QUIT("read_velocity_matrix_R", "Cannot open " + path + + ". Generate the text matrices with out_hsr 1 in the ground-state calculation."); + } + std::cout << " Reading optical matrix from " << path << std::endl; + log << " Reading optical matrix from " << path << std::endl; + } + hamilt::Read_HContainer reader(&matrix, path, nbasis, &ucell, rank); + reader.read(); +} +template std::vector> cal_commutator_velocity_mo( + const UnitCell&, const Grid_Driver&, const LCAO_Orbitals&, const Parallel_Orbitals&, + const Parallel_Blkcyclic&, const K_Vectors&, const psi::Psi&, const int, const int, + const std::vector&, const std::vector&, const bool, const hamilt::HContainer&, + const std::vector*>&); +template std::vector> cal_commutator_velocity_mo( + const UnitCell&, const Grid_Driver&, const LCAO_Orbitals&, const Parallel_Orbitals&, + const Parallel_Blkcyclic&, const K_Vectors&, const psi::Psi>&, const int, const int, + const std::vector&, const std::vector&, const bool, const hamilt::HContainer&, + const std::vector*>&); template std::vector> cal_velocity_mo(const UnitCell&, const Grid_Driver&, const TwoCenterBundle&, const Parallel_Orbitals&, const Parallel_Blkcyclic&, const K_Vectors&, const psi::Psi&, const int, const int, const int, const std::vector, const std::vector); template std::vector> cal_velocity_mo>(const UnitCell&, const Grid_Driver&, const TwoCenterBundle&, const Parallel_Orbitals&, const Parallel_Blkcyclic&, const K_Vectors&, const psi::Psi>&, const int, const int, const int, const std::vector, const std::vector); } diff --git a/source/source_lcao/module_lr/utils/spectrum_mo.h b/source/source_lcao/module_lr/utils/spectrum_mo.h index 8d292773255..fd29fa66a2b 100644 --- a/source/source_lcao/module_lr/utils/spectrum_mo.h +++ b/source/source_lcao/module_lr/utils/spectrum_mo.h @@ -1,6 +1,7 @@ #ifndef ABACUS_LR_SPECTRUM_MO_H #define ABACUS_LR_SPECTRUM_MO_H #include +#include #include #include #include "source_psi/psi.h" @@ -10,6 +11,11 @@ class TwoCenterBundle; class Parallel_Orbitals; class Parallel_Blkcyclic; // Defined in source/source_base/parallel_blkcyc.h class K_Vectors; +class LCAO_Orbitals; +namespace hamilt +{ +template class HContainer; +} namespace LR_Util { /// Compute C^dagger v C for the selected KS window; return replicated spin/cartesian/k blocks. @@ -26,6 +32,17 @@ std::vector> cal_velocity_mo(const UnitCell& ucell, const int nbasis, const std::vector nocc, const std::vector nvirt); +/// Compute the same KS window with the full generalized velocity i[H,r]. +template +std::vector> cal_commutator_velocity_mo( + const UnitCell& ucell, const Grid_Driver& gd, const LCAO_Orbitals& orb, + const Parallel_Orbitals& pmat, const Parallel_Blkcyclic& pc, const K_Vectors& kv, + const psi::Psi& psi_ks, const int nk, const int nspin, + const std::vector& nocc, const std::vector& nvirt, const bool cal_force, + const hamilt::HContainer& sr, + const std::vector*>& hr); +void read_velocity_matrix_R(hamilt::HContainer& matrix, const std::string& path, + const UnitCell& ucell, const int nbasis, const int rank, std::ostream& log); void output_spectrum_mo(const std::vector>& out_spectrum_mo, const std::string& filename, const double* const eig_ks, diff --git a/tests/08_RI/CASES_CPU.txt b/tests/08_RI/CASES_CPU.txt index 1c51dd45fd3..80c39f58855 100644 --- a/tests/08_RI/CASES_CPU.txt +++ b/tests/08_RI/CASES_CPU.txt @@ -18,6 +18,7 @@ lr_tddft_pbe_gamma lr_tddft_hf_gamma lr_tddft_hf_ulr_gamma lr_tddft_multik +lr_tddft_velocity_commutator rpa_scf_gamma rpa_scf_shrink_multik rt_tddft_pbe0_gamma diff --git a/tests/08_RI/lr_tddft_velocity_commutator/INPUT b/tests/08_RI/lr_tddft_velocity_commutator/INPUT new file mode 100644 index 00000000000..189ef8a6dca --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/INPUT @@ -0,0 +1,36 @@ +INPUT_PARAMETERS +#Parameters (1.General) +suffix autotest +pseudo_dir ../../../tests/PP_ORB +orbital_dir ../../../tests/PP_ORB +calculation scf +nbands 6 +symmetry -1 +nspin 2 + +#Parameters (2.Iteration) +ecutwfc 10 +scf_thr 1e-6 +scf_nmax 20 + +#Parameters (3.Basis) +basis_type lcao +gamma_only 0 + +#Parameters (4.Smearing) +smearing_method gaussian +smearing_sigma 0.02 + +#Parameters (5.Mixing) +mixing_type pulay +mixing_beta 0.4 + +lr_nstates 2 +xc_kernel lda +lr_solver lapack + +esolver_type ks-lr + +nvirt 2 +abs_wavelen_range 200 600 +abs_gauge velocity_commutator diff --git a/tests/08_RI/lr_tddft_velocity_commutator/KPT b/tests/08_RI/lr_tddft_velocity_commutator/KPT new file mode 100644 index 00000000000..ae9ebb2ca33 --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +2 3 1 0 0 0 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/STRU b/tests/08_RI/lr_tddft_velocity_commutator/STRU new file mode 100644 index 00000000000..4ae6cfd0ff6 --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +Si 1.000 Si.pz-vbc.UPF #Element, Mass, Pseudopotential + +NUMERICAL_ORBITAL +./Si_lda_8.0au_50Ry_2s2p1d + +LATTICE_CONSTANT +10.2 #Lattice constant + +LATTICE_VECTORS +0.0 0.5 0.5 #Lattice vector 1 +0.5 0.0 0.5 #Lattice vector 2 +0.5 0.5 0.0 #Lattice vector 3 + +ATOMIC_POSITIONS +Cartesian #Cartesian(Unit is LATTICE_CONSTANT) +Si #Name of element +0.0 #Magnetic for this element. +2 #Number of atoms +0.00 0.00 0.00 0 0 0 #x,y,z, move_x, move_y, move_z +0.25 0.25 0.25 1 1 1 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref new file mode 100644 index 00000000000..33b6a292de1 --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref @@ -0,0 +1,101 @@ +Frequency (eV) | wave length(nm) | Absorption (a.u.) +6.07766 204 0.0361544 +5.96078 208 0.0390143 +5.84831 212 0.0420752 +5.74001 216 0.0453515 +5.63564 220 0.0488588 +5.53501 224 0.0526141 +5.4379 228 0.0566358 +5.34415 232 0.0609438 +5.25357 236 0.0655601 +5.16601 240 0.0705084 +5.08132 244 0.0758146 +4.99936 248 0.0815073 +4.92001 252 0.0876175 +4.84313 256 0.0941793 +4.76862 260 0.10123 +4.69637 264 0.108811 +4.62628 268 0.116968 +4.55824 272 0.125751 +4.49218 276 0.135215 +4.42801 280 0.145421 +4.36564 284 0.156438 +4.30501 288 0.168341 +4.24603 292 0.181214 +4.18865 296 0.195151 +4.13281 300 0.210257 +4.07843 304 0.22665 +4.02546 308 0.244462 +3.97385 312 0.263842 +3.92355 316 0.284957 +3.87451 320 0.307998 +3.82667 324 0.333181 +3.78001 328 0.36075 +3.73446 332 0.390987 +3.69001 336 0.42421 +3.64659 340 0.46079 +3.60419 344 0.50115 +3.56276 348 0.54578 +3.52228 352 0.595252 +3.4827 356 0.650228 +3.44401 360 0.711485 +3.40616 364 0.779936 +3.36914 368 0.856659 +3.33291 372 0.942931 +3.29745 376 1.04028 +3.26274 380 1.15052 +3.22875 384 1.27585 +3.19547 388 1.41894 +3.16286 392 1.58302 +3.13091 396 1.77207 +3.0996 400 1.99098 +3.06892 404 2.24583 +3.03883 408 2.5442 +3.00932 412 2.89562 +2.98039 416 3.3121 +2.952 420 3.80887 +2.92416 424 4.40529 +2.89683 428 5.12597 +2.87 432 6.00201 +2.84367 436 7.07223 +2.81782 440 8.38378 +2.79244 444 9.9909 +2.7675 448 11.9493 +2.74301 452 14.3011 +2.71895 456 17.0445 +2.69531 460 20.082 +2.67207 464 23.157 +2.64923 468 25.8267 +2.62678 472 27.5501 +2.60471 476 27.9204 +2.583 480 26.8964 +2.56166 484 24.8154 +2.54066 488 22.1807 +2.52 492 19.4333 +2.49968 496 16.8513 +2.47968 500 14.5636 +2.46 504 12.6018 +2.44063 508 10.9474 +2.42157 512 9.5623 +2.40279 516 8.40409 +2.38431 520 7.43349 +2.36611 524 6.61665 +2.34819 528 5.92552 +2.33053 532 5.33729 +2.31314 536 4.83357 +2.296 540 4.39959 +2.27912 544 4.02346 +2.26249 548 3.69561 +2.24609 552 3.40826 +2.22993 556 3.15512 +2.214 560 2.93101 +2.1983 564 2.73168 +2.18282 568 2.55362 +2.16756 572 2.39391 +2.1525 576 2.2501 +2.13766 580 2.12013 +2.12302 584 2.00227 +2.10857 588 1.89504 +2.09433 592 1.79719 +2.08027 596 1.70763 +2.0664 600 1.62544 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/result.ref b/tests/08_RI/lr_tddft_velocity_commutator/result.ref new file mode 100644 index 00000000000..25e091cabbe --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/result.ref @@ -0,0 +1,6 @@ +excitationenergyref1 0.191836 +excitationenergyref2 0.192137 +excitationenergyref3 0.180837 +excitationenergyref4 0.181265 +CompareLRAbsorption_pass 0 +totaltimeref 16 diff --git a/tests/integrate/validation_tools/props_ml.sh b/tests/integrate/validation_tools/props_ml.sh index 3b9bbada15b..00147e0e927 100644 --- a/tests/integrate/validation_tools/props_ml.sh +++ b/tests/integrate/validation_tools/props_ml.sh @@ -68,6 +68,10 @@ run_ml_lr_props() { elif [ ${#lr_files[@]} -gt 0 ]; then cat "${lr_files[@]}" | awk '/Excitation Energy/{p=1; next} p && /^[[:space:]]*[0-9]+[[:space:]]/{printf "excitationenergyref%d %.6f\n", ++n, $2} /Occupied orbital/{p=0}' >>$props_result_file fi + if [ -f absorption.dat.ref ]; then + record_compare_result "$props_result_file" "CompareLRAbsorption_pass" \ + absorption.dat.ref OUT.autotest/absorption.dat 4 + fi shopt -u nullglob fi From d040f1ebc98f9c867085e0cff3cddff5d2b9f860 Mon Sep 17 00:00:00 2001 From: maki49 <1579492865@qq.com> Date: Thu, 19 Nov 2026 23:24:30 -0500 Subject: [PATCH 2/6] feat(lr): make excitation energy output precision configurable Default to eight significant digits in LR energy output and accept values up to 17. Keep 0 as the legacy-format opt-in. Apply the setting to solver output, energy reports, optical energy columns, and saved excitation energies. Refresh the HF Gamma energy references affected by the extra printed digits. Write optional LR state files outside assertions so Release builds honor out_wfc_lr. (cherry picked from commit bbc5d22f4ad21fa617933a0ec6c90702d29c200f) --- docs/advanced/elec_properties/hs_matrix.md | 8 ++++ source/source_esolver/esolver_lr_lcao_bse.cpp | 24 +++++----- .../source_esolver/esolver_lr_lcao_tddft.cpp | 48 ++++++++++++------- .../module_parameter/input_parameter.h | 1 + .../module_parameter/read_inp_tddft.cpp | 19 ++++++++ .../unittests/test_read_input_parallel.cpp | 25 ++++++++++ source/source_lcao/module_lr/hsolver_lrtd.cpp | 33 ++++++++----- source/source_lcao/module_lr/hsolver_lrtd.h | 3 +- source/source_lcao/module_lr/lr_spectrum.cpp | 17 ++++--- source/source_lcao/module_lr/lr_spectrum.h | 4 +- .../module_lr/utils/lr_util_print.h | 26 ++++++++-- tests/08_RI/lr_tddft_hf_gamma/README | 2 +- tests/08_RI/lr_tddft_hf_gamma/result.ref | 8 ++-- 13 files changed, 159 insertions(+), 59 deletions(-) diff --git a/docs/advanced/elec_properties/hs_matrix.md b/docs/advanced/elec_properties/hs_matrix.md index c6d46ac53c7..d5c1e570aa9 100644 --- a/docs/advanced/elec_properties/hs_matrix.md +++ b/docs/advanced/elec_properties/hs_matrix.md @@ -109,6 +109,14 @@ Place `hrs1_nao.csr` and `sr_nao.csr` in the LR `read_file_dir` alongside the ma For local and semilocal functionals without exact exchange, use `abs_gauge velocity`. Its direct momentum and nonlocal pseudopotential integrals avoid the additional finite-AO projection used to form the full commutator. +For finite differences of LR-TDDFT excitation energies, set +[`lr_energy_precision 17`](../input_files/input-main.md#lr_energy_precision). +The number refers to significant digits in the excitation-energy output. +Set `abs_gauge none` to report energies without evaluating optical matrix +elements. The precision setting works independently of `out_band` and +`out_wfc_lr`. The default is eight significant digits. Set +`lr_energy_precision 0` to use the legacy output formats. + ### Native Binary CSR Format Set `out_hsr 2` to write the same H(R) and S(R) matrix sets with a `.dat` suffix. For example, an `nspin = 2` calculation writes `hrs1_nao.dat`, `hrs2_nao.dat`, and `sr_nao.dat`. When `out_app_flag` is 2, the one-based ionic step is included before `_nao`, for example `hrs1g1_nao.dat` and `srg1_nao.dat`. diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index d33b5a520ad..d794dfcf028 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -412,7 +412,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { const double *const energies = &this->tda_ene[is * this->nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_tda"; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, 0); } } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "full") @@ -421,7 +421,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { const double *const energies = &this->full_ene[is * this->nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_full"; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, 0); } } } @@ -450,12 +450,12 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) spectrum.set_vmo(this->velocity_mo.data()); } spectrum.cal_spectrum(); - spectrum.transition_analysis(this->inp_->bse_spin_types[is] + "_tda"); - if (this->inp_->bse_spin_types[is] != - "triplet") // triplets has no transition dipole and no contribution to the spectrum + const std::string channel = this->inp_->bse_spin_types[is] + "_tda"; + spectrum.transition_analysis(channel, 0); + if (this->inp_->bse_spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { - spectrum.write_transition_dipole( - output_dir + "trans_dipole_" + this->inp_->bse_spin_types[is] + "_tda.dat"); + const std::string dipole_filename = output_dir + "trans_dipole_" + channel + ".dat"; + spectrum.write_transition_dipole(dipole_filename, 0); // ============================== for test ============================== if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { //// TEST the formula v/omega rather than v/(e_a-e_i) @@ -484,12 +484,12 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) spectrum.set_Y(this->full_Y[is].template data()); spectrum.set_full(true); spectrum.cal_spectrum(); - spectrum.transition_analysis(this->inp_->bse_spin_types[is] + "_full"); - if (this->inp_->bse_spin_types[is] != - "triplet") // triplets has no transition dipole and no contribution to the spectrum + const std::string channel = this->inp_->bse_spin_types[is] + "_full"; + spectrum.transition_analysis(channel, 0); + if (this->inp_->bse_spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { - spectrum.write_transition_dipole( - output_dir + "trans_dipole_" + this->inp_->bse_spin_types[is] + "_full.dat"); + const std::string dipole_filename = output_dir + "trans_dipole_" + channel + ".dat"; + spectrum.write_transition_dipole(dipole_filename, 0); } } } diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index c418cab7134..9db223ac8c4 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr_lcao_tddft.cpp @@ -91,15 +91,26 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste } else if (this->inp_->lr_solver != "spectrum") { - auto write_states = [this, &efile_out, &vfile_out]( - const std::string &label, const Real *e, const T *v, const int &dim, const int &nst, - const int &prec = 8) -> void + const int energy_precision = this->inp_->lr_energy_precision; + auto write_states = [this, &efile_out, &vfile_out, energy_precision]( + const std::string& label, const Real* e, const T* v, const int dim, const int nst) { if (this->my_rank_ == 0) { - assert(nst == LR_Util::write_value(efile_out(label), prec, e, nst)); + const std::string energy_file = efile_out(label); + if (!LR_Util::write_excitation_energy_file(energy_file, e, nst, energy_precision)) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "Failed to write " + energy_file); + } + this->ofs_running_ << " Write LR excitation energies to " << energy_file << '\n'; } - assert(nst * dim == LR_Util::write_value(vfile_out(label), prec, v, nst, dim)); + const std::string amplitude_file = vfile_out(label); + const int amplitude_digits = 8; + if (LR_Util::write_value(amplitude_file, amplitude_digits, v, nst, dim) != nst * dim) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "Failed to write " + amplitude_file); + } + this->ofs_running_ << " Write LR excitation amplitudes to " << amplitude_file << '\n'; }; std::vector precondition(this->inp_->lr_solver == "lapack" ? 0 : nloc_per_state, 1.0); // allocate and initialize A matrix and density matrix @@ -126,7 +137,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste this->pot, this->kv, this->paraX_, this->paraC_, this->paraMat_); LR::HSolver::solve( hulr, this->X[0].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, - this->paraX_, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); + this->paraX_, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true, energy_precision); if (this->inp_->out_wfc_lr) { write_states("openshell", this->pelec->ekb.c, this->X[0].template data(), nloc_per_state, nstates); @@ -156,7 +167,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste LR::HSolver::solve( hlr, this->X[is].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, this->paraX_, this->pelec->ekb.c + is * nstates, this->inp_->lr_solver, this->inp_->lr_thr, - precondition, true); + precondition, true, energy_precision); if (this->inp_->out_wfc_lr) { write_states( @@ -344,14 +355,13 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) freq[i] = 91.126664 / (lambda_min + 0.01 * static_cast(i + 1) * lambda_diff); } } - // auto spin_types = (nspin == 2 && !openshell) ? std::vector({ "singlet", "triplet" }) : - // std::vector({ "updown" }); for (int is = 0;is < this->X.size() - 1;++is) + const int energy_precision = this->inp_->lr_energy_precision; for (int is = 0; is < this->X.size(); ++is) { if (!calculate_spectrum) { - const double *const energies = &this->pelec->ekb.c[is * nstates]; - LR_Util::print_excitation_energies(this->ofs_running_, energies, nstates, spin_types[is]); + const double* const energies = &this->pelec->ekb.c[is * nstates]; + LR_Util::print_excitation_energies(this->ofs_running_, energies, nstates, spin_types[is], energy_precision); } else { @@ -365,15 +375,17 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) spectrum.set_vmo(this->velocity_mo.data()); } spectrum.cal_spectrum(); - spectrum.transition_analysis(spin_types[is] + "_tda"); - if (spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum + const std::string channel = spin_types[is] + "_tda"; + spectrum.transition_analysis(channel, energy_precision); + if (spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { spectrum.optical_absorption_method1(freq, this->inp_->abs_broadening); - spectrum.write_transition_dipole(this->out_dir + "trans_dipole_" + spin_types[is] + "_tda.dat"); - // =============================================== for test - // ==================================================== spectrum.optical_absorption_method2(freq, - // this->inp_->abs_broadening); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { // TEST - // the formula v/omega rather than v/(e_a-e_i) + const std::string dipole_filename = this->out_dir + "trans_dipole_" + channel + ".dat"; + spectrum.write_transition_dipole(dipole_filename, energy_precision); + // =============================================== for test ==================================================== + // spectrum.optical_absorption_method2(freq, this->inp_->abs_broadening); + // if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") + // { // TEST the formula v/omega rather than v/(e_a-e_i) // spectrum.test_transition_dipoles_velocity_omega(); // spectrum.write_transition_dipole(this->out_dir + // "trans_dipole_" + spin_types[is] + "_vomega_tda.dat"); diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 351c79f73c7..4372d314932 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -413,6 +413,7 @@ struct Input_para std::string xc_kernel = "LDA"; ///< exchange correlation (XC) kernel for LR-TDDFT std::string lr_solver = "dav"; ///< the eigensolver for LR-TDDFT double lr_thr = 1e-2; ///< convergence threshold of the LR-TDDFT eigensolver + int lr_energy_precision = 8; ///< significant digits in LR excitation-energy output bool out_wfc_lr = false; ///< whether to output the eigenvectors (excitation amplitudes) in the particle-hole basis bool lr_unrestricted = false; ///< whether to use the unrestricted construction for LR-TDDFT std::vector abs_wavelen_range = {}; ///< the range of wavelength(nm) to output the absorption spectrum diff --git a/source/source_io/module_parameter/read_inp_tddft.cpp b/source/source_io/module_parameter/read_inp_tddft.cpp index b854864108b..eb87696e2be 100644 --- a/source/source_io/module_parameter/read_inp_tddft.cpp +++ b/source/source_io/module_parameter/read_inp_tddft.cpp @@ -1173,6 +1173,25 @@ void ReadInput::item_lr_tddft() read_sync_double(input.lr_thr); this->add_item(item); } + { + Input_Item item("lr_energy_precision"); + item.annotation = "significant digits for LR-TDDFT excitation energies"; + item.category = "Linear Response TDDFT"; + item.type = "Integer"; + item.description = R"(Number of significant digits (1 to 17) for LR-TDDFT excitation energies in the eigensolver output, running-log energy reports, transition analysis and dipole tables, and Excitation_Energy files enabled by out_wfc_lr. The default is 8 significant digits. Set lr_energy_precision 0 to use each output's legacy format. For finite differences, use lr_energy_precision 17. The setting only changes text output and can be used without out_band or out_wfc_lr.)"; + item.default_value = "8"; + item.unit = ""; + item.set_availability("basis_type==lcao and esolver_type in [lr, ks-lr]"); + read_sync_int(input.lr_energy_precision); + item.check_value = [](const Input_Item&, const Parameter& para) { + const int precision = para.inp.lr_energy_precision; + if (precision < 0 || precision > std::numeric_limits::max_digits10) + { + ModuleBase::WARNING_QUIT("ReadInput", "lr_energy_precision must be an integer from 0 to 17"); + } + }; + this->add_item(item); + } { Input_Item item("nocc"); item.annotation = "the occupied orbital window ending at HOMO for LR-TDDFT"; diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index b1566ccd232..8f87ea77d10 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -854,3 +854,28 @@ TEST_F(InputParaTest, OpticalGaugeDefaultsToCommutatorForGroundStateExactExchang EXPECT_EQ(parameter.inp.abs_gauge, gauge); } } + +TEST_F(InputParaTest, LrEnergyPrecision) +{ + ModuleIO::ReadInput reader(0); + const auto& list = reader.get_input_lists(); + const std::map items(list.begin(), list.end()); + Parameter parameter; + EXPECT_EQ(parameter.inp.lr_energy_precision, 8); + EXPECT_EQ(parameter.inp.out_band[0], 0); + EXPECT_FALSE(parameter.inp.out_wfc_lr); + auto item = items.at("lr_energy_precision"); + for (const int digits : {0, 1, 8, 17}) + { + item.str_values = {std::to_string(digits)}; + item.read_value(item, parameter); + EXPECT_EQ(parameter.inp.lr_energy_precision, digits); + EXPECT_NO_THROW(item.check_value(item, parameter)); + } + for (const int digits : {-1, 18}) + { + item.str_values = {std::to_string(digits)}; + item.read_value(item, parameter); + EXPECT_EXIT(item.check_value(item, parameter), testing::ExitedWithCode(1), ""); + } +} diff --git a/source/source_lcao/module_lr/hsolver_lrtd.cpp b/source/source_lcao/module_lr/hsolver_lrtd.cpp index 765be265f6e..4c0e8f2ea07 100644 --- a/source/source_lcao/module_lr/hsolver_lrtd.cpp +++ b/source/source_lcao/module_lr/hsolver_lrtd.cpp @@ -36,13 +36,21 @@ namespace LR }; template - inline void print_eigs(const std::vector& eigs, const std::string& label = "", const double factor = 1.0) + inline void print_eigs(const std::vector& eigs, const std::string& label, + const double factor, const int energy_precision) { - std::streamsize old = std::cout.precision(); - std::cout << label << std::setprecision(8) << std::endl; + const auto old_precision = std::cout.precision(); + const auto old_flags = std::cout.flags(); + const int digits = energy_precision > 0 ? energy_precision : 8; + if (energy_precision > 0) + { + std::cout << std::defaultfloat; + } + std::cout << label << std::setprecision(digits) << std::endl; for (auto& e : eigs) { std::cout << e * factor << " "; } std::cout << std::endl; - std::cout.precision(old); + std::cout.precision(old_precision); + std::cout.flags(old_flags); } /// eigensolver for common Hamilt @@ -59,7 +67,8 @@ namespace LR const std::string method, const Real& diag_ethr, ///< threshold for diagonalization const std::vector>& precondition, - const bool hermitian) + const bool hermitian, + const int energy_precision) { ModuleBase::TITLE("HSolverLR", "solve"); ModuleBase::timer::start("HSolverLR", "solve"); @@ -86,7 +95,7 @@ namespace LR { std::vector> eig_complex(gdim); LR_Util::diag_lapack_nh(gdim, Amat_full.data(), eig_complex.data()); - print_eigs(eig_complex, "Right eigenvalues: of the non-Hermitian matrix: (Ry)"); + print_eigs(eig_complex, "Right eigenvalues: of the non-Hermitian matrix: (Ry)", 1.0, energy_precision); for (int i = 0; i < gdim; i++) { eigenvalue[i] = eig_complex[i].real(); } } bool openshell = std::is_same>::value; @@ -158,8 +167,8 @@ namespace LR for (int ist = 0;ist < nband;++ist) { eig[ist] = eigenvalue[ist]; } // 6. output eigenvalues and eigenvectors - print_eigs(eigenvalue, "eigenvalues: (Ry)"); - print_eigs(eigenvalue, "eigenvalues: (eV)", ModuleBase::Ry_to_eV); + print_eigs(eigenvalue, "eigenvalues: (Ry)", 1.0, energy_precision); + print_eigs(eigenvalue, "eigenvalues: (eV)", ModuleBase::Ry_to_eV, energy_precision); // normalization is already satisfied // std::cout << "check normalization of eigenvectors:" << std::endl; @@ -182,10 +191,10 @@ namespace LR << "; current threshold: " << diag_ethr << std::endl; ModuleBase::timer::end("HSolverLR", "solve"); } -template void solve>(const HamiltLR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); -template void solve>(const HamiltULR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); -template void solve, HamiltLR>>(const HamiltLR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); -template void solve, HamiltULR>>(const HamiltULR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); +template void solve>(const HamiltLR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); +template void solve>(const HamiltULR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); +template void solve, HamiltLR>>(const HamiltLR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); +template void solve, HamiltULR>>(const HamiltULR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); } } diff --git a/source/source_lcao/module_lr/hsolver_lrtd.h b/source/source_lcao/module_lr/hsolver_lrtd.h index 70f2d49c780..9391965dfd5 100644 --- a/source/source_lcao/module_lr/hsolver_lrtd.h +++ b/source/source_lcao/module_lr/hsolver_lrtd.h @@ -26,7 +26,8 @@ namespace HSolver const std::string method, const Real& diag_ethr, ///< threshold for diagonalization const std::vector>& precondition, - const bool hermitian); + const bool hermitian, + const int energy_precision); } } #endif diff --git a/source/source_lcao/module_lr/lr_spectrum.cpp b/source/source_lcao/module_lr/lr_spectrum.cpp index 945d19757f1..2c2a6dfda38 100644 --- a/source/source_lcao/module_lr/lr_spectrum.cpp +++ b/source/source_lcao/module_lr/lr_spectrum.cpp @@ -212,7 +212,7 @@ void LR::LR_Spectrum::optical_absorption_method1(const std::vector& f } template -void LR::LR_Spectrum::transition_analysis(const std::string& spintype) +void LR::LR_Spectrum::transition_analysis(const std::string& spintype, const int energy_precision) { ModuleBase::TITLE("LR::LR_Spectrum", "transition_analysis"); ModuleBase::timer::start("LR_Spectrum", "transition_analysis"); @@ -230,9 +230,11 @@ void LR::LR_Spectrum::transition_analysis(const std::string& spintype) ofs << std::setw(8) << "State" << std::setw(30) << "Excitation Energy (Ry, eV)" << std::setw(90) << "Transition dipole x, y, z (a.u.)" << std::setw(30) << "Oscillator strength(a.u.)" << '\n'; ofs << "------------------------------------------------------------------------------------ \n"; + const int digits = energy_precision > 0 ? energy_precision : 6; + const int energy_width = energy_precision > 0 ? std::max(15, digits + 8) : 15; for (int istate = 0;istate < nstate;++istate) - ofs << std::setw(8) << istate << std::setw(15) << std::setprecision(6) << omega[istate] - << std::setw(15) << omega[istate] * ModuleBase::Ry_to_eV + ofs << std::setw(8) << istate << std::setw(energy_width) << std::setprecision(digits) << omega[istate] + << std::setw(energy_width) << omega[istate] * ModuleBase::Ry_to_eV << std::setprecision(4) << std::setw(30) << transition_dipole_[istate].x << std::setw(30) << transition_dipole_[istate].y << std::setw(30) << transition_dipole_[istate].z << std::setprecision(6) << std::setw(30) << oscillator_strength_[istate] << std::endl; @@ -425,14 +427,17 @@ std::map LR::LR_Spectrum::get_pair_info(const int i) } template -void LR::LR_Spectrum::write_transition_dipole(const std::string& filename) +void LR::LR_Spectrum::write_transition_dipole(const std::string& filename, const int energy_precision) { std::ofstream ofs(filename); ofs << "Transition dipole moment (a.u.)" << std::endl; - ofs << std::setw(6) << "State" << std::setw(13) << "Energy (eV)" << std::setw(15) << "x" << std::setw(23) << "|x|^2" << std::setw(19) << "y" << std::setw(23) <<"|y|^2" << std::setw(19) << "z" << std::setw(23) <<"|z|^2" << std::setw(13) << "average" << std::endl; + const int digits = energy_precision > 0 ? energy_precision : 6; + const int energy_width = energy_precision > 0 ? std::max(13, digits + 8) : 13; + ofs << std::setw(6) << "State" << std::setw(energy_width) << "Energy (eV)" << std::setw(15) << "x" << std::setw(23) << "|x|^2" << std::setw(19) << "y" << std::setw(23) <<"|y|^2" << std::setw(19) << "z" << std::setw(23) <<"|z|^2" << std::setw(13) << "average" << std::endl; for (int istate = 0;istate < nstate;++istate) { - ofs << std::setw(4) << istate << std::setw(13) << std::setprecision(6) << omega[istate] * ModuleBase::Ry_to_eV + ofs << std::setw(4) << istate << std::setw(energy_width) << std::setprecision(digits) + << omega[istate] * ModuleBase::Ry_to_eV << std::setprecision(6) << std::setw(29) << transition_dipole_[istate].x << std::setw(13) << std::norm(transition_dipole_[istate].x) << std::setw(29) << transition_dipole_[istate].y << std::setw(13) << std::norm(transition_dipole_[istate].y) << std::setw(29) << transition_dipole_[istate].z << std::setw(13) << std::norm(transition_dipole_[istate].z) diff --git a/source/source_lcao/module_lr/lr_spectrum.h b/source/source_lcao/module_lr/lr_spectrum.h index 8a553d8ace2..8cb034acadf 100644 --- a/source/source_lcao/module_lr/lr_spectrum.h +++ b/source/source_lcao/module_lr/lr_spectrum.h @@ -53,11 +53,11 @@ namespace LR /// @brief calculate the optical absorption spectrum with lorentzian delta function void optical_absorption_method2(const std::vector& freq, const double eta); /// @brief print out the transition dipole moment and the main contributions to the transition amplitude - void transition_analysis(const std::string& spintype); + void transition_analysis(const std::string& spintype, const int energy_precision); //========================================== test functions ============================================== /// @brief write transition dipole - void write_transition_dipole(const std::string& filename); + void write_transition_dipole(const std::string& filename, const int energy_precision); /// @brief calculate transition dipole in velocity gauge using excitation eigenvalues instead of KS differences void test_transition_dipoles_velocity_omega(); diff --git a/source/source_lcao/module_lr/utils/lr_util_print.h b/source/source_lcao/module_lr/utils/lr_util_print.h index 42b7d4a8016..fa6736c6bcf 100644 --- a/source/source_lcao/module_lr/utils/lr_util_print.h +++ b/source/source_lcao/module_lr/utils/lr_util_print.h @@ -12,15 +12,16 @@ namespace LR_Util { /// Report selected excitation energies without evaluating optical matrix elements. - /// Match transition_analysis's energy precision so existing energy regressions apply. inline void print_excitation_energies(std::ostream& log, const double* energies, - const int nstates, const std::string& channel) + const int nstates, const std::string& channel, + const int energy_precision) { const auto flags = log.flags(); const auto precision = log.precision(); log << " LR excitation energies: " << channel << '\n'; log << " State Excitation Energy (Ry, eV)\n"; - log << std::defaultfloat << std::setprecision(6); + const int digits = energy_precision > 0 ? energy_precision : 6; + log << std::defaultfloat << std::setprecision(digits); for (int state = 0; state < nstates; ++state) { log << state << ' ' << energies[state] << ' ' @@ -87,6 +88,25 @@ namespace LR_Util ofs.close(); return res; } + inline bool write_excitation_energy_file(const std::string& file, const double* energies, + const int nstates, const int energy_precision) + { + if (energy_precision == 0) + { + return write_value(file, 8, energies, nstates) == nstates; + } + std::ofstream ofs(file); + const int decimals = energy_precision - 1; + ofs << std::scientific << std::setprecision(decimals); + for (int state = 0; state < nstates; ++state) + { + ofs << energies[state] << ' '; + } + ofs << '\n'; + ofs.close(); + return static_cast(ofs); + } + template int print_value(const T* ptr, const int& size) { diff --git a/tests/08_RI/lr_tddft_hf_gamma/README b/tests/08_RI/lr_tddft_hf_gamma/README index 1832aa2cb33..c773acee4a6 100644 --- a/tests/08_RI/lr_tddft_hf_gamma/README +++ b/tests/08_RI/lr_tddft_hf_gamma/README @@ -1,3 +1,3 @@ LR-TDDFT HF on H2O, gamma_only, nspin=2, lr_nstates=2, lr_solver=dav. Retains Z-CG coverage. abs_gauge=none skips optical postprocessing; -the excitation-energy and signed force references are unchanged. +the energy references use the default eight significant digits. diff --git a/tests/08_RI/lr_tddft_hf_gamma/result.ref b/tests/08_RI/lr_tddft_hf_gamma/result.ref index 5c4de9185c1..20ba339b527 100644 --- a/tests/08_RI/lr_tddft_hf_gamma/result.ref +++ b/tests/08_RI/lr_tddft_hf_gamma/result.ref @@ -1,7 +1,7 @@ totalforceref 121.6186866409 CompareLRForce_pass 0 -excitationenergyref1 1.531730 -excitationenergyref2 1.532420 -excitationenergyref3 1.353650 -excitationenergyref4 1.354670 +excitationenergyref1 1.531735 +excitationenergyref2 1.532418 +excitationenergyref3 1.353648 +excitationenergyref4 1.354671 totaltimeref 3.05 From 024b3fc5a58e091b86a8175d8015f986abe54e38 Mon Sep 17 00:00:00 2001 From: maki49 <1579492865@qq.com> Date: Mon, 23 Nov 2026 02:28:25 -0500 Subject: [PATCH 3/6] Harden LR absorption validation and cover hybrid CSR workflow --- source/source_lcao/module_lr/lr_spectrum.cpp | 17 +- tests/08_RI/CMakeLists.txt | 16 ++ .../08_RI/lr_tddft_velocity_commutator/INPUT | 57 +++-- tests/08_RI/lr_tddft_velocity_commutator/KPT | 2 +- .../08_RI/lr_tddft_velocity_commutator/README | 8 + tests/08_RI/lr_tddft_velocity_commutator/STRU | 24 +-- .../absorption.dat.ref | 200 +++++++++--------- .../lr_tddft_velocity_commutator/result.ref | 8 +- .../validation_tools/check_lr_absorption.py | 58 +++++ .../check_lr_absorption_csr.py | 75 +++++++ tests/integrate/validation_tools/props_ml.sh | 6 +- .../validation_tools/test_props_ml.py | 51 ++++- 12 files changed, 357 insertions(+), 165 deletions(-) create mode 100644 tests/08_RI/lr_tddft_velocity_commutator/README create mode 100644 tests/integrate/validation_tools/check_lr_absorption.py create mode 100644 tests/integrate/validation_tools/check_lr_absorption_csr.py diff --git a/source/source_lcao/module_lr/lr_spectrum.cpp b/source/source_lcao/module_lr/lr_spectrum.cpp index 2c2a6dfda38..83a593ac4a4 100644 --- a/source/source_lcao/module_lr/lr_spectrum.cpp +++ b/source/source_lcao/module_lr/lr_spectrum.cpp @@ -185,6 +185,10 @@ void LR::LR_Spectrum::optical_absorption_method1(const std::vector& f // this->write_transition_dipole(this->out_dir + "dipole_velocity.dat"); // exit(0); // ============test dipole================ + if (this->my_rank != 0) + { + return; + } ModuleBase::TITLE("LR::LR_Spectrum", "optical_absorption"); // 4*pi^2/V * mean_squared_dipole *delta(w-Omega_S) // = -8*pi*Omega_S/V * mean_squared_dipole * Im[1/[(w+i\eta)^2-\Omega_S^2]] @@ -192,10 +196,7 @@ void LR::LR_Spectrum::optical_absorption_method1(const std::vector& f std::vector& osc = this->oscillator_strength_; std::ofstream ofs(this->out_dir + "absorption.dat"); - if (this->my_rank == 0) - { - ofs << "Frequency (eV) | wave length(nm) | Absorption (a.u.)" << std::endl; - } + ofs << "Frequency (eV) | wave length(nm) | Absorption (a.u.)" << std::endl; double FourPI_div_c = ModuleBase::FOUR_PI / 137.036; double fac = 4 * M_PI / ucell.omega * ModuleBase::e2 / this->nk; // e2 for Ry to Hartree in the denominator @@ -206,7 +207,7 @@ void LR::LR_Spectrum::optical_absorption_method1(const std::vector& f double abs = 0.0; // for (int i = 0;i < osc.size();++i) { abs += (osc[i] / (f_complex * f_complex - omega[i] * omega[i])).imag() * freq[f] * FourPI_div_c; } for (int i = 0;i < osc.size();++i) { abs += (osc[i] / (f_complex * f_complex - omega[i] * omega[i])).imag() * fac; } - if (this->my_rank == 0) { ofs << freq[f] * ModuleBase::Ry_to_eV << "\t" << 91.126664 / freq[f] << "\t" << std::abs(abs) << std::endl; } + ofs << freq[f] * ModuleBase::Ry_to_eV << '\t' << 91.126664 / freq[f] << '\t' << std::abs(abs) << '\n'; } ofs.close(); } @@ -231,7 +232,8 @@ void LR::LR_Spectrum::transition_analysis(const std::string& spintype, const std::setw(90) << "Transition dipole x, y, z (a.u.)" << std::setw(30) << "Oscillator strength(a.u.)" << '\n'; ofs << "------------------------------------------------------------------------------------ \n"; const int digits = energy_precision > 0 ? energy_precision : 6; - const int energy_width = energy_precision > 0 ? std::max(15, digits + 8) : 15; + const int padded_digits = digits + 8; + const int energy_width = energy_precision > 0 ? std::max(15, padded_digits) : 15; for (int istate = 0;istate < nstate;++istate) ofs << std::setw(8) << istate << std::setw(energy_width) << std::setprecision(digits) << omega[istate] << std::setw(energy_width) << omega[istate] * ModuleBase::Ry_to_eV @@ -432,7 +434,8 @@ void LR::LR_Spectrum::write_transition_dipole(const std::string& filename, co std::ofstream ofs(filename); ofs << "Transition dipole moment (a.u.)" << std::endl; const int digits = energy_precision > 0 ? energy_precision : 6; - const int energy_width = energy_precision > 0 ? std::max(13, digits + 8) : 13; + const int padded_digits = digits + 8; + const int energy_width = energy_precision > 0 ? std::max(13, padded_digits) : 13; ofs << std::setw(6) << "State" << std::setw(energy_width) << "Energy (eV)" << std::setw(15) << "x" << std::setw(23) << "|x|^2" << std::setw(19) << "y" << std::setw(23) <<"|y|^2" << std::setw(19) << "z" << std::setw(23) <<"|z|^2" << std::setw(13) << "average" << std::endl; for (int istate = 0;istate < nstate;++istate) { diff --git a/tests/08_RI/CMakeLists.txt b/tests/08_RI/CMakeLists.txt index 9e6da5f118f..3e1f3852490 100644 --- a/tests/08_RI/CMakeLists.txt +++ b/tests/08_RI/CMakeLists.txt @@ -52,4 +52,20 @@ else() ${MPI_LAUNCHER_FLAGS}) set_tests_properties(08_RI_librpa_symmetry PROPERTIES PROCESSORS 2 TIMEOUT 1800) + + # This two-stage producer/consumer check needs the same SCF artifacts in + # separate LR runs, which the single-invocation Autotest cases cannot express. + find_program(LR_ABSORPTION_PYTHON python3) + if(ENABLE_MPI AND ENABLE_LCAO AND ENABLE_LIBRI AND ENABLE_LIBXC AND LR_ABSORPTION_PYTHON) + add_test( + NAME 08_RI_lr_absorption_csr + COMMAND + ${LR_ABSORPTION_PYTHON} + ${ABACUS_TEST_DIR}/integrate/validation_tools/check_lr_absorption_csr.py + --abacus ${ABACUS_BIN_PATH} + --case ${ABACUS_TEST_DIR}/08_RI/lr_tddft_velocity_commutator + --mpiexec ${MPIEXEC_EXECUTABLE} --mpi-np-flag=${MPIEXEC_NUMPROC_FLAG} + ${MPI_LAUNCHER_FLAGS}) + set_tests_properties(08_RI_lr_absorption_csr PROPERTIES PROCESSORS 4 TIMEOUT 180) + endif() endif() diff --git a/tests/08_RI/lr_tddft_velocity_commutator/INPUT b/tests/08_RI/lr_tddft_velocity_commutator/INPUT index 189ef8a6dca..37ae8ca529a 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/INPUT +++ b/tests/08_RI/lr_tddft_velocity_commutator/INPUT @@ -1,36 +1,27 @@ INPUT_PARAMETERS -#Parameters (1.General) -suffix autotest -pseudo_dir ../../../tests/PP_ORB -orbital_dir ../../../tests/PP_ORB -calculation scf -nbands 6 -symmetry -1 -nspin 2 +suffix autotest +pseudo_dir ../../PP_ORB +orbital_dir ../../PP_ORB +calculation scf +esolver_type ks-lr +basis_type lcao +gamma_only 0 +symmetry -1 +nspin 1 +nbands 2 +ks_solver scalapack_gvx -#Parameters (2.Iteration) -ecutwfc 10 -scf_thr 1e-6 -scf_nmax 20 +dft_functional hse +exx_singularity_correction limits +ecutwfc 24 +scf_thr 1e-9 +scf_nmax 80 +mixing_type broyden +mixing_beta 0.5 -#Parameters (3.Basis) -basis_type lcao -gamma_only 0 - -#Parameters (4.Smearing) -smearing_method gaussian -smearing_sigma 0.02 - -#Parameters (5.Mixing) -mixing_type pulay -mixing_beta 0.4 - -lr_nstates 2 -xc_kernel lda -lr_solver lapack - -esolver_type ks-lr - -nvirt 2 -abs_wavelen_range 200 600 -abs_gauge velocity_commutator +xc_kernel rpa +nocc 1 +nvirt 1 +lr_nstates 2 +lr_solver lapack +abs_wavelen_range 40 300 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/KPT b/tests/08_RI/lr_tddft_velocity_commutator/KPT index ae9ebb2ca33..e769af76382 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/KPT +++ b/tests/08_RI/lr_tddft_velocity_commutator/KPT @@ -1,4 +1,4 @@ K_POINTS 0 Gamma -2 3 1 0 0 0 +2 1 1 0 0 0 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/README b/tests/08_RI/lr_tddft_velocity_commutator/README new file mode 100644 index 00000000000..b7f8779133b --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/README @@ -0,0 +1,8 @@ +H2 with two k points, HSE orbitals, nspin=1, and an RPA response kernel. +Both LCAO bands are included. The default optical velocity includes +the ground-state Fock commutator, checked at all 100 spectrum points. + +The 08_RI_lr_absorption_csr test exports the same calculation's density, +orbitals and text H(R)/S(R) in scratch directories and compares the +in-memory and standalone spectra. It also evaluates direct velocity +using the same standalone inputs. diff --git a/tests/08_RI/lr_tddft_velocity_commutator/STRU b/tests/08_RI/lr_tddft_velocity_commutator/STRU index 4ae6cfd0ff6..ca3416c1690 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/STRU +++ b/tests/08_RI/lr_tddft_velocity_commutator/STRU @@ -1,21 +1,21 @@ ATOMIC_SPECIES -Si 1.000 Si.pz-vbc.UPF #Element, Mass, Pseudopotential +H 1.008 H_ONCV_PBE-1.0.upf NUMERICAL_ORBITAL -./Si_lda_8.0au_50Ry_2s2p1d +H_gga_6au_60Ry_1s.orb LATTICE_CONSTANT -10.2 #Lattice constant +12 LATTICE_VECTORS -0.0 0.5 0.5 #Lattice vector 1 -0.5 0.0 0.5 #Lattice vector 2 -0.5 0.5 0.0 #Lattice vector 3 +1 0 0 +0 1 0 +0 0 1 ATOMIC_POSITIONS -Cartesian #Cartesian(Unit is LATTICE_CONSTANT) -Si #Name of element -0.0 #Magnetic for this element. -2 #Number of atoms -0.00 0.00 0.00 0 0 0 #x,y,z, move_x, move_y, move_z -0.25 0.25 0.25 1 1 1 +Direct +H +0.0 +2 +0.5 0.5 0.444 0 0 0 +0.5 0.5 0.556 0 0 0 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref index 33b6a292de1..95e80ce49a1 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref +++ b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref @@ -1,101 +1,101 @@ Frequency (eV) | wave length(nm) | Absorption (a.u.) -6.07766 204 0.0361544 -5.96078 208 0.0390143 -5.84831 212 0.0420752 -5.74001 216 0.0453515 -5.63564 220 0.0488588 -5.53501 224 0.0526141 -5.4379 228 0.0566358 -5.34415 232 0.0609438 -5.25357 236 0.0655601 -5.16601 240 0.0705084 -5.08132 244 0.0758146 -4.99936 248 0.0815073 -4.92001 252 0.0876175 -4.84313 256 0.0941793 -4.76862 260 0.10123 -4.69637 264 0.108811 -4.62628 268 0.116968 -4.55824 272 0.125751 -4.49218 276 0.135215 -4.42801 280 0.145421 -4.36564 284 0.156438 -4.30501 288 0.168341 -4.24603 292 0.181214 -4.18865 296 0.195151 -4.13281 300 0.210257 -4.07843 304 0.22665 -4.02546 308 0.244462 -3.97385 312 0.263842 -3.92355 316 0.284957 -3.87451 320 0.307998 -3.82667 324 0.333181 -3.78001 328 0.36075 -3.73446 332 0.390987 -3.69001 336 0.42421 -3.64659 340 0.46079 -3.60419 344 0.50115 -3.56276 348 0.54578 -3.52228 352 0.595252 -3.4827 356 0.650228 -3.44401 360 0.711485 -3.40616 364 0.779936 -3.36914 368 0.856659 -3.33291 372 0.942931 -3.29745 376 1.04028 -3.26274 380 1.15052 -3.22875 384 1.27585 -3.19547 388 1.41894 -3.16286 392 1.58302 -3.13091 396 1.77207 -3.0996 400 1.99098 -3.06892 404 2.24583 -3.03883 408 2.5442 -3.00932 412 2.89562 -2.98039 416 3.3121 -2.952 420 3.80887 -2.92416 424 4.40529 -2.89683 428 5.12597 -2.87 432 6.00201 -2.84367 436 7.07223 -2.81782 440 8.38378 -2.79244 444 9.9909 -2.7675 448 11.9493 -2.74301 452 14.3011 -2.71895 456 17.0445 -2.69531 460 20.082 -2.67207 464 23.157 -2.64923 468 25.8267 -2.62678 472 27.5501 -2.60471 476 27.9204 -2.583 480 26.8964 -2.56166 484 24.8154 -2.54066 488 22.1807 -2.52 492 19.4333 -2.49968 496 16.8513 -2.47968 500 14.5636 -2.46 504 12.6018 -2.44063 508 10.9474 -2.42157 512 9.5623 -2.40279 516 8.40409 -2.38431 520 7.43349 -2.36611 524 6.61665 -2.34819 528 5.92552 -2.33053 532 5.33729 -2.31314 536 4.83357 -2.296 540 4.39959 -2.27912 544 4.02346 -2.26249 548 3.69561 -2.24609 552 3.40826 -2.22993 556 3.15512 -2.214 560 2.93101 -2.1983 564 2.73168 -2.18282 568 2.55362 -2.16756 572 2.39391 -2.1525 576 2.2501 -2.13766 580 2.12013 -2.12302 584 2.00227 -2.10857 588 1.89504 -2.09433 592 1.79719 -2.08027 596 1.70763 -2.0664 600 1.62544 +29.1043 42.6 0.0147588 +27.4301 45.2 0.00225836 +25.9381 47.8 0.00094464 +24.6 50.4 0.000542952 +23.3932 53 0.000364756 +22.2993 55.6 0.000268647 +21.3031 58.2 0.000210131 +20.3921 60.8 0.00017143 +19.5559 63.4 0.00014425 +18.7855 66 0.000124271 +18.0735 68.6 0.000109051 +17.4135 71.2 9.71183e-05 +16.8 73.8 8.75387e-05 +16.2283 76.4 7.96953e-05 +15.6942 79 7.31651e-05 +15.1941 81.6 6.76498e-05 +14.725 84.2 6.29335e-05 +14.2839 86.8 5.88564e-05 +13.8685 89.4 5.52982e-05 +13.4765 92 5.21663e-05 +13.1062 94.6 4.93888e-05 +12.7556 97.2 4.69089e-05 +12.4233 99.8 4.4681e-05 +12.1078 102.4 4.26685e-05 +11.808 105 4.08414e-05 +11.5227 107.6 3.9175e-05 +11.2508 110.2 3.76488e-05 +10.9915 112.8 3.62455e-05 +10.7439 115.4 3.49506e-05 +10.5071 118 3.37519e-05 +10.2806 120.6 3.26389e-05 +10.0637 123.2 3.16024e-05 +9.85566 125.8 3.06346e-05 +9.65609 128.4 2.97289e-05 +9.46444 131 2.88792e-05 +9.28025 133.6 2.80804e-05 +9.1031 136.2 2.7328e-05 +8.93258 138.8 2.66178e-05 +8.76833 141.4 2.59464e-05 +8.61001 144 2.53105e-05 +8.45731 146.6 2.47074e-05 +8.30993 149.2 2.41344e-05 +8.1676 151.8 2.35893e-05 +8.03006 154.4 2.30701e-05 +7.89708 157 2.25748e-05 +7.76843 159.6 2.21019e-05 +7.64391 162.2 2.16497e-05 +7.52331 164.8 2.12169e-05 +7.40646 167.4 2.08023e-05 +7.29319 170 2.04046e-05 +7.18332 172.6 2.00229e-05 +7.07672 175.2 1.96561e-05 +6.97324 177.8 1.93033e-05 +6.87274 180.4 1.89638e-05 +6.77509 183 1.86368e-05 +6.68018 185.6 1.83215e-05 +6.5879 188.2 1.80174e-05 +6.49812 190.8 1.77238e-05 +6.41076 193.4 1.74402e-05 +6.32572 196 1.7166e-05 +6.24291 198.6 1.69008e-05 +6.16224 201.2 1.66442e-05 +6.08362 203.8 1.63956e-05 +6.00699 206.4 1.61548e-05 +5.93226 209 1.59213e-05 +5.85937 211.6 1.56948e-05 +5.78824 214.2 1.54751e-05 +5.71883 216.8 1.52616e-05 +5.65106 219.4 1.50543e-05 +5.58487 222 1.48529e-05 +5.52022 224.6 1.4657e-05 +5.45705 227.2 1.44664e-05 +5.39531 229.8 1.4281e-05 +5.33495 232.4 1.41005e-05 +5.27592 235 1.39247e-05 +5.21819 237.6 1.37534e-05 +5.16171 240.2 1.35865e-05 +5.10643 242.8 1.34238e-05 +5.05233 245.4 1.32651e-05 +4.99936 248 1.31102e-05 +4.94749 250.6 1.29591e-05 +4.89669 253.2 1.28115e-05 +4.84692 255.8 1.26675e-05 +4.79815 258.4 1.25267e-05 +4.75035 261 1.23892e-05 +4.7035 263.6 1.22547e-05 +4.65756 266.2 1.21233e-05 +4.61251 268.8 1.19948e-05 +4.56832 271.4 1.1869e-05 +4.52497 274 1.1746e-05 +4.48244 276.6 1.16255e-05 +4.44069 279.2 1.15077e-05 +4.39972 281.8 1.13922e-05 +4.3595 284.4 1.12791e-05 +4.32001 287 1.11684e-05 +4.28122 289.6 1.10598e-05 +4.24313 292.2 1.09534e-05 +4.20571 294.8 1.08491e-05 +4.16894 297.4 1.07469e-05 +4.13281 300 1.06466e-05 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/result.ref b/tests/08_RI/lr_tddft_velocity_commutator/result.ref index 25e091cabbe..3cc8736eedd 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/result.ref +++ b/tests/08_RI/lr_tddft_velocity_commutator/result.ref @@ -1,6 +1,4 @@ -excitationenergyref1 0.191836 -excitationenergyref2 0.192137 -excitationenergyref3 0.180837 -excitationenergyref4 0.181265 +excitationenergyref1 1.594555 +excitationenergyref2 2.217423 CompareLRAbsorption_pass 0 -totaltimeref 16 +totaltimeref 1 diff --git a/tests/integrate/validation_tools/check_lr_absorption.py b/tests/integrate/validation_tools/check_lr_absorption.py new file mode 100644 index 00000000000..46d2d22b45c --- /dev/null +++ b/tests/integrate/validation_tools/check_lr_absorption.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Validate and compare the 100-point LR absorption tables.""" +import argparse +import math +from pathlib import Path + + +HEADER = "Frequency (eV) | wave length(nm) | Absorption (a.u.)" +SPECTRUM_POINTS = 100 + + +def read_spectrum(path): + lines = path.read_text().splitlines() + if not lines or lines[0].strip() != HEADER: + raise ValueError(f"{path}: missing absorption table header") + if len(lines) - 1 != SPECTRUM_POINTS: + raise ValueError(f"{path}: expected {SPECTRUM_POINTS} data rows, found {len(lines) - 1}") + + values = [] + for line_number, line in enumerate(lines[1:], start=2): + columns = line.split() + if len(columns) != 3: + raise ValueError(f"{path}:{line_number}: expected three numerical columns") + try: + row = tuple(float(value) for value in columns) + except ValueError as error: + raise ValueError(f"{path}:{line_number}: invalid numerical value") from error + if not all(math.isfinite(value) for value in row): + raise ValueError(f"{path}:{line_number}: non-finite absorption table value") + values.append(row) + return values + + +def compare_spectra(reference, output, tolerance=1e-4): + reference_rows = read_spectrum(reference) + output_rows = read_spectrum(output) + for line, (expected, actual) in enumerate(zip(reference_rows, output_rows), start=2): + for column, (expected_value, actual_value) in enumerate(zip(expected, actual), start=1): + if abs(expected_value - actual_value) > tolerance: + raise ValueError( + f"{output}:{line}: column {column} is {actual_value}, " + f"expected {expected_value} from {reference}" + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("reference", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + compare_spectra(args.reference, args.output) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/tests/integrate/validation_tools/check_lr_absorption_csr.py b/tests/integrate/validation_tools/check_lr_absorption_csr.py new file mode 100644 index 00000000000..350ad5666a3 --- /dev/null +++ b/tests/integrate/validation_tools/check_lr_absorption_csr.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Compare HSE LR spectra from in-memory and exported optical matrices.""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + +from check_lr_absorption import compare_spectra, read_spectrum + + +def run_case(directory, fixture, launch, parameters): + directory.mkdir() + for name in ("STRU", "KPT"): + shutil.copyfile(fixture / name, directory / name) + lines = [f"{key} {value}\n" for key, value in parameters.items()] + (directory / "INPUT").write_text("INPUT_PARAMETERS\n" + "".join(lines)) + env = dict(os.environ, OMP_NUM_THREADS="1") + result = subprocess.run(launch, cwd=directory, env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, check=False) + if result.returncode != 0: + tail = "\n".join(result.stdout.splitlines()[-40:]) + raise ValueError(f"{directory.name} failed with exit code {result.returncode}\n{tail}") + return directory / "OUT.autotest" + + +def compare_workflows(args, root): + fixture = args.case.resolve() + orbitals = fixture.parent.parent / "PP_ORB" + parameters = dict(line.split(maxsplit=1) for line in (fixture / "INPUT").read_text().splitlines() + if len(line.split(maxsplit=1)) == 2) + parameters.update(pseudo_dir=orbitals, orbital_dir=orbitals) + launch = [args.mpiexec, args.mpi_np_flag, "4", *args.mpi_preflag, + str(args.abacus.resolve()), *args.mpi_postflag] + + producer = dict(parameters, out_hsr="1 16", out_chg="1 16", + out_wfc_lcao=1, out_app_flag=0) + ks_out = run_case(root / "in-memory", fixture, launch, producer) + consumer = dict(parameters, calculation="nscf", esolver_type="lr", + init_chg="file", init_wfc="file", read_file_dir=ks_out) + csr_out = run_case(root / "standalone", fixture, launch, consumer) + compare_spectra(ks_out / "absorption.dat", csr_out / "absorption.dat") + + direct_inputs = dict(consumer, abs_gauge="velocity") + direct_out = run_case(root / "direct", fixture, launch, direct_inputs) + commutator = read_spectrum(csr_out / "absorption.dat") + direct = read_spectrum(direct_out / "absorption.dat") + if any(full[:2] != bare[:2] for full, bare in zip(commutator, direct)): + raise ValueError("The commutator and direct velocity spectra use different grids.") + peak = max(row[2] for row in commutator) + difference = max(abs(full[2] - bare[2]) for full, bare in zip(commutator, direct)) + if peak <= 0 or difference <= 0.05 * peak: + raise ValueError("The HSE commutator spectrum must differ from direct velocity by over 5% of peak height.") + print(f"In-memory and CSR spectra agree. Direct velocity differs by {difference / peak:.1%} of peak height.") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--abacus", type=Path, required=True) + parser.add_argument("--case", type=Path, required=True) + parser.add_argument("--mpiexec", required=True) + parser.add_argument("--mpi-np-flag", required=True) + parser.add_argument("--mpi-preflag", action="append", default=[]) + parser.add_argument("--mpi-postflag", action="append", default=[]) + args = parser.parse_args() + try: + with tempfile.TemporaryDirectory(prefix="abacus-lr-absorption-") as directory: + compare_workflows(args, Path(directory)) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/tests/integrate/validation_tools/props_ml.sh b/tests/integrate/validation_tools/props_ml.sh index 00147e0e927..4b33974472e 100644 --- a/tests/integrate/validation_tools/props_ml.sh +++ b/tests/integrate/validation_tools/props_ml.sh @@ -69,8 +69,10 @@ run_ml_lr_props() { cat "${lr_files[@]}" | awk '/Excitation Energy/{p=1; next} p && /^[[:space:]]*[0-9]+[[:space:]]/{printf "excitationenergyref%d %.6f\n", ++n, $2} /Occupied orbital/{p=0}' >>$props_result_file fi if [ -f absorption.dat.ref ]; then - record_compare_result "$props_result_file" "CompareLRAbsorption_pass" \ - absorption.dat.ref OUT.autotest/absorption.dat 4 + local absorption_status=0 + python3 "$PROPS_TOOLS_DIR/check_lr_absorption.py" absorption.dat.ref OUT.autotest/absorption.dat \ + || absorption_status=$? + echo "CompareLRAbsorption_pass $absorption_status" >>"$props_result_file" fi shopt -u nullglob fi diff --git a/tests/integrate/validation_tools/test_props_ml.py b/tests/integrate/validation_tools/test_props_ml.py index 7c98a9a7d1e..68daafefa6c 100644 --- a/tests/integrate/validation_tools/test_props_ml.py +++ b/tests/integrate/validation_tools/test_props_ml.py @@ -1,23 +1,35 @@ #!/usr/bin/env python3 -"""Energy regressions remain active when optical postprocessing is disabled.""" +"""Exercise the LR energy and absorption property collector.""" from pathlib import Path import shlex import subprocess import tempfile import unittest +from check_lr_absorption import HEADER, SPECTRUM_POINTS + + +SPECTRUM = HEADER + '\n' + '3.00 413.28 2.5\n' * SPECTRUM_POINTS + class LREnergyCollectorTest(unittest.TestCase): - def collect(self, log, analysis=None): + def collect(self, log, analysis=None, reference=None, spectrum=None): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) (root / 'OUT.autotest').mkdir() (root / 'running.log').write_text(log) if analysis is not None: (root / 'OUT.autotest/trans_analysis_singlet_tda.dat').write_text(analysis) - script = Path(__file__).with_name('props_ml.sh') - command = ('source ' + shlex.quote(str(script.resolve())) - + '; is_lr=1; props_result_file=result.out; running_path=running.log; run_ml_lr_props') + if reference is not None: + (root / 'absorption.dat.ref').write_text(reference) + if spectrum is not None: + (root / 'OUT.autotest/absorption.dat').write_text(spectrum) + tools_dir = Path(__file__).resolve().parent + commands = [f'source {shlex.quote(str(tools_dir / script))}' + for script in ('props_common.sh', 'props_ml.sh')] + commands += ['is_lr=1', 'props_result_file=result.out', + 'running_path=running.log', 'run_ml_lr_props'] + command = '; '.join(commands) subprocess.run(['bash', '-e', '-c', command], cwd=root, check=True) return (root / 'result.out').read_text() @@ -49,6 +61,35 @@ def test_no_spectrum_ignores_stale_optical_files(self): analysis = 'State Excitation Energy (Ry, eV)\n0 99 99\nState Occupied orbital\n' self.assertEqual(self.collect(log, analysis), 'excitationenergyref1 1.531730\n') + def test_absorption_accepts_complete_finite_table(self): + result = self.collect('', reference=SPECTRUM, spectrum=SPECTRUM) + self.assertEqual(result, 'CompareLRAbsorption_pass 0\n') + + def test_absorption_rejects_empty_and_incomplete_table(self): + truncated = '\n'.join(SPECTRUM.splitlines()[:-1]) + '\n' + for reference, spectrum in [(SPECTRUM, None), (SPECTRUM, ''), (SPECTRUM, truncated), + (truncated, truncated)]: + with self.subTest(reference_rows=len(reference.splitlines()), + output_rows=len(spectrum.splitlines()) if spectrum is not None else None): + result = self.collect('', reference=reference, spectrum=spectrum) + self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + + def test_absorption_rejects_nonfinite_values_in_all_columns(self): + for value, invalid in [('3.00', 'NaN'), ('413.28', 'inf'), ('2.5', '-inf')]: + invalid_spectrum = SPECTRUM.replace(value, invalid, 1) + for reference in (SPECTRUM, invalid_spectrum): + with self.subTest(invalid=invalid, matching=(reference == invalid_spectrum)): + result = self.collect('', reference=reference, spectrum=invalid_spectrum) + self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + + def test_absorption_rejects_wrong_columns_and_changed_values(self): + wrong_columns = SPECTRUM.replace('3.00 413.28 2.5', '3.00 413.28', 1) + changed = SPECTRUM.replace('3.00 413.28 2.5', '3.00 413.28 2.6', 1) + for spectrum in (wrong_columns, changed): + with self.subTest(spectrum_row=spectrum.splitlines()[1]): + result = self.collect('', reference=SPECTRUM, spectrum=spectrum) + self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + if __name__ == '__main__': unittest.main() From 15f7092f706f837a6e8270c99dc4357e67fec443 Mon Sep 17 00:00:00 2001 From: maki49 <1579492865@qq.com> Date: Mon, 23 Nov 2026 05:12:59 -0500 Subject: [PATCH 4/6] Preserve weak LR intensities and test spin-two CSR spectra --- tests/08_RI/CMakeLists.txt | 27 ++++++++++++------- .../08_RI/lr_tddft_velocity_commutator/README | 10 ++++--- .../validation_tools/check_lr_absorption.py | 14 +++++++--- .../check_lr_absorption_csr.py | 15 +++++++++-- .../validation_tools/test_props_ml.py | 17 ++++++++++++ 5 files changed, 64 insertions(+), 19 deletions(-) diff --git a/tests/08_RI/CMakeLists.txt b/tests/08_RI/CMakeLists.txt index 3e1f3852490..ab4c2fbc512 100644 --- a/tests/08_RI/CMakeLists.txt +++ b/tests/08_RI/CMakeLists.txt @@ -57,15 +57,22 @@ else() # separate LR runs, which the single-invocation Autotest cases cannot express. find_program(LR_ABSORPTION_PYTHON python3) if(ENABLE_MPI AND ENABLE_LCAO AND ENABLE_LIBRI AND ENABLE_LIBXC AND LR_ABSORPTION_PYTHON) - add_test( - NAME 08_RI_lr_absorption_csr - COMMAND - ${LR_ABSORPTION_PYTHON} - ${ABACUS_TEST_DIR}/integrate/validation_tools/check_lr_absorption_csr.py - --abacus ${ABACUS_BIN_PATH} - --case ${ABACUS_TEST_DIR}/08_RI/lr_tddft_velocity_commutator - --mpiexec ${MPIEXEC_EXECUTABLE} --mpi-np-flag=${MPIEXEC_NUMPROC_FLAG} - ${MPI_LAUNCHER_FLAGS}) - set_tests_properties(08_RI_lr_absorption_csr PROPERTIES PROCESSORS 4 TIMEOUT 180) + foreach(spin_count IN ITEMS 1 2) + set(spectrum_test 08_RI_lr_absorption_csr) + if(spin_count EQUAL 2) + string(APPEND spectrum_test "_spin2") + endif() + add_test( + NAME ${spectrum_test} + COMMAND + ${LR_ABSORPTION_PYTHON} + ${ABACUS_TEST_DIR}/integrate/validation_tools/check_lr_absorption_csr.py + --abacus ${ABACUS_BIN_PATH} + --case ${ABACUS_TEST_DIR}/08_RI/lr_tddft_velocity_commutator + --nspin ${spin_count} + --mpiexec ${MPIEXEC_EXECUTABLE} --mpi-np-flag=${MPIEXEC_NUMPROC_FLAG} + ${MPI_LAUNCHER_FLAGS}) + set_tests_properties(${spectrum_test} PROPERTIES PROCESSORS 4 TIMEOUT 180) + endforeach() endif() endif() diff --git a/tests/08_RI/lr_tddft_velocity_commutator/README b/tests/08_RI/lr_tddft_velocity_commutator/README index b7f8779133b..7c490ad5783 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/README +++ b/tests/08_RI/lr_tddft_velocity_commutator/README @@ -2,7 +2,9 @@ H2 with two k points, HSE orbitals, nspin=1, and an RPA response kernel. Both LCAO bands are included. The default optical velocity includes the ground-state Fock commutator, checked at all 100 spectrum points. -The 08_RI_lr_absorption_csr test exports the same calculation's density, -orbitals and text H(R)/S(R) in scratch directories and compares the -in-memory and standalone spectra. It also evaluates direct velocity -using the same standalone inputs. +The 08_RI_lr_absorption_csr and 08_RI_lr_absorption_csr_spin2 tests +run this fixture with one and two spin channels. They export density, +orbitals and text H(R)/S(R) in scratch directories, compare the in-memory +and standalone spectra, check the closed-shell spectrum against the +same reference, and evaluate direct velocity on the standalone inputs. +The two-spin test checks the read of both CSR spin blocks. diff --git a/tests/integrate/validation_tools/check_lr_absorption.py b/tests/integrate/validation_tools/check_lr_absorption.py index 46d2d22b45c..8b0f696f390 100644 --- a/tests/integrate/validation_tools/check_lr_absorption.py +++ b/tests/integrate/validation_tools/check_lr_absorption.py @@ -7,6 +7,13 @@ HEADER = "Frequency (eV) | wave length(nm) | Absorption (a.u.)" SPECTRUM_POINTS = 100 +# Keep the grid on an absolute scale. A separate floor for the intensities +# permits roundoff near zero without masking small spectral features. +COLUMN_TOLERANCES = ( + (1e-4, 0.0), # frequency (eV) + (1e-4, 0.0), # wavelength (nm) + (1e-8, 1e-4), # absorption +) def read_spectrum(path): @@ -31,12 +38,13 @@ def read_spectrum(path): return values -def compare_spectra(reference, output, tolerance=1e-4): +def compare_spectra(reference, output): reference_rows = read_spectrum(reference) output_rows = read_spectrum(output) for line, (expected, actual) in enumerate(zip(reference_rows, output_rows), start=2): - for column, (expected_value, actual_value) in enumerate(zip(expected, actual), start=1): - if abs(expected_value - actual_value) > tolerance: + columns = zip(expected, actual, COLUMN_TOLERANCES) + for column, (expected_value, actual_value, (absolute, relative)) in enumerate(columns, start=1): + if not math.isclose(expected_value, actual_value, abs_tol=absolute, rel_tol=relative): raise ValueError( f"{output}:{line}: column {column} is {actual_value}, " f"expected {expected_value} from {reference}" diff --git a/tests/integrate/validation_tools/check_lr_absorption_csr.py b/tests/integrate/validation_tools/check_lr_absorption_csr.py index 350ad5666a3..cfe57e582fa 100644 --- a/tests/integrate/validation_tools/check_lr_absorption_csr.py +++ b/tests/integrate/validation_tools/check_lr_absorption_csr.py @@ -30,16 +30,25 @@ def compare_workflows(args, root): orbitals = fixture.parent.parent / "PP_ORB" parameters = dict(line.split(maxsplit=1) for line in (fixture / "INPUT").read_text().splitlines() if len(line.split(maxsplit=1)) == 2) - parameters.update(pseudo_dir=orbitals, orbital_dir=orbitals) + parameters.update(pseudo_dir=orbitals, orbital_dir=orbitals, nspin=args.nspin) launch = [args.mpiexec, args.mpi_np_flag, "4", *args.mpi_preflag, str(args.abacus.resolve()), *args.mpi_postflag] producer = dict(parameters, out_hsr="1 16", out_chg="1 16", out_wfc_lcao=1, out_app_flag=0) ks_out = run_case(root / "in-memory", fixture, launch, producer) + reference = fixture / "absorption.dat.ref" + compare_spectra(reference, ks_out / "absorption.dat") consumer = dict(parameters, calculation="nscf", esolver_type="lr", init_chg="file", init_wfc="file", read_file_dir=ks_out) csr_out = run_case(root / "standalone", fixture, launch, consumer) + log = (csr_out / "running_nscf.log").read_text() + # In a closed-shell spin-two case the two blocks can be equal. Verify that + # standalone LR actually obtains both blocks from their separate CSR files. + for spin in range(1, args.nspin + 1): + matrix_file = ks_out / f"hrs{spin}_nao.csr" + if f"Reading optical matrix from {matrix_file}" not in log: + raise ValueError(f"Standalone LR did not read {matrix_file}") compare_spectra(ks_out / "absorption.dat", csr_out / "absorption.dat") direct_inputs = dict(consumer, abs_gauge="velocity") @@ -52,13 +61,15 @@ def compare_workflows(args, root): difference = max(abs(full[2] - bare[2]) for full, bare in zip(commutator, direct)) if peak <= 0 or difference <= 0.05 * peak: raise ValueError("The HSE commutator spectrum must differ from direct velocity by over 5% of peak height.") - print(f"In-memory and CSR spectra agree. Direct velocity differs by {difference / peak:.1%} of peak height.") + print(f"nspin={args.nspin}: in-memory and CSR spectra agree. " + f"Direct velocity differs by {difference / peak:.1%} of peak height.") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--abacus", type=Path, required=True) parser.add_argument("--case", type=Path, required=True) + parser.add_argument("--nspin", type=int, choices=(1, 2), default=1) parser.add_argument("--mpiexec", required=True) parser.add_argument("--mpi-np-flag", required=True) parser.add_argument("--mpi-preflag", action="append", default=[]) diff --git a/tests/integrate/validation_tools/test_props_ml.py b/tests/integrate/validation_tools/test_props_ml.py index 68daafefa6c..708480d810d 100644 --- a/tests/integrate/validation_tools/test_props_ml.py +++ b/tests/integrate/validation_tools/test_props_ml.py @@ -82,6 +82,23 @@ def test_absorption_rejects_nonfinite_values_in_all_columns(self): result = self.collect('', reference=reference, spectrum=invalid_spectrum) self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + def test_absorption_preserves_weak_intensity(self): + reference = SPECTRUM.replace('2.5', '2.5e-6') + nearby = reference.replace('2.5e-6', '2.505e-6', 1) + zeroed = reference.replace('2.5e-6', '0', 1) + self.assertEqual(self.collect('', reference=reference, spectrum=nearby), + 'CompareLRAbsorption_pass 0\n') + self.assertEqual(self.collect('', reference=reference, spectrum=zeroed), + 'CompareLRAbsorption_pass 1\n') + + def test_absorption_keeps_absolute_tolerances_on_both_grid_columns(self): + changed_frequency = SPECTRUM.replace('3.00', '3.0002', 1) + changed_wavelength = SPECTRUM.replace('413.28', '413.2802', 1) + for spectrum in (changed_frequency, changed_wavelength): + with self.subTest(spectrum_row=spectrum.splitlines()[1]): + result = self.collect('', reference=SPECTRUM, spectrum=spectrum) + self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + def test_absorption_rejects_wrong_columns_and_changed_values(self): wrong_columns = SPECTRUM.replace('3.00 413.28 2.5', '3.00 413.28', 1) changed = SPECTRUM.replace('3.00 413.28 2.5', '3.00 413.28 2.6', 1) From 21d948542b3cd59b7406ee49b865d185d5f6cfd4 Mon Sep 17 00:00:00 2001 From: maki49 <1579492865@qq.com> Date: Mon, 23 Nov 2026 21:33:56 -0500 Subject: [PATCH 5/6] Fix LR energy precision and add text spectrum provenance --- docs/advanced/elec_properties/hs_matrix.md | 10 ++---- source/source_esolver/esolver_lr_lcao_bse.cpp | 13 +++---- .../source_esolver/esolver_lr_lcao_tddft.cpp | 15 ++++---- source/source_esolver/esolver_lr_lcao_tddft.h | 1 + .../module_parameter/input_parameter.h | 1 - .../module_parameter/read_inp_tddft.cpp | 19 ---------- .../unittests/test_read_input_parallel.cpp | 25 ------------- source/source_lcao/module_lr/hsolver_lrtd.cpp | 27 ++++++-------- source/source_lcao/module_lr/hsolver_lrtd.h | 3 +- source/source_lcao/module_lr/lr_spectrum.cpp | 21 ++++++++--- source/source_lcao/module_lr/lr_spectrum.h | 5 ++- .../module_lr/utils/lr_util_print.h | 11 +++--- tests/08_RI/CMakeLists.txt | 27 ++++++-------- tests/08_RI/lr_tddft_hf_gamma/README | 2 +- tests/08_RI/lr_tddft_hf_gamma/result.ref | 2 +- .../08_RI/lr_tddft_velocity_commutator/README | 10 +++--- .../absorption.dat.ref | 4 ++- .../validation_tools/check_lr_absorption.py | 35 ++++++++++++++----- ...csr.py => check_lr_absorption_workflow.py} | 20 ++++++----- .../validation_tools/test_props_ml.py | 19 +++++++--- 20 files changed, 128 insertions(+), 142 deletions(-) rename tests/integrate/validation_tools/{check_lr_absorption_csr.py => check_lr_absorption_workflow.py} (86%) diff --git a/docs/advanced/elec_properties/hs_matrix.md b/docs/advanced/elec_properties/hs_matrix.md index d5c1e570aa9..5ee0c5c1888 100644 --- a/docs/advanced/elec_properties/hs_matrix.md +++ b/docs/advanced/elec_properties/hs_matrix.md @@ -109,13 +109,9 @@ Place `hrs1_nao.csr` and `sr_nao.csr` in the LR `read_file_dir` alongside the ma For local and semilocal functionals without exact exchange, use `abs_gauge velocity`. Its direct momentum and nonlocal pseudopotential integrals avoid the additional finite-AO projection used to form the full commutator. -For finite differences of LR-TDDFT excitation energies, set -[`lr_energy_precision 17`](../input_files/input-main.md#lr_energy_precision). -The number refers to significant digits in the excitation-energy output. -Set `abs_gauge none` to report energies without evaluating optical matrix -elements. The precision setting works independently of `out_band` and -`out_wfc_lr`. The default is eight significant digits. Set -`lr_energy_precision 0` to use the legacy output formats. +LR-TDDFT reports excitation energies with 17 significant digits. Use +`abs_gauge none` to report energies without evaluating optical matrix +elements. The absorption spectrum is a text table in `absorption.dat`. ### Native Binary CSR Format diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index d794dfcf028..4cb19386467 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -403,6 +403,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) } if (this->inp_->lr_solver == "spectrum" || this->inp_->lr_solver == "elpa") { + const int legacy_energy_precision = 0; const std::string gauge = LR_Util::tolower(this->inp_->abs_gauge); if (gauge == "none") { @@ -412,7 +413,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { const double *const energies = &this->tda_ene[is * this->nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_tda"; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, 0); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, legacy_energy_precision); } } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "full") @@ -421,7 +422,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { const double *const energies = &this->full_ene[is * this->nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_full"; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, 0); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, legacy_energy_precision); } } } @@ -451,11 +452,11 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) } spectrum.cal_spectrum(); const std::string channel = this->inp_->bse_spin_types[is] + "_tda"; - spectrum.transition_analysis(channel, 0); + spectrum.transition_analysis(channel, legacy_energy_precision); if (this->inp_->bse_spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { const std::string dipole_filename = output_dir + "trans_dipole_" + channel + ".dat"; - spectrum.write_transition_dipole(dipole_filename, 0); + spectrum.write_transition_dipole(dipole_filename, legacy_energy_precision); // ============================== for test ============================== if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { //// TEST the formula v/omega rather than v/(e_a-e_i) @@ -485,11 +486,11 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) spectrum.set_full(true); spectrum.cal_spectrum(); const std::string channel = this->inp_->bse_spin_types[is] + "_full"; - spectrum.transition_analysis(channel, 0); + spectrum.transition_analysis(channel, legacy_energy_precision); if (this->inp_->bse_spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { const std::string dipole_filename = output_dir + "trans_dipole_" + channel + ".dat"; - spectrum.write_transition_dipole(dipole_filename, 0); + spectrum.write_transition_dipole(dipole_filename, legacy_energy_precision); } } } diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index 9db223ac8c4..c218057d239 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr_lcao_tddft.cpp @@ -38,6 +38,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); UnitCell &ucell = static_cast(basecell); + this->last_ionic_step_ = istep + 1; ModuleBase::TITLE("ESolver_LR", "runner"); ModuleBase::timer::start("ESolver_LR", "runner"); @@ -91,14 +92,13 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste } else if (this->inp_->lr_solver != "spectrum") { - const int energy_precision = this->inp_->lr_energy_precision; - auto write_states = [this, &efile_out, &vfile_out, energy_precision]( + auto write_states = [this, &efile_out, &vfile_out]( const std::string& label, const Real* e, const T* v, const int dim, const int nst) { if (this->my_rank_ == 0) { const std::string energy_file = efile_out(label); - if (!LR_Util::write_excitation_energy_file(energy_file, e, nst, energy_precision)) + if (!LR_Util::write_excitation_energy_file(energy_file, e, nst)) { ModuleBase::WARNING_QUIT("ESolver_LR", "Failed to write " + energy_file); } @@ -137,7 +137,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste this->pot, this->kv, this->paraX_, this->paraC_, this->paraMat_); LR::HSolver::solve( hulr, this->X[0].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, - this->paraX_, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true, energy_precision); + this->paraX_, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); if (this->inp_->out_wfc_lr) { write_states("openshell", this->pelec->ekb.c, this->X[0].template data(), nloc_per_state, nstates); @@ -167,7 +167,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste LR::HSolver::solve( hlr, this->X[is].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, this->paraX_, this->pelec->ekb.c + is * nstates, this->inp_->lr_solver, this->inp_->lr_thr, - precondition, true, energy_precision); + precondition, true); if (this->inp_->out_wfc_lr) { write_states( @@ -355,7 +355,7 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) freq[i] = 91.126664 / (lambda_min + 0.01 * static_cast(i + 1) * lambda_diff); } } - const int energy_precision = this->inp_->lr_energy_precision; + const int energy_precision = LR_Util::lr_excitation_energy_digits; for (int is = 0; is < this->X.size(); ++is) { if (!calculate_spectrum) @@ -379,7 +379,8 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) spectrum.transition_analysis(channel, energy_precision); if (spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { - spectrum.optical_absorption_method1(freq, this->inp_->abs_broadening); + spectrum.optical_absorption_method1( + freq, this->inp_->abs_broadening, this->last_ionic_step_, this->ofs_running_); const std::string dipole_filename = this->out_dir + "trans_dipole_" + channel + ".dat"; spectrum.write_transition_dipole(dipole_filename, energy_precision); // =============================================== for test ==================================================== diff --git a/source/source_esolver/esolver_lr_lcao_tddft.h b/source/source_esolver/esolver_lr_lcao_tddft.h index 130ce86cda4..24989cad97a 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr_lcao_tddft.h @@ -160,6 +160,7 @@ class ESolver_LR : public ModuleESolver::ESolver_FP void initialize_from_ks_(UnitCell &ucell, const Input_para &inp); /// re-read everything that depends on the atomic positions, once per ionic step void refresh_from_ks_(UnitCell &ucell); + int last_ionic_step_ = 1; ///< one-based step of the final LR spectrum bool ks_initialized_ = false; ///< whether `initialize_from_ks_` has already run bool exx_owned_ = false; ///< `exx_lri` was built here (so its Cs/Vs are ours to refresh) diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 4372d314932..351c79f73c7 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -413,7 +413,6 @@ struct Input_para std::string xc_kernel = "LDA"; ///< exchange correlation (XC) kernel for LR-TDDFT std::string lr_solver = "dav"; ///< the eigensolver for LR-TDDFT double lr_thr = 1e-2; ///< convergence threshold of the LR-TDDFT eigensolver - int lr_energy_precision = 8; ///< significant digits in LR excitation-energy output bool out_wfc_lr = false; ///< whether to output the eigenvectors (excitation amplitudes) in the particle-hole basis bool lr_unrestricted = false; ///< whether to use the unrestricted construction for LR-TDDFT std::vector abs_wavelen_range = {}; ///< the range of wavelength(nm) to output the absorption spectrum diff --git a/source/source_io/module_parameter/read_inp_tddft.cpp b/source/source_io/module_parameter/read_inp_tddft.cpp index eb87696e2be..b854864108b 100644 --- a/source/source_io/module_parameter/read_inp_tddft.cpp +++ b/source/source_io/module_parameter/read_inp_tddft.cpp @@ -1173,25 +1173,6 @@ void ReadInput::item_lr_tddft() read_sync_double(input.lr_thr); this->add_item(item); } - { - Input_Item item("lr_energy_precision"); - item.annotation = "significant digits for LR-TDDFT excitation energies"; - item.category = "Linear Response TDDFT"; - item.type = "Integer"; - item.description = R"(Number of significant digits (1 to 17) for LR-TDDFT excitation energies in the eigensolver output, running-log energy reports, transition analysis and dipole tables, and Excitation_Energy files enabled by out_wfc_lr. The default is 8 significant digits. Set lr_energy_precision 0 to use each output's legacy format. For finite differences, use lr_energy_precision 17. The setting only changes text output and can be used without out_band or out_wfc_lr.)"; - item.default_value = "8"; - item.unit = ""; - item.set_availability("basis_type==lcao and esolver_type in [lr, ks-lr]"); - read_sync_int(input.lr_energy_precision); - item.check_value = [](const Input_Item&, const Parameter& para) { - const int precision = para.inp.lr_energy_precision; - if (precision < 0 || precision > std::numeric_limits::max_digits10) - { - ModuleBase::WARNING_QUIT("ReadInput", "lr_energy_precision must be an integer from 0 to 17"); - } - }; - this->add_item(item); - } { Input_Item item("nocc"); item.annotation = "the occupied orbital window ending at HOMO for LR-TDDFT"; diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 8f87ea77d10..b1566ccd232 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -854,28 +854,3 @@ TEST_F(InputParaTest, OpticalGaugeDefaultsToCommutatorForGroundStateExactExchang EXPECT_EQ(parameter.inp.abs_gauge, gauge); } } - -TEST_F(InputParaTest, LrEnergyPrecision) -{ - ModuleIO::ReadInput reader(0); - const auto& list = reader.get_input_lists(); - const std::map items(list.begin(), list.end()); - Parameter parameter; - EXPECT_EQ(parameter.inp.lr_energy_precision, 8); - EXPECT_EQ(parameter.inp.out_band[0], 0); - EXPECT_FALSE(parameter.inp.out_wfc_lr); - auto item = items.at("lr_energy_precision"); - for (const int digits : {0, 1, 8, 17}) - { - item.str_values = {std::to_string(digits)}; - item.read_value(item, parameter); - EXPECT_EQ(parameter.inp.lr_energy_precision, digits); - EXPECT_NO_THROW(item.check_value(item, parameter)); - } - for (const int digits : {-1, 18}) - { - item.str_values = {std::to_string(digits)}; - item.read_value(item, parameter); - EXPECT_EXIT(item.check_value(item, parameter), testing::ExitedWithCode(1), ""); - } -} diff --git a/source/source_lcao/module_lr/hsolver_lrtd.cpp b/source/source_lcao/module_lr/hsolver_lrtd.cpp index 4c0e8f2ea07..f46e7bc290c 100644 --- a/source/source_lcao/module_lr/hsolver_lrtd.cpp +++ b/source/source_lcao/module_lr/hsolver_lrtd.cpp @@ -37,16 +37,12 @@ namespace LR template inline void print_eigs(const std::vector& eigs, const std::string& label, - const double factor, const int energy_precision) + const double factor) { const auto old_precision = std::cout.precision(); const auto old_flags = std::cout.flags(); - const int digits = energy_precision > 0 ? energy_precision : 8; - if (energy_precision > 0) - { - std::cout << std::defaultfloat; - } - std::cout << label << std::setprecision(digits) << std::endl; + const int digits = LR_Util::lr_excitation_energy_digits; + std::cout << label << std::defaultfloat << std::setprecision(digits) << std::endl; for (auto& e : eigs) { std::cout << e * factor << " "; } std::cout << std::endl; std::cout.precision(old_precision); @@ -67,8 +63,7 @@ namespace LR const std::string method, const Real& diag_ethr, ///< threshold for diagonalization const std::vector>& precondition, - const bool hermitian, - const int energy_precision) + const bool hermitian) { ModuleBase::TITLE("HSolverLR", "solve"); ModuleBase::timer::start("HSolverLR", "solve"); @@ -95,7 +90,7 @@ namespace LR { std::vector> eig_complex(gdim); LR_Util::diag_lapack_nh(gdim, Amat_full.data(), eig_complex.data()); - print_eigs(eig_complex, "Right eigenvalues: of the non-Hermitian matrix: (Ry)", 1.0, energy_precision); + print_eigs(eig_complex, "Right eigenvalues: of the non-Hermitian matrix: (Ry)", 1.0); for (int i = 0; i < gdim; i++) { eigenvalue[i] = eig_complex[i].real(); } } bool openshell = std::is_same>::value; @@ -167,8 +162,8 @@ namespace LR for (int ist = 0;ist < nband;++ist) { eig[ist] = eigenvalue[ist]; } // 6. output eigenvalues and eigenvectors - print_eigs(eigenvalue, "eigenvalues: (Ry)", 1.0, energy_precision); - print_eigs(eigenvalue, "eigenvalues: (eV)", ModuleBase::Ry_to_eV, energy_precision); + print_eigs(eigenvalue, "eigenvalues: (Ry)", 1.0); + print_eigs(eigenvalue, "eigenvalues: (eV)", ModuleBase::Ry_to_eV); // normalization is already satisfied // std::cout << "check normalization of eigenvectors:" << std::endl; @@ -191,10 +186,10 @@ namespace LR << "; current threshold: " << diag_ethr << std::endl; ModuleBase::timer::end("HSolverLR", "solve"); } -template void solve>(const HamiltLR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); -template void solve>(const HamiltULR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); -template void solve, HamiltLR>>(const HamiltLR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); -template void solve, HamiltULR>>(const HamiltULR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool, const int); +template void solve>(const HamiltLR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); +template void solve>(const HamiltULR&, double*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); +template void solve, HamiltLR>>(const HamiltLR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); +template void solve, HamiltULR>>(const HamiltULR>&, std::complex*, const int&, const int&, const int&, const std::vector&, const std::vector&, const std::vector&, double*, const std::string, const double&, const std::vector&, const bool); } } diff --git a/source/source_lcao/module_lr/hsolver_lrtd.h b/source/source_lcao/module_lr/hsolver_lrtd.h index 9391965dfd5..70f2d49c780 100644 --- a/source/source_lcao/module_lr/hsolver_lrtd.h +++ b/source/source_lcao/module_lr/hsolver_lrtd.h @@ -26,8 +26,7 @@ namespace HSolver const std::string method, const Real& diag_ethr, ///< threshold for diagonalization const std::vector>& precondition, - const bool hermitian, - const int energy_precision); + const bool hermitian); } } #endif diff --git a/source/source_lcao/module_lr/lr_spectrum.cpp b/source/source_lcao/module_lr/lr_spectrum.cpp index 83a593ac4a4..65d205a9d80 100644 --- a/source/source_lcao/module_lr/lr_spectrum.cpp +++ b/source/source_lcao/module_lr/lr_spectrum.cpp @@ -3,6 +3,9 @@ #include "source_base/global_variable.h" #include "source_lcao/module_lr/dm_trans/dm_trans.h" #include "source_base/parallel_reduce.h" +#include "source_base/tool_quit.h" +#include "source_io/module_output/provenance_header.h" +#include "source_io/module_output/write_notice.h" #include "source_lcao/module_lr/utils/lr_util.h" #include "source_lcao/module_lr/utils/lr_util_hcontainer.h" #include "source_lcao/module_lr/utils/lr_util_print.h" @@ -176,7 +179,8 @@ void LR::LR_Spectrum::oscillator_strength() } template -void LR::LR_Spectrum::optical_absorption_method1(const std::vector& freq, const double eta) +void LR::LR_Spectrum::optical_absorption_method1(const std::vector& freq, const double eta, + const int ionic_step, std::ofstream& running_log) { // ============test dipole================ // this->cal_transition_dipoles_length(); @@ -194,9 +198,17 @@ void LR::LR_Spectrum::optical_absorption_method1(const std::vector& f // = -8*pi*Omega_S/V * mean_squared_dipole * Im[1/[(w+i\eta)^2-\Omega_S^2]] // = -4*pi/V * oscilator_strength * Im[1/[(w+i\eta)^2-\Omega_S^2]] std::vector& osc = this->oscillator_strength_; - std::ofstream ofs(this->out_dir + "absorption.dat"); - - ofs << "Frequency (eV) | wave length(nm) | Absorption (a.u.)" << std::endl; + const std::string filename = this->out_dir + "absorption.dat"; + std::ofstream ofs(filename); + if (!ofs) + { + const std::string message = "Cannot write " + filename; + ModuleBase::WARNING_QUIT("optical_absorption_method1", message); + } + const std::string timestamp = ModuleIO::local_timestamp(); + ofs << ModuleIO::prov_step(ionic_step, timestamp); + ofs << "# " << freq.size() << " # number of points\n"; + ofs << "# Frequency (eV) | wave length(nm) | Absorption (a.u.)\n"; double FourPI_div_c = ModuleBase::FOUR_PI / 137.036; double fac = 4 * M_PI / ucell.omega * ModuleBase::e2 / this->nk; // e2 for Ry to Hartree in the denominator @@ -210,6 +222,7 @@ void LR::LR_Spectrum::optical_absorption_method1(const std::vector& f ofs << freq[f] * ModuleBase::Ry_to_eV << '\t' << 91.126664 / freq[f] << '\t' << std::abs(abs) << '\n'; } ofs.close(); + ModuleIO::write_notice(running_log, "LR absorption spectrum", filename); } template diff --git a/source/source_lcao/module_lr/lr_spectrum.h b/source/source_lcao/module_lr/lr_spectrum.h index 8cb034acadf..b9b03f369f2 100644 --- a/source/source_lcao/module_lr/lr_spectrum.h +++ b/source/source_lcao/module_lr/lr_spectrum.h @@ -9,6 +9,8 @@ #include "source_lcao/module_rt/velocity_op.h" #include "source_lcao/module_lr/utils/spectrum_mo.h" +#include + namespace LR { template @@ -49,7 +51,8 @@ namespace LR this->oscillator_strength(); } /// @brief calculate the optical absorption spectrum with $Im[1/[(w+i\eta)^2-\Omega_S^2]]$ - void optical_absorption_method1(const std::vector& freq, const double eta); + void optical_absorption_method1(const std::vector& freq, const double eta, + const int ionic_step, std::ofstream& running_log); /// @brief calculate the optical absorption spectrum with lorentzian delta function void optical_absorption_method2(const std::vector& freq, const double eta); /// @brief print out the transition dipole moment and the main contributions to the transition amplitude diff --git a/source/source_lcao/module_lr/utils/lr_util_print.h b/source/source_lcao/module_lr/utils/lr_util_print.h index fa6736c6bcf..4b28c7f15d7 100644 --- a/source/source_lcao/module_lr/utils/lr_util_print.h +++ b/source/source_lcao/module_lr/utils/lr_util_print.h @@ -4,6 +4,7 @@ #include #include "source_base/constants.h" #include +#include #include #include "source_psi/psi.h" #ifdef __EXX @@ -11,6 +12,8 @@ #endif namespace LR_Util { + constexpr int lr_excitation_energy_digits = std::numeric_limits::max_digits10; + /// Report selected excitation energies without evaluating optical matrix elements. inline void print_excitation_energies(std::ostream& log, const double* energies, const int nstates, const std::string& channel, @@ -89,14 +92,10 @@ namespace LR_Util return res; } inline bool write_excitation_energy_file(const std::string& file, const double* energies, - const int nstates, const int energy_precision) + const int nstates) { - if (energy_precision == 0) - { - return write_value(file, 8, energies, nstates) == nstates; - } std::ofstream ofs(file); - const int decimals = energy_precision - 1; + const int decimals = lr_excitation_energy_digits - 1; ofs << std::scientific << std::setprecision(decimals); for (int state = 0; state < nstates; ++state) { diff --git a/tests/08_RI/CMakeLists.txt b/tests/08_RI/CMakeLists.txt index ab4c2fbc512..e41ea3e1711 100644 --- a/tests/08_RI/CMakeLists.txt +++ b/tests/08_RI/CMakeLists.txt @@ -57,22 +57,15 @@ else() # separate LR runs, which the single-invocation Autotest cases cannot express. find_program(LR_ABSORPTION_PYTHON python3) if(ENABLE_MPI AND ENABLE_LCAO AND ENABLE_LIBRI AND ENABLE_LIBXC AND LR_ABSORPTION_PYTHON) - foreach(spin_count IN ITEMS 1 2) - set(spectrum_test 08_RI_lr_absorption_csr) - if(spin_count EQUAL 2) - string(APPEND spectrum_test "_spin2") - endif() - add_test( - NAME ${spectrum_test} - COMMAND - ${LR_ABSORPTION_PYTHON} - ${ABACUS_TEST_DIR}/integrate/validation_tools/check_lr_absorption_csr.py - --abacus ${ABACUS_BIN_PATH} - --case ${ABACUS_TEST_DIR}/08_RI/lr_tddft_velocity_commutator - --nspin ${spin_count} - --mpiexec ${MPIEXEC_EXECUTABLE} --mpi-np-flag=${MPIEXEC_NUMPROC_FLAG} - ${MPI_LAUNCHER_FLAGS}) - set_tests_properties(${spectrum_test} PROPERTIES PROCESSORS 4 TIMEOUT 180) - endforeach() + add_test( + NAME 08_RI_lr_absorption_workflow + COMMAND + ${LR_ABSORPTION_PYTHON} + ${ABACUS_TEST_DIR}/integrate/validation_tools/check_lr_absorption_workflow.py + --abacus ${ABACUS_BIN_PATH} + --case ${ABACUS_TEST_DIR}/08_RI/lr_tddft_velocity_commutator + --mpiexec ${MPIEXEC_EXECUTABLE} --mpi-np-flag=${MPIEXEC_NUMPROC_FLAG} + ${MPI_LAUNCHER_FLAGS}) + set_tests_properties(08_RI_lr_absorption_workflow PROPERTIES PROCESSORS 4 TIMEOUT 180) endif() endif() diff --git a/tests/08_RI/lr_tddft_hf_gamma/README b/tests/08_RI/lr_tddft_hf_gamma/README index c773acee4a6..3a12576bab8 100644 --- a/tests/08_RI/lr_tddft_hf_gamma/README +++ b/tests/08_RI/lr_tddft_hf_gamma/README @@ -1,3 +1,3 @@ LR-TDDFT HF on H2O, gamma_only, nspin=2, lr_nstates=2, lr_solver=dav. Retains Z-CG coverage. abs_gauge=none skips optical postprocessing; -the energy references use the default eight significant digits. +the excitation energies are printed with 17 significant digits. diff --git a/tests/08_RI/lr_tddft_hf_gamma/result.ref b/tests/08_RI/lr_tddft_hf_gamma/result.ref index 20ba339b527..58fab6ef18d 100644 --- a/tests/08_RI/lr_tddft_hf_gamma/result.ref +++ b/tests/08_RI/lr_tddft_hf_gamma/result.ref @@ -3,5 +3,5 @@ CompareLRForce_pass 0 excitationenergyref1 1.531735 excitationenergyref2 1.532418 excitationenergyref3 1.353648 -excitationenergyref4 1.354671 +excitationenergyref4 1.354670 totaltimeref 3.05 diff --git a/tests/08_RI/lr_tddft_velocity_commutator/README b/tests/08_RI/lr_tddft_velocity_commutator/README index 7c490ad5783..07f434dd89b 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/README +++ b/tests/08_RI/lr_tddft_velocity_commutator/README @@ -2,9 +2,7 @@ H2 with two k points, HSE orbitals, nspin=1, and an RPA response kernel. Both LCAO bands are included. The default optical velocity includes the ground-state Fock commutator, checked at all 100 spectrum points. -The 08_RI_lr_absorption_csr and 08_RI_lr_absorption_csr_spin2 tests -run this fixture with one and two spin channels. They export density, -orbitals and text H(R)/S(R) in scratch directories, compare the in-memory -and standalone spectra, check the closed-shell spectrum against the -same reference, and evaluate direct velocity on the standalone inputs. -The two-spin test checks the read of both CSR spin blocks. +The 08_RI_lr_absorption_workflow test runs this fixture with one and two +spin channels. It compares the text absorption.dat tables produced using +H(R)/S(R) in memory or read from CSR, and evaluates direct velocity on +the same standalone inputs. The two-spin run checks both CSR H(R) inputs. diff --git a/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref index 95e80ce49a1..028fb32f8b6 100644 --- a/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref +++ b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref @@ -1,4 +1,6 @@ -Frequency (eV) | wave length(nm) | Absorption (a.u.) +# Ionic_Step 1 +# 100 # number of points +# Frequency (eV) | wave length(nm) | Absorption (a.u.) 29.1043 42.6 0.0147588 27.4301 45.2 0.00225836 25.9381 47.8 0.00094464 diff --git a/tests/integrate/validation_tools/check_lr_absorption.py b/tests/integrate/validation_tools/check_lr_absorption.py index 8b0f696f390..4a42717e2bb 100644 --- a/tests/integrate/validation_tools/check_lr_absorption.py +++ b/tests/integrate/validation_tools/check_lr_absorption.py @@ -3,9 +3,10 @@ import argparse import math from pathlib import Path +import re -HEADER = "Frequency (eV) | wave length(nm) | Absorption (a.u.)" +HEADER = "# Frequency (eV) | wave length(nm) | Absorption (a.u.)" SPECTRUM_POINTS = 100 # Keep the grid on an absolute scale. A separate floor for the intensities # permits roundoff near zero without masking small spectral features. @@ -16,15 +17,31 @@ ) -def read_spectrum(path): +def read_spectrum(path, *, require_provenance=False): lines = path.read_text().splitlines() - if not lines or lines[0].strip() != HEADER: + metadata_start = 0 + if lines and lines[0].startswith("# ABACUS version: "): + if len(lines) < 2 or not re.fullmatch(r"# Written at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", lines[1]): + raise ValueError(f"{path}: missing or invalid write timestamp") + metadata_start = 2 + elif require_provenance: + raise ValueError(f"{path}: missing ABACUS version header") + + point_count = f"# {SPECTRUM_POINTS} # number of points" + metadata = lines[metadata_start:metadata_start + 3] + if len(metadata) != 3 or not re.fullmatch(r"# Ionic_Step [1-9][0-9]*", metadata[0]): + raise ValueError(f"{path}: missing or invalid one-based ionic step") + if metadata[1] != point_count: + raise ValueError(f"{path}: expected header {point_count}") + if metadata[2] != HEADER: raise ValueError(f"{path}: missing absorption table header") - if len(lines) - 1 != SPECTRUM_POINTS: - raise ValueError(f"{path}: expected {SPECTRUM_POINTS} data rows, found {len(lines) - 1}") + data_start = metadata_start + 3 + data_rows = lines[data_start:] + if len(data_rows) != SPECTRUM_POINTS: + raise ValueError(f"{path}: expected {SPECTRUM_POINTS} data rows, found {len(data_rows)}") values = [] - for line_number, line in enumerate(lines[1:], start=2): + for line_number, line in enumerate(data_rows, start=data_start + 1): columns = line.split() if len(columns) != 3: raise ValueError(f"{path}:{line_number}: expected three numerical columns") @@ -40,13 +57,13 @@ def read_spectrum(path): def compare_spectra(reference, output): reference_rows = read_spectrum(reference) - output_rows = read_spectrum(output) - for line, (expected, actual) in enumerate(zip(reference_rows, output_rows), start=2): + output_rows = read_spectrum(output, require_provenance=True) + for line, (expected, actual) in enumerate(zip(reference_rows, output_rows), start=1): columns = zip(expected, actual, COLUMN_TOLERANCES) for column, (expected_value, actual_value, (absolute, relative)) in enumerate(columns, start=1): if not math.isclose(expected_value, actual_value, abs_tol=absolute, rel_tol=relative): raise ValueError( - f"{output}:{line}: column {column} is {actual_value}, " + f"{output}: data row {line}, column {column} is {actual_value}, " f"expected {expected_value} from {reference}" ) diff --git a/tests/integrate/validation_tools/check_lr_absorption_csr.py b/tests/integrate/validation_tools/check_lr_absorption_workflow.py similarity index 86% rename from tests/integrate/validation_tools/check_lr_absorption_csr.py rename to tests/integrate/validation_tools/check_lr_absorption_workflow.py index cfe57e582fa..4295c409ef6 100644 --- a/tests/integrate/validation_tools/check_lr_absorption_csr.py +++ b/tests/integrate/validation_tools/check_lr_absorption_workflow.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Compare HSE LR spectra from in-memory and exported optical matrices.""" +"""Compare text HSE LR absorption spectra using in-memory and exported H(R)/S(R).""" import argparse import os from pathlib import Path @@ -25,12 +25,12 @@ def run_case(directory, fixture, launch, parameters): return directory / "OUT.autotest" -def compare_workflows(args, root): +def compare_workflow(args, root, nspin): fixture = args.case.resolve() orbitals = fixture.parent.parent / "PP_ORB" parameters = dict(line.split(maxsplit=1) for line in (fixture / "INPUT").read_text().splitlines() if len(line.split(maxsplit=1)) == 2) - parameters.update(pseudo_dir=orbitals, orbital_dir=orbitals, nspin=args.nspin) + parameters.update(pseudo_dir=orbitals, orbital_dir=orbitals, nspin=nspin) launch = [args.mpiexec, args.mpi_np_flag, "4", *args.mpi_preflag, str(args.abacus.resolve()), *args.mpi_postflag] @@ -45,7 +45,7 @@ def compare_workflows(args, root): log = (csr_out / "running_nscf.log").read_text() # In a closed-shell spin-two case the two blocks can be equal. Verify that # standalone LR actually obtains both blocks from their separate CSR files. - for spin in range(1, args.nspin + 1): + for spin in range(1, nspin + 1): matrix_file = ks_out / f"hrs{spin}_nao.csr" if f"Reading optical matrix from {matrix_file}" not in log: raise ValueError(f"Standalone LR did not read {matrix_file}") @@ -53,15 +53,15 @@ def compare_workflows(args, root): direct_inputs = dict(consumer, abs_gauge="velocity") direct_out = run_case(root / "direct", fixture, launch, direct_inputs) - commutator = read_spectrum(csr_out / "absorption.dat") - direct = read_spectrum(direct_out / "absorption.dat") + commutator = read_spectrum(csr_out / "absorption.dat", require_provenance=True) + direct = read_spectrum(direct_out / "absorption.dat", require_provenance=True) if any(full[:2] != bare[:2] for full, bare in zip(commutator, direct)): raise ValueError("The commutator and direct velocity spectra use different grids.") peak = max(row[2] for row in commutator) difference = max(abs(full[2] - bare[2]) for full, bare in zip(commutator, direct)) if peak <= 0 or difference <= 0.05 * peak: raise ValueError("The HSE commutator spectrum must differ from direct velocity by over 5% of peak height.") - print(f"nspin={args.nspin}: in-memory and CSR spectra agree. " + print(f"nspin={nspin}: spectra from in-memory and CSR matrix inputs agree. " f"Direct velocity differs by {difference / peak:.1%} of peak height.") @@ -69,7 +69,6 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--abacus", type=Path, required=True) parser.add_argument("--case", type=Path, required=True) - parser.add_argument("--nspin", type=int, choices=(1, 2), default=1) parser.add_argument("--mpiexec", required=True) parser.add_argument("--mpi-np-flag", required=True) parser.add_argument("--mpi-preflag", action="append", default=[]) @@ -77,7 +76,10 @@ def main(): args = parser.parse_args() try: with tempfile.TemporaryDirectory(prefix="abacus-lr-absorption-") as directory: - compare_workflows(args, Path(directory)) + for nspin in (1, 2): + spin_dir = Path(directory) / f"spin{nspin}" + spin_dir.mkdir() + compare_workflow(args, spin_dir, nspin) except (OSError, ValueError) as error: parser.exit(1, f"{error}\n") diff --git a/tests/integrate/validation_tools/test_props_ml.py b/tests/integrate/validation_tools/test_props_ml.py index 708480d810d..d248d0fe1c8 100644 --- a/tests/integrate/validation_tools/test_props_ml.py +++ b/tests/integrate/validation_tools/test_props_ml.py @@ -9,7 +9,9 @@ from check_lr_absorption import HEADER, SPECTRUM_POINTS -SPECTRUM = HEADER + '\n' + '3.00 413.28 2.5\n' * SPECTRUM_POINTS +REFERENCE = (f'# Ionic_Step 1\n# {SPECTRUM_POINTS} # number of points\n' + + HEADER + '\n' + '3.00 413.28 2.5\n' * SPECTRUM_POINTS) +SPECTRUM = '# ABACUS version: test\n# Written at 2026-01-01 00:00:00\n' + REFERENCE class LREnergyCollectorTest(unittest.TestCase): @@ -62,9 +64,18 @@ def test_no_spectrum_ignores_stale_optical_files(self): self.assertEqual(self.collect(log, analysis), 'excitationenergyref1 1.531730\n') def test_absorption_accepts_complete_finite_table(self): - result = self.collect('', reference=SPECTRUM, spectrum=SPECTRUM) + result = self.collect('', reference=REFERENCE, spectrum=SPECTRUM) self.assertEqual(result, 'CompareLRAbsorption_pass 0\n') + def test_absorption_checks_provenance_step_and_point_count(self): + no_timestamp = SPECTRUM.replace('# Written at 2026-01-01 00:00:00\n', '') + wrong_step = SPECTRUM.replace('Ionic_Step 1', 'Ionic_Step 0') + wrong_count = SPECTRUM.replace('# 100 # number of points', '# 99 # number of points') + for spectrum in (REFERENCE, no_timestamp, wrong_step, wrong_count): + with self.subTest(metadata=spectrum.splitlines()[:5]): + result = self.collect('', reference=REFERENCE, spectrum=spectrum) + self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + def test_absorption_rejects_empty_and_incomplete_table(self): truncated = '\n'.join(SPECTRUM.splitlines()[:-1]) + '\n' for reference, spectrum in [(SPECTRUM, None), (SPECTRUM, ''), (SPECTRUM, truncated), @@ -95,7 +106,7 @@ def test_absorption_keeps_absolute_tolerances_on_both_grid_columns(self): changed_frequency = SPECTRUM.replace('3.00', '3.0002', 1) changed_wavelength = SPECTRUM.replace('413.28', '413.2802', 1) for spectrum in (changed_frequency, changed_wavelength): - with self.subTest(spectrum_row=spectrum.splitlines()[1]): + with self.subTest(spectrum_row=spectrum.splitlines()[5]): result = self.collect('', reference=SPECTRUM, spectrum=spectrum) self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') @@ -103,7 +114,7 @@ def test_absorption_rejects_wrong_columns_and_changed_values(self): wrong_columns = SPECTRUM.replace('3.00 413.28 2.5', '3.00 413.28', 1) changed = SPECTRUM.replace('3.00 413.28 2.5', '3.00 413.28 2.6', 1) for spectrum in (wrong_columns, changed): - with self.subTest(spectrum_row=spectrum.splitlines()[1]): + with self.subTest(spectrum_row=spectrum.splitlines()[5]): result = self.collect('', reference=SPECTRUM, spectrum=spectrum) self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') From ff7dbc29c19107662435bcb78cd1d25dd1456a3c Mon Sep 17 00:00:00 2001 From: maki49 <1579492865@qq.com> Date: Tue, 24 Nov 2026 03:33:29 -0500 Subject: [PATCH 6/6] Test full-precision LR excitation energy round trip --- .../module_lr/unittests/CMakeLists.txt | 4 +++ .../unittests/test_lr_util_print.cpp | 26 +++++++++++++++++++ .../module_lr/utils/lr_util_print.h | 11 +++++--- 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 source/source_lcao/module_lr/unittests/test_lr_util_print.cpp diff --git a/source/source_lcao/module_lr/unittests/CMakeLists.txt b/source/source_lcao/module_lr/unittests/CMakeLists.txt index 9bcc49191ca..03a2f37fd70 100644 --- a/source/source_lcao/module_lr/unittests/CMakeLists.txt +++ b/source/source_lcao/module_lr/unittests/CMakeLists.txt @@ -167,3 +167,7 @@ AddTest( TARGET MODULE_LR_spectrum_weights SOURCES test_spectrum_weights.cpp ) + +AddTest( + TARGET MODULE_LR_util_print + SOURCES test_lr_util_print.cpp) diff --git a/source/source_lcao/module_lr/unittests/test_lr_util_print.cpp b/source/source_lcao/module_lr/unittests/test_lr_util_print.cpp new file mode 100644 index 00000000000..dbcdfbe39a4 --- /dev/null +++ b/source/source_lcao/module_lr/unittests/test_lr_util_print.cpp @@ -0,0 +1,26 @@ +#include "source_lcao/module_lr/utils/lr_util_print.h" + +#include +#include +#include +#include +#include +#include + +#include + +TEST(LRUtilPrint, ExcitationEnergyFileRoundTripsDoublePrecision) +{ + constexpr int nstates = 2; + // At 16 significant digits, the next double above 1.0 rounds to 1.0. + const std::array energies = {std::nextafter(1.0, 2.0), 1e-12}; + const std::string filename = testing::TempDir() + "lr_excitation_energies_" + std::to_string(getpid()) + ".dat"; + EXPECT_TRUE(LR_Util::write_excitation_energy_file(filename, energies.data(), nstates)); + + std::array restored{}; + std::ifstream input(filename); + EXPECT_TRUE(static_cast(input >> restored[0] >> restored[1])); + input.close(); + EXPECT_EQ(std::remove(filename.c_str()), 0); + EXPECT_EQ(restored, energies); +} diff --git a/source/source_lcao/module_lr/utils/lr_util_print.h b/source/source_lcao/module_lr/utils/lr_util_print.h index 4b28c7f15d7..eeadea1eb5b 100644 --- a/source/source_lcao/module_lr/utils/lr_util_print.h +++ b/source/source_lcao/module_lr/utils/lr_util_print.h @@ -1,12 +1,17 @@ #ifndef ABACUS_SOURCE_LCAO_MODULE_LR_UTILS_LR_UTIL_PRINT_H #define ABACUS_SOURCE_LCAO_MODULE_LR_UTILS_LR_UTIL_PRINT_H -#include #include "source_base/constants.h" +#include "source_base/parallel_blkcyc.h" +#include "source_psi/psi.h" + +#include +#include +#include #include +#include #include -#include -#include "source_psi/psi.h" +#include #ifdef __EXX #include #endif