diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 502f29b9e05..7bddffb5958 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1200,6 +1200,8 @@ OBJS_LR_GRAD=lr_force.o\ grad_jt.o\ gradient_output.o\ lr_grad_cs.o\ + window_response.o\ + window_response_math.o\ lr_grad_os.o\ exx_proj.o\ cvcx_serial.o\ diff --git a/source/source_esolver/esolver_lr_grad.cpp b/source/source_esolver/esolver_lr_grad.cpp index 146956d9adc..62a98a9fc89 100644 --- a/source/source_esolver/esolver_lr_grad.cpp +++ b/source/source_esolver/esolver_lr_grad.cpp @@ -8,6 +8,7 @@ #include "source_lcao/module_lr/gradient_output.h" #include "source_lcao/module_lr/lr_amp.h" #include "source_lcao/module_lr/lr_force.h" +#include "source_lcao/module_lr/window_response.h" #include "source_lcao/module_lr/zeq_solver.h" #include #include @@ -71,7 +72,11 @@ ct::Tensor ModuleESolver::ESolver_LR::pad_X_to_z_(const int ispin, const } template -ct::Tensor ModuleESolver::ESolver_LR::solve_zvector_eqation(const int ispin, const int nst, const ct::Tensor &Xz) +ct::Tensor ModuleESolver::ESolver_LR::solve_zvector_eqation( + const int ispin, + const int nst, + const ct::Tensor &Xz, + const std::vector> &window_density) { ModuleBase::TITLE("ESolver_LR", "cal_force"); ModuleBase::timer::start("ESolver_LR", "solve_zvector_eqation"); @@ -91,7 +96,7 @@ ct::Tensor ModuleESolver::ESolver_LR::solve_zvector_eqation(const int isp std::weak_ptr pot_weak = inputs.pot[ispin]; Z_vector_equation( inputs, x_data, z_data, nst, pot_weak, this->spin_types[ispin], this->in_dir, this->openshell, - this->inp_->lr_grad_solver); + this->inp_->lr_grad_solver, window_density); ModuleBase::timer::end("ESolver_LR", "solve_zvector_eqation"); return Z; } @@ -149,9 +154,11 @@ std::vector ModuleESolver::ESolver_LR::cal_force_Xz( ModuleBase::timer::start("ESolver_LR", "cal_force_Xz"); const int nst = static_cast(omega.size()); const int channel = ispin; - const ct::Tensor Z = this->solve_zvector_eqation(channel, nst, Xz); - const auto dm_gs = this->cal_dm_gs(); const LR::GradientInputs inputs = this->gradient_inputs_(); + const LR::WindowResponse window + = LR::build_window_response(inputs, Xz, nst, this->nvirt[0], ispin, this->in_dir); + const ct::Tensor Z = this->solve_zvector_eqation(channel, nst, Xz, window.density); + const auto dm_gs = this->cal_dm_gs(); const LR::ForceSettings force_settings{ this->nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; LR_Force force_terms( @@ -162,7 +169,8 @@ std::vector ModuleESolver::ESolver_LR::cal_force_Xz( inputs.exx_lri, inputs.hybrid_alpha #endif ); - const auto forces = LR::evaluate_closed_shell_force(inputs, force_terms, dm_gs, Xz, Z, omega, label_begin, ispin); + const auto forces = + LR::evaluate_closed_shell_force(inputs, force_terms, dm_gs, Xz, Z, omega, label_begin, ispin, window); ModuleBase::timer::end("ESolver_LR", "cal_force_Xz"); return forces; } @@ -346,9 +354,10 @@ std::vector ModuleESolver::ESolver_LR::cal_force_open ModuleBase::timer::start("ESolver_LR", "cal_force_openshell_Xz"); const int nst = static_cast(omega.size()); const int channel = 0; - const ct::Tensor Z = this->solve_zvector_eqation(channel, nst, Xz); - const auto dm_gs = this->cal_dm_gs(); const LR::GradientInputs inputs = this->gradient_inputs_(); + const LR::WindowResponse window = LR::build_open_shell_window_response(inputs, Xz, nst, this->nvirt); + const ct::Tensor Z = this->solve_zvector_eqation(channel, nst, Xz, window.density); + const auto dm_gs = this->cal_dm_gs(); const LR::ForceSettings force_settings{ this->nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; LR_Force force_terms( @@ -359,7 +368,7 @@ std::vector ModuleESolver::ESolver_LR::cal_force_open inputs.exx_lri, inputs.hybrid_alpha #endif ); - const auto forces = LR::evaluate_open_shell_force(inputs, force_terms, dm_gs, Xz, Z, omega, label_begin); + const auto forces = LR::evaluate_open_shell_force(inputs, force_terms, dm_gs, Xz, Z, omega, label_begin, window); ModuleBase::timer::end("ESolver_LR", "cal_force_openshell_Xz"); return forces; } diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index 67cb43729e7..c4d3762b9b0 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr_lcao_tddft.cpp @@ -74,6 +74,11 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste this->spin_types = this->openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); + if (this->nspin == 1) + { + this->spin_types = {this->inp_->lr_target_spin}; + } + // a relaxation writes these once per ionic step; without the suffix every step would overwrite // the last, and the trajectory would be impossible to inspect afterwards const std::string step_suffix = this->excited_relax_ ? "_step" + std::to_string(istep) : ""; @@ -203,6 +208,11 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste } } } + if (this->ks_ && this->inp_->cal_force && !this->excited_relax_) + { + // Cache the KS force shared by all single-point excited states. + this->ks_->cal_force(ucell, this->force_gs_); + } if (this->excited_relax_) { // Re-select which root to follow BEFORE taking the gradient, so the force belongs to @@ -266,7 +276,8 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) for (int is = 0; is < this->nspin; ++is) { const T *const amplitudes = this->X[0].template data(); - lr_density.output_eh_density_all_states(amplitudes, is, nstates, this->ofs_running_); + const std::string density_label = is == 0 ? "up" : "down"; + lr_density.output_eh_density_all_states(amplitudes, is, nstates, density_label, this->ofs_running_); } } else @@ -274,7 +285,8 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) for (int is = 0; is < this->X.size(); ++is) { const T *const amplitudes = this->X[is].template data(); - lr_density.output_eh_density_all_states(amplitudes, is, nstates, this->ofs_running_); + lr_density.output_eh_density_all_states( + amplitudes, is, nstates, this->spin_types[is], this->ofs_running_); } } } diff --git a/source/source_esolver/esolver_lr_lcao_tddft.h b/source/source_esolver/esolver_lr_lcao_tddft.h index 130ce86cda4..c7e4ecdfd62 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr_lcao_tddft.h @@ -258,7 +258,11 @@ class ESolver_LR : public ModuleESolver::ESolver_FP ///========================== for gradient calculation ========================= void init_pot_groundstate(const Charge &chg_gs); /// Solve the Z-vector equation for `nst` independent blocks of `Xz`. - ct::Tensor solve_zvector_eqation(const int ispin, const int nst, const ct::Tensor &Xz); + ct::Tensor solve_zvector_eqation( + const int ispin, + const int nst, + const ct::Tensor &Xz, + const std::vector> &window_density); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state: geometry relaxation follows a single state, and the /// Z-vector solve dominates the cost. -1 does all `nstates`. diff --git a/source/source_esolver/esolver_lr_orb.cpp b/source/source_esolver/esolver_lr_orb.cpp index c91ba2291da..fa60b4aac4e 100644 --- a/source/source_esolver/esolver_lr_orb.cpp +++ b/source/source_esolver/esolver_lr_orb.cpp @@ -8,6 +8,7 @@ #include "source_lcao/module_lr/ri_benchmark/ri_benchmark.h" #include "source_lcao/module_lr/utils/lr_util.h" #include +#include using namespace LR; @@ -281,8 +282,12 @@ void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) // the same windows. Diagnose once, without changing the truncated eigenproblem. if (!this->ks_initialized_) { - const std::string warning = - LR_Util::force_window_warning(this->nbasis, this->eig_ks_all.nc, start_band, this->nvirt, this->nvirt_z_); + // Real-Gamma forces include the virtual-window response for both spin formulations. + // Retain diagnostics for missing occupied orbitals and uncomputed bands. + const bool virtual_response = std::is_same::value && this->nk == 1 && start_band == 0; + const auto &diagnosed_virtuals = virtual_response ? this->nvirt_z_ : this->nvirt; + const std::string warning = LR_Util::force_window_warning( + this->nbasis, this->eig_ks_all.nc, start_band, diagnosed_virtuals, this->nvirt_z_); if (!warning.empty()) { this->ofs_running_ << warning << std::endl; diff --git a/source/source_esolver/esolver_lr_rlx.cpp b/source/source_esolver/esolver_lr_rlx.cpp index 10d4a7d3a45..b941c002909 100644 --- a/source/source_esolver/esolver_lr_rlx.cpp +++ b/source/source_esolver/esolver_lr_rlx.cpp @@ -70,18 +70,13 @@ void ModuleESolver::ESolver_LR::setup_relax_target_() "triplet are separate states with separate gradients. Pick one of them, or set " "lr_unrestricted to run spin-unrestricted."); } - this->target_is_ = (spin == "triplet") ? 1 : 0; - if (this->target_is_ >= this->nspin) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR", "lr_target_spin=triplet requires nspin=2: the triplet channel is not built here."); - } + this->target_is_ = (spin == "triplet" && this->nspin == 2) ? 1 : 0; } this->force_gs_.create(this->ucell_->nat, 3); this->lr_force_.create(this->ucell_->nat, 3); this->target_state_ = this->inp_->lr_target_state; // seed; overlap takes over from step 2 this->ofs_running_ << " Excited-state relaxation follows state " << this->inp_->lr_target_state << " of the " - << (this->openshell ? "updown" : (this->target_is_ == 1 ? "triplet" : "singlet")) + << (this->openshell ? "updown" : this->inp_->lr_target_spin) << " channel, tracked by cross-geometry orbital and amplitude overlap." << std::endl; } @@ -133,6 +128,10 @@ void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase: { basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); const UnitCell &ucell = static_cast(basecell); + if (this->ks_ && this->force_gs_.nr == ucell.nat) + { + ModuleIO::print_force(this->ofs_running_, ucell, "GROUND-STATE FORCE (eV/Angstrom)", this->force_gs_, false); + } if (!this->excited_relax_) { // single-point runs print the gradients of every state from `after_all_runners` instead return; @@ -143,9 +142,8 @@ void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase: "ESolver_LR::cal_force", "the excited-state gradient has not been computed for this geometry."); } // Both halves already follow the ABACUS force convention F = -dE/dR (Ry/Bohr), so they add. - // The "Gradients of each excited state" heading that `cal_force(int)` prints under is a - // misnomer: the finite-difference reference it was validated against (`abacus-fd lr-custom`) - // computes (E(-h) - E(+h))/h, which is -d(Omega)/dR, and the two agree in sign. + // The per-state LR table reports the excitation-energy contribution -d(Omega)/dR; + // adding the ground-state force gives the total force on the excited-state surface. force.create(ucell.nat, 3); force = this->force_gs_ + this->lr_force_; ModuleIO::print_force(this->ofs_running_, ucell, "EXCITED-STATE TOTAL-FORCE (eV/Angstrom)", force, false); diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 351c79f73c7..6a90fa9bb36 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -402,7 +402,7 @@ struct Input_para // ============== #Parameters (10.lr-tddft) =========================== int lr_nstates = 1; ///< the number of 2-particle states to be solved int lr_target_state = 0; ///< which excited state the geometry relaxation follows (0-based) - std::string lr_target_spin = "singlet"; ///< spin channel of that state: singlet / triplet / updown + std::string lr_target_spin = "singlet"; ///< nspin=1 LR channel, or relaxation target at nspin=2: singlet / triplet / updown double lr_degen_thr = 0.0; ///< max excitation-energy spread of a degenerate multiplet whose gradient matrix is computed (Ry); 0 disables std::string lr_degen_mode = "state"; ///< what a relaxation follows when the target state sits in a degenerate multiplet: state / average diff --git a/source/source_io/module_parameter/read_inp_tddft.cpp b/source/source_io/module_parameter/read_inp_tddft.cpp index 8a7d8f28274..1b683e4e274 100644 --- a/source/source_io/module_parameter/read_inp_tddft.cpp +++ b/source/source_io/module_parameter/read_inp_tddft.cpp @@ -1117,7 +1117,7 @@ void ReadInput::item_lr_tddft() item.type = "Vector of String (>=1 values)"; item.description = R"(The method to initalize the xc kernel. * "default": Calculate xc kernel from the ground-state charge density. -* "file": Read the xc kernel on grid from the provided files. The following words should be the paths of ".cube" files, where the first 1 (nspin==1) or 3 (nspin==2, namely spin-aa, spin-ab and spin-bb) will be read in. The parameter xc_kernel will be invalid. Now only LDA-type kernel is supported as the potential will be calculated by directly multiplying the transition density. +* "file": Read the xc kernel on grid from the provided files. The following words should be the paths of ".cube" files, where the first 1 (nspin==1) or 3 (nspin==2, namely spin-aa, spin-ab and spin-bb) will be read in. For `nspin=1, lr_target_spin=triplet`, provide three spin-resolved files (aa, ab, bb) as well. The parameter xc_kernel will be invalid. Now only LDA-type kernel is supported as the potential will be calculated by directly multiplying the transition density. [NOTE] The "file" and "from_charge_file" modes support spectra only. Excited-state forces and relaxation require the consistent ground-state density and its response; externally supplied kernels or frozen densities do not provide these derivatives. * "from_charge_file": Calculate fxc from the charge density read from the provided files. The following words should be the paths of ".cube" files, where the first nspin files will be read in.)"; item.default_value = "\"default\""; @@ -1180,7 +1180,7 @@ void ReadInput::item_lr_tddft() * If omitted, non-positive, or larger than the occupied majority-spin channel, all occupied orbitals are used. * The full occupied window is determined by the effective electron number (including nelec_delta once) and the ground-state spin populations. For nspin=2, the minority-spin window has abs(N_up-N_down) fewer occupied orbitals. -[NOTE] For reliable excited-state forces and relaxation, retain all occupied orbitals. With a truncated occupied or virtual X window, the current analytic force is an approximation and may differ from finite differences of the selected truncated excitation energy. Zero-padding X into a larger Z virtual space is retained, but does not restore every active/inactive orbital-response term. Check force/window convergence.)"; +[NOTE] Retain all occupied orbitals for reliable excited-state forces and relaxation: response from omitted occupied orbitals is not restored. For real-Gamma calculations, the force includes the response of a truncated virtual window within the available KS bands, provided the retained/discarded virtual boundary is nondegenerate. This correction does not recover uncomputed KS bands (nbands < NLOCAL) or converge the excitation model with respect to its orbital window. Check window convergence.)"; item.default_value = "all occupied orbitals"; item.unit = ""; read_sync_int(input.nocc); @@ -1194,7 +1194,7 @@ void ReadInput::item_lr_tddft() item.type = "Integer"; item.description = R"(The number of virtual orbitals (starting from LUMO) used in the LR-TDDFT calculation. -[NOTE] For reliable excited-state forces and relaxation, use all occupied orbitals, nbands = NLOCAL (the AO basis size), and the full spin-resolved virtual window, nvirt = nbands - nocc. Merely setting nvirt = nbands - nocc is insufficient when nbands < NLOCAL. The Z virtual window is widened to the available ground-state bands and X is zero-padded without changing the selected excitation energy; this does not make the force an exact derivative of a truncated-X problem. Changing nvirt itself generally changes the excitation energies. Truncated-window forces remain available with a warning and require convergence checks, especially before optimization.)"; +[NOTE] For real-Gamma calculations with all occupied orbitals, analytic forces include the retained/discarded virtual-subspace response without changing the selected truncated excitation energy. The Z equation spans the available KS virtuals. The orbital-energy gap across the retained/discarded virtual boundary must be nonzero: a degenerate boundary is rejected; increase nvirt to include the complete multiplet. The correction does not recover omitted occupied orbitals or uncomputed KS bands. Use nbands = NLOCAL (the AO basis size) to make every AO-supported virtual available. Complex/multi-k force requests with a truncated virtual window are rejected; use the full available virtual window to avoid this restriction. Changing nvirt generally changes energies and forces, so convergence of the excitation window remains necessary, especially before optimization.)"; item.default_value = "1"; item.unit = ""; read_sync_int(input.nvirt); @@ -1228,8 +1228,7 @@ Ignored outside `calculation = relax`: a single-point run solves and reports the item.default_value = "0"; item.unit = ""; item.check_value = [](const Input_Item& item, const Parameter& para) { - // Both parameters only steer a relaxation. A single-point run solves and reports every - // state, so they are dead there and must not be able to abort it. + // The state index only selects a relaxation target; single points report every state. if (para.input.calculation != "relax") { return; @@ -1244,16 +1243,6 @@ Ignored outside `calculation = relax`: a single-point run solves and reports the { ModuleBase::WARNING_QUIT("ReadInput", "lr_target_state must be < lr_nstates"); } - const std::vector spins = { "singlet", "triplet", "updown" }; - if (std::find(spins.begin(), spins.end(), para.input.lr_target_spin) == spins.end()) - { - ModuleBase::WARNING_QUIT("ReadInput", "lr_target_spin must be singlet, triplet or updown"); - } - if (para.input.lr_target_spin == "triplet" && para.input.nspin == 1) - { - ModuleBase::WARNING_QUIT("ReadInput", - "lr_target_spin=triplet requires nspin=2: only the singlet channel is built at nspin=1"); - } }; read_sync_int(input.lr_target_state); this->add_item(item); @@ -1362,19 +1351,30 @@ The threshold proposes candidates; it cannot tell a true degeneracy from an acci } { Input_Item item("lr_target_spin"); - item.annotation = "spin channel of lr_target_state: singlet, triplet or updown"; + item.annotation = "nspin=1 LR channel, or nspin=2 relaxation target: singlet, triplet or updown"; item.category = "Linear Response TDDFT"; item.type = "String"; item.description = R"(Which spin channel `lr_target_state` indexes. -* singlet / triplet: the two closed-shell channels solved at `nspin = 2`. At `nspin = 1` only `singlet` exists. +* singlet / triplet: the two closed-shell channels solved at `nspin = 2`. At `nspin = 1`, only the channel selected here is solved (default: `singlet`). * updown: the single spin-conserving channel of an open-shell calculation (`lr_unrestricted`, or a spin-polarised ground state with a non-zero moment). An open-shell calculation has only one channel, so any value is accepted there and relaxes that channel; an explicit `triplet` is reported as ignored. A closed-shell calculation rejects `updown`, since singlet and triplet are separate states with separate gradients. -Ignored outside `calculation = relax`.)"; +At `nspin = 2` this selects only the relaxation target; single-point runs still solve both closed-shell channels.)"; item.default_value = "singlet"; item.unit = ""; + item.check_value = [](const Input_Item&, const Parameter& para) { + const std::string& spin = para.input.lr_target_spin; + if (spin != "singlet" && spin != "triplet" && spin != "updown") + { + ModuleBase::WARNING_QUIT("ReadInput", "lr_target_spin must be singlet, triplet or updown"); + } + if (para.input.nspin == 1 && spin == "updown") + { + ModuleBase::WARNING_QUIT("ReadInput", "lr_target_spin=updown requires nspin=2"); + } + }; read_sync_string(input.lr_target_spin); 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..f5ed00ff313 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -800,3 +800,26 @@ TEST_F(InputParaTest, OpticalGaugeCanDisableSpectrum) item.read_value(item, param); EXPECT_EXIT(item.check_value(item, param), testing::ExitedWithCode(1), ""); } + +TEST_F(InputParaTest, ScalarLrSpinSelection) +{ + 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_target_spin, "singlet"); + auto item = items.at("lr_target_spin"); + for (const std::string spin : {"singlet", "triplet"}) + { + item.str_values = {spin}; + item.read_value(item, parameter); + EXPECT_EQ(parameter.inp.lr_target_spin, spin); + EXPECT_NO_THROW(item.check_value(item, parameter)); + } + for (const std::string spin : {"updown", "invalid"}) + { + item.str_values = {spin}; + item.read_value(item, parameter); + EXPECT_EXIT(item.check_value(item, parameter), testing::ExitedWithCode(1), ""); + } +} diff --git a/source/source_lcao/force_stress_assemble.cpp b/source/source_lcao/force_stress_assemble.cpp index 331b75d39f3..57a1619d868 100644 --- a/source/source_lcao/force_stress_assemble.cpp +++ b/source/source_lcao/force_stress_assemble.cpp @@ -244,6 +244,7 @@ void assemble_print_force(const UnitCell& ucell, const double force_threshold, ModuleBase::matrix& fcs) { + const Input_para& input = PARAM.inp; const int nat = ucell.nat; //--------------------------------- // sum all parts of force! @@ -257,7 +258,7 @@ void assemble_print_force(const UnitCell& ucell, } } - if (PARAM.inp.gate_flag || PARAM.inp.efield_flag) + if (input.gate_flag || input.efield_flag) { GlobalV::ofs_running << "Atomic forces are not shifted if gate_flag or efield_flag == true!" << std::endl; } @@ -283,13 +284,13 @@ void assemble_print_force(const UnitCell& ucell, } net_force[i] = sum; } - if (!(PARAM.inp.gate_flag || PARAM.inp.efield_flag)) + if (!(input.gate_flag || input.efield_flag)) { ModuleBase::remove_net_force(nat, fcs); } // compute forces using the DeePKS model - DeePKS_domain::write_forces(fcs, parts.fvnl_dalpha, dpks_out_type, PARAM.inp); + DeePKS_domain::write_forces(fcs, parts.fvnl_dalpha, dpks_out_type, input); if (istestf) { @@ -298,8 +299,11 @@ void assemble_print_force(const UnitCell& ucell, GlobalV::ofs_running << std::setiosflags(std::ios::left); - // this->printforce_total(ry, istestf, fcs); - ModuleIO::print_force(GlobalV::ofs_running, ucell, "TOTAL-FORCE (eV/Angstrom)", fcs, false); + // The coupled LR solver reports the ground-state force with the LR forces. + if (input.esolver_type != "ks-lr") + { + ModuleIO::print_force(GlobalV::ofs_running, ucell, "TOTAL-FORCE (eV/Angstrom)", fcs, false); + } net_force*= ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A; ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Net force vector (eV/Ang)", net_force.x, net_force.y, net_force.z); ModuleBase::GlobalFunc::OUT(GlobalV::ofs_running, "Total drift (ev/Ang)", net_force.norm()); diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 18abcd3cbea..fb99c99e87d 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -41,6 +41,8 @@ if(ENABLE_LCAO) potentials/xc_kernel.cpp potentials/xc_kxc.cpp gradient_output.cpp + window_response.cpp + window_response_math.cpp lr_grad_cs.cpp lr_grad_os.cpp lr_force.cpp diff --git a/source/source_lcao/module_lr/cal_edm.h b/source/source_lcao/module_lr/cal_edm.h index eece20786a9..4da3a084419 100644 --- a/source/source_lcao/module_lr/cal_edm.h +++ b/source/source_lcao/module_lr/cal_edm.h @@ -184,7 +184,8 @@ namespace LR module_dm::DensityMatrix& dm_trans, const psi::Psi& c, // preserve the caller's single-spin view std::weak_ptr pot, - const std::string& spin_type = "singlet") + const std::string& spin_type, + const std::vector& relaxed_density) { const int& nspin = inputs.nspin; const int& naos = inputs.nbasis; @@ -216,7 +217,7 @@ namespace LR ); } std::vector W(p_occ_occ[0].size() * nk, 0.0); - cal_W_from_Z(inputs, W.data(), Z, X, eig_ext_istate, eig_ks, c, p_occ_occ, spin_type); + cal_W_from_Z(inputs, W.data(), relaxed_density, X, eig_ext_istate, eig_ks, c, p_occ_occ, spin_type); // std::cout << "W: " << std::endl; // LR_Util::print_value(W.data(), nk, p_occ_occ[0].ncloc(), p_occ_occ[0].nrloc()); @@ -256,7 +257,8 @@ namespace LR const double eig_ext_istate, const double* const eig_ks, const module_dm::DensityMatrix& dm_trans, // retained for signature symmetry - std::weak_ptr pot) + std::weak_ptr pot, + const std::vector>& relaxed_density) { const int& nspin = inputs.nspin; const int& naos = inputs.nbasis; @@ -297,7 +299,7 @@ namespace LR ); } std::vector> W; - cal_W_from_Z_openshell(inputs, W, Z, X, eig_ext_istate, eig_ks, p_occ_occ); + cal_W_from_Z_openshell(inputs, W, relaxed_density, X, eig_ext_istate, eig_ks, p_occ_occ); // 2. $W^X_{ai\sigma}=2\sum_j X_{aj\sigma}K_{ji\sigma}[D^X]$. // The free spin sits on X (hence `psi_in = X + off_x[sl]`, laid out over `px[sl]`), diff --git a/source/source_lcao/module_lr/cal_w_from_z.h b/source/source_lcao/module_lr/cal_w_from_z.h index 0fa7f047c4e..e91cf09781d 100644 --- a/source/source_lcao/module_lr/cal_w_from_z.h +++ b/source/source_lcao/module_lr/cal_w_from_z.h @@ -2,7 +2,6 @@ #define ABACUS_SOURCE_LCAO_MODULE_LR_CAL_W_FROM_Z_H #include "gradient_inputs.h" #include "source_hamilt/hamilt.h" -#include "source_lcao/module_lr/dm_trans/dm_diff.h" #include "source_estate/module_dm/density_matrix.h" #include "source_lcao/module_lr/potentials/pot_grad_xc.h" #include "source_lcao/module_lr/operator_casida/op_gxc_ulr.h" @@ -63,10 +62,11 @@ namespace LR } } + // relaxed_density[k] is the symmetric T + DZ + Dwin used by the force contraction. template void cal_W_from_Z(const GradientInputs& inputs, T* const W, - const T* const Z, + const std::vector& relaxed_density, const T* const X, const double eig, const double* const eig_ks, @@ -101,10 +101,10 @@ namespace LR // allocate memory for DMs module_dm::DensityMatrix DM_trans(&pmat, 1, kv.kvec_d, nk); //DX LR_Util::initialize_DMR(DM_trans, pmat, ucell, gd, orb_cutoff); - module_dm::DensityMatrix DM_diff_relaxed(&pmat, 1, kv.kvec_d, nk); //T+DZ + module_dm::DensityMatrix DM_diff_relaxed(&pmat, 1, kv.kvec_d, nk); //T+DZ+Dwin LR_Util::initialize_DMR(DM_diff_relaxed, pmat, ucell, gd, orb_cutoff); /// operators - // 1. 0.5$H_ij[T+Z]$, equals to $K_ij[T+Z]$ when $(T+Z)$ is symmetrized + // 1. Hgs_ij[T + DZ + Dwin]/2; the supplied density is symmetric. // Note that K_Hxc(singlet) = 2* pot_hxc_gs, that's why there's factor 2 here. OperatorLRHxc op_ht(nspin, naos, nocc, nvirt, psi_ks, DM_diff_relaxed, pot_hxc_gs, ucell, orb_cutoff, gd, kv, p_occ_occ, pc, pmat, @@ -121,13 +121,14 @@ namespace LR // correct way is to use `shared_ptr = make_shared()` and then assign it to weak_ptr // `weak_ptr=shared_ptr` is automatically called in the constructor of OperatorLRHxc, so we don't need to do it manually // if `pot_grad` is passed into a function rather than a class, we need to write `weak_ptr=shared_ptr` explicitly - // This quadratic term differentiates the LR kernel K, unlike H[T+DZ] above. + // This quadratic term differentiates the LR kernel K, unlike H[T+DZ+Dwin] above. const bool triplet = spin_type == "triplet"; - const int ispin = triplet ? 1 : 0; + const int ispin = triplet && nspin == 2 ? 1 : 0; const std::shared_ptr& pot_lr = inputs.pot[ispin]; + const int kernel_nspin = pot_lr->xc_kernel_components().nspin(); std::shared_ptr pot_grad = std::make_shared(pot_lr->xc_kernel_components(), pot_lr->get_rho_basis(), - ucell, pot_lr->nrxx, nspin, triplet); + ucell, pot_lr->nrxx, kernel_nspin, triplet); OperatorLRHxc op_gxc(nspin, naos, nocc, nvirt, psi_ks, DM_trans, pot_grad, ucell, orb_cutoff, gd, kv, p_occ_occ, pc, pmat, // Factor 1.0 according to the $W^c$ formula (`pot_grad` carries $2*g^{xc}$: uu+ud or uu-ud). @@ -136,7 +137,6 @@ namespace LR { 0 }, T(1.0), ATYPE::CC_oo, hamilt::calculation_type::lr_dmtrans_hxc); std::vector dm_trans_2d; - std::vector dm_diff_2d; auto cal_dm_trans = [&psi_ks, nk, &dm_trans_2d, &px, &pc, naos, &nocc, &nvirt, &pmat, &DM_trans](const int is, const T* const x_ptr)->void //DX { const auto psi_ks_is = LR_Util::get_psi_spin(psi_ks, is, nk); @@ -154,36 +154,16 @@ namespace LR DM_trans.set_dmk_ptr(ik, dm_trans_2d[ik].data()); } }; - auto cal_dm_diff_relaxed = [&psi_ks, nk, &px, &pc, naos, &nocc, &nvirt, &pmat, &dm_diff_2d, &DM_diff_relaxed](const int& is, const T* const x_ptr, const T* const z_ptr)->void // T+DZ - { - const auto psi_ks_is = LR_Util::get_psi_spin(psi_ks, is, nk); -#ifdef __MPI - std::vector z_2d = cal_dm_trans_pblas(z_ptr, px[is], psi_ks_is, pc, naos, nocc[is], nvirt[is], pmat.para_2d()); - for (auto& t: z_2d) - LR_Util::matsym(t.data(), naos, pmat.para_2d()); -#else - std::vector z_2d = cal_dm_trans_blas(z_ptr, psi_ks_is, nocc[is], nvirt[is]); - for (auto& t: z_2d) - LR_Util::matsym(t.data(), naos); -#endif - -#ifdef __MPI - dm_diff_2d = cal_dm_diff_pblas(x_ptr, px[is], psi_ks_is, pc, naos, nocc[is], nvirt[is], pmat.para_2d()); -#else - dm_diff_2d = cal_dm_diff_blas(x_ptr, psi_ks_is, naos, nocc[is], nvirt[is]); -#endif - for (int ik = 0;ik < nk;++ik) - { - dm_diff_2d[ik] = dm_diff_2d[ik] + z_2d[ik]; - DM_diff_relaxed.set_dmk_ptr(ik, dm_diff_2d[ik].data()); - } - }; + // The caller owns T + DZ + Dwin for this state, shared with the force contraction. + for (int ik = 0; ik < nk; ++ik) + { + DM_diff_relaxed.set_dmk_ptr(ik, relaxed_density[ik].data()); + } // act the operators onto current state const int ld_vo = nk * px[0].size(); const int ld_oo = nk * p_occ_occ[0].size(); cal_dm_trans(0, X); // transition density matrix DX - cal_dm_diff_relaxed(0, X, Z); // relaxed difference density matrix T+DZ // the 3 terms op_ht.act(/*nband=*/1, ld_oo, /*npol=*/1, X, W); //comment out this line to test H[T+Z]=0 // std::cout << "W (H[T+Z])) local terms: " << std::endl; @@ -213,10 +193,11 @@ namespace LR /// $\tfrac12 H^S = K^S = 2\cdot$`pot_hxc_gs` because `pot_hxc_gs` is the halved `S2_gs`; /// here it is `S2_updown`, one $K_{\sigma\sigma'}$ component, and the $\sum_{\sigma'}$ /// is done by the block loop below. + // relaxed_density[spin][k] includes Dwin; sum both input spins with the GS kernel. template void cal_W_from_Z_openshell(const GradientInputs& inputs, std::vector>& W, - const T* const Z, + const std::vector>& relaxed_density, const T* const X, const double eig, const double* const eig_ks, @@ -292,38 +273,12 @@ namespace LR } } #endif - // the relaxed difference density matrix of one spin channel - std::vector dm_buf; - auto set_dm_diff_relaxed = [&psi_ks, nk, X, Z, &off_x, &px, &pc, naos, &nocc, &nvirt, &pmat, &dm_buf, &DM_diff_relaxed](const int is)->void - { - const auto psi_ks_is = LR_Util::get_psi_spin(psi_ks, is, nk); - const T* const x_ptr = X + off_x[is]; - const T* const z_ptr = Z + off_x[is]; -#ifdef __MPI - std::vector z_2d = cal_dm_trans_pblas(z_ptr, px[is], psi_ks_is, pc, naos, nocc[is], nvirt[is], pmat.para_2d()); - for (auto& t: z_2d) - { - LR_Util::matsym(t.data(), naos, pmat.para_2d()); - } - dm_buf = cal_dm_diff_pblas(x_ptr, px[is], psi_ks_is, pc, naos, nocc[is], nvirt[is], pmat.para_2d()); -#else - std::vector z_2d = cal_dm_trans_blas(z_ptr, psi_ks_is, nocc[is], nvirt[is]); - for (auto& t: z_2d) - { - LR_Util::matsym(t.data(), naos); - } - dm_buf = cal_dm_diff_blas(x_ptr, psi_ks_is, naos, nocc[is], nvirt[is]); -#endif - for (int ik = 0;ik < nk;++ik) - { - dm_buf[ik] = dm_buf[ik] + z_2d[ik]; - DM_diff_relaxed.set_dmk_ptr(ik, dm_buf[ik].data()); - } - }; - for (int is_in : {0, 1}) { - set_dm_diff_relaxed(is_in); + for (int ik = 0; ik < nk; ++ik) + { + DM_diff_relaxed.set_dmk_ptr(ik, relaxed_density[is_in][ik].data()); + } for (int is_out : {0, 1}) { op_ht[(is_out << 1) + is_in]->act(/*nband=*/1, ld_oo[is_out], /*npol=*/1, @@ -341,7 +296,7 @@ namespace LR // $\sum_{\sigma'\sigma''}D^X_{\sigma'}D^X_{\sigma''}g^{xc}_{\dots,ij\tau}$, coefficient 1 // in the spin-orbital formula. Quadratic in $D^X$, so it does not fit the block loop above. // Use the LR kernel's density derivative, consistently with the Z-vector RHS. - // The separate H[T+DZ] operators above retain the GS kernel. + // The separate H[T+DZ+Dwin] operators above retain the GS kernel. if (LR_Util::has_local_xc(xc_kernel)) { const std::shared_ptr& pot_lr = inputs.pot[0]; diff --git a/source/source_lcao/module_lr/gradient_inputs.h b/source/source_lcao/module_lr/gradient_inputs.h index c0aa7723f52..f4688f61152 100644 --- a/source/source_lcao/module_lr/gradient_inputs.h +++ b/source/source_lcao/module_lr/gradient_inputs.h @@ -4,6 +4,7 @@ #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" namespace LR { +template struct WindowResponse; // Explicit, borrowed inputs for one gradient evaluation. No solver ownership or caches. template struct GradientInputs @@ -44,12 +45,14 @@ std::vector evaluate_closed_shell_force( const GradientInputs& inputs, LR_Force& force_terms, const module_dm::DensityMatrix& dm_gs, const ct::Tensor& Xz, const ct::Tensor& Z, - const std::vector& omega, int label_begin, int ispin); + const std::vector& omega, int label_begin, int ispin, + const WindowResponse& window); template std::vector evaluate_open_shell_force( const GradientInputs& inputs, LR_Force& force_terms, const module_dm::DensityMatrix& dm_gs, const ct::Tensor& Xz, const ct::Tensor& Z, - const std::vector& omega, int label_begin); + const std::vector& omega, int label_begin, + const WindowResponse& window); } #endif diff --git a/source/source_lcao/module_lr/gradient_output.cpp b/source/source_lcao/module_lr/gradient_output.cpp index 192b80d85b0..83644292488 100644 --- a/source/source_lcao/module_lr/gradient_output.cpp +++ b/source/source_lcao/module_lr/gradient_output.cpp @@ -13,7 +13,7 @@ void print_lr_force(const std::vector& force, std::ostream& const std::ios::fmtflags old_flags = ofs.flags(); const std::streamsize old_precision = ofs.precision(); const int nstate = force.size(); - ofs << "Forces (-gradients) of each excited state: (eV/Angstrom)" << std::endl; + ofs << "Excitation-energy force contributions (-dOmega/dR) of each state: (eV/Angstrom)" << std::endl; ofs << std::fixed << std::setprecision(10) << std::setw(6) << "state" << std::setw(6) << "atom" << std::setw(20) << "x" << std::setw(20) << "y" << std::setw(20) << "z" << std::endl; const double fac = ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A; diff --git a/source/source_lcao/module_lr/hamilt_ulr.cpp b/source/source_lcao/module_lr/hamilt_ulr.cpp index 5e0b37309fe..4e0557a9ae1 100644 --- a/source/source_lcao/module_lr/hamilt_ulr.cpp +++ b/source/source_lcao/module_lr/hamilt_ulr.cpp @@ -22,14 +22,14 @@ HamiltULR::HamiltULR(const std::string& xc_kernel, const std::vector& nvirt, ///< {up, down} const UnitCell& ucell_in, const std::vector& orb_cutoff, - Grid_Driver& gd_in, + const Grid_Driver& gd_in, const psi::Psi& psi_ks_in, const ModuleBase::matrix& eig_ks, #ifdef __EXX std::weak_ptr> exx_lri_in, const double& exx_alpha, #endif - std::vector>& pot_in, + const std::vector>& pot_in, const K_Vectors& kv_in, const std::vector& pX_in, ///< {up, down} const Parallel_Blkcyclic& pc_in, diff --git a/source/source_lcao/module_lr/hamilt_ulr.h b/source/source_lcao/module_lr/hamilt_ulr.h index 368b0eb4f1a..9b803525e56 100644 --- a/source/source_lcao/module_lr/hamilt_ulr.h +++ b/source/source_lcao/module_lr/hamilt_ulr.h @@ -40,14 +40,14 @@ namespace LR const std::vector& nvirt, ///< {up, down} const UnitCell& ucell_in, const std::vector& orb_cutoff, - Grid_Driver& gd_in, + const Grid_Driver& gd_in, const psi::Psi& psi_ks_in, const ModuleBase::matrix& eig_ks, #ifdef __EXX std::weak_ptr> exx_lri_in, const double& exx_alpha, #endif - std::vector>& pot_in, + const std::vector>& pot_in, const K_Vectors& kv_in, const std::vector& pX_in, ///< {up, down} const Parallel_Blkcyclic& pc_in, diff --git a/source/source_lcao/module_lr/hamilt_zeq_l.h b/source/source_lcao/module_lr/hamilt_zeq_l.h index a54a55776ea..db8397cfd2e 100644 --- a/source/source_lcao/module_lr/hamilt_zeq_l.h +++ b/source/source_lcao/module_lr/hamilt_zeq_l.h @@ -179,8 +179,10 @@ namespace LR } protected: - void set_dm(const int is, const T* const X) override + void set_dm(const int is, const T* const X, + const std::vector* density_add) override { + assert(density_add == nullptr); // The linear Hessian reads only its input Z. const auto psi_ks_is = LR_Util::get_psi_spin(this->psi_ks_, is, this->nk); #ifdef __MPI this->dm_buf_ = cal_dm_trans_pblas(X, this->pX[is], psi_ks_is, this->pc_, diff --git a/source/source_lcao/module_lr/hamilt_zeq_r.h b/source/source_lcao/module_lr/hamilt_zeq_r.h index dc6f60997ee..269c421936d 100644 --- a/source/source_lcao/module_lr/hamilt_zeq_r.h +++ b/source/source_lcao/module_lr/hamilt_zeq_r.h @@ -101,8 +101,9 @@ namespace LR const auto& kernel = lr_potential->xc_kernel_components(); const auto& rho_basis = lr_potential->get_rho_basis(); const bool triplet = spin_type == "triplet"; + const int kernel_nspin = kernel.nspin(); this->pot_grad = std::make_shared(kernel, rho_basis, ucell, - lr_potential->nrxx, nspin, triplet); + lr_potential->nrxx, kernel_nspin, triplet); hamilt::Operator* op_gxc = new OperatorLRHxc(nspin, naos, nocc, nvirt, psi_ks, *this->DM_trans, this->pot_grad, ucell, orb_cutoff, gd, kv, pX, pc, pmat, { 0 }, T(-2.0), ATYPE::CC_vo, hamilt::calculation_type::lr_dmtrans_gxc); @@ -152,7 +153,7 @@ namespace LR } }; - this->cal_dm_diff = [this, &psi_ks, &pc, naos, &nocc, &nvirt, &pmat](const int& is, const T* const X)->void + this->cal_dm_diff = [this, &psi_ks, &pc, naos, &nocc, &nvirt, &pmat](const int& is, const T* const X, const std::vector* density_add)->void { const auto psi_ks_is = LR_Util::get_psi_spin(psi_ks, is, this->nk); #ifdef __MPI @@ -166,6 +167,10 @@ namespace LR #endif for (int ik = 0; ik < this->nk; ++ik) { + if (density_add != nullptr) + { + dm_diff_2d[ik] = dm_diff_2d[ik] + density_add->at(ik); + } this->DM_diff->set_dmk_ptr(ik, dm_diff_2d[ik].data()); } // std::cout << "difference density matrix" << std::endl; @@ -176,12 +181,21 @@ namespace LR } virtual void hPsi(const T* const psi, T* const hpsi, const int ld_psi, const int nband) const override { + const std::vector> no_density; + this->hPsi(psi, hpsi, ld_psi, nband, no_density); + } + // Each state supplies symmetric Dwin; only the linear Hgs[T] term reads it. + void hPsi(const T* psi, T* hpsi, const int ld_psi, const int nband, + const std::vector>& window_density) const + { + assert(window_density.empty() || window_density.size() == nband); assert(ld_psi == this->nk * this->pX[0].size()); for (int ib = 0;ib < nband;++ib) { const int offset = ib * ld_psi; this->cal_dm_trans(0, psi + offset); // transition density matrix, only for test - this->cal_dm_diff(0, psi + offset); // difference density matrix + const auto* density_add = window_density.empty() ? nullptr : &window_density[ib]; + this->cal_dm_diff(0, psi + offset, density_add); // T + Dwin hamilt::Operator* node(this->ops); while (node != nullptr) { @@ -193,7 +207,7 @@ namespace LR private: std::unique_ptr> DM_diff; - std::function cal_dm_diff; + std::function*)> cal_dm_diff; std::shared_ptr pot_grad; }; @@ -326,7 +340,8 @@ namespace LR /// Rebuild BOTH density matrices from the `is` block of X: the CXC operators read /// $D^X$ (transposed, un-symmetrized -- see the closed-shell `Z_vector_R` for why), /// the CC_vo operators read the difference density matrix $T$ (symmetrized). - void set_dm(const int is, const T* const X) override + void set_dm(const int is, const T* const X, + const std::vector* density_add) override { const auto psi_ks_is = LR_Util::get_psi_spin(this->psi_ks_, is, this->nk); #ifdef __MPI @@ -364,6 +379,11 @@ namespace LR for (int ik = 0;ik < this->nk;++ik) { this->DM_trans->set_dmk_ptr(ik, this->dmx_buf_[ik].template data()); + if (density_add != nullptr) + { + const int block = is * this->nk + ik; + this->dmd_buf_[ik] = this->dmd_buf_[ik] + density_add->at(block); + } this->DM_diff->set_dmk_ptr(ik, this->dmd_buf_[ik].template data()); } } diff --git a/source/source_lcao/module_lr/hamilt_zequlr.h b/source/source_lcao/module_lr/hamilt_zequlr.h index d03131230a6..86e640e735a 100644 --- a/source/source_lcao/module_lr/hamilt_zequlr.h +++ b/source/source_lcao/module_lr/hamilt_zequlr.h @@ -52,12 +52,30 @@ namespace LR } void hPsi(const T* const psi_in, T* const hpsi, const int ld_psi, const int nband) + { + this->apply(psi_in, hpsi, ld_psi, nband, nullptr); + } + + // The nonlinear RHS may supply one additive AO density per state/spin/k. + void hPsi(const T* psi_in, T* hpsi, const int ld_psi, const int nband, + const std::vector>& window_density) + { + assert(window_density.empty() || window_density.size() == nband); + this->apply(psi_in, hpsi, ld_psi, nband, &window_density); + } + + protected: + void apply(const T* const psi_in, T* const hpsi, const int ld_psi, + const int nband, + const std::vector>* window_density) { assert(ld_psi == this->ldim); const std::vector ldim_is = { static_cast(nk * pX[0].size()), static_cast(nk * pX[1].size()) }; for (int ib = 0;ib < nband;++ib) { const int offset_band = ib * ld_psi; + const auto* density_add = window_density == nullptr || window_density->empty() + ? nullptr : &window_density->at(ib); // All four spin blocks accumulate into this band's output, and the diagonal // `OperatorLRDiag`s now add rather than assign (see `operator_lr_diag.h`), so the // buffer has to start clean. @@ -69,7 +87,7 @@ namespace LR for (int is_in : {0, 1}) { const int offset_in = offset_band + is_in * ldim_is[0]; - this->set_dm(is_in, psi_in + offset_in); + this->set_dm(is_in, psi_in + offset_in, density_add); typename OperatorLRHxc::TransitionDensityCache density_cache; for (int is_out : {0, 1}) { @@ -94,6 +112,7 @@ namespace LR } } + public: /// @brief The full (replicated) matrix, column by column. Only used by the LAPACK solver. std::vector matrix() { @@ -121,7 +140,7 @@ namespace LR { X_col[loffset_in + ik_in * px.size() + lj * px.nrloc() + lb] = T(1); } - this->set_dm(is_in, X_col.data() + loffset_in); + this->set_dm(is_in, X_col.data() + loffset_in, nullptr); std::vector col(this->ldim, T(0)); for (int is_out : {0, 1}) { @@ -165,7 +184,8 @@ namespace LR protected: /// @brief rebuild the density matrices the operators read, from the `is` block of X - virtual void set_dm(const int is, const T* const X) = 0; + virtual void set_dm(const int is, const T* const X, + const std::vector* density_add) = 0; /// @brief optional per-band contribution that does not fit the 2x2 block structure. /// NOTE `matrix()` deliberately does NOT call this: it exists for the right-hand side, /// which is not a linear operator, while `matrix()` is only ever used for the LHS. diff --git a/source/source_lcao/module_lr/kernel_pots.cpp b/source/source_lcao/module_lr/kernel_pots.cpp index 37efdca4eb7..d758d59525d 100644 --- a/source/source_lcao/module_lr/kernel_pots.cpp +++ b/source/source_lcao/module_lr/kernel_pots.cpp @@ -19,16 +19,27 @@ KernelPotentials prepare_lr_potentials(const Input_para& input, const std::strin const bool oshell = (nspin == 2) && openshell; // $g^{xc}$ (third-order) is only ever needed by the LR gradient, and only for the spin // combinations that are actually going to be requested. + const bool scalar_triplet = nspin == 1 && input.lr_target_spin == "triplet"; + if (scalar_triplet && input.lr_init_xc_kernel[0] == "file" + && input.lr_init_xc_kernel.size() < 4) + { + throw std::invalid_argument("nspin=1 triplet requires three spin-resolved XC kernel files (uu, ud, dd)"); + } + const int kernel_nspin = scalar_triplet ? 2 : nspin; + const int scalar_gxc = scalar_triplet ? GX::Triplet : GX::Singlet; const int gxc_lr = (!input.cal_force || !LR_Util::has_local_xc(xc_kernel)) ? GX::NoGxc - : ((nspin == 1) ? GX::Singlet : GX::BothSpins); + : ((nspin == 1) ? scalar_gxc : GX::BothSpins); result.kernel = LR::build_xc_kernel( - xc_kernel, rho_basis, ucell, chg_gs, grid, nspin, oshell, gxc_lr, input.lr_init_xc_kernel); + xc_kernel, rho_basis, ucell, chg_gs, grid, kernel_nspin, oshell, gxc_lr, input.lr_init_xc_kernel); switch (nspin) { case 1: - result.pot[0] = std::make_shared(result.kernel, rho_basis, ucell, chg_gs.nrxx, nspin, ST::S1); + { + const ST spin = scalar_triplet ? ST::S2_triplet : ST::S1; + result.pot[0] = std::make_shared(result.kernel, rho_basis, ucell, chg_gs.nrxx, kernel_nspin, spin); break; + } case 2: { const ST first_spin = oshell ? ST::S2_updown : ST::S2_singlet; @@ -70,11 +81,27 @@ std::shared_ptr prepare_gs_potential(const Input_para& input, const st // contribution to W and the force use the corresponding LR potential instead. const int gxc_gs = (!LR_Util::has_local_xc(xc_kernel) || !LR_Util::has_local_xc(xc_kernel_gs)) ? GX::NoGxc : ((nspin == 1) ? GX::Singlet : GX::BothSpins); - // When the LR kernel *is* the ground-state functional -- the usual TDDFT case -- the two - // `KernelXC` are bit-for-bit identical, so reuse the one just built. - const bool share_lr = (xc_kernel_gs == xc_kernel) && ((prepared.gxc & gxc_gs) == gxc_gs); - std::shared_ptr kernel_gs = share_lr ? prepared.kernel - : LR::build_xc_kernel(xc_kernel_gs, rho_basis, ucell, chg_gs, grid, nspin, oshell, gxc_gs, input.lr_init_xc_kernel); + // HSE GS response starts raw and reports an approximate fallback only for non-finite coefficients. + // Other matching functionals retain sharing when spin layouts and derivative orders agree. + // Legacy GS/LR low-density cutoffs remain different; this fixes only the sigma-floor mismatch. + const bool separate_hse_response = xc_kernel_gs == "hse"; + const bool share_lr = !separate_hse_response && prepared.kernel->nspin() == nspin + && xc_kernel_gs == xc_kernel && ((prepared.gxc & gxc_gs) == gxc_gs); + std::shared_ptr kernel_gs; + if (separate_hse_response) + { + kernel_gs = LR::build_gs_xc_kernel(xc_kernel_gs, rho_basis, ucell, chg_gs, + grid, nspin, oshell, input.lr_init_xc_kernel); + } + else if (share_lr) + { + kernel_gs = prepared.kernel; + } + else + { + kernel_gs = LR::build_xc_kernel(xc_kernel_gs, rho_basis, ucell, chg_gs, + grid, nspin, oshell, gxc_gs, input.lr_init_xc_kernel); + } return std::make_shared(kernel_gs, rho_basis, ucell, chg_gs.nrxx, nspin, st_gs); } } diff --git a/source/source_lcao/module_lr/kernel_pots.h b/source/source_lcao/module_lr/kernel_pots.h index 950823a0fd8..c4bf4c6a52e 100644 --- a/source/source_lcao/module_lr/kernel_pots.h +++ b/source/source_lcao/module_lr/kernel_pots.h @@ -22,7 +22,9 @@ struct KernelPotentials std::shared_ptr kernel; int gxc = 0; }; -/// Prepare one LR kernel and bind its singlet/triplet or open-shell potential views. +/// Prepare LR potential views. At nspin=1, lr_target_spin selects a single channel; +/// triplets use a polarized kernel evaluated at rho_up=rho_down=rho/2. +/// nspin=2 retains both closed-shell views or the unrestricted spin blocks. KernelPotentials prepare_lr_potentials(const Input_para&, const std::string& xc_kernel, const ModulePW::PW_Basis&, const UnitCell&, const Charge&, const Parallel_Grid&, int nspin, bool openshell); /// Reuse LR coefficients for an identical GS functional and sufficient derivative order. diff --git a/source/source_lcao/module_lr/lr_density.cpp b/source/source_lcao/module_lr/lr_density.cpp index d27b28eebab..9b724bb5dae 100644 --- a/source/source_lcao/module_lr/lr_density.cpp +++ b/source/source_lcao/module_lr/lr_density.cpp @@ -52,8 +52,6 @@ LR_Density::LR_Density(const UnitCell& ucell, openshell_(openshell), out_chg_precision_(output_precision), global_out_dir_(output_directory) { nk_ = kv.get_nks() / nspin; - spintype_ = openshell ? std::vector({ "up", "down" }) - : std::vector({ "singlet", "triplet" }); } template @@ -63,7 +61,7 @@ void LR_Density::cal_eh_density_single_state(const T* const X_istate, const i ModuleBase::GlobalFunc::ZEROS(density[0], this->pgrid_.get_nrxx()); // 1. calculate the density matrix in AO basis // Closed-shell singlet and triplet amplitudes both use the spin-up KS orbitals. - // ispin still selects the response window and the output label. + // ispin selects the response window; the caller supplies the output label. const int orbital_spin = this->openshell_ ? ispin : 0; auto c_spin = LR_Util::get_psi_spin(psi_ks_, orbital_spin, nk_); #ifdef __MPI @@ -92,7 +90,7 @@ void LR_Density::write_density_single_state(const double* const* const densit template void LR_Density::output_eh_density_all_states(const T* const X, const int ispin, const int nstate, - std::ofstream& ofs_running) + const std::string& channel_label, std::ofstream& ofs_running) { ModuleBase::TITLE("LR_Density", "cal_eh_density_all_states"); const int up_size = this->pX_[0].size(); @@ -105,7 +103,7 @@ void LR_Density::output_eh_density_all_states(const T* const X, const int isp const int offset = LR::electron_hole_offset(istate, nk_, up_size, down_size, ispin, openshell_); const T* const amplitudes = X + offset; this->cal_eh_density_single_state(amplitudes, ispin, density); - const std::string filepath = this->global_out_dir_ + "LR_e-h_density_" + spintype_[ispin] + "_" + std::to_string(istate + 1) + ".cube"; + const std::string filepath = this->global_out_dir_ + "LR_e-h_density_" + channel_label + "_" + std::to_string(istate + 1) + ".cube"; this->write_density_single_state(density, filepath, ofs_running); } LR_Util::_deallocate_2order_nested_ptr(density, 1); diff --git a/source/source_lcao/module_lr/lr_density.h b/source/source_lcao/module_lr/lr_density.h index 76d82525c1d..84339f0d719 100644 --- a/source/source_lcao/module_lr/lr_density.h +++ b/source/source_lcao/module_lr/lr_density.h @@ -26,7 +26,6 @@ namespace LR const Parallel_Blkcyclic& pc_; const Parallel_Orbitals& pmat_; const bool openshell_; - std::vector spintype_; /// cached aliases, read once here instead of at every call site below const int out_chg_precision_; const std::string global_out_dir_; @@ -57,7 +56,7 @@ namespace LR std::ofstream& ofs_running); void output_eh_density_all_states(const T* const X, const int ispin, const int nstate, - std::ofstream& ofs_running); + const std::string& channel_label, std::ofstream& ofs_running); }; } diff --git a/source/source_lcao/module_lr/lr_grad_cs.cpp b/source/source_lcao/module_lr/lr_grad_cs.cpp index ec25a01a588..634cfc71ec8 100644 --- a/source/source_lcao/module_lr/lr_grad_cs.cpp +++ b/source/source_lcao/module_lr/lr_grad_cs.cpp @@ -1,4 +1,5 @@ #include "gradient_inputs.h" +#include "source_lcao/module_lr/window_response.h" #include "gradient_output.h" #include "gradient_checks.h" #include "cal_edm.h" @@ -13,7 +14,8 @@ std::vector evaluate_closed_shell_force( const GradientInputs& inputs, LR_Force& lr_force, const module_dm::DensityMatrix& dm_gs, const ct::Tensor& Xz, const ct::Tensor& Z, - const std::vector& omega, const int label_begin, const int ispin) + const std::vector& omega, const int label_begin, const int ispin, + const WindowResponse& window) { ModuleBase::timer::start("LR", "evaluate_closed_shell_force"); // for each block, calculate dm_trans, dm_relaxed_diff, edm and force @@ -105,7 +107,11 @@ std::vector evaluate_closed_shell_force( // std::cout << "dm_relaxed_k Z(k) after symmetrization, istate " + std::to_string(istate) << std::endl; // LR_Util::print_value(dm_relaxed_k[0].data(), inputs.pmat.get_col_size(), inputs.pmat.get_row_size()); // relaxed difference density matrix - const std::vector& relaxed_diff_dm_k = dm_diff_k + dm_relaxed_k; + std::vector relaxed_diff_dm_k = dm_diff_k + dm_relaxed_k; + if (!window.density.empty()) + { + relaxed_diff_dm_k = relaxed_diff_dm_k + window.density[istate - ist_begin]; + } const module_dm::DensityMatrix& diff_dm = LR_Util::build_dm_from_dmk(dm_diff_k, inputs.pmat, inputs.nk, inputs.kv.kvec_d, inputs.ucell, inputs.gd, inputs.orb_cutoff); @@ -135,9 +141,13 @@ std::vector evaluate_closed_shell_force( const T* const x_istate = Xz.data() + offset; const T* const z_istate = Z.template data() + zoffset; const double omega_istate = omega[istate - ist_begin]; - const std::vector& edm_k = cal_edm_from_XZ_istate( + std::vector edm_k = cal_edm_from_XZ_istate( inputs, x_istate, z_istate, omega_istate, inputs.eig_ks.c, - dm_trans, c, pot_weak, inputs.spin_types[ispin]); + dm_trans, c, pot_weak, inputs.spin_types[ispin], relaxed_diff_dm_k); + if (!window.direct_edm.empty()) + { + edm_k = edm_k + window.direct_edm[istate - ist_begin]; + } if (inputs.test_force && inputs.nocc[0] == 1 && nvirt_g[0] == 1) { #ifdef __MPI @@ -176,8 +186,9 @@ std::vector evaluate_closed_shell_force( // The density dependence of K[D^X]D^X belongs to the LR functional. const std::shared_ptr& pot_lr = inputs.pot[ispin]; const bool triplet = inputs.spin_types[ispin] == "triplet"; + const int kernel_nspin = pot_lr->xc_kernel_components().nspin(); PotGradXCLR pot_grad(pot_lr->xc_kernel_components(), pot_lr->get_rho_basis(), - inputs.ucell, pot_lr->nrxx, inputs.nspin, triplet); + inputs.ucell, pot_lr->nrxx, kernel_nspin, triplet); ModuleBase::matrix force_gxc_dmtrans = lr_force.cal_force_gxc_dmtrans(dm_trans_real, dm_gs, pot_grad); if (inputs.test_force) ModuleIO::print_force(inputs.ofs, inputs.ucell, "GXC DMTRANS FORCE (eV/Angstrom)", force_gxc_dmtrans, false); @@ -252,6 +263,6 @@ std::vector evaluate_closed_shell_force( } -template std::vector evaluate_closed_shell_force(const GradientInputs&, LR_Force&, const module_dm::DensityMatrix&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int, int); -template std::vector evaluate_closed_shell_force>(const GradientInputs>&, LR_Force>&, const module_dm::DensityMatrix, double>&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int, int); +template std::vector evaluate_closed_shell_force(const GradientInputs&, LR_Force&, const module_dm::DensityMatrix&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int, int, const WindowResponse&); +template std::vector evaluate_closed_shell_force>(const GradientInputs>&, LR_Force>&, const module_dm::DensityMatrix, double>&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int, int, const WindowResponse>&); } diff --git a/source/source_lcao/module_lr/lr_grad_os.cpp b/source/source_lcao/module_lr/lr_grad_os.cpp index cf81071269f..b94105a1b0a 100644 --- a/source/source_lcao/module_lr/lr_grad_os.cpp +++ b/source/source_lcao/module_lr/lr_grad_os.cpp @@ -1,4 +1,5 @@ #include "gradient_inputs.h" +#include "window_response.h" #include "gradient_output.h" #include "gradient_checks.h" #include "cal_edm.h" @@ -13,7 +14,8 @@ std::vector evaluate_open_shell_force( const GradientInputs& inputs, LR_Force& lr_force, const module_dm::DensityMatrix& dm_gs, const ct::Tensor& Xz, const ct::Tensor& Z, - const std::vector& omega, const int label_begin) + const std::vector& omega, const int label_begin, + const WindowResponse& window) { ModuleBase::timer::start("LR", "evaluate_open_shell_force"); const int nst = static_cast(omega.size()); @@ -72,6 +74,14 @@ std::vector evaluate_open_shell_force( } #endif relaxed_k[is] = dmdiff_k[is] + dmz_k; + if (!window.density.empty()) + { + const int state = istate - ist_begin; + for (int ik = 0; ik < inputs.nk; ++ik) + { + relaxed_k[is][ik] = relaxed_k[is][ik] + window.density[state][is * inputs.nk + ik]; + } + } } // 2. $D^X$. Complex and UN-symmetrized first (the EXX kernel needs the full @@ -96,8 +106,19 @@ std::vector evaluate_open_shell_force( // 4. the energy-weighted density matrix std::weak_ptr pot_weak = inputs.pot[0]; const double omega_istate = omega[istate - ist_begin]; - const std::vector>& edm_k = cal_edm_from_XZ_istate_openshell( - inputs, X_istate, Z_istate, omega_istate, inputs.eig_ks.c, dm_trans, pot_weak); + std::vector> edm_k = cal_edm_from_XZ_istate_openshell( + inputs, X_istate, Z_istate, omega_istate, inputs.eig_ks.c, dm_trans, pot_weak, relaxed_k); + if (!window.direct_edm.empty()) + { + const int state = istate - ist_begin; + for (int is = 0; is < 2; ++is) + { + for (int ik = 0; ik < inputs.nk; ++ik) + { + edm_k[is][ik] = edm_k[is][ik] + window.direct_edm[state][is * inputs.nk + ik]; + } + } + } module_dm::DensityMatrix edm_real = LR_Util::build_dm_from_dmk_spin(edm_k, inputs.pmat, inputs.nk, inputs.kv.kvec_d, inputs.ucell, inputs.gd, inputs.orb_cutoff, /*symmetrize=*/true); @@ -182,6 +203,6 @@ std::vector evaluate_open_shell_force( } -template std::vector evaluate_open_shell_force(const GradientInputs&, LR_Force&, const module_dm::DensityMatrix&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int); -template std::vector evaluate_open_shell_force>(const GradientInputs>&, LR_Force>&, const module_dm::DensityMatrix, double>&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int); +template std::vector evaluate_open_shell_force(const GradientInputs&, LR_Force&, const module_dm::DensityMatrix&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int, const WindowResponse&); +template std::vector evaluate_open_shell_force>(const GradientInputs>&, LR_Force>&, const module_dm::DensityMatrix, double>&, const ct::Tensor&, const ct::Tensor&, const std::vector&, int, const WindowResponse>&); } diff --git a/source/source_lcao/module_lr/potentials/pot_grad_xc.cpp b/source/source_lcao/module_lr/potentials/pot_grad_xc.cpp index 43e21a6eba4..ebda70f98e1 100644 --- a/source/source_lcao/module_lr/potentials/pot_grad_xc.cpp +++ b/source/source_lcao/module_lr/potentials/pot_grad_xc.cpp @@ -111,8 +111,11 @@ namespace LR const double* const e_st = g.e_st.data(); const double* const e_t2 = g.e_t2.data(); const double* const e_q = g.e_q.data(); - const double* const c_s = g.c_s.data(); - const double* const c_t = g.c_t.data(); + const auto& coefficients = kxc.closed_shell_gga(this->triplet_); + const double* const rs = coefficients.rho_sigma.data(); + const double* const ss = coefficients.sigma_sigma.data(); + // nspin=1 gxc includes the singlet factor 4; nspin=2 already uses spin sums. + const double transition_gradient_factor = (kxc.nspin() == 1) ? 8. : 2.; const double* const a_s2 = g.a_s2.data(); const double* const a_st = g.a_st.data(); const double* const a_t2 = g.a_t2.data(); @@ -134,7 +137,7 @@ namespace LR const double q = drho1[ir] * drho1[ir]; // $\nabla\rho^1\cdot\nabla\rho^1$ const double e = e_s2[ir] * (s * s) + e_st[ir] * (s * t) + e_t2[ir] * (t * t) + e_q[ir] * q; - gdot_terms[ir] = -(drho * e + drho1[ir] * (c_s[ir] * s + c_t[ir] * t)); + gdot_terms[ir] = -(drho * e + drho1[ir] * (transition_gradient_factor * (rs[ir] * s + ss[ir] * t))); } XC_Functional::grad_dot(gdot_terms, v_tmp, &this->rho_basis_, this->tpiba_); @@ -187,6 +190,7 @@ namespace LR const std::vector& v3r2s = kxc.v3rho2sigma; const std::vector& v3rs2 = kxc.v3rhosigma2; const std::vector& v3s3 = kxc.v3sigma3; + const std::vector& sigma_jacobian = kxc.sigma_jacobian(); // Branch on THIS kernel's own GGA-ness, not the ground state's (see `cal_v_eff`). if (!kxc.is_gga()) // LDA: only $g^{\rho\rho\rho}$ survives @@ -277,6 +281,8 @@ namespace LR // $u'_a$ and $u''_a$ do not depend on $\tau$; only the $\theta$ weights and the // channel selector below do. ModuleBase::Vector3 E(0., 0., 0.); + const double* const rho_sigma_coefficients = v2rs.data() + o6; + const double* const sigma_sigma_coefficients = v2s2.data() + o6; for (int a = 0;a < 3;++a) { const double th = theta[tau][a]; @@ -285,16 +291,9 @@ namespace LR continue; } const int c = chan[tau][a]; - double up = 0.; + const double up = sigma_potential_derivative( + rho_sigma_coefficients, sigma_sigma_coefficients, a, s, S, 0, 2); double upp = 0.; - for (int s0 = 0; s0 < 2; ++s0) - { - up += s[s0] * v2rs[o6 + rs(s0, a)]; - } - for (int b = 0; b < 3; ++b) - { - up += S[b] * v2s2[o6 + p2[a][b]]; - } for (int s0 = 0;s0 < 2;++s0) { for (int s1 = 0; s1 < 2; ++s1) @@ -319,7 +318,10 @@ namespace LR upp += Q[b] * v2s2[o6 + p2[a][b]]; } - E += th * (drho[c] * upp + dr1[c] * (2. * up)); + // Prepared-sigma coefficients carry J; explicit transition-gradient + // factors retain their full derivative, including below the floor. + const double jacobian = sigma_jacobian.empty() ? 1.0 : sigma_jacobian[3 * ir + a]; + E += th * (drho[c] * (upp * jacobian) + dr1[c] * (2. * up)); } gdot_terms[ir] = -E; // `grad_dot` then yields $-\nabla\cdot\boldsymbol{E}_\tau$ } diff --git a/source/source_lcao/module_lr/potentials/pot_grad_xc.h b/source/source_lcao/module_lr/potentials/pot_grad_xc.h index 6920e1fb3c5..b4f6f9720d8 100644 --- a/source/source_lcao/module_lr/potentials/pot_grad_xc.h +++ b/source/source_lcao/module_lr/potentials/pot_grad_xc.h @@ -22,6 +22,9 @@ namespace LR /// $\tau$ is the output index, but BOTH channels of the transition density enter the /// same expression, so `rho1` must carry `rho1[0]` and `rho1[1]` together. /// $v^{(2)}_\tau = A_\tau - \nabla\cdot\boldsymbol{E}_\tau$ + /// For stabilized LR coefficients this differentiates the actual LR quadratic form: + /// only implicit sigma dependencies carry the preparation Jacobian; explicit gradient + /// factors and local terms remain active. Both transition channels have nrxx entries. void cal_v_eff_openshell(const double* const* const rho1, const UnitCell& ucell, ModuleBase::matrix& v_eff, const int tau) const; /// kernel components from PotHxcLR diff --git a/source/source_lcao/module_lr/potentials/pot_hxc_lrtd.cpp b/source/source_lcao/module_lr/potentials/pot_hxc_lrtd.cpp index f3cd475758c..b5edbc1c7f3 100644 --- a/source/source_lcao/module_lr/potentials/pot_hxc_lrtd.cpp +++ b/source/source_lcao/module_lr/potentials/pot_hxc_lrtd.cpp @@ -280,8 +280,9 @@ namespace LR double* const vxc = scratch().vxc.data(); Vec3* const e_drho = scratch().gdot.data(); - const Vec3* const rs2 = fxc.v2rhosigma_2drho.data(); - const Vec3* const ss4 = fxc.v2sigma2_4drho.data(); + const auto& coefficients = fxc.closed_shell_gga(false); + const double* const rs2 = coefficients.rho_sigma.data(); + const double* const ss4 = coefficients.sigma_sigma.data(); const Vec3* const dgs = fxc.drho_gs.at(0).data(); const double* const vsig = fxc.vsigma.data(); const double* const rr = fxc.v2rho2.data(); @@ -292,8 +293,8 @@ namespace LR #endif for (int ir = 0;ir < nrxx;++ir) { - e_drho[ir] = -(rs2[ir] * rho[ir] - + ss4[ir] * (dgs[ir] * drho[ir]) + e_drho[ir] = -(dgs[ir] * (rs2[ir] * rho[ir] + + ss4[ir] * (dgs[ir] * drho[ir])) + drho[ir] * (vsig[ir] * 2.)); } XC_Functional::grad_dot(e_drho, vxc, &this->rho_basis_, this->tpiba_); @@ -304,7 +305,7 @@ namespace LR #endif for (int ir = 0;ir < nrxx;++ir) { - vxc[ir] += rr[ir] * rho[ir] + rs2[ir] * drho[ir]; + vxc[ir] += rr[ir] * rho[ir] + rs2[ir] * (dgs[ir] * drho[ir]); } BlasConnector::axpy(nrxx, ModuleBase::e2 * prefac, vxc, 1, v_eff.c, 1); }; @@ -326,10 +327,9 @@ namespace LR double* const vxc = scratch().vxc.data(); Vec3* const gdot = scratch().gdot.data(); - const Vec3* const rs = triplet ? fxc.v2rhosigma_drho_triplet.data() - : fxc.v2rhosigma_drho_singlet.data(); - const Vec3* const ss = triplet ? fxc.v2sigma2_drho_triplet.data() - : fxc.v2sigma2_drho_singlet.data(); + const auto& coefficients = fxc.closed_shell_gga(triplet); + const double* const rs = coefficients.rho_sigma.data(); + const double* const ss = coefficients.sigma_sigma.data(); const Vec3* const dgs = fxc.drho_gs.at(0).data(); const double* const vsig = this->vsigma_comb_.data(); // 2*vsigma_uu -+ vsigma_ud const double* const rr = this->v2rho2_comb_.data(); // v2rho2_uu -+ v2rho2_ud @@ -340,8 +340,8 @@ namespace LR #endif for (int ir = 0;ir < nrxx;++ir) { - gdot[ir] = -(rs[ir] * rho[ir] - + ss[ir] * (dgs[ir] * drho[ir]) + gdot[ir] = -(dgs[ir] * (rs[ir] * rho[ir] + + ss[ir] * (dgs[ir] * drho[ir])) + drho[ir] * vsig[ir]); } XC_Functional::grad_dot(gdot, vxc, &this->rho_basis_, this->tpiba_); @@ -352,7 +352,7 @@ namespace LR #endif for (int ir = 0;ir < nrxx;++ir) { - vxc[ir] += rho[ir] * rr[ir] + drho[ir] * rs[ir]; + vxc[ir] += rho[ir] * rr[ir] + (drho[ir] * dgs[ir]) * rs[ir]; } BlasConnector::axpy(nrxx, ModuleBase::e2 * prefac, vxc, 1, v_eff.c, 1); }; @@ -372,79 +372,65 @@ namespace LR const double* const vsig = fxc.vsigma.data(); const double* const rr = fxc.v2rho2.data(); - // the four (sigma, sigma') blocks: which pre-contracted arrays to read, - // which vsigma component multiplies drho^X, and which v2rho2 component. - const int blk = ispin_op[0] << 1 | ispin_op[1]; - const Vec3* rs = nullptr; - const Vec3* su = nullptr; - const Vec3* sd = nullptr; - int i_vsig = 0; - int i_rr = 0; - double vsig_fac = 1.; - // `rs2` is the v2rhosigma array used again in the non-divergence term; - // for the off-diagonal blocks it is the transposed one (ud vs du). - const Vec3* rs2 = nullptr; - switch (blk) + const int output_spin = ispin_op[0]; + const int input_spin = ispin_op[1]; + if (output_spin < 0 || output_spin > 1 || input_spin < 0 || input_spin > 1) { - case 0: // (0,0) - rs = fxc.v2rhosigma_drho_uu.data(); - rs2 = rs; - su = fxc.v2sigma2_drho_uu_u.data(); - sd = fxc.v2sigma2_drho_uu_d.data(); - i_vsig = 0; - vsig_fac = 2.; - i_rr = 0; - break; - case 1: // (0,1): rho_d, drho_u - rs = fxc.v2rhosigma_drho_du.data(); - rs2 = fxc.v2rhosigma_drho_ud.data(); - su = fxc.v2sigma2_drho_ud_u.data(); - sd = fxc.v2sigma2_drho_ud_d.data(); - i_vsig = 1; - vsig_fac = 1.; - i_rr = 1; - break; - case 2: // (1,0): rho_u, drho_d - rs = fxc.v2rhosigma_drho_ud.data(); - rs2 = fxc.v2rhosigma_drho_du.data(); - su = fxc.v2sigma2_drho_du_u.data(); - sd = fxc.v2sigma2_drho_du_d.data(); - i_vsig = 1; - vsig_fac = 1.; - i_rr = 1; - break; - case 3: // (1,1) - rs = fxc.v2rhosigma_drho_dd.data(); - rs2 = rs; - su = fxc.v2sigma2_drho_dd_u.data(); - sd = fxc.v2sigma2_drho_dd_d.data(); - i_vsig = 2; - vsig_fac = 2.; - i_rr = 2; - break; - default: throw std::runtime_error("Invalid ispin_op"); } - // 1. the terms in grad_dot int f_uu + const double* const rho_sigma = fxc.v2rhosigma.data(); + const double* const sigma_sigma = fxc.v2sigma2.data(); + // Each input spin perturbs two adjacent sigma invariants. Select all + // spin-dependent gradients and coefficient indices before the grid loops. + const int in0 = input_spin; + const int in1 = input_spin + 1; + const int out0 = output_spin; + const int out1 = output_spin + 1; + const Vec3* const gs_gradient[2] = {dgs_u, dgs_d}; + const Vec3* const in_gradient0 = gs_gradient[libxc_idx::chan[input_spin][in0]]; + const Vec3* const in_gradient1 = gs_gradient[libxc_idx::chan[input_spin][in1]]; + const Vec3* const out_gradient0 = gs_gradient[libxc_idx::chan[output_spin][out0]]; + const Vec3* const out_gradient1 = gs_gradient[libxc_idx::chan[output_spin][out1]]; + const double in_weight0 = libxc_idx::theta[input_spin][in0]; + const double in_weight1 = libxc_idx::theta[input_spin][in1]; + const double out_weight0 = libxc_idx::theta[output_spin][out0]; + const double out_weight1 = libxc_idx::theta[output_spin][out1]; + const int rs0 = 3 * input_spin + out0; + const int rs1 = 3 * input_spin + out1; + const int ss00 = libxc_idx::p2[out0][in0]; + const int ss01 = libxc_idx::p2[out0][in1]; + const int ss10 = libxc_idx::p2[out1][in0]; + const int ss11 = libxc_idx::p2[out1][in1]; + const int local_rs0 = 3 * output_spin + in0; + const int local_rs1 = 3 * output_spin + in1; + const int spin_pair = output_spin + input_spin; + const double gradient_weight = (output_spin == input_spin) ? 2. : 1.; #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif - for (int ir = 0;ir < nrxx;++ir) + for (int ir = 0; ir < nrxx; ++ir) { - gdot[ir] = -(rs[ir] * rho[ir] - + su[ir] * (dgs_u[ir] * drho[ir]) - + sd[ir] * (dgs_d[ir] * drho[ir]) - + drho[ir] * (vsig[ir * 3 + i_vsig] * vsig_fac)); + const double sigma0 = in_weight0 * (in_gradient0[ir] * drho[ir]); + const double sigma1 = in_weight1 * (in_gradient1[ir] * drho[ir]); + const double* const rs = rho_sigma + 6 * ir; + const double* const ss = sigma_sigma + 6 * ir; + const double derivative0 = rs[rs0] * rho[ir] + ss[ss00] * sigma0 + ss[ss01] * sigma1; + const double derivative1 = rs[rs1] * rho[ir] + ss[ss10] * sigma0 + ss[ss11] * sigma1; + gdot[ir] = -(out_gradient0[ir] * (out_weight0 * derivative0) + + out_gradient1[ir] * (out_weight1 * derivative1) + + drho[ir] * (gradient_weight * vsig[3 * ir + spin_pair])); } XC_Functional::grad_dot(gdot, vxc, &this->rho_basis_, this->tpiba_); - - // 2. terms not in grad_dot #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif - for (int ir = 0;ir < nrxx;++ir) + for (int ir = 0; ir < nrxx; ++ir) { - vxc[ir] += rho[ir] * rr[3 * ir + i_rr] + drho[ir] * rs2[ir]; + const double sigma0 = in_weight0 * (in_gradient0[ir] * drho[ir]); + const double sigma1 = in_weight1 * (in_gradient1[ir] * drho[ir]); + const double* const rs = rho_sigma + 6 * ir; + vxc[ir] += rho[ir] * rr[3 * ir + spin_pair] + + rs[local_rs0] * sigma0 + rs[local_rs1] * sigma1; } BlasConnector::axpy(nrxx, ModuleBase::e2, vxc, 1, v_eff.c, 1); }; diff --git a/source/source_lcao/module_lr/potentials/xc_kernel.cpp b/source/source_lcao/module_lr/potentials/xc_kernel.cpp index 556a957e5f9..eff1352919e 100644 --- a/source/source_lcao/module_lr/potentials/xc_kernel.cpp +++ b/source/source_lcao/module_lr/potentials/xc_kernel.cpp @@ -3,6 +3,8 @@ #include "source_hamilt/module_xc/xc_functional.h" #include "source_io/module_parameter/parameter.h" #include "source_base/timer.h" +#include "source_base/parallel_reduce.h" +#include #include "source_base/tool_quit.h" #include "source_lcao/module_lr/utils/lr_util.h" #include "source_lcao/module_lr/utils/lr_util_xc.hpp" @@ -17,6 +19,35 @@ #ifdef __LIBXC #include #include "source_hamilt/module_xc/libxc_abacus.h" + +namespace +{ +/// Count all coefficients read by a GGA response, including its first-order sigma term. +/// Empty grid ranks still join the reduction and the resulting retry decision. +void count_nonfinite_gga_response(const std::vector& vsigma, + const std::vector& rho_rho, const std::vector& rho_sigma, + const std::vector& sigma_sigma, long long* counts) +{ + const std::vector* coefficients[4] = {&vsigma, &rho_rho, &rho_sigma, &sigma_sigma}; + for (int component = 0; component < 4; ++component) + { + counts[component] = 0; + for (const double value : *coefficients[component]) + { + if (!std::isfinite(value)) + { + ++counts[component]; + } + } + } + Parallel_Reduce::reduce_all(counts, 4); +} + +bool has_nonfinite_response(const long long* counts) +{ + return counts[0] != 0 || counts[1] != 0 || counts[2] != 0 || counts[3] != 0; +} +} // namespace #endif #ifdef _OPENMP #include @@ -39,9 +70,38 @@ LR::KernelXC::KernelXC(const ModulePW::PW_Basis& rho_basis, const std::string& kernel_name, const std::vector& lr_init_xc_kernel, const bool openshell, - const int gxc_spin) :nspin_(nspin), kernel_name_(kernel_name), gxc_spin_(gxc_spin), - rho_basis_(rho_basis), openshell_(openshell) + const int gxc_spin) + : KernelXC(Purpose::LinearResponse, rho_basis, ucell, chg_gs, pgrid, nspin, + kernel_name, lr_init_xc_kernel, openshell, gxc_spin) +{ +} + +std::shared_ptr LR::build_gs_xc_kernel(const std::string& kernel_name, + const ModulePW::PW_Basis& rho_basis, const UnitCell& ucell, const Charge& chg_gs, + const Parallel_Grid& pgrid, const int nspin, const bool openshell, + const std::vector& lr_init_xc_kernel) +{ + return std::make_shared(KernelXC::Purpose::GroundStateResponse, + rho_basis, ucell, chg_gs, pgrid, nspin, kernel_name, lr_init_xc_kernel, + openshell, KernelXC::NoGxc); +} + +LR::KernelXC::KernelXC(Purpose purpose, const ModulePW::PW_Basis& rho_basis, + const UnitCell& ucell, + const Charge& chg_gs, + const Parallel_Grid& pgrid, + const int& nspin, + const std::string& kernel_name, + const std::vector& lr_init_xc_kernel, + const bool openshell, + const int gxc_spin) + : nspin_(nspin), kernel_name_(kernel_name), gxc_spin_(gxc_spin), purpose_(purpose), + rho_basis_(rho_basis), openshell_(openshell) { + if (purpose == Purpose::GroundStateResponse && gxc_spin != NoGxc) + { + throw std::invalid_argument("KernelXC: ground-state response requires only second derivatives"); + } if (!LR_Util::has_local_xc(kernel_name)) { return; @@ -84,9 +144,30 @@ LR::KernelXC::KernelXC(const ModulePW::PW_Basis& rho_basis, ModuleIO::read_vdata_palgrid(pgrid, GlobalV::MY_RANK, GlobalV::ofs_running, file, rho_for_fxc[is], ucell.nat); } + if (nspin == 2 && chg_gs.nspin == 1) + { + // Charge-file input follows the GS convention: one total-density file. + for (int ir = 0; ir < nrxx; ++ir) + { + rho_for_fxc[0][ir] *= 0.5; + rho_for_fxc[1][ir] = rho_for_fxc[0][ir]; + } + } this->f_xc_libxc(nspin, ucell.omega, ucell.tpiba, rho_for_fxc, chg_gs.rho_core); LR_Util::_deallocate_2order_nested_ptr(rho_for_fxc, nspin); } + else if (nspin == 2 && chg_gs.nspin == 1) + { + // A spin-unpolarized GS still has a triplet response. Evaluate the polarized + // kernel at rho_up = rho_down = rho/2; the scalar kernel cannot supply f_uu-f_ud. + std::vector half_density(nrxx); + for (int ir = 0; ir < nrxx; ++ir) + { + half_density[ir] = 0.5 * chg_gs.rho[0][ir]; + } + const double* spin_density[2] = {half_density.data(), half_density.data()}; + this->f_xc_libxc(nspin, ucell.omega, ucell.tpiba, spin_density, chg_gs.rho_core); + } else { this->f_xc_libxc(nspin, ucell.omega, ucell.tpiba, chg_gs.rho, chg_gs.rho_core); } #else ModuleBase::WARNING_QUIT("KernelXC", "to calculate xc-kernel in LR-TDDFT, compile with LIBXC"); @@ -121,9 +202,11 @@ inline void cutoff_grid_data_spin2(std::vector& func, const std::vecto const int nrxx = mask.size() / 2; if (nrxx == 0) { - ModuleBase::WARNING_QUIT("LR::cutoff_grid_data_spin2", - "An MPI rank has no local real-space grid points for the LR XC kernel. " - "Reduce the number of MPI processes (and increase OpenMP threads if needed)."); + if (!func.empty()) + { + throw std::invalid_argument("LR::cutoff_grid_data_spin2: nonempty data with an empty local grid"); + } + return; } assert(func.size() % nrxx == 0 && func.size() / nrxx > 1); const int n_component = func.size() / nrxx; @@ -320,12 +403,58 @@ void LR::KernelXC::f_xc_libxc(const int& nspin, const double& omega, const doubl // of functionals that were never broken; also confirmed to resolve 08_BeH2/hse (both // its DZP and TZDP bases, all excited states). const bool is_hse06 = func.info->number == XC_HYB_GGA_XC_HSE06; + // SCF does not use the LR floor. Try raw GS coefficients first; only + // non-finite HSE response coefficients permit the approximate fallback below. + const bool stabilize_hse = is_hse06 && purpose_ == Purpose::LinearResponse; std::vector hse_sigma; - const std::vector& sigma_input = LR_Util::prepare_xc_sigma(sigma, is_hse06, hse_sigma); + // Differentiate the LR matrix actually used: only implicit dependence on + // max(sigma, sigma_cut) carries its Jacobian, not explicit gradient factors. + const std::vector* sigma_input_ptr = nullptr; + if (need_kxc) + { + sigma_input_ptr = &LR_Util::prepare_xc_sigma(sigma, stabilize_hse, + hse_sigma, sigma_jacobian_); + } + else + { + sigma_input_ptr = &LR_Util::prepare_xc_sigma(sigma, stabilize_hse, hse_sigma); + } + const std::vector& sigma_input = *sigma_input_ptr; xc_gga_vxc(&func, nrxx, rho.data(), sigma_input.data(), vrho_tmp.data(), vsigma_tmp.data()); xc_gga_fxc(&func, nrxx, rho.data(), sigma_input.data(), v2rho2_tmp.data(), v2rhosigma_tmp.data(), v2sigma2_tmp.data()); - // std::cout << "max element of v2sigma2_tmp: " << *std::max_element(v2sigma2_tmp.begin(), v2sigma2_tmp.end()) << std::endl; - // std::cout << "rho corresponding to max element of v2sigma2_tmp: " << rho[(std::max_element(v2sigma2_tmp.begin(), v2sigma2_tmp.end()) - v2sigma2_tmp.begin()) / 6] << std::endl; + if (is_hse06 && purpose_ == Purpose::GroundStateResponse) + { + long long invalid[4] = {0, 0, 0, 0}; + count_nonfinite_gga_response(vsigma_tmp, v2rho2_tmp, v2rhosigma_tmp, v2sigma2_tmp, invalid); + if (has_nonfinite_response(invalid)) + { + // Recompute the complete GGA response on every rank, not just its NaNs. + // Keep e_sigma and all FXC blocks at the same evaluation point. + const std::vector& fallback_sigma = LR_Util::prepare_xc_sigma(sigma, true, hse_sigma); + xc_gga_vxc(&func, nrxx, rho.data(), fallback_sigma.data(), vrho_tmp.data(), vsigma_tmp.data()); + xc_gga_fxc(&func, nrxx, rho.data(), fallback_sigma.data(), + v2rho2_tmp.data(), v2rhosigma_tmp.data(), v2sigma2_tmp.data()); + long long remaining[4] = {0, 0, 0, 0}; + count_nonfinite_gga_response(vsigma_tmp, v2rho2_tmp, v2rhosigma_tmp, v2sigma2_tmp, remaining); + if (has_nonfinite_response(remaining)) + { + XC_Functional_Libxc::finish_func(funcs); + ModuleBase::timer::end("XC_Functional", "f_xc_libxc"); + throw std::runtime_error("HSE GS response remains non-finite after the sigma-floor retry; " + "cannot compute excitation-energy gradients"); + } + gs_sigma_fallback_used_ = true; + std::ostringstream message; + message << "Non-finite HSE GS response: e_sigma=" << invalid[0] + << ", e_rhorho=" << invalid[1] << ", e_rhosigma=" << invalid[2] + << ", e_sigmasigma=" << invalid[3] + << ". Recomputed e_sigma and all FXC on every rank at sigma >= " + << LR_Util::hse_sigma_floor() << " a0^-8. Using an approximate GS orbital Hessian; " + "the SCF potential is unchanged and gradients are not guaranteed to match finite differences."; + const std::string warning = message.str(); + ModuleBase::WARNING("KernelXC::GroundStateResponse", warning); + } + } // cut off by sgn. nspin=2 only: `cutoff_grid_data_spin2` assumes >1 component per // grid point (it asserts on it), and at nspin=1 there is exactly one, for which both // of its `for_each` ranges are empty -- the cutoff is a no-op anyway. @@ -385,83 +514,38 @@ void LR::KernelXC::f_xc_libxc(const int& nspin, const double& omega, const doubl if (nspin == 1) { - // 1. $2f^{\rho\sigma}*\nabla\rho$ - this->v2rhosigma_2drho_.resize(nrxx); -#ifdef _OPENMP -#pragma omp parallel for schedule(static, 4096) -#endif - for (size_t i = 0; i < nrxx; ++i) - { - this->v2rhosigma_2drho_[i] = gradrho[0][i] * v2rs[i] * 2.; - } - - // 2. $4f^{\sigma\sigma}*\nabla\rho$ - this->v2sigma2_4drho_.resize(nrxx); + this->closed_shell_gga_s_.rho_sigma.resize(nrxx); + this->closed_shell_gga_s_.sigma_sigma.resize(nrxx); #ifdef _OPENMP #pragma omp parallel for schedule(static, 4096) #endif - for (size_t i = 0; i < nrxx; ++i) + for (int i = 0; i < nrxx; ++i) { - this->v2sigma2_4drho_[i] = gradrho[0][i] * v2s2[i] * 4.; + this->closed_shell_gga_s_.rho_sigma[i] = v2rs[i] * 2.; + this->closed_shell_gga_s_.sigma_sigma[i] = v2s2[i] * 4.; } - - // The third-order kernels contracted with $\nabla\rho$ used to be pre-built here; - // they are now folded into `GxcCoef::e_*` (with $\nabla\rho$ factored back out) } else if (2 == nspin) //close-shell { if (!openshell_) { - this->v2rhosigma_drho_singlet_.resize(nrxx); - this->v2sigma2_drho_singlet_.resize(nrxx); - this->v2rhosigma_drho_triplet_.resize(nrxx); - this->v2sigma2_drho_triplet_.resize(nrxx); -#ifdef _OPENMP -#pragma omp parallel for schedule(static, 4096) -#endif - for (int i = 0;i < nrxx;++i) - { - const int istart = i * 6; - this->v2rhosigma_drho_singlet_[i] = gradrho[0][i] * (v2rs[istart] + v2rs[istart + 1] + v2rs[istart + 2]) * 2.; - this->v2sigma2_drho_singlet_[i] = gradrho[0][i] * (v2s2[istart] * 2. + v2s2[istart + 1] * 3. + v2s2[istart + 2] * 2. + v2s2[istart + 3] + v2s2[istart + 4]) * 2.; - this->v2rhosigma_drho_triplet_[i] = gradrho[0][i] * (v2rs[istart] - v2rs[istart + 2]) * 2.; - this->v2sigma2_drho_triplet_[i] = gradrho[0][i] * (v2s2[istart] * 2. + v2s2[istart + 1] - v2s2[istart + 2] * 2. - v2s2[istart + 4]) * 2.; - } - } - else - { - this->v2rhosigma_drho_uu_.resize(nrxx); - this->v2rhosigma_drho_ud_.resize(nrxx); - this->v2rhosigma_drho_du_.resize(nrxx); - this->v2rhosigma_drho_dd_.resize(nrxx); - this->v2sigma2_drho_uu_u_.resize(nrxx); - this->v2sigma2_drho_uu_d_.resize(nrxx); - this->v2sigma2_drho_ud_u_.resize(nrxx); - this->v2sigma2_drho_ud_d_.resize(nrxx); - this->v2sigma2_drho_du_u_.resize(nrxx); - this->v2sigma2_drho_du_d_.resize(nrxx); - this->v2sigma2_drho_dd_u_.resize(nrxx); - this->v2sigma2_drho_dd_d_.resize(nrxx); + this->closed_shell_gga_s_.rho_sigma.resize(nrxx); + this->closed_shell_gga_s_.sigma_sigma.resize(nrxx); + this->closed_shell_gga_t_.rho_sigma.resize(nrxx); + this->closed_shell_gga_t_.sigma_sigma.resize(nrxx); #ifdef _OPENMP #pragma omp parallel for schedule(static, 4096) #endif for (int i = 0;i < nrxx;++i) { const int istart = i * 6; - this->v2rhosigma_drho_uu_[i] = gradrho[0][i] * v2rs[istart] * 2. + gradrho[1][i] * v2rs[istart + 1]; - this->v2rhosigma_drho_ud_[i] = gradrho[0][i] * v2rs[istart + 1] + gradrho[1][i] * v2rs[istart + 2] * 2.; - this->v2rhosigma_drho_du_[i] = gradrho[0][i] * v2rs[istart + 3] * 2. + gradrho[1][i] * v2rs[istart + 4]; - this->v2rhosigma_drho_dd_[i] = gradrho[0][i] * v2rs[istart + 4] + gradrho[1][i] * v2rs[istart + 5] * 2.; - this->v2sigma2_drho_uu_u_[i] = gradrho[0][i] * v2s2[istart] * 4. + gradrho[1][i] * v2s2[istart + 1] * 2.; - this->v2sigma2_drho_uu_d_[i] = gradrho[0][i] * v2s2[istart + 1] * 2. + gradrho[1][i] * v2s2[istart + 3]; - this->v2sigma2_drho_ud_u_[i] = gradrho[0][i] * v2s2[istart + 1] * 2. + gradrho[1][i] * v2s2[istart + 3]; - this->v2sigma2_drho_ud_d_[i] = gradrho[0][i] * v2s2[istart + 2] * 4. + gradrho[1][i] * v2s2[istart + 4] * 2.; - this->v2sigma2_drho_du_u_[i] = gradrho[1][i] * v2s2[istart + 2] * 4. + gradrho[0][i] * v2s2[istart + 1] * 2.; - this->v2sigma2_drho_du_d_[i] = gradrho[1][i] * v2s2[istart + 4] * 2. + gradrho[0][i] * v2s2[istart + 3]; - this->v2sigma2_drho_dd_u_[i] = gradrho[1][i] * v2s2[istart + 4] * 2. + gradrho[0][i] * v2s2[istart + 3]; - this->v2sigma2_drho_dd_d_[i] = gradrho[1][i] * v2s2[istart + 5] * 4. + gradrho[0][i] * v2s2[istart + 4] * 2.; + this->closed_shell_gga_s_.rho_sigma[i] = (v2rs[istart] + v2rs[istart + 1] + v2rs[istart + 2]) * 2.; + this->closed_shell_gga_s_.sigma_sigma[i] = (v2s2[istart] * 2. + v2s2[istart + 1] * 3. + v2s2[istart + 2] * 2. + v2s2[istart + 3] + v2s2[istart + 4]) * 2.; + this->closed_shell_gga_t_.rho_sigma[i] = (v2rs[istart] - v2rs[istart + 2]) * 2.; + this->closed_shell_gga_t_.sigma_sigma[i] = (v2s2[istart] * 2. + v2s2[istart + 1] - v2s2[istart + 2] * 2. - v2s2[istart + 4]) * 2.; } } + } else { @@ -485,10 +569,12 @@ void LR::KernelXC::f_xc_libxc(const int& nspin, const double& omega, const doubl if (nspin == 1 || (this->gxc_spin_ & GxcSpin::Singlet)) // Singlet or Bothspin { this->build_gxc_coef(this->gxc_s_, /*triplet=*/false, nspin, is_gga); + this->gxc_s_.built = true; } if (nspin == 2 && (this->gxc_spin_ & GxcSpin::Triplet)) // Triplet or Bothspin { this->build_gxc_coef(this->gxc_t_, /*triplet=*/true, nspin, is_gga); + this->gxc_t_.built = true; } } if (is_gga) @@ -605,7 +691,6 @@ void LR::KernelXC::build_gxc_coef(GxcCoef& dst, const bool triplet, const int& n const double mu[3] = { 1., triplet ? 0. : 1., triplet ? -1. : 1. }; const double nu[3] = { 1., triplet ? -1. : 1., 1. }; const double th[3] = { 2., 1., 0. }; - const double tht[3] = { 2., triplet ? -1. : 1., 0. }; dst.a_s2.resize(nrxx, 0.); if (is_gga) @@ -613,8 +698,6 @@ void LR::KernelXC::build_gxc_coef(GxcCoef& dst, const bool triplet, const int& n dst.a_st.resize(nrxx, 0.); dst.a_t2.resize(nrxx, 0.); dst.a_q.resize(nrxx, 0.); - dst.c_s.resize(nrxx, 0.); - dst.c_t.resize(nrxx, 0.); dst.e_s2.resize(nrxx); dst.e_st.resize(nrxx); dst.e_t2.resize(nrxx); @@ -656,12 +739,11 @@ void LR::KernelXC::build_gxc_coef(GxcCoef& dst, const bool triplet, const int& n dst.a_st[i] = to_singlet * v3r2s[i] * 4.; dst.a_t2[i] = to_singlet * v3rs2[i] * 4.; dst.a_q[i] = to_singlet * v2rs[i] * 2.; - dst.c_s[i] = to_singlet * v2rs[i] * 4.; - dst.c_t[i] = to_singlet * v2s2[i] * 8.; - dst.e_s2[i] = to_singlet * v3r2s[i] * 2.; - dst.e_st[i] = to_singlet * v3rs2[i] * 8.; - dst.e_t2[i] = to_singlet * v3s3[i] * 8.; - dst.e_q[i] = to_singlet * v2s2[i] * 4.; + const double sigma_jacobian = sigma_jacobian_.empty() ? 1.0 : sigma_jacobian_[i]; + dst.e_s2[i] = to_singlet * v3r2s[i] * 2. * sigma_jacobian; + dst.e_st[i] = to_singlet * v3rs2[i] * 8. * sigma_jacobian; + dst.e_t2[i] = to_singlet * v3s3[i] * 8. * sigma_jacobian; + dst.e_q[i] = to_singlet * v2s2[i] * 4. * sigma_jacobian; } return; } @@ -728,12 +810,10 @@ void LR::KernelXC::build_gxc_coef(GxcCoef& dst, const bool triplet, const int& n double Q = 0.; double R = 0.; double S = 0.; - double T = 0.; - double St = 0.; for (int a = 0;a < 3;++a) { - const double w = th[a]; - const double wt = tht[a]; + const double sigma_jacobian = sigma_jacobian_.empty() ? 1.0 : sigma_jacobian_[3 * i + a]; + const double w = th[a] * sigma_jacobian; if (w != 0.) { P += w * (eta[0] * eta[0] * v3r2s[o9 + 0 + a] @@ -756,20 +836,7 @@ void LR::KernelXC::build_gxc_coef(GxcCoef& dst, const bool triplet, const int& n S += w * nu[c] * v2s2[o6 + p2[a][c]]; } } - if (wt != 0.) - { - for (int sg = 0; sg < 2; ++sg) - { - T += wt * eta[sg] * v2rs[o6 + 3 * sg + a]; - } - for (int c = 0; c < 3; ++c) - { - St += wt * mu[c] * v2s2[o6 + p2[a][c]]; - } - } } - dst.c_s[i] = T * 2.; - dst.c_t[i] = St * 4.; dst.e_s2[i] = P; dst.e_st[i] = Q * 4.; dst.e_t2[i] = R * 4.; diff --git a/source/source_lcao/module_lr/potentials/xc_kernel.h b/source/source_lcao/module_lr/potentials/xc_kernel.h index c33ac488a6b..48dd50e091b 100644 --- a/source/source_lcao/module_lr/potentials/xc_kernel.h +++ b/source/source_lcao/module_lr/potentials/xc_kernel.h @@ -8,7 +8,6 @@ #include #include #define CREF(x) const std::vector& x = x##_ -#define CREF3(x) const std::vector>& x = x##_ namespace LR { /// libxc component layout for the spin-POLARIZED case, shared by the closed- and open-shell @@ -58,14 +57,37 @@ namespace LR constexpr int chan[2][3] = { {0, 1, -1}, {-1, 0, 1} }; } + /// Derivative of the local energy's sigma-channel partial derivative along a density + /// perturbation. Input coefficients are the packed LibXC arrays for ONE grid point; + /// density_response has two components and sigma_response has (uu, ud, dd). + /// The half-open spin range selects one input spin or both. Only structurally active + /// sigma channels are read, avoiding artificial zero-times-NaN contributions. + /// Used by the unrestricted second-order potential contraction. + inline double sigma_potential_derivative(const double* rho_sigma, const double* sigma_sigma, + const int channel, const double* density_response, const double* sigma_response, + const int first_spin, const int end_spin) + { + double response = 0.; + for (int spin = first_spin; spin < end_spin; ++spin) + { + response += rho_sigma[libxc_idx::rs(spin, channel)] * density_response[spin]; + } + for (int a = first_spin; a < end_spin + 1; ++a) + { + response += sigma_sigma[libxc_idx::p2[channel][a]] * sigma_response[a]; + } + return response; + } + /// @brief Calculate the exchange-correlation (XC) kernel ($f_{xc}=\delta^2E_xc/\delta\rho^2$) and store its components. class KernelXC { using Tvec = std::vector; - using Tvec3 = std::vector>; public: /// Which spin combinations of the $g^{xc}$ coefficient set (`GxcCoef`) to build. enum GxcSpin { NoGxc = 0, Singlet = 1, Triplet = 2, BothSpins = 3 }; + /// GS response starts from raw sigma; non-finite HSE coefficients trigger a reported fallback. + enum class Purpose { LinearResponse, GroundStateResponse }; KernelXC(const ModulePW::PW_Basis& rho_basis, const UnitCell& ucell, const Charge& chg_gs, @@ -75,6 +97,12 @@ namespace LR const std::vector& lr_init_xc_kernel, const bool openshell = false, const int gxc_spin = GxcSpin::NoGxc); + /// Explicit response role; GS response requests only second derivatives. + /// Density and grid are borrowed and never modified; their spin layouts must agree. + KernelXC(Purpose purpose, const ModulePW::PW_Basis& rho_basis, + const UnitCell& ucell, const Charge& chg_gs, const Parallel_Grid& pgrid, + const int& nspin, const std::string& kernel_name, + const std::vector& lr_init_xc_kernel, bool openshell, int gxc_spin); ~KernelXC() {} /// Metadata belongs to this coefficient set, independent of later global XC changes. @@ -91,17 +119,33 @@ namespace LR return kernel_name_; } + /// Construction metadata: true only after a collective HSE GS-response fallback. + /// This flags an approximate orbital Hessian; the SCF potential is unchanged. + bool gs_sigma_fallback_used() const { return gs_sigma_fallback_used_; } + // const references CREF(vrho);CREF(vsigma); CREF(v2rho2); CREF(v2rhosigma); CREF(v2sigma2); - CREF3(v2rhosigma_2drho); CREF3(v2sigma2_4drho); - CREF3(v2rhosigma_drho_singlet); CREF3(v2rhosigma_drho_triplet); CREF3(v2sigma2_drho_singlet);CREF3(v2sigma2_drho_triplet); - CREF3(v2rhosigma_drho_uu); CREF3(v2rhosigma_drho_ud); CREF3(v2rhosigma_drho_du); CREF3(v2rhosigma_drho_dd); - CREF3(v2sigma2_drho_uu_u); CREF3(v2sigma2_drho_uu_d); CREF3(v2sigma2_drho_ud_u); CREF3(v2sigma2_drho_ud_d); - CREF3(v2sigma2_drho_du_u); CREF3(v2sigma2_drho_du_d); CREF3(v2sigma2_drho_dd_u); CREF3(v2sigma2_drho_dd_d); CREF(v3rho3); CREF(v3rho2sigma); CREF(v3rhosigma2); CREF(v3sigma3); + /// Scalar mixed-density/gradient and gradient/gradient GGA response coefficients. + /// The common ground-state gradient is supplied by the potential contraction. + /// These same arrays supply the transition-gradient terms of gxc; no duplicate cache. + struct ClosedShellGga + { + Tvec rho_sigma; + Tvec sigma_sigma; + }; + const ClosedShellGga& closed_shell_gga(const bool triplet) const + { + if (openshell_) + { + throw std::logic_error("Closed-shell GGA coefficients requested for an open-shell kernel"); + } + return (nspin_ == 1 || !triplet) ? closed_shell_gga_s_ : closed_shell_gga_t_; + } + /// @brief The coefficients of /// $v^{(2)}(r)=\iint dr'dr''\,g^{xc}(r,r',r'')\rho^1(r')\rho^1(r'')$ /// for ONE spin combination, stored exactly as they appear in the final formula: @@ -110,7 +154,9 @@ namespace LR /// + (c_s\,s + c_t\,t)\,\nabla\rho^1\,]$ /// with $s=\rho^1$, $t=\nabla\rho\cdot\nabla\rho^1$, $q=\nabla\rho^1\cdot\nabla\rho^1$. /// - /// Every numeric factor and every spin sum is folded in here, so `PotGradXCLR::cal_v_eff` + /// The transition-gradient scalars c_s and c_t reuse ClosedShellGga (factor 2 for + /// nspin=2, factor 8 for singlet-normalized nspin=1). The other factors are folded + /// in here, so `PotGradXCLR::cal_v_eff` /// is a literal transcription of the formula with no arithmetic of its own, and nspin=1, /// singlet and triplet all run through the same code. For LDA only `a_s2` is filled. /// $v^{(2)} = A - \nabla\cdot E$ @@ -120,14 +166,13 @@ namespace LR /// divergence, this factorization no longer holds and they must go back to `Vector3`. struct GxcCoef { + /// Availability is independent of the number of points assigned to this rank. + bool built = false; // Local part A. std::vector a_s2; std::vector a_st; std::vector a_t2; std::vector a_q; - // Scalars multiplying the transition-density gradient. - std::vector c_s; - std::vector c_t; // Divergence coefficients, all multiplying the ground-state density gradient. std::vector e_s2; std::vector e_st; @@ -140,7 +185,7 @@ namespace LR const GxcCoef& gxc(const bool triplet) const { const GxcCoef& ret = (nspin_ == 1 || !triplet) ? gxc_s_ : gxc_t_; - if (ret.a_s2.empty()) + if (!ret.built) { throw std::runtime_error( "KernelXC: the " + std::string(triplet ? "triplet" : "singlet") @@ -149,6 +194,11 @@ namespace LR return ret; } + /// Componentwise derivative of prepared sigma; empty means identity. + /// Borrowed for the kernel lifetime, point-major: one component at nspin=1, + /// or (uu, ud, dd) at nspin=2. Only implicit coefficient derivatives use it. + const Tvec& sigma_jacobian() const { return sigma_jacobian_; } + const bool& openshell = openshell_; const std::vector>>& drho_gs = drho_gs_; /// Whether THIS kernel (built for its own functional name, which may differ from the @@ -188,28 +238,9 @@ namespace LR // std::map>> grad_kernel_set_;// [kernel_type][nrxx][nspin], intermediate terms for GGA // for nspin=1, gga std::vector>> drho_gs_; ///< $\nabla\rho$ of the ground state, size: nspin*nrxx - std::vector> v2rhosigma_2drho_; ///< $f^{\rho\sigma}*\nabla\rho *2$ - std::vector> v2sigma2_4drho_; ///< $f^{\sigma\sigma}*\nabla\rho *4$ - - // for nspin=2 (close-shell), gga kernels - Tvec3 v2rhosigma_drho_singlet_; ///< $2(f^{\rho_u\sigma_{uu}}+f^{\rho_u\sigma_{ud}}+f^{\rho_u\sigma_{dd}})*\nabla\rho)$ - Tvec3 v2rhosigma_drho_triplet_; ///< $2(f^{\rho_u\sigma_{uu}}-f^{\rho_u\sigma_{ud}})*\nabla\rho)$ - Tvec3 v2sigma2_drho_singlet_; /// < $(4f^{\sigma_{uu}\sigma_{uu}}+6f^{\sigma_{uu}\sigma_{ud}}+4f^{\sigma_{uu}\sigma_{dd}}+2f^{\sigma_{ud}\sigma_{ud}}+2f^{\sigma_{ud}\sigma_{dd}})\nabla\rho$ - Tvec3 v2sigma2_drho_triplet_; /// < $(4f^{\sigma_{uu}\sigma_{uu}}+2f^{\sigma_{uu}\sigma_{ud}}-4f^{\sigma_{uu}\sigma_{dd}}-2f^{\sigma_{ud}\sigma_{dd}})\nabla\rho$ - - // for nspin=2 (open shell), gga kernels - Tvec3 v2rhosigma_drho_uu_; ///< $2f^{\rho_u\sigma_{uu}}\nabla\rho_u+f^{\rho_u\sigma_{ud}}\nabla\rho_d$ - Tvec3 v2rhosigma_drho_ud_; ///< $f^{\rho_u\sigma_{ud}}\nabla\rho_u+2f^{\rho_u\sigma_{dd}}\nabla\rho_d$ - Tvec3 v2rhosigma_drho_du_; ///< $2f^{\rho_d\sigma_{uu}}\nabla\rho_u+f^{\rho_d\sigma_{ud}}\nabla\rho_d$ - Tvec3 v2rhosigma_drho_dd_; ///< $f^{\rho_d\sigma_{ud}}\nabla\rho_u+2f^{\rho_d\sigma_{dd}}\nabla\rho_d$ - Tvec3 v2sigma2_drho_uu_u_; /// $4f^{\sigma_{uu}\sigma_{uu}}\nabla\rho_u+2f^{\sigma_{uu}\sigma_{ud}\nabla\rho_d$ - Tvec3 v2sigma2_drho_uu_d_; /// $2f^{\sigma_{uu}\sigma_{ud}}\nabla\rho_u+f^{\sigma_{ud}\sigma_{ud}}\nabla\rho_d$ - Tvec3 v2sigma2_drho_ud_u_; /// $2f^{\sigma_{uu}\sigma_{ud}}\nabla\rho_u+f^{\sigma_{ud}\sigma_{ud}}\nabla\rho_d$ - Tvec3 v2sigma2_drho_ud_d_; /// $4f^{\sigma_{uu}\sigma_{dd}}\nabla\rho_u+2f^{\sigma_{ud}\sigma_{dd}\nabla\rho_d$ - Tvec3 v2sigma2_drho_du_u_; /// $4f^{\sigma_{uu}\sigma_{dd}}\nabla\rho_d+2f^{\sigma_{uu}\sigma_{ud}\nabla\rho_u$ - Tvec3 v2sigma2_drho_du_d_; /// $2f^{\sigma_{ud}\sigma_{dd}}\nabla\rho_d+f^{\sigma_{ud}\sigma_{ud}}\nabla\rho_u$ - Tvec3 v2sigma2_drho_dd_u_; /// $2f^{\sigma_{ud}\sigma_{dd}}\nabla\rho_d+f^{\sigma_{ud}\sigma_{ud}}\nabla\rho_u$ - Tvec3 v2sigma2_drho_dd_d_; /// $4f^{\sigma_{dd}\sigma_{dd}}\nabla\rho_d+2f^{\sigma_{ud}\sigma_{dd}\nabla\rho_u$ + ClosedShellGga closed_shell_gga_s_; + ClosedShellGga closed_shell_gga_t_; + // ================================== XC kernels ============================================ // ================================== XC kernel Gradiants ==================================== Tvec v3rho3_; @@ -228,6 +259,9 @@ namespace LR const std::string kernel_name_; int functional_type_ = 0; const int gxc_spin_ = GxcSpin::NoGxc; ///< which `GxcCoef` sets to build, see `GxcSpin` + const Purpose purpose_; + Tvec sigma_jacobian_; + bool gs_sigma_fallback_used_ = false; // ================================== XC kernel Gradiants ==================================== const ModulePW::PW_Basis& rho_basis_; const bool openshell_ = false; @@ -239,6 +273,13 @@ namespace LR const ModulePW::PW_Basis& rho_basis, const UnitCell& ucell, const Charge& chg_gs, const Parallel_Grid& pgrid, const int nspin, const bool openshell, const int gxc_spin, const std::vector& lr_init_xc_kernel); + /// Build immutable GS response from raw coefficients, retrying non-finite HSE with the LR floor. + /// Uses the supplied GS functional, density and grid, requesting no third derivatives. + std::shared_ptr build_gs_xc_kernel(const std::string& kernel_name, + const ModulePW::PW_Basis& rho_basis, const UnitCell& ucell, const Charge& chg_gs, + const Parallel_Grid& pgrid, int nspin, bool openshell, + const std::vector& lr_init_xc_kernel); + } #endif // ABACUS_SOURCE_LCAO_MODULE_LR_POTENTIALS_XC_KERNEL_H diff --git a/source/source_lcao/module_lr/unittests/CMakeLists.txt b/source/source_lcao/module_lr/unittests/CMakeLists.txt index 9bcc49191ca..19af6135dc3 100644 --- a/source/source_lcao/module_lr/unittests/CMakeLists.txt +++ b/source/source_lcao/module_lr/unittests/CMakeLists.txt @@ -2,19 +2,6 @@ if(ENABLE_MPI) set(test_zeqlin_solv_main ../../../source_base/test/mpi_test_main.cpp) endif() if(ENABLE_LIBXC) - addtest( - TARGET MODULE_LR_pot_hxc_lrtd - LIBS base parameter device container psi Libxc::xc - SOURCES test_pot_hxc_lrtd.cpp - ../potentials/pot_hxc_lrtd.cpp - ../kernel_pots.cpp - ../potentials/pot_grad_xc.cpp - ../potentials/xc_kernel.cpp - ../potentials/xc_kxc.cpp - ../utils/lr_util.cpp - ../../../source_hamilt/module_xc/xc_functional.cpp - ../../../source_hamilt/module_xc/libxc_setup.cpp) - addtest( TARGET MODULE_LR_xc_kxc LIBS Libxc::xc @@ -167,3 +154,55 @@ AddTest( TARGET MODULE_LR_spectrum_weights SOURCES test_spectrum_weights.cpp ) + +if(ENABLE_LIBXC) + addtest( + TARGET MODULE_LR_pot_hxc_lrtd + LIBS base parameter device container psi Libxc::xc + SOURCES test_pot_hxc_lrtd.cpp + ../potentials/pot_hxc_lrtd.cpp + ../kernel_pots.cpp + ../potentials/pot_grad_xc.cpp + ../potentials/xc_kernel.cpp + ../potentials/xc_kxc.cpp + ../utils/lr_util.cpp + ../../../source_hamilt/module_xc/xc_functional.cpp + ../../../source_hamilt/module_xc/libxc_setup.cpp) + + addtest( + TARGET MODULE_LR_xc_kernel + LIBS base parameter device container psi Libxc::xc + SOURCES test_xc_kernel.cpp + ../potentials/xc_kxc.cpp + ../potentials/xc_kernel.cpp + ../utils/lr_util.cpp + ../../../source_hamilt/module_xc/xc_functional.cpp + ../../../source_hamilt/module_xc/libxc_setup.cpp) + + addtest( + TARGET MODULE_LR_pot_grad_xc + LIBS base parameter device container psi Libxc::xc + SOURCES test_pot_grad_xc.cpp + ../potentials/pot_grad_xc.cpp + ../potentials/xc_kernel.cpp + ../potentials/xc_kxc.cpp + ../utils/lr_util.cpp + ../../../source_hamilt/module_xc/xc_functional.cpp + ../../../source_hamilt/module_xc/libxc_setup.cpp) + + if(ENABLE_MPI) + foreach(target MODULE_LR_pot_hxc_lrtd MODULE_LR_xc_kernel MODULE_LR_pot_grad_xc) + target_sources(${target} PRIVATE ../../../source_base/test/mpi_test_main.cpp) + endforeach() + add_test(NAME MODULE_LR_xc_kernel_parallel + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS} + --gtest_filter=KernelXCTest.HseGroundResponseFallback*:KernelXCTest.HseGroundResponseRetry*) + set_tests_properties(MODULE_LR_xc_kernel_parallel PROPERTIES PROCESSORS 4 TIMEOUT 120) + endif() +endif() + +AddTest( + TARGET MODULE_LR_window_response + SOURCES test_window_response_math.cpp ../window_response_math.cpp +) diff --git a/source/source_lcao/module_lr/unittests/test_pot_grad_xc.cpp b/source/source_lcao/module_lr/unittests/test_pot_grad_xc.cpp new file mode 100644 index 00000000000..edc225b277f --- /dev/null +++ b/source/source_lcao/module_lr/unittests/test_pot_grad_xc.cpp @@ -0,0 +1,426 @@ +#include "../potentials/pot_grad_xc.h" +#include "source_base/constants.h" +#include "source_base/matrix.h" +#include "source_hamilt/module_xc/libxc_abacus.h" +#include "source_hamilt/module_xc/xc_functional.h" +#include "source_io/module_output/cube_io.h" +#include +#include + +// Isolate the real LibXC contraction. The three-point periodic difference and +// divergence below are negative adjoints, so an independently differenced LR +// quadratic form tests the complete local-plus-divergence potential. +UnitCell::UnitCell() {} +UnitCell::~UnitCell() {} +Magnetism::Magnetism() {} +Magnetism::~Magnetism() {} +SepPot::SepPot() {} +SepPot::~SepPot() {} +Sep_Cell::Sep_Cell() noexcept {} +Sep_Cell::~Sep_Cell() noexcept {} +Charge::Charge() {} +Charge::~Charge() {} +namespace ModuleBase +{ +FFT_Bundle::~FFT_Bundle() {} +} // namespace ModuleBase +namespace ModulePW +{ +PW_Basis::PW_Basis() {} +PW_Basis::~PW_Basis() {} +void PW_Basis::initgrids(double, ModuleBase::Matrix3, double) {} +void PW_Basis::initgrids( + double, + ModuleBase::Matrix3, + int, + int, + int) +{ +} +void PW_Basis::distribute_r() {} +template +void PW_Basis::real2recip( + const T *in, + std::complex *out, + const bool, + const T) const +{ + for (int point = 0; point < npw; ++point) + { + out[point] = in[point]; + } +} +template void PW_Basis::real2recip( + const double *, + std::complex *, + bool, + double) const; +template +void PW_Basis::recip2real( + const std::complex *in, + std::complex *out, + const bool, + const T) const +{ + for (int point = 0; point < nrxx; ++point) + { + out[point] = in[point]; + } +} +template void PW_Basis::recip2real( + const std::complex *, + std::complex *, + bool, + double) const; +} // namespace ModulePW +void XC_Functional::grad_rho( + const std::complex *in, + ModuleBase::Vector3 *out, + const ModulePW::PW_Basis *basis, + const double tpiba) +{ + const ModuleBase::Vector3 direction(0.1, 0.2, 0.3); + for (int point = 0; point < basis->nrxx; ++point) + { + const int next = (point + 1) % basis->nrxx; + const int previous = (point + basis->nrxx - 1) % basis->nrxx; + const double difference = (in[next].real() - in[previous].real()) * tpiba; + out[point] = direction * difference; + } +} +void XC_Functional::grad_dot( + const ModuleBase::Vector3 *in, + double *out, + const ModulePW::PW_Basis *basis, + const double tpiba) +{ + const ModuleBase::Vector3 direction(0.1, 0.2, 0.3); + for (int point = 0; point < basis->nrxx; ++point) + { + const int next = (point + 1) % basis->nrxx; + const int previous = (point + basis->nrxx - 1) % basis->nrxx; + out[point] = ((in[next] - in[previous]) * direction) * tpiba; + } +} +namespace ModuleIO +{ +bool read_vdata_palgrid( + const Parallel_Grid &, + const int, + std::ostream &, + const std::string &, + double *const, + const int) +{ + throw std::logic_error("The isolated gradient test does not read coefficient files"); +} +} // namespace ModuleIO +namespace XC_Functional_Libxc +{ +std::vector cal_sgn( + const double, + const double, + const xc_func_type &, + const int nspin, + const std::size_t nrxx, + const std::vector &, + const std::vector &) +{ + return std::vector(nrxx * nspin, 1.0); +} +} // namespace XC_Functional_Libxc + +/** @brief Compare unrestricted GXC with a separate derivative of the LR quadratic form. */ +class PotGradXCTest : public testing::Test +{ + protected: + ModulePW::PW_Basis basis; + UnitCell cell; + Charge charge; + Parallel_Grid grid; + std::vector up; + std::vector down; + double *density[2]; + + void SetUp() override + { + basis.nrxx = 3; + basis.npw = 3; + basis.nmaxgr = 3; + cell.omega = 3.0; + cell.tpiba = 1.0; + charge.nrxx = 3; + up = {0.3, 0.3001, 0.2999}; + down = up; + density[0] = up.data(); + density[1] = down.data(); + charge.rho = density; + } + + /** @return Whether this installed HSE implementation advertises KXC. */ + bool has_hse_kxc() + { + XC_Functional::set_xc_type("hse"); + const double alpha = XC_Functional::get_hybrid_alpha(); + const double omega = XC_Functional::get_hse_omega(); + auto functions = XC_Functional_Libxc::init_func( + XC_Functional::get_func_id(), + XC_POLARIZED, + alpha, + omega); + bool available = true; + for (const auto &functional : functions) + { + available = available && (functional.info->flags & XC_FLAGS_HAVE_KXC) != 0; + } + XC_Functional_Libxc::finish_func(functions); + return available; + } + + /** @return Borrowed-grid kernel with explicit shell layout and derivative request. */ + std::shared_ptr kernel(const std::string &name, const bool open, const int gxc) + { + const std::vector initialization = {"default"}; + return std::make_shared( + basis, + cell, + charge, + grid, + 2, + name, + initialization, + open, + gxc); + } + + /** @return Discrete gradient with the same linear operator as the isolated FFT mock. */ + std::vector> gradient(const std::vector &values) const + { + std::vector> reciprocal(values.begin(), values.end()); + std::vector> result(3); + XC_Functional::grad_rho( + reciprocal.data(), + result.data(), + &basis, + cell.tpiba); + return result; + } + + /** + * @brief Independently evaluate the second-order LR quadratic form, without KXC. + * @param[in] name Functional for the evaluated LR kernel. + * @param[in] transition Two real transition-density channels on the three-point grid. + * @return Unweighted quadratic form in Hartree conventions. + */ + double quadratic(const std::string &name, const std::vector transition[2]) + { + const auto second = kernel(name, true, LR::KernelXC::NoGxc); + const auto first_gradient = gradient(transition[0]); + const auto second_gradient = gradient(transition[1]); + double result = 0.0; + for (int point = 0; point < 3; ++point) + { + const double u[2] = {transition[0][point], transition[1][point]}; + const auto &gu = second->drho_gs[0][point]; + const auto &gd = second->drho_gs[1][point]; + const auto &vu = first_gradient[point]; + const auto &vd = second_gradient[point]; + const double linear[3] = {2.0 * (gu * vu), gu * vd + gd * vu, 2.0 * (gd * vd)}; + const double quadratic_gradient[3] = {2.0 * (vu * vu), 2.0 * (vu * vd), 2.0 * (vd * vd)}; + for (int s = 0; s < 2; ++s) + { + for (int t = 0; t < 2; ++t) + { + result += second->v2rho2[3 * point + LR::libxc_idx::r2(s, t)] * u[s] * u[t]; + } + for (int a = 0; a < 3; ++a) + { + result += 2.0 * second->v2rhosigma[6 * point + 3 * s + a] * u[s] * linear[a]; + } + } + for (int a = 0; a < 3; ++a) + { + result += second->vsigma[3 * point + a] * quadratic_gradient[a]; + for (int b = 0; b < 3; ++b) + { + result += second->v2sigma2[6 * point + LR::libxc_idx::p2[a][b]] * linear[a] * linear[b]; + } + } + } + return result; + } +}; + +TEST_F(PotGradXCTest, UnrestrictedReducesToClosedShellWithClippedHse) +{ + if (!has_hse_kxc()) + { + GTEST_SKIP() << "Installed LibXC does not advertise HSE KXC"; + } + std::vector transition = {0.8, -0.4, 0.7}; + for (const std::string &name : {"pbe", "hse"}) + { + const auto closed = kernel(name, false, LR::KernelXC::BothSpins); + const auto open = kernel(name, true, LR::KernelXC::BothSpins); + for (const bool triplet : {false, true}) + { + std::vector second = transition; + if (triplet) + { + for (double &value : second) + { + value = -value; + } + } + double *channels[2] = {transition.data(), second.data()}; + LR::PotGradXCLR reference( + *closed, + basis, + cell, + 3, + 2, + triplet); + LR::PotGradXCLR candidate( + *open, + basis, + cell, + 3, + 2, + false); + ModuleBase::matrix expected(1, 3); + reference.cal_v_eff(channels, cell, expected); + // Closed-shell coefficients pin the free derivative index to up. + // Compare that same contraction strictly. Both free-spin derivatives + // are independently checked by the quadratic-form FD test below. + const int tau = 0; + ModuleBase::matrix actual(1, 3); + candidate.cal_v_eff_openshell( + channels, + cell, + actual, + tau); + for (int point = 0; point < 3; ++point) + { + EXPECT_NEAR(actual(0, point), expected(0, point), 1e-11) + << name << " tau=" << tau << " triplet=" << triplet; + } + } + } +} + +TEST_F(PotGradXCTest, UnrestrictedHseMatchesIndependentQuadraticFiniteDifference) +{ + if (!has_hse_kxc()) + { + GTEST_SKIP() << "Installed LibXC does not advertise HSE KXC"; + } + const std::vector transition[2] = {{0.8, -0.4, 0.7}, {-0.5, 0.6, 0.3}}; + const double perturbation[3] = {0.4, -0.3, 0.2}; + for (const double orientation : {1.0, -1.0}) + { + up = {0.3, 0.4, 0.2}; + down = {0.18, 0.18 + orientation * 0.005, 0.18 - orientation * 0.005}; + density[0] = up.data(); + density[1] = down.data(); + cell.tpiba = 0.1; + const auto coefficients = kernel("hse", true, LR::KernelXC::BothSpins); + const double *channels[2] = {transition[0].data(), transition[1].data()}; + LR::PotGradXCLR potential( + *coefficients, + basis, + cell, + 3, + 2, + false); + for (int tau = 0; tau < 2; ++tau) + { + ModuleBase::matrix derivative(1, 3); + potential.cal_v_eff_openshell( + channels, + cell, + derivative, + tau); + double analytic = 0.0; + for (int point = 0; point < 3; ++point) + { + analytic += derivative(0, point) * perturbation[point] / ModuleBase::e2; + } + std::vector &varied = tau == 0 ? up : down; + const std::vector original = varied; + for (const double h : {1e-4, 5e-5}) + { + for (int point = 0; point < 3; ++point) + { + varied[point] = original[point] + h * perturbation[point]; + } + const double plus = quadratic("hse", transition); + for (int point = 0; point < 3; ++point) + { + varied[point] = original[point] - h * perturbation[point]; + } + const double minus = quadratic("hse", transition); + for (int point = 0; point < 3; ++point) + { + varied[point] = original[point]; + } + const double finite_difference = (plus - minus) / (2.0 * h); + const double tolerance = 2e-8 + 2e-8 * std::abs(finite_difference); + EXPECT_NEAR(analytic, finite_difference, tolerance) + << "tau=" << tau << " orientation=" << orientation << " h=" << h; + } + } + } +} + +TEST_F(PotGradXCTest, EmptyLocalGridPreservesEmptySpinChannels) +{ + basis.nrxx = 0; + basis.npw = 0; + basis.nmaxgr = 0; + charge.nrxx = 0; + const auto coefficients = kernel("pbe", true, LR::KernelXC::BothSpins); + LR::PotGradXCLR potential( + *coefficients, + basis, + cell, + 0, + 2, + false); + const double *channels[2] = {nullptr, nullptr}; + for (int tau = 0; tau < 2; ++tau) + { + ModuleBase::matrix result(1, 0); + EXPECT_NO_THROW(potential.cal_v_eff_openshell( + channels, + cell, + result, + tau)); + EXPECT_EQ(result.nc, 0); + } +} + + +TEST_F(PotGradXCTest, EmptyClosedShellGridRetainsRequestedCoefficients) +{ + basis.nrxx = 0; + basis.npw = 0; + basis.nmaxgr = 0; + charge.nrxx = 0; + const std::vector initialization = {"default"}; + for (const std::string name : {"lda", "pbe"}) + { + for (const int spins : {1, 2}) + { + const auto coefficients = LR::build_xc_kernel(name, basis, cell, charge, + grid, spins, false, LR::KernelXC::BothSpins, initialization); + double* channels[2] = {nullptr, nullptr}; + for (const bool triplet : {false, true}) + { + LR::PotGradXCLR potential(*coefficients, basis, cell, 0, spins, triplet); + ModuleBase::matrix result(1, 0); + EXPECT_NO_THROW(potential.cal_v_eff(channels, cell, result)); + EXPECT_EQ(result.nc, 0); + } + } + } +} diff --git a/source/source_lcao/module_lr/unittests/test_pot_hxc_lrtd.cpp b/source/source_lcao/module_lr/unittests/test_pot_hxc_lrtd.cpp index 12c08a3fa44..4c8f1dd4522 100644 --- a/source/source_lcao/module_lr/unittests/test_pot_hxc_lrtd.cpp +++ b/source/source_lcao/module_lr/unittests/test_pot_hxc_lrtd.cpp @@ -1,4 +1,6 @@ #include +#include +#include "source_base/constants.h" #include "../kernel_pots.h" #include "../potentials/pot_grad_xc.h" #include "source_io/module_parameter/input_parameter.h" @@ -7,6 +9,12 @@ #include "source_hamilt/module_xc/libxc_abacus.h" #include "source_io/module_output/cube_io.h" +namespace +{ +ModuleBase::Vector3 last_gga_divergence; +bool asymmetric_test_gradients = false; +} + // Keep the real kernel/LibXC and potential code. Mock geometry ownership, FFTs, // external coefficient-file input, and grid masks: exercise binding and metadata. UnitCell::UnitCell() {} @@ -46,14 +54,21 @@ void PW_Basis::recip2real(const std::complex* in, std::complex* out, const template void PW_Basis::recip2real(const std::complex*, std::complex*, bool, double) const; } -void XC_Functional::grad_rho(const std::complex*, ModuleBase::Vector3* out, +void XC_Functional::grad_rho(const std::complex* in, ModuleBase::Vector3* out, const ModulePW::PW_Basis*, const double) { out[0] = ModuleBase::Vector3(0.1, 0.2, 0.3); + if (asymmetric_test_gradients && in[0].real() < 0.25) + { + out[0] = (in[0].real() > 0.15) + ? ModuleBase::Vector3(-0.3, 0.1, 0.05) + : ModuleBase::Vector3(0.2, -0.15, 0.4); + } } -void XC_Functional::grad_dot(const ModuleBase::Vector3*, double* out, +void XC_Functional::grad_dot(const ModuleBase::Vector3* in, double* out, const ModulePW::PW_Basis*, const double) { + last_gga_divergence = in[0]; out[0] = 0.; } namespace ModuleIO @@ -88,6 +103,7 @@ class PotHxcLRTest : public testing::Test std::vector init = {"default"}; void SetUp() override { + asymmetric_test_gradients = false; basis.nrxx = 1; basis.npw = 1; basis.nmaxgr = 1; @@ -315,3 +331,208 @@ TEST_F(PotHxcLRTest, ScopedGsTypeRestoresLibxcBackend) EXPECT_EQ(XC_Functional::get_func_id(), ids); EXPECT_EQ(XC_Functional::output_info(), description); } + +TEST_F(PotHxcLRTest, ScalarTripletMatchesPolarizedClosedShellResponse) +{ + Input_para input; + input.cal_force = true; + input.lr_target_spin = "triplet"; + input.lr_init_xc_kernel = init; + for (const std::string functional : {"lda", "pbe", "hf"}) + { + input.dft_functional = functional; + charge.nspin = 1; + up = 0.6; + const auto scalar = LR::prepare_lr_potentials(input, functional, + basis, cell, charge, grid, 1, false); + ASSERT_EQ(scalar.pot.size(), 1); + EXPECT_EQ(scalar.kernel->nspin(), 2); + const auto gs = LR::prepare_gs_potential(input, functional, + basis, cell, charge, grid, 1, false, scalar); + EXPECT_EQ(gs->xc_kernel_components().nspin(), 1); + EXPECT_NE(&gs->xc_kernel_components(), scalar.kernel.get()); + charge.nspin = 2; + up = 0.3; + down = 0.3; + const auto polarized = LR::prepare_lr_potentials(input, functional, + basis, cell, charge, grid, 2, false); + EXPECT_EQ(scalar.kernel->v2rho2, polarized.kernel->v2rho2); + ModuleBase::matrix actual(1, 1); + ModuleBase::matrix expected(1, 1); + scalar.pot[0]->cal_v_eff(density, cell, actual); + polarized.pot[1]->cal_v_eff(density, cell, expected); + EXPECT_DOUBLE_EQ(actual(0, 0), expected(0, 0)); + if (functional == "hf") + { + EXPECT_DOUBLE_EQ(actual(0, 0), 0.0); + continue; + } + // Equal spin densities do not imply f_uu = f_ud: the triplet XC response survives. + EXPECT_NE(actual(0, 0), 0.0); + LR::PotGradXCLR scalar_grad(*scalar.kernel, basis, cell, 1, 2, true); + LR::PotGradXCLR polarized_grad(*polarized.kernel, basis, cell, 1, 2, true); + actual.zero_out(); + expected.zero_out(); + scalar_grad.cal_v_eff(density, cell, actual); + polarized_grad.cal_v_eff(density, cell, expected); + EXPECT_DOUBLE_EQ(actual(0, 0), expected(0, 0)); + } +} + +TEST_F(PotHxcLRTest, ScalarTripletRequiresSpinResolvedKernelFiles) +{ + Input_para input; + input.lr_target_spin = "triplet"; + input.lr_init_xc_kernel = {"file", "scalar"}; + charge.nspin = 1; + EXPECT_THROW(LR::prepare_lr_potentials(input, "lda", basis, cell, charge, grid, 1, false), + std::invalid_argument); + input.lr_init_xc_kernel = {"file", "uu", "ud", "dd"}; + const auto prepared = LR::prepare_lr_potentials(input, "lda", basis, cell, charge, grid, 1, false); + EXPECT_EQ(prepared.kernel->v2rho2.size(), 3); +} + +TEST_F(PotHxcLRTest, ClosedShellScalarReuseMatchesIndependentGxcContractions) +{ + down = up; + for (const int nspin : {1, 2}) + { + const auto kernel = LR::build_xc_kernel("pbe", basis, cell, charge, grid, + nspin, false, LR::KernelXC::BothSpins, init); + const int spin_cases = (nspin == 1) ? 1 : 2; + for (int spin = 0; spin < spin_cases; ++spin) + { + const bool triplet = (spin == 1); + const auto& scalar = kernel->closed_shell_gga(triplet); + ASSERT_EQ(scalar.rho_sigma.size(), 1u); + ASSERT_EQ(scalar.sigma_sigma.size(), 1u); + const auto& g = kernel->gxc(triplet); + const double eta[2] = {1., triplet ? -1. : 1.}; + const double mu[3] = {1., triplet ? 0. : 1., triplet ? -1. : 1.}; + const double weight[3] = {2., triplet ? -1. : 1., 0.}; + double cs = 0.; + double ct = 0.; + if (nspin == 1) + { + EXPECT_DOUBLE_EQ(scalar.rho_sigma[0], 2. * kernel->v2rhosigma[0]); + EXPECT_DOUBLE_EQ(scalar.sigma_sigma[0], 4. * kernel->v2sigma2[0]); + cs = 16. * kernel->v2rhosigma[0]; + ct = 32. * kernel->v2sigma2[0]; + } + else + { + for (int a = 0; a < 3; ++a) + { + for (int b = 0; b < 2; ++b) + { + cs += 2. * weight[a] * eta[b] * kernel->v2rhosigma[3 * b + a]; + } + for (int b = 0; b < 3; ++b) + { + ct += 4. * weight[a] * mu[b] * kernel->v2sigma2[LR::libxc_idx::p2[a][b]]; + } + } + EXPECT_NEAR(2. * scalar.rho_sigma[0], cs, 1e-11); + EXPECT_NEAR(2. * scalar.sigma_sigma[0], ct, 1e-11); + } + LR::PotGradXCLR potential(*kernel, basis, cell, 1, nspin, triplet); + ModuleBase::matrix result(1, 1); + potential.cal_v_eff(density, cell, result); + const auto& dg = kernel->drho_gs[0][0]; + const ModuleBase::Vector3 dx(0.1, 0.2, 0.3); + const double t = dg * dx; + const double q = dx * dx; + const double e = g.e_s2[0] * up * up + g.e_st[0] * up * t + + g.e_t2[0] * t * t + g.e_q[0] * q; + const auto expected = -(dg * e + dx * (cs * up + ct * t)); + EXPECT_NEAR(last_gga_divergence.x, expected.x, 1e-11); + EXPECT_NEAR(last_gga_divergence.y, expected.y, 1e-11); + EXPECT_NEAR(last_gga_divergence.z, expected.z, 1e-11); + } + } +} + +TEST_F(PotHxcLRTest, HseGroundResponseDoesNotReuseLrSigmaFloor) +{ + Input_para input; + input.dft_functional = "hse"; + input.lr_init_xc_kernel = init; + for (const int spins : {1, 2}) + { + const auto prepared = LR::prepare_lr_potentials(input, input.dft_functional, + basis, cell, charge, grid, spins, false); + const auto gs = LR::prepare_gs_potential(input, input.dft_functional, + basis, cell, charge, grid, spins, false, prepared); + EXPECT_NE(&gs->xc_kernel_components(), prepared.kernel.get()); + EXPECT_EQ(gs->xc_kernel_components().nspin(), spins); + EXPECT_TRUE(gs->xc_kernel_components().v3rho3.empty()); + } +} + +TEST_F(PotHxcLRTest, UnrestrictedScalarContractionPreservesAllSpinBlocks) +{ + asymmetric_test_gradients = true; + basis.ig_gge0 = 0; + const auto kernel = LR::build_xc_kernel("pbe", basis, cell, charge, grid, + 2, true, LR::KernelXC::BothSpins, init); + LR::PotHxcLR potential(kernel, basis, cell, 1, 2, LR::PotHxcLR::S2_updown); + const auto& gu = kernel->drho_gs[0][0]; + const auto& gd = kernel->drho_gs[1][0]; + const auto gradient_cross = ModuleBase::cross(gu, gd); + EXPECT_GT(gradient_cross.norm(), 0.01); + const ModuleBase::Vector3 zero(0., 0., 0.); + const ModuleBase::Vector3 sigma_gradient[2][3] = { + {gu * 2., gd, zero}, {zero, gu, gd * 2.}}; + const ModuleBase::Vector3 perturbation_gradient(0.2, -0.15, 0.4); + double perturbation = 0.07; + double* response[1] = {&perturbation}; + for (int output = 0; output < 2; ++output) + { + for (int input = 0; input < 2; ++input) + { + ModuleBase::matrix result(1, 1); + const std::vector block = {output, input}; + potential.cal_v_eff(response, cell, result, block); + ModuleBase::Vector3 mixed_divergence(0., 0., 0.); + ModuleBase::Vector3 mixed_local(0., 0., 0.); + ModuleBase::Vector3 hessian_action(0., 0., 0.); + for (int a = 0; a < 3; ++a) + { + mixed_divergence += sigma_gradient[output][a] * kernel->v2rhosigma[3 * input + a]; + mixed_local += sigma_gradient[input][a] * kernel->v2rhosigma[3 * output + a]; + for (int b = 0; b < 3; ++b) + { + const double coefficient = kernel->v2sigma2[LR::libxc_idx::p2[a][b]]; + const double contraction = sigma_gradient[input][b] * perturbation_gradient; + hessian_action += sigma_gradient[output][a] * (coefficient * contraction); + } + } + const int component = (output == input) ? 2 * output : 1; + const double multiplicity = (output == input) ? 2. : 1.; + hessian_action += perturbation_gradient * (multiplicity * kernel->vsigma[component]); + const auto expected = -(mixed_divergence * perturbation + hessian_action); + EXPECT_NEAR(last_gga_divergence.x, expected.x, 1e-12); + EXPECT_NEAR(last_gga_divergence.y, expected.y, 1e-12); + EXPECT_NEAR(last_gga_divergence.z, expected.z, 1e-12); + const double local = kernel->v2rho2[output + input] * perturbation + + mixed_local * perturbation_gradient; + EXPECT_NEAR(result(0, 0), ModuleBase::e2 * local, 1e-12); + } + } + asymmetric_test_gradients = false; +} + +TEST_F(PotHxcLRTest, UnrestrictedBlockDoesNotReadInactiveScalarComponents) +{ + const double nan = std::numeric_limits::quiet_NaN(); + const double rho_sigma[6] = {1., 2., 3., nan, nan, nan}; + const double sigma_sigma[6] = {4., 5., nan, 6., nan, nan}; + const double density_response[2] = {0.2, 0.}; + const double sigma_response[3] = {0.1, 0.3, 0.}; + const double first = LR::sigma_potential_derivative( + rho_sigma, sigma_sigma, 0, density_response, sigma_response, 0, 1); + const double second = LR::sigma_potential_derivative( + rho_sigma, sigma_sigma, 1, density_response, sigma_response, 0, 1); + EXPECT_DOUBLE_EQ(first, 0.2 + 0.4 + 1.5); + EXPECT_DOUBLE_EQ(second, 0.4 + 0.5 + 1.8); +} diff --git a/source/source_lcao/module_lr/unittests/test_window_response_math.cpp b/source/source_lcao/module_lr/unittests/test_window_response_math.cpp new file mode 100644 index 00000000000..5ae99ca3c64 --- /dev/null +++ b/source/source_lcao/module_lr/unittests/test_window_response_math.cpp @@ -0,0 +1,109 @@ +#include +#include "../window_response_math.h" +#include +#include + +TEST(WindowResponse, MovingGeneralizedEigenvectorMatchesFiniteDifference) +{ + const double eps[] = {0.7, 2.3}; + const double X[] = {1.0, 0.0}; + const double AX[] = {1.1, 0.31}; + const auto W = LR::window_multipliers(1, 2, 1, eps, X, AX); + // Generalized F c = S c eps, with off-diagonal F'=0.23, S'=0.17. + // The truncated excitation includes a fixed AO kernel K. + const auto energy = [](const double t) + { + const double b = 0.23 * t; + const double s = 0.17 * t; + const double qa = 1.0 - s * s; + const double qb = -(0.7 + 2.3) + 2.0 * b * s; + const double qc = 0.7 * 2.3 - b * b; + const double eig = (-qb - std::sqrt(qb * qb - 4.0 * qa * qc)) / (2.0 * qa); + const double ratio = -(b - eig * s) / (2.3 - eig); + const double norm = 1.0 + 2.0 * s * ratio + ratio * ratio; + return eig + (0.4 + 2.0 * 0.31 * ratio + 0.2 * ratio * ratio) / norm; + }; + const double step = 1e-5; + const double fd = (energy(step) - energy(-step)) / (2.0 * step); + EXPECT_NEAR(W[1] * (0.23 - eps[0] * 0.17), fd, 1e-10); + EXPECT_EQ(W[0], 0.0); + EXPECT_EQ(W[2], 0.0); + EXPECT_EQ(W[3], 0.0); +} + +TEST(WindowResponse, FullWindowVanishesAndDegenerateBoundaryIsRejected) +{ + const double eps[] = {1.0, 1.0}; + const double X[] = {1.0, 0.0}; + const double AX[] = {1.0, 0.3}; + EXPECT_THROW(LR::window_multipliers(1, 2, 1, eps, X, AX), std::runtime_error); + const auto W = LR::window_multipliers(1, 2, 2, eps, X, AX); + for (const double value : W) + { + EXPECT_EQ(value, 0.0); + } +} + +TEST(WindowResponse, QuadraticAndIndependentOfAmplitudePhase) +{ + const double eps[] = {1.0, 2.0, 3.0}; + const double X[] = {0.3, 0.4, 0.0, 0.5, 0.2, 0.0}; + const double AX[] = {0.1, 0.2, 0.6, 0.3, 0.4, -0.7}; + double scaled_x[6]; + double scaled_ax[6]; + for (int i = 0; i < 6; ++i) + { + scaled_x[i] = -2.0 * X[i]; + scaled_ax[i] = -2.0 * AX[i]; + } + const auto W = LR::window_multipliers(2, 3, 2, eps, X, AX); + const auto scaled_w = LR::window_multipliers(2, 3, 2, eps, scaled_x, scaled_ax); + for (int i = 0; i < 9; ++i) + { + EXPECT_NEAR(scaled_w[i], 4.0 * W[i], 1e-15); + } +} + + +TEST(WindowResponse, CoupledSpinEnergyUsesJointNormalization) +{ + const double up_eps[] = {0.7, 2.3}; + const double down_eps[] = {0.9, 3.1}; + // The retained 2x2 Casida matrix has eigenvalue 1 and vector (0.6, 0.8). + const double up_x[] = {0.6, 0.0}; + const double down_x[] = {0.8, 0.0}; + const double up_ax[] = {0.6, 0.31 * 0.6 - 0.17 * 0.8}; + const double down_ax[] = {0.8, 0.23 * 0.6 - 0.29 * 0.8}; + const auto up_w = LR::window_multipliers(1, 2, 1, up_eps, up_x, up_ax); + const auto down_w = LR::window_multipliers(1, 2, 1, down_eps, down_x, down_ax); + const auto orbital = [](const double t, const double e0, const double e1, + const double fprime, const double sprime) + { + const double b = fprime * t; + const double s = sprime * t; + const double qa = 1.0 - s * s; + const double qb = -(e0 + e1) + 2.0 * b * s; + const double qc = e0 * e1 - b * b; + const double eig = (-qb - std::sqrt(qb * qb - 4.0 * qa * qc)) / (2.0 * qa); + const double ratio = -(b - eig * s) / (e1 - eig); + const double norm = std::sqrt(1.0 + 2.0 * s * ratio + ratio * ratio); + return std::vector{eig, 1.0 / norm, ratio / norm}; + }; + const auto energy = [&orbital](const double t) + { + const auto u = orbital(t, 0.7, 2.3, 0.23, 0.17); + const auto d = orbital(t, 0.9, 3.1, -0.19, 0.11); + const double auu = u[0] + 1.1 * u[1] * u[1] + 0.62 * u[1] * u[2] + 0.2 * u[2] * u[2]; + const double add = d[0] + 0.55 * d[1] * d[1] - 0.58 * d[1] * d[2] + 0.4 * d[2] * d[2]; + const double aud = -0.6 * u[1] * d[1] + 0.23 * u[1] * d[2] + - 0.17 * u[2] * d[1] + 0.1 * u[2] * d[2]; + const double delta = auu - add; + return 0.5 * (auu + add - std::sqrt(delta * delta + 4.0 * aud * aud)); + }; + const double analytic = up_w[1] * (0.23 - up_eps[0] * 0.17) + + down_w[1] * (-0.19 - down_eps[0] * 0.11); + const double step = 1e-5; + const double fd = (energy(step) - energy(-step)) / (2.0 * step); + EXPECT_NEAR(energy(0.0), 1.0, 1e-14); + EXPECT_NEAR(analytic, fd, 1e-10); +} diff --git a/source/source_lcao/module_lr/unittests/test_xc_kernel.cpp b/source/source_lcao/module_lr/unittests/test_xc_kernel.cpp new file mode 100644 index 00000000000..c8ed7211a17 --- /dev/null +++ b/source/source_lcao/module_lr/unittests/test_xc_kernel.cpp @@ -0,0 +1,456 @@ +#include "../potentials/xc_kernel.h" +#include "../utils/lr_util.h" +#include "source_hamilt/module_xc/libxc_abacus.h" +#include "source_hamilt/module_xc/xc_functional.h" +#include "source_io/module_output/cube_io.h" +#include +#include "source_base/parallel_cell.h" +#include + +// Keep the actual LibXC evaluation and coefficient construction. Geometry ownership, +// FFTs and grid masks are isolated; no local grid point may be accessed on an empty rank. +UnitCell::UnitCell() {} +UnitCell::~UnitCell() {} +Magnetism::Magnetism() {} +Magnetism::~Magnetism() {} +SepPot::SepPot() {} +SepPot::~SepPot() {} +Sep_Cell::Sep_Cell() noexcept {} +Sep_Cell::~Sep_Cell() noexcept {} +Charge::Charge() {} +Charge::~Charge() {} + +namespace ModuleBase +{ +FFT_Bundle::~FFT_Bundle() {} +} // namespace ModuleBase + +namespace ModulePW +{ +PW_Basis::PW_Basis() {} +PW_Basis::~PW_Basis() {} +void PW_Basis::initgrids(double, ModuleBase::Matrix3, double) {} +void PW_Basis::initgrids( + double, + ModuleBase::Matrix3, + int, + int, + int) +{ +} +void PW_Basis::distribute_r() {} +template +void PW_Basis::real2recip( + const T *in, + std::complex *out, + const bool, + const T) const +{ + for (int point = 0; point < npw; ++point) + { + out[point] = in[point]; + } +} +template void PW_Basis::real2recip( + const double *, + std::complex *, + bool, + double) const; +template +void PW_Basis::recip2real( + const std::complex *in, + std::complex *out, + const bool, + const T) const +{ + for (int point = 0; point < nrxx; ++point) + { + out[point] = in[point]; + } +} +template void PW_Basis::recip2real( + const std::complex *, + std::complex *, + bool, + double) const; +} // namespace ModulePW + +void XC_Functional::grad_rho( + const std::complex *, + ModuleBase::Vector3 *out, + const ModulePW::PW_Basis *basis, + const double tpiba) +{ + for (int point = 0; point < basis->nrxx; ++point) + { + out[point] = ModuleBase::Vector3(0.1, 0.2, 0.3) * tpiba; + } +} +void XC_Functional::grad_dot( + const ModuleBase::Vector3 *, + double *out, + const ModulePW::PW_Basis *basis, + const double) +{ + for (int point = 0; point < basis->nrxx; ++point) + { + out[point] = 0.0; + } +} +namespace ModuleIO +{ +bool read_vdata_palgrid( + const Parallel_Grid &, + const int, + std::ostream &, + const std::string &, + double *const, + const int) +{ + throw std::logic_error("This coefficient test does not read kernel files"); +} +} // namespace ModuleIO +namespace XC_Functional_Libxc +{ +std::vector cal_sgn( + const double, + const double, + const xc_func_type &, + const int nspin, + const std::size_t nrxx, + const std::vector &, + const std::vector &) +{ + return std::vector(nrxx * nspin, 1.0); +} +} // namespace XC_Functional_Libxc + +/** @brief Exercise coefficient availability with real LibXC on zero or one local grid point. */ +class KernelXCTest : public testing::Test +{ + protected: + ModulePW::PW_Basis basis; + UnitCell cell; + Charge charge; + Parallel_Grid grid; + double density_value = 0.3; + double *density[2] = {&density_value, &density_value}; + + void SetUp() override + { + basis.nrxx = 0; + basis.npw = 0; + basis.nmaxgr = 0; + cell.omega = 1.0; + cell.tpiba = 1.0; + charge.nrxx = 0; + charge.rho = density; + } + + std::shared_ptr build(const std::string &name, const int spins, const int requested) + { + const std::vector initialization = {"default"}; + return LR::build_xc_kernel( + name, + basis, + cell, + charge, + grid, + spins, + false, + requested, + initialization); + } + + /** + * @brief Respect the installed LibXC HSE derivative capability in coefficient tests. + * @param[in] spins Native spin-component count, one or two. + * @return Whether every HSE component advertises third derivatives. + */ + bool hse_has_kxc(const int spins) + { + XC_Functional::set_xc_type("hse"); + const int polarization = spins == 1 ? XC_UNPOLARIZED : XC_POLARIZED; + const double alpha = XC_Functional::get_hybrid_alpha(); + const double omega = XC_Functional::get_hse_omega(); + auto functions = XC_Functional_Libxc::init_func( + XC_Functional::get_func_id(), + polarization, + alpha, + omega); + bool available = true; + for (const auto &functional : functions) + { + available = available && (functional.info->flags & XC_FLAGS_HAVE_KXC) != 0; + } + XC_Functional_Libxc::finish_func(functions); + return available; + } +}; + +TEST_F(KernelXCTest, HseGroundResponseUsesUnmodifiedSigma) +{ + basis.nrxx = 1; + basis.npw = 1; + basis.nmaxgr = 1; + charge.nrxx = 1; + cell.tpiba = 0.001; + const std::vector initialization = {"default"}; + const auto ground = LR::build_gs_xc_kernel( + "hse", + basis, + cell, + charge, + grid, + 1, + false, + initialization); + const auto response = build("hse", 1, LR::KernelXC::NoGxc); + const auto gradient = ModuleBase::Vector3(0.1, 0.2, 0.3) * cell.tpiba; + const double sigma = gradient * gradient; + const double alpha = XC_Functional::get_hybrid_alpha(); + const double omega = XC_Functional::get_hse_omega(); + auto functions = XC_Functional_Libxc::init_func( + XC_Functional::get_func_id(), + XC_UNPOLARIZED, + alpha, + omega); + ASSERT_EQ(functions.size(), 1); + double frr = 0.0; + double frs = 0.0; + double fss = 0.0; + xc_func_set_dens_threshold(&functions[0], 1e-14); + xc_gga_fxc( + &functions[0], + 1, + &density_value, + &sigma, + &frr, + &frs, + &fss); + XC_Functional_Libxc::finish_func(functions); + EXPECT_FALSE(ground->gs_sigma_fallback_used()); + EXPECT_DOUBLE_EQ(ground->v2rho2[0], frr); + EXPECT_DOUBLE_EQ(ground->v2rhosigma[0], frs); + EXPECT_DOUBLE_EQ(ground->v2sigma2[0], fss); + EXPECT_NE(ground->v2rhosigma[0], response->v2rhosigma[0]); + EXPECT_THROW(ground->gxc(false), std::runtime_error); + EXPECT_THROW( + LR::KernelXC( + LR::KernelXC::Purpose::GroundStateResponse, + basis, + cell, + charge, + grid, + 1, + "hse", + initialization, + false, + LR::KernelXC::Singlet), + std::invalid_argument); +} + +// A genuine LibXC HSE small-gradient failure. Only one rank has points; all ranks +// must retry together, including empty ranks. Compare every spin coefficient with +// a separately evaluated floored LR kernel, including finite raw entries. +TEST_F(KernelXCTest, HseGroundResponseFallbackIncludesEmptyRanksAndAllSpinBlocks) +{ + const auto domain = ModuleBase::world_comm_domain(); + const int candidate_rank = domain.rank(); + for (const int spins : {1, 2}) + { + const bool owns_points = candidate_rank == 0; + basis.nrxx = owns_points ? 1 : 0; + basis.npw = basis.nrxx; + basis.nmaxgr = basis.nrxx; + charge.nrxx = basis.nrxx; + cell.tpiba = 0.; // The fixture's mock gradient is zero: sigma = 0. + const std::vector initialization = {"default"}; + const auto ground = LR::build_gs_xc_kernel( + "hse", basis, cell, charge, grid, spins, false, initialization); + const auto floored = build("hse", spins, LR::KernelXC::NoGxc); + // A library with a corrected sigma=0 evaluation need not take the fallback. + // The installed KXC-enabled LibXC 5.2.3 exercises it for both spin layouts. + if (!ground->gs_sigma_fallback_used()) + { + GTEST_SKIP() << "Installed LibXC evaluates this raw HSE point finitely"; + } + EXPECT_EQ(ground->vsigma, floored->vsigma); + EXPECT_EQ(ground->v2rho2, floored->v2rho2); + EXPECT_EQ(ground->v2rhosigma, floored->v2rhosigma); + EXPECT_EQ(ground->v2sigma2, floored->v2sigma2); + EXPECT_TRUE(ground->sigma_jacobian().empty()); + EXPECT_THROW(ground->gxc(false), std::runtime_error); + } +} + +TEST_F(KernelXCTest, HseGroundResponseRetryFailsCollectivelyIfStillNonfinite) +{ + const auto domain = ModuleBase::world_comm_domain(); + const bool owns_points = domain.rank() == 0; + basis.nrxx = owns_points ? 1 : 0; + basis.npw = basis.nrxx; + basis.nmaxgr = basis.nrxx; + charge.nrxx = basis.nrxx; + cell.tpiba = std::numeric_limits::quiet_NaN(); + const std::vector initialization = {"default"}; + EXPECT_THROW(LR::build_gs_xc_kernel( + "hse", basis, cell, charge, grid, 1, false, initialization), std::runtime_error); +} + +TEST_F(KernelXCTest, SigmaFloorJacobianPreservesOtherFunctionals) +{ + const std::vector sigma = {-2.0, + 0.5e-6, + 1e-6, + 2e-6}; + std::vector buffer; + std::vector jacobian; + const auto &original = LR_Util::prepare_xc_sigma( + sigma, + false, + buffer, + jacobian); + EXPECT_EQ(&original, &sigma); + EXPECT_TRUE(jacobian.empty()); + const auto &stabilized = LR_Util::prepare_xc_sigma( + sigma, + true, + buffer, + jacobian); + EXPECT_EQ( + stabilized, (std::vector{1e-6, + 1e-6, + 1e-6, + 2e-6})); + EXPECT_EQ( + jacobian, (std::vector{0.0, + 0.0, + 0.0, + 1.0})); + const std::vector empty; + EXPECT_TRUE( + LR_Util::prepare_xc_sigma( + empty, + true, + buffer, + jacobian) + .empty()); + EXPECT_TRUE(jacobian.empty()); +} + + +TEST_F(KernelXCTest, HseClippedKernelGradientMatchesIndependentFiniteDifference) +{ + if (!hse_has_kxc(1)) + { + GTEST_SKIP() << "Installed LibXC does not advertise HSE third derivatives"; + } + basis.nrxx = 1; + basis.npw = 1; + basis.nmaxgr = 1; + charge.nrxx = 1; + cell.tpiba = 0.001; + const auto kernel = build("hse", 1, LR::KernelXC::Singlet); + const auto &coefficients = kernel->gxc(false); + const ModuleBase::Vector3 base_gradient(0.1, 0.2, 0.3); + const ModuleBase::Vector3 perturbation_gradient(0.03, -0.02, 0.04); + const double u = 0.4; + const auto gradient = base_gradient * cell.tpiba; + const double t = gradient * perturbation_gradient; + const double q = perturbation_gradient * perturbation_gradient; + const double radial = coefficients.e_s2[0] * u * u + coefficients.e_st[0] * u * t + coefficients.e_t2[0] * t * t + + coefficients.e_q[0] * q; + const auto& second_order = kernel->closed_shell_gga(false); + const double explicit_gradient = 8.0 * (second_order.rho_sigma[0] * u + second_order.sigma_sigma[0] * t); + const auto derivative = gradient * radial + perturbation_gradient * explicit_gradient; + const double analytic = (derivative * base_gradient) / 4.0; + // Differentiate the second-order LR quadratic form, without using any third derivative. + const auto quadratic = [&](const double scale) -> double + { + cell.tpiba = scale; + const auto second = build("hse", 1, LR::KernelXC::NoGxc); + const double projection = (base_gradient * scale) * perturbation_gradient; + return second->v2rho2[0] * u * u + 4.0 * second->v2rhosigma[0] * u * projection + + 4.0 * second->v2sigma2[0] * projection * projection + 2.0 * second->vsigma[0] * q; + }; + for (const double h : {1e-5, 5e-6}) + { + const double plus = quadratic(0.001 + h); + const double minus = quadratic(0.001 - h); + const double finite_difference = (plus - minus) / (2.0 * h); + EXPECT_NEAR(analytic, finite_difference, 1e-9); + } + EXPECT_DOUBLE_EQ(radial, 0.0); + EXPECT_NE(explicit_gradient, 0.0); +} + +TEST_F(KernelXCTest, PolarizedHseClippingMasksOnlyImplicitSigmaDerivatives) +{ + if (!hse_has_kxc(2)) + { + GTEST_SKIP() << "Installed LibXC does not advertise polarized HSE third derivatives"; + } + basis.nrxx = 1; + basis.npw = 1; + basis.nmaxgr = 1; + charge.nrxx = 1; + cell.tpiba = 0.001; + const auto kernel = build("hse", 2, LR::KernelXC::BothSpins); + for (const bool triplet : {false, true}) + { + const auto &coefficients = kernel->gxc(triplet); + EXPECT_DOUBLE_EQ(coefficients.e_s2[0], 0.0); + EXPECT_DOUBLE_EQ(coefficients.e_st[0], 0.0); + EXPECT_DOUBLE_EQ(coefficients.e_t2[0], 0.0); + EXPECT_DOUBLE_EQ(coefficients.e_q[0], 0.0); + EXPECT_NE(kernel->closed_shell_gga(triplet).rho_sigma[0], 0.0); + } + const auto pbe = build("pbe", 2, LR::KernelXC::BothSpins); + EXPECT_NE(pbe->gxc(false).e_s2[0], 0.0); +} + +TEST_F(KernelXCTest, RequestedCoefficientsExistOnEmptyRanks) +{ + for (const std::string &name : {"lda", "pbe"}) + { + for (const int spins : {1, 2}) + { + const auto kernel = build(name, spins, LR::KernelXC::BothSpins); + EXPECT_TRUE(kernel->gxc(false).a_s2.empty()); + EXPECT_TRUE(kernel->gxc(true).a_s2.empty()); + EXPECT_EQ(kernel->is_gga(), name == "pbe"); + } + } +} + +TEST_F(KernelXCTest, MissingSpinStillThrowsOnEmptyRanks) +{ + const auto absent = build("pbe", 2, LR::KernelXC::NoGxc); + EXPECT_THROW(absent->gxc(false), std::runtime_error); + EXPECT_THROW(absent->gxc(true), std::runtime_error); + const auto singlet = build("pbe", 2, LR::KernelXC::Singlet); + EXPECT_NO_THROW(singlet->gxc(false)); + EXPECT_THROW(singlet->gxc(true), std::runtime_error); + const auto triplet = build("pbe", 2, LR::KernelXC::Triplet); + EXPECT_THROW(triplet->gxc(false), std::runtime_error); + EXPECT_NO_THROW(triplet->gxc(true)); + const auto nonlocal = build("hf", 2, LR::KernelXC::BothSpins); + EXPECT_THROW(nonlocal->gxc(false), std::runtime_error); +} + +TEST_F(KernelXCTest, RequestedCoefficientsRetainLocalValues) +{ + basis.nrxx = 1; + basis.npw = 1; + basis.nmaxgr = 1; + charge.nrxx = 1; + const auto kernel = build("lda", 2, LR::KernelXC::BothSpins); + ASSERT_EQ(kernel->v3rho3.size(), 4); + const double expected_singlet = kernel->v3rho3[0] + 2.0 * kernel->v3rho3[1] + kernel->v3rho3[2]; + const double expected_triplet = kernel->v3rho3[0] - 2.0 * kernel->v3rho3[1] + kernel->v3rho3[2]; + ASSERT_EQ(kernel->gxc(false).a_s2.size(), 1); + ASSERT_EQ(kernel->gxc(true).a_s2.size(), 1); + EXPECT_DOUBLE_EQ(kernel->gxc(false).a_s2[0], expected_singlet); + EXPECT_DOUBLE_EQ(kernel->gxc(true).a_s2[0], expected_triplet); +} diff --git a/source/source_lcao/module_lr/utils/lr_util.cpp b/source/source_lcao/module_lr/utils/lr_util.cpp index f50ecc8c47a..4c47068807e 100644 --- a/source/source_lcao/module_lr/utils/lr_util.cpp +++ b/source/source_lcao/module_lr/utils/lr_util.cpp @@ -9,6 +9,7 @@ #include "source_base/module_external/scalapack_connector.h" namespace LR_Util { + double hse_sigma_floor() { return 1e-6; } int spin_population_difference(const ModuleBase::matrix& wg, const int kpar, const int rank_in_pool) { // only for nspin=2 const int nk = wg.nr / 2; @@ -116,13 +117,34 @@ namespace LR_Util return sigma; } hse_buffer.resize(sigma.size()); + const double sigma_floor = hse_sigma_floor(); for (std::size_t index = 0; index < sigma.size(); ++index) { - hse_buffer[index] = std::max(sigma[index], 1e-6); + hse_buffer[index] = std::max(sigma[index], sigma_floor); } return hse_buffer; } + const std::vector &prepare_xc_sigma( + const std::vector &sigma, + const bool is_hse06, + std::vector &hse_buffer, + std::vector &jacobian) + { + const std::vector &prepared = prepare_xc_sigma(sigma, is_hse06, hse_buffer); + jacobian.clear(); + if (is_hse06) + { + jacobian.resize(sigma.size()); + const double sigma_floor = hse_sigma_floor(); + for (std::size_t index = 0; index < sigma.size(); ++index) + { + jacobian[index] = sigma[index] > sigma_floor ? 1.0 : 0.0; + } + } + return prepared; + } + /// =================PHYSICS==================== int cal_nocc(int nelec) { return nelec / ModuleBase::DEGSPIN + nelec % static_cast(ModuleBase::DEGSPIN); } diff --git a/source/source_lcao/module_lr/utils/lr_util.h b/source/source_lcao/module_lr/utils/lr_util.h index a2dba5d48cc..6621d8a97c2 100644 --- a/source/source_lcao/module_lr/utils/lr_util.h +++ b/source/source_lcao/module_lr/utils/lr_util.h @@ -29,6 +29,9 @@ template <> struct ToComplex> { using type = std::complex& hse_buffer); + /** + * @brief Prepare stabilized sigma and its componentwise derivative. + * @param[in] sigma LibXC sigma invariants, in bohr^-8, in native spin layout. + * @param[in] is_hse06 Whether to apply the existing HSE LR stabilization. + * @param[out] hse_buffer Owned stabilized values; unused for other kernels. + * @param[out] jacobian Derivatives of stabilized values with respect to raw + * sigma. Empty means identity; the clipped branch uses zero, including the + * nondifferentiable junction itself. + * @return A borrowed reference to sigma or hse_buffer, valid while its owner lives. + */ + const std::vector &prepare_xc_sigma( + const std::vector &sigma, + bool is_hse06, + std::vector &hse_buffer, + std::vector &jacobian); + /// =====================PHYSICS==================== /// @brief the xc kernels that carry an exact-exchange (EXX) term /// diff --git a/source/source_lcao/module_lr/window_response.cpp b/source/source_lcao/module_lr/window_response.cpp new file mode 100644 index 00000000000..0fabb6705c8 --- /dev/null +++ b/source/source_lcao/module_lr/window_response.cpp @@ -0,0 +1,251 @@ +#include "window_response.h" +#include "window_response_math.h" +#include "gradient_inputs.h" +#include "hamilt_casida.h" +#include "hamilt_ulr.h" +#include "utils/lr_util.h" +#include "source_base/timer.h" +#include +#include +#include + +namespace LR +{ +namespace +{ +std::vector transform_window_matrix(const GradientInputs& inputs, + const psi::Psi& c, const Parallel_Blkcyclic& pm, const double* matrix, + const LR_Util::MO_TYPE type, const int spin) +{ +#ifdef __MPI + auto result = cal_dm_trans_pblas(matrix, pm, c, inputs.pc, inputs.nbasis, + inputs.nocc[spin], inputs.nvirt[spin], inputs.pmat.para_2d(), 1.0, type); + for (auto& tensor : result) + { + LR_Util::matsym(tensor.data(), inputs.nbasis, inputs.pmat.para_2d()); + } +#else + auto result = cal_dm_trans_blas(matrix, c, inputs.nocc[spin], inputs.nvirt[spin], 1.0, type); + for (auto& tensor : result) + { + LR_Util::matsym(tensor.data(), inputs.nbasis); + } +#endif + return result; +} +} + +template <> +WindowResponse build_window_response(const GradientInputs& inputs, + const container::Tensor& X, const int nstates, const int nactive, const int ispin, + const std::string& in_dir) +{ + ModuleBase::timer::start("LR", "build_window_response"); + WindowResponse result; + const int nv = inputs.nvirt[0]; + const int no = inputs.nocc[0]; + if (nactive == nv) + { + ModuleBase::timer::end("LR", "build_window_response"); + return result; + } + if (inputs.nk != 1) + { + throw std::runtime_error("Window response currently requires real Gamma orbitals"); + } + const auto c = LR_Util::get_psi_spin(inputs.psi_ks, 0, inputs.nk); + const Parallel_Blkcyclic& px = inputs.px[0]; + Parallel_Blkcyclic pvv; + LR_Util::setup_2d_division(pvv, px.nb(), nv, nv +#ifdef __MPI + , px.ictxt() +#endif + ); + std::weak_ptr pot_lr = inputs.pot[ispin]; + HamiltLR full_casida(inputs.xc_kernel, inputs.nspin, inputs.nbasis, + inputs.nocc, inputs.nvirt, inputs.ucell, inputs.orb_cutoff, inputs.gd, + inputs.psi_ks, inputs.eig_ks, +#ifdef __EXX + inputs.exx_lri, inputs.hybrid_alpha, +#endif + pot_lr, inputs.kv, inputs.px, inputs.pc, inputs.pmat, + inputs.spin_types[ispin], in_dir, inputs.out_dir); + const int batch_size = nstates * inputs.nloc; + const int batch_storage = std::max(batch_size, 1); + std::vector AX(batch_storage, 0.0); + const double empty_block = 0.0; + const double* const x_data = X.data() == nullptr ? &empty_block : X.data(); + full_casida.hPsi(x_data, AX.data(), inputs.nloc, nstates); + + const int pairs = nv * no; + const int vv_storage = std::max(pvv.size(), 1); + const double* const virtual_energies = inputs.eig_ks.c + no; + for (int state = 0; state < nstates; ++state) + { + const int offset = state * inputs.nloc; + const double* x = x_data + offset; + const double* const ax = AX.data() + offset; + std::vector x_full(pairs, 0.0); + std::vector ax_full(pairs, 0.0); +#ifdef __MPI + LR_Util::gather_2d_to_full(px, x, x_full.data(), false, nv, no); + LR_Util::gather_2d_to_full(px, ax, ax_full.data(), false, nv, no); +#else + const double* const x_end = x + pairs; + const double* const ax_end = ax + pairs; + std::copy(x, x_end, x_full.begin()); + std::copy(ax, ax_end, ax_full.begin()); +#endif + const auto W = window_multipliers(no, nv, nactive, virtual_energies, + x_full.data(), ax_full.data()); + std::vector w_local(vv_storage, 0.0); + std::vector ew_local(w_local.size(), 0.0); + for (int col = 0; col < pvv.ncloc(); ++col) + { + const int a = pvv.icglb(col); + for (int row = 0; row < pvv.nrloc(); ++row) + { + const int r = pvv.irglb(row); + const int index = col * pvv.nrloc() + row; + w_local[index] = W[a * nv + r]; + ew_local[index] = virtual_energies[a] * w_local[index]; + } + } + result.density.push_back(transform_window_matrix(inputs, c, pvv, w_local.data(), LR_Util::MO_TYPE::VV, 0)); + result.direct_edm.push_back(transform_window_matrix(inputs, c, pvv, ew_local.data(), LR_Util::MO_TYPE::VV, 0)); + } + inputs.ofs << "Window response: " << nactive << " / " << nv + << " virtual orbitals; " << nstates << " " << inputs.spin_types[ispin] + << " amplitudes; Dwin and direct EDM constructed; GS Hessian uses the combined density." << std::endl; + ModuleBase::timer::end("LR", "build_window_response"); + return result; +} + +template <> +WindowResponse> build_window_response( + const GradientInputs>& inputs, const container::Tensor& X, + const int nstates, const int nactive, const int ispin, const std::string& in_dir) +{ + if (nactive != inputs.nvirt[0]) + { + throw std::runtime_error("Window response currently requires real Gamma orbitals"); + } + return {}; +} + +template <> +WindowResponse build_open_shell_window_response(const GradientInputs& inputs, + const container::Tensor& X, const int nstates, const std::vector& nactive) +{ + ModuleBase::timer::start("LR", "build_open_shell_window_response"); + WindowResponse result; + if (nactive == inputs.nvirt) + { + ModuleBase::timer::end("LR", "build_open_shell_window_response"); + return result; + } + if (inputs.nspin != 2 || inputs.nk != 1 || nactive.size() != 2) + { + throw std::runtime_error("Open-shell window response requires two spins and real Gamma orbitals"); + } + std::vector> c; + std::vector pvv(2); + std::vector local_size(2); + for (int spin = 0; spin < 2; ++spin) + { + c.push_back(LR_Util::get_psi_spin(inputs.psi_ks, spin, inputs.nk)); + const Parallel_Blkcyclic& px = inputs.px[spin]; + local_size[spin] = px.size(); + LR_Util::setup_2d_division(pvv[spin], px.nb(), + inputs.nvirt[spin], inputs.nvirt[spin] +#ifdef __MPI + , px.ictxt() +#endif + ); + } + const std::vector spin_offset = {0, local_size[0]}; + HamiltULR full_casida(inputs.xc_kernel, inputs.nspin, inputs.nbasis, + inputs.nocc, inputs.nvirt, inputs.ucell, inputs.orb_cutoff, inputs.gd, + inputs.psi_ks, inputs.eig_ks, +#ifdef __EXX + inputs.exx_lri, inputs.hybrid_alpha, +#endif + inputs.pot, inputs.kv, inputs.px, inputs.pc, inputs.pmat); + const int batch_size = nstates * inputs.nloc; + const int batch_storage = std::max(batch_size, 1); + std::vector AX(batch_storage, 0.0); + const double empty_block = 0.0; + const double* const x_data = X.data() == nullptr ? &empty_block : X.data(); + // Both spin blocks enter AX. Do not normalize the individual spin amplitudes. + full_casida.hPsi(x_data, AX.data(), inputs.nloc, nstates); + + result.density.resize(nstates); + result.direct_edm.resize(nstates); + for (int state = 0; state < nstates; ++state) + { + const int state_offset = state * inputs.nloc; + for (int spin = 0; spin < 2; ++spin) + { + const int no = inputs.nocc[spin]; + const int nv = inputs.nvirt[spin]; + const int pairs = no * nv; + const int offset = state_offset + spin_offset[spin]; + const double* const x = x_data + offset; + const double* const ax = AX.data() + offset; + const Parallel_Blkcyclic& px = inputs.px[spin]; + std::vector x_full(pairs, 0.0); + std::vector ax_full(pairs, 0.0); +#ifdef __MPI + LR_Util::gather_2d_to_full(px, x, x_full.data(), false, nv, no); + LR_Util::gather_2d_to_full(px, ax, ax_full.data(), false, nv, no); +#else + const double* const x_end = x + pairs; + const double* const ax_end = ax + pairs; + std::copy(x, x_end, x_full.begin()); + std::copy(ax, ax_end, ax_full.begin()); +#endif + const double* const virtual_energies = inputs.eig_ks.c + spin * inputs.eig_ks.nc + no; + const auto W = window_multipliers(no, nv, nactive[spin], virtual_energies, + x_full.data(), ax_full.data()); + const Parallel_Blkcyclic& pv = pvv[spin]; + const int vv_storage = std::max(pv.size(), 1); + std::vector w_local(vv_storage, 0.0); + std::vector ew_local(vv_storage, 0.0); + for (int col = 0; col < pv.ncloc(); ++col) + { + const int a = pv.icglb(col); + for (int row = 0; row < pv.nrloc(); ++row) + { + const int r = pv.irglb(row); + const int index = col * pv.nrloc() + row; + w_local[index] = W[a * nv + r]; + ew_local[index] = virtual_energies[a] * w_local[index]; + } + } + const auto density = transform_window_matrix(inputs, c[spin], pv, + w_local.data(), LR_Util::MO_TYPE::VV, spin); + const auto edm = transform_window_matrix(inputs, c[spin], pv, + ew_local.data(), LR_Util::MO_TYPE::VV, spin); + result.density[state].push_back(density[0]); + result.direct_edm[state].push_back(edm[0]); + } + } + inputs.ofs << "Open-shell window response: up " << nactive[0] << " / " << inputs.nvirt[0] + << ", down " << nactive[1] << " / " << inputs.nvirt[1] << "; " << nstates + << " amplitudes; spin densities and direct EDM constructed; GS Hessian uses combined densities." << std::endl; + ModuleBase::timer::end("LR", "build_open_shell_window_response"); + return result; +} + +template <> +WindowResponse> build_open_shell_window_response( + const GradientInputs>& inputs, const container::Tensor& X, + const int nstates, const std::vector& nactive) +{ + if (nactive != inputs.nvirt) + { + throw std::runtime_error("Open-shell window response currently requires real Gamma orbitals"); + } + return {}; +} +} diff --git a/source/source_lcao/module_lr/window_response.h b/source/source_lcao/module_lr/window_response.h new file mode 100644 index 00000000000..cc3e1c48714 --- /dev/null +++ b/source/source_lcao/module_lr/window_response.h @@ -0,0 +1,27 @@ +#ifndef ABACUS_LR_WINDOW_RESPONSE_H +#define ABACUS_LR_WINDOW_RESPONSE_H +#include +#include +#include +namespace LR +{ +template struct GradientInputs; +// Owned corrections for one batch of amplitudes. Empty means a full window. +template +struct WindowResponse +{ + // [state][spin * nk + k]; one spin block for spin-adapted amplitudes. + std::vector> density; + // Direct sym(C_r epsilon_a W_ra C_a^T) only; the occupied contribution + // is obtained from Hgs[T + Dwin + DZ]/2 in the existing Wc calculation. + std::vector> direct_edm; +}; +template +WindowResponse build_window_response(const GradientInputs& inputs, + const container::Tensor& X, int nstates, int nactive, int ispin, + const std::string& in_dir); +template +WindowResponse build_open_shell_window_response(const GradientInputs& inputs, + const container::Tensor& X, int nstates, const std::vector& nactive); +} +#endif diff --git a/source/source_lcao/module_lr/window_response_math.cpp b/source/source_lcao/module_lr/window_response_math.cpp new file mode 100644 index 00000000000..64f6968801d --- /dev/null +++ b/source/source_lcao/module_lr/window_response_math.cpp @@ -0,0 +1,36 @@ +#include "window_response_math.h" +#include +#include +namespace LR +{ +std::vector window_multipliers(const int nocc, const int nvirt, const int nactive, + const double* virtual_energies, const double* X, const double* AX) +{ + if (nocc <= 0 || nactive <= 0 || nactive > nvirt) + { + throw std::invalid_argument("Invalid orbital dimensions for window response"); + } + const int matrix_size = nvirt * nvirt; + std::vector W(matrix_size, 0.0); + for (int a = 0; a < nactive; ++a) + { + for (int r = nactive; r < nvirt; ++r) + { + const double gap = virtual_energies[a] - virtual_energies[r]; + // A spectral projector is not differentiable across a degenerate + // boundary. Include the entire multiplet instead of clipping gaps. + if (std::abs(gap) < 1e-8) + { + throw std::runtime_error("LR window cuts a degenerate virtual multiplet; increase nvirt"); + } + double coupling = 0.0; + for (int i = 0; i < nocc; ++i) + { + coupling += X[i * nvirt + a] * AX[i * nvirt + r]; + } + W[a * nvirt + r] = 2.0 * coupling / gap; + } + } + return W; +} +} diff --git a/source/source_lcao/module_lr/window_response_math.h b/source/source_lcao/module_lr/window_response_math.h new file mode 100644 index 00000000000..eb8cffda101 --- /dev/null +++ b/source/source_lcao/module_lr/window_response_math.h @@ -0,0 +1,11 @@ +#ifndef ABACUS_LR_WINDOW_RESPONSE_MATH_H +#define ABACUS_LR_WINDOW_RESPONSE_MATH_H +#include +namespace LR +{ +// Column-major matrices; X and AX span all available virtuals. Only the +// retained columns of the virtual-virtual multiplier can be nonzero. +std::vector window_multipliers(int nocc, int nvirt, int nactive, + const double* virtual_energies, const double* X, const double* AX); +} +#endif diff --git a/source/source_lcao/module_lr/zeq_solver.cpp b/source/source_lcao/module_lr/zeq_solver.cpp index b3ebedfc1c3..d775ad40e4e 100644 --- a/source/source_lcao/module_lr/zeq_solver.cpp +++ b/source/source_lcao/module_lr/zeq_solver.cpp @@ -12,7 +12,7 @@ namespace LR const std::string& spin_type, const std::string& in_dir, const bool openshell, - const std::string& zvec_solver) + const std::string& zvec_solver, const std::vector>& window_density) { const int& nspin = inputs.nspin; const int& naos = inputs.nbasis; @@ -61,7 +61,7 @@ namespace LR exx_lri, exx_alpha, #endif pot_hxc_gs, kv, px, pc, pmat, dft_functional, nk, nloc_per_band, global_dimension); - build_and_solve_zeq(ops_R, ops_L, /*nspin_x=*/2, X, R, Z, nloc_per_band, nstates, zvec_solver, test_force); + build_and_solve_zeq(ops_R, ops_L, /*nspin_x=*/2, X, R, Z, nloc_per_band, nstates, zvec_solver, test_force, window_density); } else { @@ -77,9 +77,9 @@ namespace LR exx_lri, exx_alpha, #endif pot_hxc_gs, kv, px, pc, pmat, spin_type, in_dir, out_dir, dft_functional); - build_and_solve_zeq(ops_R, ops_L, /*nspin_x=*/1, X, R, Z, nloc_per_band, nstates, zvec_solver, test_force); + build_and_solve_zeq(ops_R, ops_L, /*nspin_x=*/1, X, R, Z, nloc_per_band, nstates, zvec_solver, test_force, window_density); } } -template void Z_vector_equation(const GradientInputs&, const double* const, double* const, const int&, std::weak_ptr, const std::string&, const std::string&, const bool, const std::string&); -template void Z_vector_equation>(const GradientInputs>&, const std::complex* const, std::complex* const, const int&, std::weak_ptr, const std::string&, const std::string&, const bool, const std::string&); +template void Z_vector_equation(const GradientInputs&, const double* const, double* const, const int&, std::weak_ptr, const std::string&, const std::string&, const bool, const std::string&, const std::vector>&); +template void Z_vector_equation>(const GradientInputs>&, const std::complex* const, std::complex* const, const int&, std::weak_ptr, const std::string&, const std::string&, const bool, const std::string&, const std::vector>&); } diff --git a/source/source_lcao/module_lr/zeq_solver.h b/source/source_lcao/module_lr/zeq_solver.h index 35ecc143742..b938a507420 100644 --- a/source/source_lcao/module_lr/zeq_solver.h +++ b/source/source_lcao/module_lr/zeq_solver.h @@ -315,10 +315,10 @@ namespace LR template void build_and_solve_zeq(TOpsR& ops_R, TOpsL& ops_L, const int nspin_x, const T* const X, container::Tensor& R, T* const Z, - const int nloc_per_band, const int nstates, const std::string& zvec_solver, const bool test_force) + const int nloc_per_band, const int nstates, const std::string& zvec_solver, const bool test_force, const std::vector>& window_density) { ModuleBase::timer::start("Z_vector", "build_and_solve_zeq"); - ops_R.hPsi(X, R.template data(), nloc_per_band, nstates); // act each operator on X + ops_R.hPsi(X, R.template data(), nloc_per_band, nstates, window_density); // std::cout << "The right side of the Z-vector equation:" << std::endl; // LR_Util::print_value(R.template data(), nstates, nloc_per_band); solve_zeq_with(Z, R.template data(), nloc_per_band, nstates, ops_L, nspin_x, zvec_solver, test_force); @@ -334,6 +334,6 @@ namespace LR const std::string& spin_type, const std::string& in_dir, const bool openshell, - const std::string& zvec_solver); + const std::string& zvec_solver, const std::vector>& window_density); } #endif diff --git a/tests/08_RI/CASES_CPU.txt b/tests/08_RI/CASES_CPU.txt index 1c51dd45fd3..56cf6164ee2 100644 --- a/tests/08_RI/CASES_CPU.txt +++ b/tests/08_RI/CASES_CPU.txt @@ -14,6 +14,7 @@ scf_campbeh_gamma scf_hse_soc_symm_multik lr_tddft_lda_gamma lr_tddft_lda_s1_gamma +lr_tddft_lda_triplet_window_gamma lr_tddft_pbe_gamma lr_tddft_hf_gamma lr_tddft_hf_ulr_gamma diff --git a/tests/08_RI/lr_tddft_hf_ulr_gamma/INPUT b/tests/08_RI/lr_tddft_hf_ulr_gamma/INPUT index 776333c7356..95ec9a6180a 100644 --- a/tests/08_RI/lr_tddft_hf_ulr_gamma/INPUT +++ b/tests/08_RI/lr_tddft_hf_ulr_gamma/INPUT @@ -10,9 +10,9 @@ nspin 2 #Parameters (2.Iteration) ecutwfc 10 -scf_thr 1e-7 +scf_thr 1e-2 scf_nmax 20 -exx_hybrid_step 1 +exx_hybrid_step 2 #Parameters (3.Basis) basis_type lcao diff --git a/tests/08_RI/lr_tddft_hf_ulr_gamma/README b/tests/08_RI/lr_tddft_hf_ulr_gamma/README index 51146c016fb..d525352eea2 100644 --- a/tests/08_RI/lr_tddft_hf_ulr_gamma/README +++ b/tests/08_RI/lr_tddft_hf_ulr_gamma/README @@ -1,4 +1,9 @@ LR-TDDFT HF on H2O, gamma_only, nspin=2, lr_unrestricted=1, lr_nstates=3, lr_solver=lapack. -Uses direct LU for the small Z equation and skips optical postprocessing with -abs_gauge=none. Energy and signed force references are unchanged; -the closed-shell HF case retains Z-CG coverage. +Uses scf_thr=1e-2 so the preliminary SCF reaches the EXX update and the run +can exercise ground-state force output. The old 1e-7 setting exhausted +scf_nmax before EXX was initialized. exx_hybrid_step=2 allows the second +exchange update; limiting it to one left negative LR roots despite a completed +inner SCF. The three referenced roots are now positive. This coarse, +truncated-window case checks code behavior rather than physical accuracy. +Direct LU solves the small Z equation; abs_gauge=none skips optical output. +The closed-shell HF case retains Z-CG coverage. diff --git a/tests/08_RI/lr_tddft_hf_ulr_gamma/lr_force.ref b/tests/08_RI/lr_tddft_hf_ulr_gamma/lr_force.ref index 97c5bb60a8c..a8be7489e7a 100644 --- a/tests/08_RI/lr_tddft_hf_ulr_gamma/lr_force.ref +++ b/tests/08_RI/lr_tddft_hf_ulr_gamma/lr_force.ref @@ -1,10 +1,10 @@ -# channel state atom Fx Fy Fz (eV/Angstrom); unscreened LR exchange density -updown 0 0 0.0783539518 0.2111545572 -14.6814182951 -updown 0 1 -0.0418772646 0.0211554410 14.8361278315 -updown 0 2 -1.0109257784 -1.2242370465 -0.2174699602 -updown 1 0 0.6376133514 0.7356855678 -14.5450192597 -updown 1 1 0.5461463630 0.5639723455 14.6965355269 -updown 1 2 -2.0539922011 -2.4383634187 -0.2141248469 -updown 2 0 0.2103351811 0.4540829017 -13.7429038170 -updown 2 1 0.0635295752 0.2042483865 13.7840355695 -updown 2 2 -1.1152971573 -1.7406883553 -0.1137998634 +# channel state atom Fx Fy Fz (eV/Angstrom); two EXX updates, LR excitation-energy forces +updown 0 0 0.1313650152 0.1801171242 -16.8977193455 +updown 0 1 0.0563052469 0.0444464366 16.8852046498 +updown 0 2 -1.5062134508 -0.6511566625 -0.0372072981 +updown 1 0 0.1797303211 0.2729768456 -15.3922220742 +updown 1 1 0.1223224255 0.1665519845 15.3763532701 +updown 1 2 -0.6073871530 -1.8945959581 -0.0291299505 +updown 2 0 0.3778356985 0.3893553683 -18.4970350984 +updown 2 1 0.2606187679 0.1842116220 18.3323920275 +updown 2 2 -2.2197450809 -0.8666847720 0.1010323676 diff --git a/tests/08_RI/lr_tddft_hf_ulr_gamma/result.ref b/tests/08_RI/lr_tddft_hf_ulr_gamma/result.ref index d599ee502e1..32c30a1e8f2 100644 --- a/tests/08_RI/lr_tddft_hf_ulr_gamma/result.ref +++ b/tests/08_RI/lr_tddft_hf_ulr_gamma/result.ref @@ -1,6 +1,6 @@ -totalforceref 100.1830938113 +totalforceref 111.6599160153 CompareLRForce_pass 0 -excitationenergyref1 -0.981239 -excitationenergyref2 -0.977363 -excitationenergyref3 -0.765038 +excitationenergyref1 0.111364 +excitationenergyref2 0.114812 +excitationenergyref3 0.309791 totaltimeref 5.68 diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/INPUT b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/INPUT new file mode 100644 index 00000000000..a5c96c0eb04 --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/INPUT @@ -0,0 +1,30 @@ +INPUT_PARAMETERS +suffix autotest +pseudo_dir ../../../tests/PP_ORB +orbital_dir ../../../tests/PP_ORB +calculation scf +esolver_type ks-lr +basis_type lcao +gamma_only 1 +symmetry -1 +nspin 1 +nbands 6 +ecutwfc 80 +scf_thr 1e-10 +scf_nmax 100 +smearing_method fixed +mixing_type pulay +mixing_beta 0.4 +mixing_gg0 0 +dft_functional lda +xc_kernel lda +lr_target_spin triplet +lr_nstates 2 +lr_solver lapack +lr_grad_solver lapack +lr_thr 1e-10 +nocc 0 +nvirt 1 +abs_gauge none +cal_force 1 +out_chg 1 diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/KPT b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/README b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/README new file mode 100644 index 00000000000..fb26962ce37 --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/README @@ -0,0 +1,16 @@ +Real-Gamma scalar-triplet LDA window-response and density-output regression. +All six AO-supported KS bands and four occupied orbitals are available; +the Casida problem retains one virtual and discards the second. Dense LR/Z. +The signed force reference comes independently from central differences of +the same one-virtual excitation energies at +/-0.0005 Angstrom for every +atom and Cartesian direction (fixed integer occupations, SCF threshold 1e-10). +The 80 Ry grid and printed Ry energies (converted with Ry_to_eV=13.605698) +give a maximum component difference of 1.7e-4 eV/Angstrom on the reference run. +This exercises the AO window density, Z-source and direct-EDM force path. +out_chg=1 must write two triplet-labelled electron-hole cubes, never singlet. +The 1e-3 eV/Angstrom component/total tolerance accommodates printed-energy +precision and finite-step error; it does not compare against a full-window model. +lr_density.ref selects the electron-hole filename check; no separate ground-state +charge-cube reference is needed. totalforceref is the absolute sum of the FD forces. +Autotest clears this opted-in case's old LR electron-hole cubes before every run +so stale expected or extra-channel files cannot mask missing output or cause failures. diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/STRU b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/STRU new file mode 100644 index 00000000000..a5d6ec84bfe --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/STRU @@ -0,0 +1,28 @@ +ATOMIC_SPECIES +H 1.008 H_ONCV_PBE-1.0.upf +O 15.9994 O_ONCV_PBE-1.0.upf + +NUMERICAL_ORBITAL +H_gga_6au_60Ry_1s.orb +O_gga_6au_60Ry_1s1p.orb + +LATTICE_CONSTANT +1 + +LATTICE_VECTORS +12 0 0 +0 12 0 +0 0 12 + +ATOMIC_POSITIONS +Cartesian_angstrom + +H +0 +2 +0.01 0.02 1.03 0 0 0 +0.96 0.10 -0.22 0 0 0 +O +0 +1 +0.03 0.04 0.05 0 0 0 diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/lr_density.ref b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/lr_density.ref new file mode 100644 index 00000000000..34610c06a7b --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/lr_density.ref @@ -0,0 +1,2 @@ +LR_e-h_density_triplet_1.cube +LR_e-h_density_triplet_2.cube diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/lr_force.ref b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/lr_force.ref new file mode 100644 index 00000000000..115ea12aeeb --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/lr_force.ref @@ -0,0 +1,7 @@ +# Same-window excitation-energy central FD, +/-0.0005 Angstrom; independent of analytic forces. +triplet 0 0 -2.6976017425 -0.4017762619 12.7715326556 +triplet 0 1 10.2742067877 0.7087208088 -5.5697645903 +triplet 0 2 -7.5766050453 -0.3049036922 -7.2016320084 +triplet 1 0 -5.2145198155 -0.5298058801 11.6955940578 +triplet 1 1 8.3028772045 0.6351139826 -7.6722531022 +triplet 1 2 -3.0886295030 -0.1055802165 -4.0232048986 diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/result.ref b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/result.ref new file mode 100644 index 00000000000..ca47ab20cbf --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/result.ref @@ -0,0 +1,6 @@ +totalforceref 88.7743222534 +CompareLRForce_pass 0 +CompareLRDensity_pass 0 +excitationenergyref1 0.693763 +excitationenergyref2 0.807609 +totaltimeref 3.47 diff --git a/tests/08_RI/lr_tddft_lda_triplet_window_gamma/threshold b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/threshold new file mode 100644 index 00000000000..db97fef9111 --- /dev/null +++ b/tests/08_RI/lr_tddft_lda_triplet_window_gamma/threshold @@ -0,0 +1,2 @@ +# Independent same-window central energy differences, half-step 0.0005 Angstrom. +force_threshold 0.001 diff --git a/tests/08_RI/lr_tddft_pbe_gamma/README b/tests/08_RI/lr_tddft_pbe_gamma/README index ed8d8ab79df..923c223f7c2 100644 --- a/tests/08_RI/lr_tddft_pbe_gamma/README +++ b/tests/08_RI/lr_tddft_pbe_gamma/README @@ -1 +1,6 @@ LR-TDDFT PBE on H2O, gamma_only, nspin=2, lr_nstates=2, lr_solver=dav. +All INPUT settings are retained, including scf_thr=1e-3. The force references +follow closed-shell scalar XC coefficient reuse. A small local spin-density +residual at this loose SCF tolerance makes the spin-symmetry coefficient +identities only approximate; paired tight-SCF checks recover identical forces. +Excitation-energy references and force tolerances are unchanged. diff --git a/tests/08_RI/lr_tddft_pbe_gamma/lr_force.ref b/tests/08_RI/lr_tddft_pbe_gamma/lr_force.ref index d711b59d63c..38c6c643e4f 100644 --- a/tests/08_RI/lr_tddft_pbe_gamma/lr_force.ref +++ b/tests/08_RI/lr_tddft_pbe_gamma/lr_force.ref @@ -1,10 +1,10 @@ -# channel state atom Fx Fy Fz (eV/Angstrom), pre-change numerical baseline -singlet 0 0 4.0434834747 -2.9663464187 -1.3171067716 -singlet 0 1 -2.4643213231 3.1087225602 -3.8533477645 -singlet 0 2 -1.8163985540 -4.9815297512 7.7067515962 -singlet 1 0 3.0924987281 -2.8179121099 2.0399232442 -singlet 1 1 -3.7567798496 3.2106504398 -0.6136681140 -singlet 1 2 1.7352484094 0.9895508498 -5.6936587848 +# channel state atom Fx Fy Fz (eV/Angstrom); current LR excitation-energy forces +singlet 0 0 4.0434835476 -2.9663465060 -1.3171067883 +singlet 0 1 -2.4643213706 3.1087226975 -3.8533478538 +singlet 0 2 -1.8163987088 -4.9815337361 7.7067430057 +singlet 1 0 3.0924984223 -2.8179118972 2.0399234824 +singlet 1 1 -3.7567796998 3.2106503729 -0.6136677372 +singlet 1 2 1.7352518209 0.9895481970 -5.6936623540 triplet 0 0 4.1419826458 -2.9956164092 -1.1763835450 triplet 0 1 -2.5196997657 3.2535205578 -3.7137334951 triplet 0 2 -1.3425889349 -3.7665128960 9.5319047911 diff --git a/tests/08_RI/lr_tddft_pbe_gamma/result.ref b/tests/08_RI/lr_tddft_pbe_gamma/result.ref index 935cb093d6f..828fb22899e 100644 --- a/tests/08_RI/lr_tddft_pbe_gamma/result.ref +++ b/tests/08_RI/lr_tddft_pbe_gamma/result.ref @@ -1,4 +1,4 @@ -totalforceref 114.0143587607 +totalforceref 114.0143582150 CompareLRForce_pass 0 excitationenergyref1 0.589604 excitationenergyref2 0.731319 diff --git a/tests/integrate/Autotest.sh b/tests/integrate/Autotest.sh index f2d901432d4..7f1cfd19cdf 100755 --- a/tests/integrate/Autotest.sh +++ b/tests/integrate/Autotest.sh @@ -352,7 +352,12 @@ run_case() { TIMEFORMAT='[----------] Time elapsed: %R seconds' #parallel test time { - if [ "$np" -le 0 ] 2>/dev/null; then + # Opted-in density checks must see only this run's LR cubes. Preserve + # other output and restart files, including the ground-state charge. + if [ -f lr_density.ref ] && ! rm -f -- OUT.autotest/LR_e-h_density_*.cube; then + echo "Error: cannot clear previous LR density cubes" >log.txt + false + elif [ "$np" -le 0 ] 2>/dev/null; then # serial build: run the binary directly, no MPI launcher. # This lets a serial ABACUS (ENABLE_MPI=OFF, e.g. the native # Windows build) reuse this harness unchanged. diff --git a/tests/integrate/validation_tools/catch_properties.sh b/tests/integrate/validation_tools/catch_properties.sh index 6add6375a60..e433fb90841 100755 --- a/tests/integrate/validation_tools/catch_properties.sh +++ b/tests/integrate/validation_tools/catch_properties.sh @@ -27,6 +27,7 @@ source "$PROPS_SCRIPT_DIR/props_dfpt.sh" # trailing totaltimeref entry. Add a new category by dropping a # props_.sh next to the others and calling run__props here. run_lr_force_props +run_lr_density_props run_basic_props || exit 1 #--------------------------------------- diff --git a/tests/integrate/validation_tools/lr_force_check.py b/tests/integrate/validation_tools/lr_force_check.py index 3edf378db53..142b2c509f6 100644 --- a/tests/integrate/validation_tools/lr_force_check.py +++ b/tests/integrate/validation_tools/lr_force_check.py @@ -7,6 +7,10 @@ import sys CHANNEL = re.compile(r'Start to calculate excited-state force of (singlet|triplet|updown)\b') +FORCE_TABLE_HEADERS = ( + 'Forces (-gradients) of each excited state:', + 'Excitation-energy force contributions (-dOmega/dR) of each state:', +) ROW = re.compile(r'^\s*(?:(\d+)\s+)?(\d+)\s+force\s+(\S+)\s+(\S+)\s+(\S+)\s*$') @@ -31,7 +35,7 @@ def read_forces(log): channel = match.group(1) active = False continue - if 'Forces (-gradients) of each excited state:' in line: + if any(header in line for header in FORCE_TABLE_HEADERS): if channel is None: raise ValueError('LR force table has no spin channel') active = True diff --git a/tests/integrate/validation_tools/props_cube.sh b/tests/integrate/validation_tools/props_cube.sh index 7b599439092..07f7b996bf6 100644 --- a/tests/integrate/validation_tools/props_cube.sh +++ b/tests/integrate/validation_tools/props_cube.sh @@ -56,7 +56,11 @@ run_cube_props() { #--------------------------------------- #echo $out_chg if ! test -z "$out_chg" && [ $out_chg -ge 1 ]; then - record_compare_result "$props_result_file" "chg.cube_pass" "chg.cube.ref" "OUT.autotest/chg.cube" 6 + # A channel-density regression can opt into lr_density.ref instead of + # storing a separate ground-state cube. Still check both if both exist. + if [ "$is_lr" != 1 ] || [ ! -f lr_density.ref ] || [ -f chg.cube.ref ]; then + record_compare_result "$props_result_file" "chg.cube_pass" "chg.cube.ref" "OUT.autotest/chg.cube" 6 + fi fi #--------------------------------------- diff --git a/tests/integrate/validation_tools/props_lr.sh b/tests/integrate/validation_tools/props_lr.sh index bd754fc71ea..16ed08fbbaa 100644 --- a/tests/integrate/validation_tools/props_lr.sh +++ b/tests/integrate/validation_tools/props_lr.sh @@ -20,7 +20,20 @@ run_lr_tracking_props() { run_lr_force_props() { # LR prints a separate force table for each excited state and spin channel. if [ $is_lr == 1 ] && ! test -z "$has_force" && [ $has_force == 1 ]; then - awk '/Forces \(-gradients\) of each excited state/{flag=1; next} flag{for(i=1;i<=NF;i++) if($i=="force"){print $(i+1),$(i+2),$(i+3)}}' "$running_path" >lr_force.txt + awk ' + /Forces \(-gradients\) of each excited state:|Excitation-energy force contributions \(-dOmega\/dR\) of each state:/ { + active = 1 + next + } + active && (NF == 0 || ($1 == "state" && $2 == "atom")) { next } + active && ($2 == "force" || $3 == "force") { + for (i = 1; i <= NF; ++i) { + if ($i == "force") print $(i+1), $(i+2), $(i+3) + } + next + } + active { active = 0 } + ' "$running_path" >lr_force.txt # Accumulate all components before rounding the LR force total. total_lr_force=$(awk '{for (i=1; i<=NF; ++i) sum += sqrt($i*$i)} END {printf "%.10f\n", sum}' lr_force.txt) rm lr_force.txt @@ -42,3 +55,29 @@ run_lr_force_props() { fi } + +# Optional exact filename check for channel-labelled electron-hole densities. +run_lr_density_props() { + if [ "$is_lr" != 1 ] || [ ! -f lr_density.ref ]; then + return 0 + fi + local expected_names + local actual_names="" + local density_file + local valid=1 + expected_names=$(sed '/^[[:space:]]*$/d' lr_density.ref | sort) + for density_file in OUT.autotest/LR_e-h_density_*.cube; do + if [ ! -s "$density_file" ]; then + valid=0 + else + actual_names+="${density_file##*/}"$'\n' + fi + done + actual_names=$(printf '%s' "$actual_names" | sort) + if [ "$valid" == 1 ] && [ -n "$expected_names" ] && [ "$actual_names" = "$expected_names" ]; then + echo "CompareLRDensity_pass 0" >>"$props_result_file" + else + echo "LR density filenames missing, empty, or inconsistent with lr_density.ref" >&2 + echo "CompareLRDensity_pass 1" >>"$props_result_file" + fi +} diff --git a/tests/integrate/validation_tools/test_lr_force_check.py b/tests/integrate/validation_tools/test_lr_force_check.py index 9c11dd4ddad..3d87e887e91 100644 --- a/tests/integrate/validation_tools/test_lr_force_check.py +++ b/tests/integrate/validation_tools/test_lr_force_check.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Signed force regression must catch changes hidden by an absolute-value sum.""" import unittest +import os from pathlib import Path import subprocess import tempfile @@ -25,6 +26,10 @@ EXCITED-STATE TOTAL-FORCE (eV/Angstrom) H1 88 88 88 ''' +NEW_LOG = LOG.replace( + 'Forces (-gradients) of each excited state:', + 'Excitation-energy force contributions (-dOmega/dR) of each state:') + REFERENCE = '''singlet 0 0 1 -2 3 singlet 0 1 -4 5 -6 singlet 1 0 7 -8 9 @@ -40,6 +45,18 @@ def test_signed_components_match_and_exclude_gs_and_total(self): self.assertEqual(len(actual), 6) compare(actual, read_reference(REFERENCE), 1e-6) + def test_new_and_mixed_titles_match_the_same_reference(self): + mixed_log = NEW_LOG.replace( + 'Excitation-energy force contributions (-dOmega/dR) of each state:', + 'Forces (-gradients) of each excited state:', 1) + extra_tables = (NEW_LOG + 'GROUND-STATE FORCE (eV/Angstrom)\n' + '0 0 force 999 999 999\n' + 'EXCITED-STATE TOTAL-FORCE (eV/Angstrom)\n' + '0 0 force 888 888 888\n') + for log in (NEW_LOG, mixed_log, extra_tables): + with self.subTest(log=log): + compare(read_forces(log), read_reference(REFERENCE), 1e-6) + def test_sign_reversal_fails_with_identical_absolute_sum(self): actual = read_forces(LOG) flipped = {key: tuple(-v for v in row) for key, row in actual.items()} @@ -86,8 +103,13 @@ def test_shell_collector_emits_failure_for_sign_change_or_missing_data(self): 'source "$1/props_common.sh"', 'source "$1/props_lr.sh"', 'PROPS_SCRIPT_DIR="$1"', 'is_lr=1', 'has_force=1', 'running_path=running.log', 'props_result_file=result.out', 'run_lr_force_props']) - variants = [(LOG, '0'), (LOG.replace('1 -2 3', '-1 2 -3'), '1'), - (LOG.replace(' 1 force -16 17 -18\n', ''), '1')] + extra_tables = (NEW_LOG + 'GROUND-STATE FORCE (eV/Angstrom)\n' + '0 0 force 999 999 999\n' + 'EXCITED-STATE TOTAL-FORCE (eV/Angstrom)\n' + '0 0 force 888 888 888\n') + variants = [(LOG, '0'), (NEW_LOG, '0'), (extra_tables, '0'), + (NEW_LOG.replace('1 -2 3', '-1 2 -3'), '1'), + (NEW_LOG.replace(' 1 force -16 17 -18\n', ''), '1')] with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) (root / 'lr_force.ref').write_text(REFERENCE) @@ -99,6 +121,8 @@ def test_shell_collector_emits_failure_for_sign_change_or_missing_data(self): self.assertEqual(result.returncode, 0, result.stderr) values = dict(line.split() for line in (root / 'result.out').read_text().splitlines()) self.assertEqual(values['CompareLRForce_pass'], expected) + if expected == '0': + self.assertEqual(float(values['totalforceref']), 171.0) def test_tolerance_is_absolute_per_component(self): expected = read_forces(LOG) @@ -111,6 +135,88 @@ def test_tolerance_is_absolute_per_component(self): with self.assertRaises(ValueError): compare(changed, expected, tolerance) + def test_density_collector_requires_exact_nonempty_channel_files(self): + tools = Path(__file__).resolve().parent + script = '\n'.join([ + 'source "$1/props_lr.sh"', 'is_lr=1', + 'props_result_file=result.out', 'run_lr_density_props']) + expected_names = ['LR_e-h_density_triplet_1.cube', 'LR_e-h_density_triplet_2.cube'] + variants = [ + (dict.fromkeys(expected_names, 'cube data'), '0'), + ({name.replace('triplet', 'singlet'): 'cube data' for name in expected_names}, '1'), + ({expected_names[0]: 'cube data'}, '1'), + ({expected_names[0]: 'cube data', expected_names[1]: ''}, '1'), + (dict.fromkeys(expected_names + ['LR_e-h_density_singlet_1.cube'], 'cube data'), '1'), + ({}, '1')] + for files, expected in variants: + with self.subTest(files=files), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + output = root / 'OUT.autotest' + output.mkdir() + (root / 'lr_density.ref').write_text('\n'.join(expected_names) + '\n') + for name, contents in files.items(): + (output / name).write_text(contents) + result = subprocess.run(['bash', '-e', '-c', script, 'collector-test', str(tools)], + cwd=root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((root / 'result.out').read_text().strip(), + 'CompareLRDensity_pass ' + expected) + + def test_autotest_rerun_clears_only_opted_in_lr_density_cubes(self): + integrate = Path(__file__).resolve().parents[1] + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / 'integrate').symlink_to(integrate, target_is_directory=True) + suite = root / '08_RI' + case = suite / 'density_rerun' + output = case / 'OUT.autotest' + output.mkdir(parents=True) + (suite / 'CASES_CPU.txt').write_text('density_rerun\n') + (case / 'INPUT').write_text('calculation scf\nesolver_type ks-lr\nnspin 1\nout_chg 1\n') + (case / 'result.ref').write_text('CompareLRDensity_pass 0\n') + (case / 'lr_density.ref').write_text('LR_e-h_density_triplet_1.cube\n') + (output / 'LR_e-h_density_triplet_1.cube').write_text('stale expected cube') + (output / 'LR_e-h_density_singlet_1.cube').write_text('stale wrong label') + charge = output / 'chg.cube' + charge.write_text('preserve ground-state output') + executable = root / 'fake-abacus' + executable.write_text('''#!/usr/bin/env python3 +from pathlib import Path +output = Path('OUT.autotest') +if Path('lr_density.ref').exists(): + assert not list(output.glob('LR_e-h_density_*.cube')), 'stale cubes reached executable' +assert (output / 'chg.cube').read_text() == 'preserve ground-state output' +(output / 'running_scf.log').write_text('atomic_world 0.01 0.01\\n') +if Path('emit-density').exists(): + (output / 'LR_e-h_density_triplet_1.cube').write_text('current run cube') +''') + executable.chmod(0o755) + command = ['bash', str(integrate / 'Autotest.sh'), '-a', str(executable), + '-n', '0', '-o', '1', '-j', '1'] + environment = dict(os.environ, OMP_NUM_THREADS='1') + # First rerun removes both old labels and accepts newly generated cubes. + emit = case / 'emit-density' + emit.touch() + result = subprocess.run(command, cwd=suite, env=environment, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual((output / 'LR_e-h_density_triplet_1.cube').read_text(), 'current run cube') + self.assertFalse((output / 'LR_e-h_density_singlet_1.cube').exists()) + # A run that emits nothing must not pass on the preceding run's cube. + emit.unlink() + result = subprocess.run(command, cwd=suite, env=environment, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('CompareLRDensity_pass 1', (case / 'result.out').read_text()) + self.assertFalse(list(output.glob('LR_e-h_density_*.cube'))) + self.assertEqual(charge.read_text(), 'preserve ground-state output') + # No opt-in reference means no cleanup, even when using the same harness. + (case / 'lr_density.ref').unlink() + stale = output / 'LR_e-h_density_singlet_1.cube' + stale.write_text('unmanaged output') + result = subprocess.run(command + ['-p'], cwd=suite, env=environment, + capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(stale.read_text(), 'unmanaged output') + if __name__ == '__main__': unittest.main()