diff --git a/docs/advanced/elec_properties/hs_matrix.md b/docs/advanced/elec_properties/hs_matrix.md index 4a800b0b305..5ee0c5c1888 100644 --- a/docs/advanced/elec_properties/hs_matrix.md +++ b/docs/advanced/elec_properties/hs_matrix.md @@ -93,6 +93,26 @@ 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. + +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 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_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index d33b5a520ad..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); + 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); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel, legacy_energy_precision); } } } @@ -450,12 +451,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, legacy_energy_precision); + 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, 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) @@ -484,12 +485,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, legacy_energy_precision); + 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, legacy_energy_precision); } } } diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index 67cb43729e7..c218057d239 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" @@ -37,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 +93,24 @@ 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 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)) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "Failed to write " + energy_file); + } + this->ofs_running_ << " Write LR excitation energies to " << energy_file << '\n'; + } + 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); } - assert(nst * dim == LR_Util::write_value(vfile_out(label), prec, v, nst, dim)); + 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 @@ -282,14 +294,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) { @@ -307,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 = LR_Util::lr_excitation_energy_digits; 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 { @@ -322,21 +369,24 @@ 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()); } 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) + 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 ==================================================== + // 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_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_hamilt/module_hcontainer/read_hcontainer.cpp b/source/source_hamilt/module_hcontainer/read_hcontainer.cpp index 71319c5b750..96e737848b3 100644 --- a/source/source_hamilt/module_hcontainer/read_hcontainer.cpp +++ b/source/source_hamilt/module_hcontainer/read_hcontainer.cpp @@ -3,6 +3,7 @@ #include "hcontainer_funcs.h" #include "source_base/module_out/csr_reader.h" #include "source_base/module_out/sparse_matrix.h" +#include "source_base/tool_quit.h" #include "transfer.h" #include @@ -56,9 +57,14 @@ void Read_HContainer::read() { #endif ModuleIO::csrFileReader csr(this->_filename); - int step = csr.getStep(); - int matrix_dimension = csr.getMatrixDimension(); - int r_number = csr.getNumberOfR(); + const int matrix_dimension = csr.getMatrixDimension(); + if (matrix_dimension != this->_nlocal) + { + const std::string message = + "Matrix dimension in " + this->_filename + " does not match the number of basis functions."; + ModuleBase::WARNING_QUIT("Read_HContainer::read", message); + } + const int r_number = csr.getNumberOfR(); // construct serial hcontainer firstly // prepare atom index mapping from csr row/col to atom index diff --git a/source/source_hamilt/module_xc/exx_info.cpp b/source/source_hamilt/module_xc/exx_info.cpp index c0f6a60d8af..131610cb073 100644 --- a/source/source_hamilt/module_xc/exx_info.cpp +++ b/source/source_hamilt/module_xc/exx_info.cpp @@ -23,11 +23,7 @@ bool init_general_exx_info(General_Exx_Info &info, const Input_para &inp) std::string dft_functional_lower = inp.dft_functional; std::transform(inp.dft_functional.begin(), inp.dft_functional.end(), 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 ccc7cb7837b..6602db87d61 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/hsolver_lrtd.cpp b/source/source_lcao/module_lr/hsolver_lrtd.cpp index 765be265f6e..f46e7bc290c 100644 --- a/source/source_lcao/module_lr/hsolver_lrtd.cpp +++ b/source/source_lcao/module_lr/hsolver_lrtd.cpp @@ -36,13 +36,17 @@ 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) { - 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 = 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); + std::cout.precision(old_precision); + std::cout.flags(old_flags); } /// eigensolver for common Hamilt @@ -86,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)"); + 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; @@ -158,7 +162,7 @@ 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: (Ry)", 1.0); print_eigs(eigenvalue, "eigenvalues: (eV)", ModuleBase::Ry_to_eV); // normalization is already satisfied 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..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(); @@ -185,17 +189,26 @@ 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]] // = -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"); - - if (this->my_rank == 0) - { - 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 @@ -206,20 +219,21 @@ 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(); + ModuleIO::write_notice(running_log, "LR absorption spectrum", filename); } 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"); 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"); @@ -230,9 +244,12 @@ 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 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(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; @@ -248,7 +265,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"; } @@ -425,14 +442,18 @@ 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 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) { - 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 28845d12186..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 @@ -38,19 +40,27 @@ 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]]$ - 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 - 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/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 42b7d4a8016..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,26 +1,35 @@ #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 -#include +#include "source_base/parallel_blkcyc.h" #include "source_psi/psi.h" + +#include +#include +#include +#include +#include +#include +#include #ifdef __EXX #include #endif namespace LR_Util { + constexpr int lr_excitation_energy_digits = std::numeric_limits::max_digits10; + /// 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 +96,21 @@ namespace LR_Util ofs.close(); return res; } + inline bool write_excitation_energy_file(const std::string& file, const double* energies, + const int nstates) + { + std::ofstream ofs(file); + const int decimals = lr_excitation_energy_digits - 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/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/CMakeLists.txt b/tests/08_RI/CMakeLists.txt index 9e6da5f118f..e41ea3e1711 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_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 1832aa2cb33..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 excitation-energy and signed force references are unchanged. +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 5c4de9185c1..58fab6ef18d 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 +excitationenergyref1 1.531735 +excitationenergyref2 1.532418 +excitationenergyref3 1.353648 excitationenergyref4 1.354670 totaltimeref 3.05 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..37ae8ca529a --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/INPUT @@ -0,0 +1,27 @@ +INPUT_PARAMETERS +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 + +dft_functional hse +exx_singularity_correction limits +ecutwfc 24 +scf_thr 1e-9 +scf_nmax 80 +mixing_type broyden +mixing_beta 0.5 + +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 new file mode 100644 index 00000000000..e769af76382 --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +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..07f434dd89b --- /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_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/STRU b/tests/08_RI/lr_tddft_velocity_commutator/STRU new file mode 100644 index 00000000000..ca3416c1690 --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/STRU @@ -0,0 +1,21 @@ +ATOMIC_SPECIES +H 1.008 H_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +H_gga_6au_60Ry_1s.orb + +LATTICE_CONSTANT +12 + +LATTICE_VECTORS +1 0 0 +0 1 0 +0 0 1 + +ATOMIC_POSITIONS +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 new file mode 100644 index 00000000000..028fb32f8b6 --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/absorption.dat.ref @@ -0,0 +1,103 @@ +# 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 +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 new file mode 100644 index 00000000000..3cc8736eedd --- /dev/null +++ b/tests/08_RI/lr_tddft_velocity_commutator/result.ref @@ -0,0 +1,4 @@ +excitationenergyref1 1.594555 +excitationenergyref2 2.217423 +CompareLRAbsorption_pass 0 +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..4a42717e2bb --- /dev/null +++ b/tests/integrate/validation_tools/check_lr_absorption.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Validate and compare the 100-point LR absorption tables.""" +import argparse +import math +from pathlib import Path +import re + + +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, *, require_provenance=False): + lines = path.read_text().splitlines() + 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") + 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(data_rows, start=data_start + 1): + 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): + reference_rows = read_spectrum(reference) + 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}: data row {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_workflow.py b/tests/integrate/validation_tools/check_lr_absorption_workflow.py new file mode 100644 index 00000000000..4295c409ef6 --- /dev/null +++ b/tests/integrate/validation_tools/check_lr_absorption_workflow.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Compare text HSE LR absorption spectra using in-memory and exported H(R)/S(R).""" +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_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=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, 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") + direct_out = run_case(root / "direct", fixture, launch, direct_inputs) + 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={nspin}: spectra from in-memory and CSR matrix inputs 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("--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: + 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") + + +if __name__ == "__main__": + main() diff --git a/tests/integrate/validation_tools/props_ml.sh b/tests/integrate/validation_tools/props_ml.sh index 3b9bbada15b..4b33974472e 100644 --- a/tests/integrate/validation_tools/props_ml.sh +++ b/tests/integrate/validation_tools/props_ml.sh @@ -68,6 +68,12 @@ 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 + 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..d248d0fe1c8 100644 --- a/tests/integrate/validation_tools/test_props_ml.py +++ b/tests/integrate/validation_tools/test_props_ml.py @@ -1,23 +1,37 @@ #!/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 + + +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): - 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 +63,61 @@ 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=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), + (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_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()[5]): + 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) + for spectrum in (wrong_columns, changed): + with self.subTest(spectrum_row=spectrum.splitlines()[5]): + result = self.collect('', reference=SPECTRUM, spectrum=spectrum) + self.assertEqual(result, 'CompareLRAbsorption_pass 1\n') + if __name__ == '__main__': unittest.main()