From 2e6d405053c5abe455c63388e0a834f29fa2a041 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 14:27:41 +0800 Subject: [PATCH 01/26] refactor(lr): move LR dimension resolution into module_lr Extract set_dimension/reset_dim_spin2 from ESolver_LR into LR::resolve_dim and LR::apply_spin_pol so the solver only assembles inputs and copies the resolved dimensions back. Rename the members to set_dim/reset_dim_spin and register lr_dim.cpp in both build systems. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr_cfg.cpp | 185 +++++------------- source/source_esolver/esolver_lr_init.cpp | 12 +- source/source_esolver/esolver_lr_lcao_bse.cpp | 4 +- source/source_esolver/esolver_lr_lcao_tddft.h | 4 +- source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/cal_w_from_z.h | 2 +- source/source_lcao/module_lr/lr_dim.cpp | 170 ++++++++++++++++ source/source_lcao/module_lr/lr_dim.h | 64 ++++++ 9 files changed, 296 insertions(+), 147 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_dim.cpp create mode 100644 source/source_lcao/module_lr/lr_dim.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 976e438be8..2c2d8dd6fb 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1194,6 +1194,7 @@ OBJS_TENSOR=tensor.o\ lr_spectrum.o\ lr_spectrum_velocity.o\ hamilt_casida.o\ + lr_dim.o\ esolver_lr_orb.o\ esolver_lr_init.o\ esolver_lr_cfg.o\ diff --git a/source/source_esolver/esolver_lr_cfg.cpp b/source/source_esolver/esolver_lr_cfg.cpp index 0be75bad78..0a8e7897d0 100644 --- a/source/source_esolver/esolver_lr_cfg.cpp +++ b/source/source_esolver/esolver_lr_cfg.cpp @@ -1,151 +1,64 @@ #include "source_lcao/module_lr/kernel_pots.h" -// Resolve LR dimensions, validate solver options, and initialize kernel potentials. +// Resolve LR dimensions and initialize kernel potentials. #include "esolver_lr_lcao_tddft.h" #include "source_io/module_parameter/parameter.h" -#include "source_io/module_wf/read_wfc_nao.h" -#include "source_lcao/module_lr/init_helpers.h" -#include "source_lcao/module_lr/utils/lr_io.h" -#include "source_lcao/module_lr/utils/lr_util.h" -#include -#include -#include - -using namespace LR; +#include "source_lcao/module_lr/lr_dim.h" +#include +#include template -void ModuleESolver::ESolver_LR::set_dimension() +void ModuleESolver::ESolver_LR::set_dim() { - this->nspin = this->inp_->nspin; - this->nstates = this->inp_->lr_nstates; - this->nbasis = PARAM.globalv.nlocal; - int ks_nbands = this->inp_->nbands; - if (this->nspin == 2) - { - this->nupdown = static_cast(std::lround(this->inp_->nupdown)); - if (this->ks_) - { - this->nupdown = LR_Util::spin_population_difference( - this->ks_->pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); - } - else if (this->inp_->ri_hartree_benchmark != "aims" && this->inp_->ri_hartree_benchmark != "aims-librpa") - { - std::vector populations; - const bool gamma_only = std::is_same::value; - const bool binary = this->inp_->init_wfc_file_format == "binary"; - if (!ModuleIO::read_wfc_nao_spin_populations( - this->in_dir, this->kv.get_nkstot(), this->nspin, gamma_only, binary, this->my_rank_, populations)) - { - ModuleBase::WARNING_QUIT("ESolver_LR", "read complete KS occupations failed"); - } - this->nupdown = static_cast(std::lround(populations[0]) - std::lround(populations[1])); - } - } - // read_pseudo/ParamUpdater has already resolved nelec and applied nelec_delta. - this->nocc_max = LR_Util::cal_nocc(this->inp_->nelec, this->nspin, this->nupdown); - if (this->inp_->ri_hartree_benchmark == "aims" || - this->inp_->ri_hartree_benchmark == "aims-librpa" && !this->inp_->aims_nbasis.empty()) - { - // Total basis size: sum the per-atom basis size times the atom count for each type. - int total_nbasis = 0; - for (std::size_t it = 0; it < this->inp_->aims_nbasis.size(); ++it) - { - total_nbasis += this->inp_->aims_nbasis[it] * this->ucell_->atoms[it].na; - } - this->nbasis = total_nbasis; - std::cout << "nbasis from aims: " << this->nbasis << std::endl; - for (int it = 0; it < this->ucell_->ntype; ++it) - { - this->ucell_->atoms[it].nw = this->inp_->aims_nbasis[it]; - } - const_cast(this->ucell_)->set_iat2iwt(1); // update iat2iwt for aims_nbasis 25-05-23 + LR::DimSrc src; + src.inp = this->inp_; + src.nlocal = PARAM.globalv.nlocal; + src.nks = this->kv.get_nks(); + src.nkstot = this->kv.get_nkstot(); + src.rank = this->my_rank_; + src.gamma_only = std::is_same::value; + src.wg_ks = this->ks_ ? &this->ks_->pelec->wg : nullptr; + src.kpar = this->kv.para_k.kpar; + src.rank_in_pool = this->kv.para_k.rank_in_pool; + src.in_dir = this->in_dir; + src.ucell = const_cast(this->ucell_); + src.log = &this->ofs_running_; - int nbands_file = 0; - int nk_file = 0; - int nspin_file = 0; - int nocc_file = 0; - LR_IO::parse_band_out_file(this->inp_->rpa_outdir, nbands_file, nk_file, nspin_file, nocc_file); - std::cout << "nocc from band_out: " << nocc_file << std::endl; - ks_nbands = nbands_file; - this->nocc_max = nocc_file; - } - // calculate the number of occupied and unoccupied states - // which determines the basis size of the excited states - this->nocc_in = LR_Util::cal_nocc_window(this->inp_->nocc, this->nocc_max); - this->nvirt_in = ks_nbands - this->nocc_max; // nbands-nocc - if (this->inp_->nvirt > this->nvirt_in) - { - this->ofs_running_ << "ESolver_LR: input nvirt is too large to cover by nbands, set nvirt = nbands - nocc = " - << this->nvirt_in << std::endl; - } - else if (this->inp_->nvirt > 0) - { - this->nvirt_in = this->inp_->nvirt; - } - this->nbands = this->nocc_in + this->nvirt_in; - this->nk = this->inp_->nspin == 2 ? this->kv.get_nks() / 2 : this->kv.get_nks(); - this->nocc.resize(nspin, nocc_in); - this->nvirt.resize(nspin, nvirt_in); - if (this->nstates <= 0) - { - this->nstates = nk * nocc_in * nvirt_in; - this->ofs_running_ << "ESolver_LR: lr_nstates <= 0, set nstates = nk * nocc * nvirt = " << this->nstates - << std::endl; - } - for (int is = 0; is < nspin; ++is) - { - this->npairs.push_back(nocc[is] * nvirt[is]); - } - this->ofs_running_ << "Setting LR-TDDFT parameters: " << std::endl; - this->ofs_running_ << "full occupied bands in largest spin channel: " << nocc_max << std::endl; - const int skipped_core_bands = nocc_max - nocc_in; - this->ofs_running_ << "shared core bands omitted from LR window: " << skipped_core_bands << std::endl; - this->ofs_running_ << "number of occupied bands: " << nocc_in << std::endl; - this->ofs_running_ << "number of virtual bands: " << nvirt_in << std::endl; - this->ofs_running_ << "number of Atom orbitals (LCAO-basis size): " << this->nbasis << std::endl; - // eig_ks is allocated after set_dimension; report the resolved counts here. - this->ofs_running_ << "number of KS bands: " << ks_nbands << std::endl; - this->ofs_running_ << "number of KS bands in LR window: " << this->nbands << std::endl; - this->ofs_running_ << "number of excited states to be solved: " << this->nstates << std::endl; + const LR::Dim dim = LR::resolve_dim(src); + + this->nspin = dim.nspin; + this->nstates = dim.nstates; + this->nbasis = dim.nbasis; + this->nbands = dim.nbands; + this->nk = dim.nk; + this->nupdown = dim.nupdown; + this->nocc_in = dim.nocc_in; + this->nocc_max = dim.nocc_max; + this->nvirt_in = dim.nvirt_in; + this->openshell = dim.openshell; + this->nocc = dim.nocc; + this->nvirt = dim.nvirt; + this->npairs = dim.npairs; } template -void ModuleESolver::ESolver_LR::reset_dim_spin2() +void ModuleESolver::ESolver_LR::reset_dim_spin() { - if (nspin != 2) - { - return; - } - if (nupdown != 0) - { - this->openshell = true; - const int minority_spin = nupdown > 0 ? 1 : 0; - const int polarization = std::abs(nupdown); - nocc[minority_spin] -= polarization; - nvirt[minority_spin] += polarization; - npairs = {nocc[0] * nvirt[0], nocc[1] * nvirt[1]}; - std::cout << "** Solve the spin-up and spin-down states separately for open-shell system. **" << std::endl; - } - for (int is : {0, 1}) - { - if (npairs[is] <= 0) - { - throw std::invalid_argument( - std::string("ESolver_LR: npairs (nocc*nvirt) <= 0 for spin") + std::string(is == 0 ? "up" : "down")); - } - } + LR::Dim dim; + dim.nspin = this->nspin; + dim.nstates = this->nstates; + dim.nk = this->nk; + dim.nupdown = this->nupdown; + dim.openshell = this->openshell; + dim.nocc = this->nocc; + dim.nvirt = this->nvirt; + dim.npairs = this->npairs; - if (nstates > (npairs[0] + npairs[1]) * nk) - { - throw std::invalid_argument("ESolver_LR: nstates > nocc*nvirt*nk"); - } - if (this->inp_->lr_unrestricted) - { - this->openshell = true; - } - if (!this->openshell) - { - std::cout << " ** Assuming degenerate spin-up and spin-down states **" << std::endl; - } + LR::apply_spin_pol(dim, *this->inp_); + + this->nocc = dim.nocc; + this->nvirt = dim.nvirt; + this->npairs = dim.npairs; + this->openshell = dim.openshell; } template diff --git a/source/source_esolver/esolver_lr_init.cpp b/source/source_esolver/esolver_lr_init.cpp index 41223492a1..21ff9789f7 100644 --- a/source/source_esolver/esolver_lr_init.cpp +++ b/source/source_esolver/esolver_lr_init.cpp @@ -162,7 +162,7 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); - this->set_dimension(); + this->set_dim(); // KS and LR must use the same AO distribution, including its BLACS grid. const int ks_block_size = ks_sol.pv.para_2d().nb(); @@ -296,7 +296,7 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) if (!this->ks_initialized_) { this->nupdown = nupdown_now; - reset_dim_spin2(); // shifts nocc/nvirt between the spin channels: must run exactly once + reset_dim_spin(); // shifts nocc/nvirt between the spin channels: must run exactly once } else if (nupdown_now != this->nupdown) { @@ -331,7 +331,7 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) // re-publishes in its `before_scf`; make sure it names the object we integrate on ModuleGint::Gint::set_gint_info(this->ks_->gint_info_.get()); - // the Z-vector window: after `reset_dim_spin2`, so nocc/nvirt/openshell are final + // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final #ifdef __MPI this->fill_z_window_(ks_sol.pv.desc_wfc); #else @@ -389,7 +389,7 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell LR::setup_2center_table(this->two_center_bundle_own_, ucell, *this->inp_); } - this->set_dimension(); + this->set_dim(); // setup 2d-block distribution for AO-matrix and KS wfc LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); this->set_parallel_orbitals_band(this->paraMat_, this->nbands); @@ -409,9 +409,9 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell if (nspin == 2) { // Complete file populations were read before selecting the occupied window. - reset_dim_spin2(); + reset_dim_spin(); } - // the Z-vector window: after `reset_dim_spin2`, so nocc/nvirt/openshell are final + // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final #ifdef __MPI this->fill_z_window_(paraMat_all_.desc_wfc); #else diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index d33b5a520a..82bb183557 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -53,7 +53,7 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para LR::setup_2center_table(this->two_center_bundle_own_, ucell, *this->inp_); } - this->set_dimension(); + this->set_dim(); // setup 2d-block distribution for AO-matrix and KS wfc LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); #ifdef __MPI @@ -74,7 +74,7 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para { this->nupdown = LR_Util::spin_population_difference(this->pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); - this->reset_dim_spin2(); + this->reset_dim_spin(); } LR_Util::setup_2d_division( diff --git a/source/source_esolver/esolver_lr_lcao_tddft.h b/source/source_esolver/esolver_lr_lcao_tddft.h index 130ce86cda..5b8ea93651 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr_lcao_tddft.h @@ -248,9 +248,9 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// @brief check the legality of the input parameters /// @brief set nocc, nvirt, nbasis, npairs and nstates - void set_dimension(); + void set_dim(); /// reset nocc, nvirt, npairs after read ground-state wavefunction when nspin=2 - void reset_dim_spin2(); + void reset_dim_spin(); /// setup Parallel_Orbitals info. beyond Parallel_Blkcyclic void set_parallel_orbitals_band(Parallel_Orbitals &p, const int nbands_in); diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 18abcd3cbe..991c5db802 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -25,6 +25,7 @@ if(ENABLE_LCAO) potentials/pot_hxc_lrtd.cpp potentials/pot_grad_xc.cpp kernel_pots.cpp + lr_dim.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp 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 0fa7f047c4..de7be9600d 100644 --- a/source/source_lcao/module_lr/cal_w_from_z.h +++ b/source/source_lcao/module_lr/cal_w_from_z.h @@ -251,7 +251,7 @@ namespace LR const std::vector ld_x = { static_cast(nk * px[0].size()), static_cast(nk * px[1].size()) }; const std::vector ld_oo = { static_cast(nk * p_occ_occ[0].size()), static_cast(nk * p_occ_occ[1].size()) }; const std::vector off_x = { 0, ld_x[0] }; - const int nband_window = nocc[0] + nvirt[0]; // common KS window, see `set_dimension` + const int nband_window = nocc[0] + nvirt[0]; // common KS window, see `set_dim` W.assign(2, {}); for (int is: {0, 1}) diff --git a/source/source_lcao/module_lr/lr_dim.cpp b/source/source_lcao/module_lr/lr_dim.cpp new file mode 100644 index 0000000000..b6ba8c192f --- /dev/null +++ b/source/source_lcao/module_lr/lr_dim.cpp @@ -0,0 +1,170 @@ +#include "source_lcao/module_lr/lr_dim.h" + +#include "source_base/matrix.h" +#include "source_base/tool_quit.h" +#include "source_cell/unitcell.h" +#include "source_io/module_parameter/input_parameter.h" +#include "source_io/module_wf/read_wfc_nao.h" +#include "source_lcao/module_lr/utils/lr_io.h" +#include "source_lcao/module_lr/utils/lr_util.h" + +#include +#include +#include +#include + +namespace LR +{ + +Dim resolve_dim(const DimSrc& src) +{ + Dim dim; + const Input_para& inp = *src.inp; + + dim.nspin = inp.nspin; + dim.nstates = inp.lr_nstates; + dim.nbasis = src.nlocal; + dim.ks_nbands = inp.nbands; + if (dim.nspin == 2) + { + dim.nupdown = static_cast(std::lround(inp.nupdown)); + if (src.wg_ks) + { + dim.nupdown = LR_Util::spin_population_difference(*src.wg_ks, src.kpar, src.rank_in_pool); + } + else if (inp.ri_hartree_benchmark != "aims" && inp.ri_hartree_benchmark != "aims-librpa") + { + std::vector populations; + const bool binary = inp.init_wfc_file_format == "binary"; + if (!ModuleIO::read_wfc_nao_spin_populations( + src.in_dir, src.nkstot, dim.nspin, src.gamma_only, binary, src.rank, populations)) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "read complete KS occupations failed"); + } + dim.nupdown = static_cast(std::lround(populations[0]) - std::lround(populations[1])); + } + } + // read_pseudo/ParamUpdater has already resolved nelec and applied nelec_delta. + dim.nocc_max = LR_Util::cal_nocc(inp.nelec, dim.nspin, dim.nupdown); + if (inp.ri_hartree_benchmark == "aims" + || (inp.ri_hartree_benchmark == "aims-librpa" && !inp.aims_nbasis.empty())) + { + resolve_aims_basis(*src.ucell, inp, dim); + } + // calculate the number of occupied and unoccupied states + // which determines the basis size of the excited states + dim.nocc_in = LR_Util::cal_nocc_window(inp.nocc, dim.nocc_max); + dim.nvirt_in = dim.ks_nbands - dim.nocc_max; // nbands-nocc + if (inp.nvirt > dim.nvirt_in) + { + if (src.log) + { + *src.log << "ESolver_LR: input nvirt is too large to cover by nbands, set nvirt = nbands - nocc = " + << dim.nvirt_in << std::endl; + } + } + else if (inp.nvirt > 0) + { + dim.nvirt_in = inp.nvirt; + } + dim.nbands = dim.nocc_in + dim.nvirt_in; + dim.nk = inp.nspin == 2 ? src.nks / 2 : src.nks; + dim.nocc.assign(dim.nspin, dim.nocc_in); + dim.nvirt.assign(dim.nspin, dim.nvirt_in); + if (dim.nstates <= 0) + { + dim.nstates = dim.nk * dim.nocc_in * dim.nvirt_in; + if (src.log) + { + *src.log << "ESolver_LR: lr_nstates <= 0, set nstates = nk * nocc * nvirt = " << dim.nstates << std::endl; + } + } + dim.npairs.resize(dim.nspin); + for (int is = 0; is < dim.nspin; ++is) + { + dim.npairs[is] = dim.nocc[is] * dim.nvirt[is]; + } + if (src.log) + { + std::ostream& log = *src.log; + log << "Setting LR-TDDFT parameters: " << std::endl; + log << "full occupied bands in largest spin channel: " << dim.nocc_max << std::endl; + const int skipped_core_bands = dim.nocc_max - dim.nocc_in; + log << "shared core bands omitted from LR window: " << skipped_core_bands << std::endl; + log << "number of occupied bands: " << dim.nocc_in << std::endl; + log << "number of virtual bands: " << dim.nvirt_in << std::endl; + log << "number of Atom orbitals (LCAO-basis size): " << dim.nbasis << std::endl; + // eig_ks is allocated after resolve_dim; report the resolved counts here. + log << "number of KS bands: " << dim.ks_nbands << std::endl; + log << "number of KS bands in LR window: " << dim.nbands << std::endl; + log << "number of excited states to be solved: " << dim.nstates << std::endl; + } + return dim; +} + +void resolve_aims_basis(UnitCell& ucell, const Input_para& inp, Dim& dim) +{ + // Total basis size: sum the per-atom basis size times the atom count for each type. + int total_nbasis = 0; + for (std::size_t it = 0; it < inp.aims_nbasis.size(); ++it) + { + total_nbasis += inp.aims_nbasis[it] * ucell.atoms[it].na; + } + dim.nbasis = total_nbasis; + std::cout << "nbasis from aims: " << dim.nbasis << std::endl; + for (int it = 0; it < ucell.ntype; ++it) + { + ucell.atoms[it].nw = inp.aims_nbasis[it]; + } + ucell.set_iat2iwt(1); // update iat2iwt for aims_nbasis + + int nbands_file = 0; + int nk_file = 0; + int nspin_file = 0; + int nocc_file = 0; + LR_IO::parse_band_out_file(inp.rpa_outdir, nbands_file, nk_file, nspin_file, nocc_file); + std::cout << "nocc from band_out: " << nocc_file << std::endl; + dim.ks_nbands = nbands_file; + dim.nocc_max = nocc_file; +} + +void apply_spin_pol(Dim& dim, const Input_para& inp) +{ + if (dim.nspin != 2) + { + return; + } + if (dim.nupdown != 0) + { + dim.openshell = true; + const int minority_spin = dim.nupdown > 0 ? 1 : 0; + const int polarization = std::abs(dim.nupdown); + dim.nocc[minority_spin] -= polarization; + dim.nvirt[minority_spin] += polarization; + dim.npairs = {dim.nocc[0] * dim.nvirt[0], dim.nocc[1] * dim.nvirt[1]}; + std::cout << "** Solve the spin-up and spin-down states separately for open-shell system. **" << std::endl; + } + for (int is : {0, 1}) + { + if (dim.npairs[is] <= 0) + { + throw std::invalid_argument( + std::string("ESolver_LR: npairs (nocc*nvirt) <= 0 for spin") + std::string(is == 0 ? "up" : "down")); + } + } + + if (dim.nstates > (dim.npairs[0] + dim.npairs[1]) * dim.nk) + { + throw std::invalid_argument("ESolver_LR: nstates > nocc*nvirt*nk"); + } + if (inp.lr_unrestricted) + { + dim.openshell = true; + } + if (!dim.openshell) + { + std::cout << " ** Assuming degenerate spin-up and spin-down states **" << std::endl; + } +} + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_dim.h b/source/source_lcao/module_lr/lr_dim.h new file mode 100644 index 0000000000..3f5a835b6a --- /dev/null +++ b/source/source_lcao/module_lr/lr_dim.h @@ -0,0 +1,64 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_DIM_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_DIM_H + +#include +#include +#include + +namespace ModuleBase +{ +class matrix; +} +class UnitCell; +struct Input_para; + +namespace LR +{ +/// Resolved dimensions of the LR(-TDDFT) problem. +struct Dim +{ + int nspin = 1; + int nstates = 1; + int nbasis = 1; + int nbands = 2; + int nk = 1; + int nupdown = 0; + int nocc_in = 1; + int nocc_max = 1; + int nvirt_in = 1; + int ks_nbands = 0; + bool openshell = false; + std::vector nocc; + std::vector nvirt; + std::vector npairs; +}; + +/// Everything `resolve_dim` needs from the caller; no solver state is read implicitly. +struct DimSrc +{ + const Input_para* inp = nullptr; + int nlocal = 0; ///< PARAM.globalv.nlocal + int nks = 0; ///< K_Vectors::get_nks() + int nkstot = 0; ///< K_Vectors::get_nkstot() + int rank = 0; ///< MPI rank in the world communicator + bool gamma_only = false; ///< real build + const ModuleBase::matrix* wg_ks = nullptr; ///< KS occupations; null on the file (`lr`) path + int kpar = 1; ///< K_Vectors::para_k.kpar + int rank_in_pool = 0; ///< K_Vectors::para_k.rank_in_pool + std::string in_dir; + UnitCell* ucell = nullptr; ///< only written on the AIMS benchmark path + std::ostream* log = nullptr; ///< `ofs_running`; may be null +}; + +/// Resolve nspin/nstates/nbasis/nbands/nk/nocc/nvirt/npairs from input and the ground state. +Dim resolve_dim(const DimSrc& src); + +/// AIMS / AIMS-LibRPA benchmark: basis size and band count come from `aims_nbasis` + band_out. +void resolve_aims_basis(UnitCell& ucell, const Input_para& inp, Dim& dim); + +/// `nspin == 2`: split nocc/nvirt between the spin channels and decide open/closed shell. +void apply_spin_pol(Dim& dim, const Input_para& inp); + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_DIM_H From 199e40dd86e6eb87f364d2e4581f62627532daa2 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 14:39:24 +0800 Subject: [PATCH 02/26] refactor(lr): move ground-state setup into module_lr Add LR::set_band_layout, make_amp_layout, set_x_init, read_wfc_*, build_z_win and read_gs_chg so esolver_lr_orb.cpp only forwards member state. Wavefunction/charge reading, amplitude distributions and the Z-vector window no longer depend on the solver class. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr_lcao_tddft.h | 1 - source/source_esolver/esolver_lr_orb.cpp | 307 ++-------------- source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/lr_gs.cpp | 344 ++++++++++++++++++ source/source_lcao/module_lr/lr_gs.h | 87 +++++ 6 files changed, 468 insertions(+), 273 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_gs.cpp create mode 100644 source/source_lcao/module_lr/lr_gs.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 2c2d8dd6fb..47b20af075 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1195,6 +1195,7 @@ OBJS_TENSOR=tensor.o\ lr_spectrum_velocity.o\ hamilt_casida.o\ lr_dim.o\ + lr_gs.o\ esolver_lr_orb.o\ esolver_lr_init.o\ esolver_lr_cfg.o\ diff --git a/source/source_esolver/esolver_lr_lcao_tddft.h b/source/source_esolver/esolver_lr_lcao_tddft.h index 5b8ea93651..1eea8c632c 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr_lcao_tddft.h @@ -237,7 +237,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// @brief allocate and set the inital value of X void setup_eigenvectors_X(); - void set_X_initial_guess(); /// @brief read in the ground state wave function, band energy and occupation virtual void read_ks_wfc(); diff --git a/source/source_esolver/esolver_lr_orb.cpp b/source/source_esolver/esolver_lr_orb.cpp index a397110f43..71438c970f 100644 --- a/source/source_esolver/esolver_lr_orb.cpp +++ b/source/source_esolver/esolver_lr_orb.cpp @@ -1,68 +1,30 @@ // LR orbital distributions, excitation amplitudes, and ground-state file input. #include "esolver_lr_lcao_tddft.h" -#include "source_base/module_external/scalapack_connector.h" -#include "source_base/module_parallel/para_bridge.h" -#include "source_estate/module_charge/chg_rhog_io.h" -#include "source_io/module_output/cube_io.h" -#include "source_io/module_wf/read_wfc_nao.h" -#include "source_lcao/module_lr/ri_benchmark/ri_benchmark.h" +#include "source_base/tool_quit.h" +#include "source_base/tool_title.h" +#include "source_lcao/module_lr/lr_gs.h" #include "source_lcao/module_lr/utils/lr_util.h" -#include -using namespace LR; +#include +#include +#include template void ModuleESolver::ESolver_LR::set_parallel_orbitals_band(Parallel_Orbitals &pmat, const int nbands_in) { -#ifdef __MPI - pmat.set_wfc_and_mo_layouts(this->nbasis, nbands_in); - // The KS helper rejects empty band columns. LR windows may legitimately - // have fewer blocks than the inherited KS process grid has columns. - Parallel_Blkcyclic bands; - const int block_size = pmat.para_2d().nb(); - LR_Util::setup_2d_division(bands, block_size, this->nbasis, nbands_in, pmat.para_2d().ictxt()); - pmat.nbands = nbands_in; - pmat.nrow_bands = bands.nrloc(); - pmat.ncol_bands = bands.ncloc(); - pmat.nloc_wfc = bands.size(); - // Skipped for the aims benchmark: with `aims_nbasis` the per-atom orbital counts behind - // `iat2iwt` do not match `nbasis`, so the atomic trace would be wrong. The guard came from - // d4fe3fe84 ("Support different basis number from aims"), and was silently undone by - // 1e4c1c6af (BSE, #7718) re-adding an unconditional call above it. - if (this->inp_->ri_hartree_benchmark != "aims") - { - pmat.set_atomic_trace(this->ucell_->get_iat2iwt(), this->ucell_->nat, this->nbasis); - } -#else - pmat.nrow_bands = this->nbasis; - pmat.ncol_bands = nbands_in; -#endif + LR::set_band_layout(pmat, this->nbasis, nbands_in, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); } template void ModuleESolver::ESolver_LR::setup_eigenvectors_X() { ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); - // this function is called once per `runner`, and `paraX_` is only ever appended to, - // so without this reset a second ionic step would double its size - this->paraX_.clear(); - const int block_size = this->paraC_.nb(); - for (int is = 0; is < nspin; ++is) - { - Parallel_Blkcyclic px; - LR_Util::setup_2d_division( - px, block_size, this->nvirt[is], this->nocc[is] -#ifdef __MPI - , - this->paraC_.ictxt() -#endif - ); // nvirt - row, nocc - col - this->paraX_.emplace_back(std::move(px)); - } - this->nloc_per_state = nk * (openshell ? paraX_[0].size() + paraX_[1].size() : paraX_[0].size()); + LR::AmpLayout layout = LR::make_amp_layout(this->paraC_, this->nocc, this->nvirt, this->nk, this->openshell); + this->paraX_ = std::move(layout.para_x); + this->nloc_per_state = layout.nloc; - this->X.resize(openshell ? 1 : nspin, LR_Util::newTensor({nstates, nloc_per_state})); - for (container::Tensor& x : X) + this->X.resize(this->openshell ? 1 : this->nspin, LR_Util::newTensor({this->nstates, this->nloc_per_state})); + for (container::Tensor& x : this->X) { x.zero(); } @@ -70,65 +32,8 @@ void ModuleESolver::ESolver_LR::setup_eigenvectors_X() // if spectrum-only, read the LR-eigenstates from file and return if (this->inp_->lr_solver != "spectrum") { - set_X_initial_guess(); - } -} - -template -void ModuleESolver::ESolver_LR::set_X_initial_guess() -{ - // set the initial guess of X - for (int is = 0; is < this->nspin; ++is) - { - const int &no = this->nocc[is]; - const int &nv = this->nvirt[is]; - const int &np = this->npairs[is]; - const Parallel_Blkcyclic &px = this->paraX_[is]; - - // if (E_{lumo}-E_{homo-1} < E_{lumo+1}-E{homo}), mode = 0, else 1(smaller first) - bool ix_mode = false; // default - if (this->eig_ks.nc > no + 1 && no >= 2 && - eig_ks(is, no) - eig_ks(is, no - 2) - 1e-5 > eig_ks(is, no + 1) - eig_ks(is, no - 1)) - { - ix_mode = true; - } - this->ofs_running_ << "setting the initial guess of X of spin" << is << std::endl; - if (no >= 2 && eig_ks.nc > no) - { - this->ofs_running_ << "E_{lumo}-E_{homo-1}=" << eig_ks(is, no) - eig_ks(is, no - 2) << std::endl; - } - if (no >= 1 && eig_ks.nc > no + 1) - { - this->ofs_running_ << "E_{lumo+1}-E{homo}=" << eig_ks(is, no + 1) - eig_ks(is, no - 1) << std::endl; - } - this->ofs_running_ << "mode of X-index: " << ix_mode << std::endl; - - /// global index map between (i,c) and ix - ModuleBase::matrix ioiv2ix; - std::vector> ix2ioiv; - std::pair>> indexmap = - LR_Util::set_ix_map_diagonal(ix_mode, no, nv); - - ioiv2ix = std::move(std::get<0>(indexmap)); - ix2ioiv = std::move(std::get<1>(indexmap)); - - for (int ib = 0; ib < nstates; ++ib) - { - const int ipair = ib % np; - const int occ_global = std::get<0>(ix2ioiv[ipair]); // occ - const int virt_global = std::get<1>(ix2ioiv[ipair]); // virt - const int ik = ib / np; - const int xstart_b = ib * nloc_per_state; // start index of band ib - const int xstart_bs = - (openshell && is == 1) ? xstart_b + nk * paraX_[0].size() : xstart_b; // start index of band ib, spin is - const int is_in_x = openshell ? 0 : is; // if openshell, spin-up and spin-down are put together - if (px.in_this_processor(virt_global, occ_global)) - { - const int xstart_pair = ik * px.size(); - const int ipair_loc = px.icloc(occ_global) * px.nrloc() + px.irloc(virt_global); - X[is_in_x].data()[xstart_bs + xstart_pair + ipair_loc] = (static_cast(1.0) / static_cast(nk)); - } - } + LR::set_x_init(this->X, this->eig_ks, this->nocc, this->nvirt, this->npairs, this->paraX_, this->nstates, + this->nloc_per_state, this->nk, this->openshell, this->ofs_running_); } } @@ -140,31 +45,12 @@ void ModuleESolver::ESolver_LR::read_ks_wfc() this->wg_ks.create(this->kv.get_nks(), this->nbands); if (this->inp_->ri_hartree_benchmark == "aims") // for aims benchmark { -#ifdef __EXX - int ncore = 0; - std::vector eig_ks_vec = - RI_Benchmark::read_aims_ebands(this->in_dir + "band_out", nocc_in, nvirt_in, ncore); - std::cout << "ncore=" << ncore << ", nocc=" << nocc_in << ", nvirt=" << nvirt_in << ", nbands=" << this->nbands - << std::endl; - std::cout << "eig_ks_vec.size()=" << eig_ks_vec.size() << std::endl; - if (eig_ks_vec.size() != this->nbands) - { - ModuleBase::WARNING_QUIT("ESolver_LR", "read_aims_ebands failed."); - }; - for (int i = 0; i < nbands; ++i) - { - this->eig_ks(0, i) = eig_ks_vec[i]; - } - RI_Benchmark::read_aims_eigenvectors( - *this->psi_ks, this->in_dir + "KS_eigenvectors.out", ncore, nbands, nbasis); -#else - ModuleBase::WARNING_QUIT("ESolver_LR", "RI benchmark is only supported when compile with LibRI."); -#endif + LR::read_wfc_aims(*this->psi_ks, this->eig_ks, this->in_dir, this->nocc_in, this->nvirt_in, this->nbands, + this->nbasis); } - else if (!ModuleIO::read_wfc_nao( - this->in_dir, this->paraMat_, *this->psi_ks, this->eig_ks, this->wg_ks, this->kv.ik2iktot, - this->kv.get_nkstot(), this->inp_->nspin, this->inp_->init_wfc_file_format == "binary", - /*skip_bands=*/this->nocc_max - this->nocc_in)) + else if (!LR::read_wfc_win(this->in_dir, this->paraMat_, *this->psi_ks, this->eig_ks, this->wg_ks, this->kv, + this->inp_->nspin, this->inp_->init_wfc_file_format == "binary", + /*skip_bands=*/this->nocc_max - this->nocc_in)) { ModuleBase::WARNING_QUIT("ESolver_LR", "read ground-state wavefunction failed."); } @@ -176,10 +62,8 @@ void ModuleESolver::ESolver_LR::read_ks_wfc() this->psi_ks_all_ = this->psi_ks_all_own_.get(); this->eig_ks_all.create(this->kv.get_nks(), this->inp_->nbands); this->wg_ks_all.create(this->kv.get_nks(), this->inp_->nbands); - if (!ModuleIO::read_wfc_nao( - this->in_dir, paraMat_all_, *this->psi_ks_all_, this->eig_ks_all, this->wg_ks_all, this->kv.ik2iktot, - this->kv.get_nkstot(), this->inp_->nspin, this->inp_->init_wfc_file_format == "binary", - /*skip_bands=*/0)) + if (!LR::read_wfc_all(this->in_dir, paraMat_all_, *this->psi_ks_all_, this->eig_ks_all, this->wg_ks_all, + this->kv, this->inp_->nspin, this->inp_->init_wfc_file_format == "binary")) { ModuleBase::WARNING_QUIT("ESolver_LR", "read all ground-state wavefunctions for force calculation failed."); } @@ -191,146 +75,25 @@ template void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) { ModuleBase::TITLE("ESolver_LR", "fill_z_window_"); - if (!this->inp_->cal_force || this->psi_ks_all_ == nullptr) - { - return; - } - - const int max_occupied_bands = *std::max_element(nocc.begin(), nocc.end()); - const int start_band = this->nocc_max - max_occupied_bands; - // Every band the ground state solved, from the window start upward. `eig_ks_all` is the - // authority on how many there are: on the ks-lr path it is the KS solver's `ekb`, on the - // file path it was read with `skip_bands = 0`. - this->nbands_z_ = this->eig_ks_all.nc - start_band; - if (this->nbands_z_ <= this->nbands) - { // nothing to widen: nbands was already at (or below) the X window - this->nbands_z_ = this->nbands; - } - this->nvirt_z_.assign(this->nspin, 0); - for (int is = 0; is < this->nspin; ++is) - { - this->nvirt_z_[is] = this->nbands_z_ - this->nocc[is]; - } - - const int block_size = this->paraC_.nb(); - LR_Util::setup_2d_division( - this->paraC_z_, block_size, this->nbasis, this->nbands_z_ -#ifdef __MPI - , - this->paraMat_.para_2d().ictxt() -#endif - ); - this->paraX_z_.clear(); - for (int is = 0; is < this->nspin; ++is) - { - Parallel_Blkcyclic px; - LR_Util::setup_2d_division( - px, block_size, this->nvirt_z_[is], this->nocc[is] -#ifdef __MPI - , - this->paraC_z_.ictxt() -#endif - ); - this->paraX_z_.emplace_back(std::move(px)); - } - // Open shell solves one eigenproblem whose vector is the concatenation [up | down], so a - // state's block is as long as both channels together; the closed-shell singlet/triplet - // algorithm carries a single channel. (Same rule as `nloc_per_state` in - // `setup_eigenvectors_X`, applied to the widened windows.) - this->nloc_per_state_z_ = - this->nk * (this->openshell ? this->paraX_z_[0].size() + this->paraX_z_[1].size() : this->paraX_z_[0].size()); - -#ifdef __MPI - this->psi_ks_z_.reset( - new psi::Psi(this->kv.get_nks(), this->paraC_z_.ncloc(), this->paraC_z_.nrloc(), this->kv.ngk, true)); -#else - this->psi_ks_z_.reset(new psi::Psi(this->kv.get_nks(), this->nbands_z_, this->nbasis, this->kv.ngk, true)); -#endif - this->eig_ks_z_.create(this->kv.get_nks(), this->nbands_z_); - - for (int ik = 0; ik < this->kv.get_nks(); ++ik) - { - // same redistribution `refresh_from_ks_` does for the X window, over more bands -#ifdef __MPI - this->psi_ks_all_->fix_k(ik); - this->psi_ks_z_->fix_k(ik); - const int first_band = start_band + 1; - Cpxgemr2d( - this->nbasis, this->nbands_z_, this->psi_ks_all_->get_pointer(), 1, first_band, const_cast(desc_src), - this->psi_ks_z_->get_pointer(), 1, 1, const_cast(this->paraC_z_.desc()), this->paraC_z_.ictxt()); -#else - for (int ib = 0; ib < this->nbands_z_; ++ib) - { - const auto *start = &(*this->psi_ks_all_)(ik, start_band + ib, 0); - std::copy(start, start + this->nbasis, &(*this->psi_ks_z_)(ik, ib, 0)); - } -#endif - for (int ib = 0; ib < this->nbands_z_; ++ib) - { - this->eig_ks_z_(ik, ib) = this->eig_ks_all(ik, start_band + ib); - } - } - this->ofs_running_ << "Z-vector window: nbands = " << this->nbands_z_ << " (X window: " << this->nbands - << "), nvirt ="; - for (int is = 0; is < this->nspin; ++is) - { - this->ofs_running_ << " " << this->nvirt_z_[is] << "(X window: " << this->nvirt[is] << ")"; - } - this->ofs_running_ << std::endl; - // Initialization precedes ks_initialized_; subsequent geometry refreshes keep - // 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_); - if (!warning.empty()) - { - this->ofs_running_ << warning << std::endl; - } - } + LR::ZWin z = LR::build_z_win(this->psi_ks_all_, this->eig_ks_all, this->nocc, this->nvirt, this->nocc_max, + this->nbands, this->nbasis, this->nk, this->openshell, this->kv, this->paraC_, + this->paraMat_, desc_src, this->inp_->cal_force, !this->ks_initialized_, + this->ofs_running_); + this->psi_ks_z_ = std::move(z.psi); + this->eig_ks_z_ = std::move(z.eig); + this->paraC_z_ = std::move(z.para_c); + this->paraX_z_ = std::move(z.para_x); + this->nvirt_z_ = std::move(z.nvirt); + this->nbands_z_ = z.nbands; + this->nloc_per_state_z_ = z.nloc; } template void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) { - chg_gs.set_rhopw(this->pw_rho); - const bool kin_den = XC_Functional::get_ked_flag() || (this->inp_->out_elf[0] > 0); // mohan add 20251202 - chg_gs.allocate(this->nspin, kin_den, XC_Functional::get_ked_flag(), this->inp_->test_charge); - // Keep the existing cube input authoritative. Choose one density source for - // all spin channels and broadcast the decision before collective readers. - const Parallel::ParaWorld world = Parallel::make_pw_world(); - const bool have_cubes = module_charge::has_complete_charge_cubes(this->in_dir, this->nspin, world); - if (!have_cubes) - { - const std::string density_file = this->in_dir + this->inp_->suffix + "-CHARGE-DENSITY.restart"; - const bool loaded = module_charge::read_rho_from_binary( - density_file, *this->pw_rho, this->nspin, chg_gs.rhog, chg_gs.rho, world, this->ofs_running_); - if (!loaded) - { - const std::string message = "No complete charge cube set or readable density restart in " + this->in_dir; - ModuleBase::WARNING_QUIT("ESolver_LR::read_ks_chg", message); - } - return; - } - this->ofs_running_ << " try to read charge from file : "; - for (int is = 0; is < this->nspin; ++is) - { - std::stringstream ssc; - if (this->nspin == 1) - { - ssc << this->in_dir << "chg.cube"; - } - else - { - ssc << this->in_dir << "chgs" << is + 1 << ".cube"; - } - this->ofs_running_ << ssc.str() << std::endl; - if (ModuleIO::read_vdata_palgrid( - pgrid(), this->my_rank_, this->ofs_running_, ssc.str(), chg_gs.rho[is], this->ucell_->nat)) - { - this->ofs_running_ << " Read in the charge density: " << ssc.str() << std::endl; - } - } + LR::read_gs_chg(this->in_dir, *this->inp_, this->nspin, *this->ucell_, pgrid(), this->pw_rho, chg_gs, + this->my_rank_, this->ofs_running_); } + template class ModuleESolver::ESolver_LR; template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 991c5db802..211d6e0a53 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -26,6 +26,7 @@ if(ENABLE_LCAO) potentials/pot_grad_xc.cpp kernel_pots.cpp lr_dim.cpp + lr_gs.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/lr_gs.cpp b/source/source_lcao/module_lr/lr_gs.cpp new file mode 100644 index 0000000000..7a057c58b3 --- /dev/null +++ b/source/source_lcao/module_lr/lr_gs.cpp @@ -0,0 +1,344 @@ +// LR ground-state distributions, excitation amplitudes, and file input. +#include "source_lcao/module_lr/lr_gs.h" + +#include "source_base/module_external/scalapack_connector.h" +#include "source_base/module_parallel/para_bridge.h" +#include "source_base/tool_quit.h" +#include "source_basis/module_pw/pw_basis.h" +#include "source_cell/klist.h" +#include "source_cell/unitcell.h" +#include "source_estate/module_charge/charge.h" +#include "source_estate/module_charge/chg_rhog_io.h" +#include "source_hamilt/module_xc/xc_functional.h" +#include "source_io/module_output/cube_io.h" +#include "source_io/module_parameter/input_parameter.h" +#include "source_io/module_wf/read_wfc_nao.h" +#include "source_lcao/module_lr/ri_benchmark/ri_benchmark.h" + +#include +#include +#include + +namespace LR +{ + +void set_band_layout(Parallel_Orbitals& pmat, int nbasis, int nbands, const UnitCell& ucell, bool aims) +{ +#ifdef __MPI + pmat.set_wfc_and_mo_layouts(nbasis, nbands); + // The KS helper rejects empty band columns. LR windows may legitimately + // have fewer blocks than the inherited KS process grid has columns. + Parallel_Blkcyclic bands; + const int block_size = pmat.para_2d().nb(); + LR_Util::setup_2d_division(bands, block_size, nbasis, nbands, pmat.para_2d().ictxt()); + pmat.nbands = nbands; + pmat.nrow_bands = bands.nrloc(); + pmat.ncol_bands = bands.ncloc(); + pmat.nloc_wfc = bands.size(); + // Skipped for the aims benchmark: with `aims_nbasis` the per-atom orbital counts behind + // `iat2iwt` do not match `nbasis`, so the atomic trace would be wrong. The guard came from + // d4fe3fe84 ("Support different basis number from aims"), and was silently undone by + // 1e4c1c6af (BSE, #7718) re-adding an unconditional call above it. + if (!aims) + { + pmat.set_atomic_trace(ucell.get_iat2iwt(), ucell.nat, nbasis); + } +#else + pmat.nrow_bands = nbasis; + pmat.ncol_bands = nbands; +#endif +} + +AmpLayout make_amp_layout(const Parallel_Blkcyclic& para_c, const std::vector& nocc, + const std::vector& nvirt, int nk, bool openshell) +{ + AmpLayout layout; + const int block_size = para_c.nb(); + layout.para_x.reserve(nocc.size()); + for (int is = 0; is < static_cast(nocc.size()); ++is) + { + Parallel_Blkcyclic px; + LR_Util::setup_2d_division(px, block_size, nvirt[is], nocc[is] +#ifdef __MPI + , + para_c.ictxt() +#endif + ); // nvirt - row, nocc - col + layout.para_x.emplace_back(std::move(px)); + } + layout.nloc = + nk * (openshell ? layout.para_x[0].size() + layout.para_x[1].size() : layout.para_x[0].size()); + return layout; +} + +template +void set_x_init(std::vector& X, const ModuleBase::matrix& eig_ks, const std::vector& nocc, + const std::vector& nvirt, const std::vector& npairs, + const std::vector& para_x, int nstates, int nloc, int nk, bool openshell, + std::ostream& log) +{ + // set the initial guess of X + for (int is = 0; is < static_cast(nocc.size()); ++is) + { + const int& no = nocc[is]; + const int& nv = nvirt[is]; + const int& np = npairs[is]; + const Parallel_Blkcyclic& px = para_x[is]; + + // if (E_{lumo}-E_{homo-1} < E_{lumo+1}-E{homo}), mode = 0, else 1(smaller first) + bool ix_mode = false; // default + if (eig_ks.nc > no + 1 && no >= 2 + && eig_ks(is, no) - eig_ks(is, no - 2) - 1e-5 > eig_ks(is, no + 1) - eig_ks(is, no - 1)) + { + ix_mode = true; + } + log << "setting the initial guess of X of spin" << is << std::endl; + if (no >= 2 && eig_ks.nc > no) + { + log << "E_{lumo}-E_{homo-1}=" << eig_ks(is, no) - eig_ks(is, no - 2) << std::endl; + } + if (no >= 1 && eig_ks.nc > no + 1) + { + log << "E_{lumo+1}-E{homo}=" << eig_ks(is, no + 1) - eig_ks(is, no - 1) << std::endl; + } + log << "mode of X-index: " << ix_mode << std::endl; + + /// global index map between (i,c) and ix + const auto indexmap = LR_Util::set_ix_map_diagonal(ix_mode, no, nv); + const std::vector>& ix2ioiv = std::get<1>(indexmap); + + for (int ib = 0; ib < nstates; ++ib) + { + const int ipair = ib % np; + const int occ_global = ix2ioiv[ipair].first; + const int virt_global = ix2ioiv[ipair].second; + const int ik = ib / np; + const int xstart_b = ib * nloc; // start index of band ib + const int xstart_bs = + (openshell && is == 1) ? xstart_b + nk * para_x[0].size() : xstart_b; // start index of band ib, spin is + const int is_in_x = openshell ? 0 : is; // if openshell, spin-up and spin-down are put together + if (px.in_this_processor(virt_global, occ_global)) + { + const int xstart_pair = ik * px.size(); + const int ipair_loc = px.icloc(occ_global) * px.nrloc() + px.irloc(virt_global); + X[is_in_x].data()[xstart_bs + xstart_pair + ipair_loc] = (static_cast(1.0) / static_cast(nk)); + } + } + } +} + +template +void read_wfc_aims(psi::Psi& psi, ModuleBase::matrix& eig, const std::string& in_dir, int nocc_in, int nvirt_in, + int nbands, int nbasis) +{ +#ifdef __EXX + int ncore = 0; + std::vector eig_ks_vec = + RI_Benchmark::read_aims_ebands(in_dir + "band_out", nocc_in, nvirt_in, ncore); + std::cout << "ncore=" << ncore << ", nocc=" << nocc_in << ", nvirt=" << nvirt_in << ", nbands=" << nbands + << std::endl; + std::cout << "eig_ks_vec.size()=" << eig_ks_vec.size() << std::endl; + if (eig_ks_vec.size() != static_cast(nbands)) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "read_aims_ebands failed."); + } + for (int i = 0; i < nbands; ++i) + { + eig(0, i) = eig_ks_vec[i]; + } + RI_Benchmark::read_aims_eigenvectors(psi, in_dir + "KS_eigenvectors.out", ncore, nbands, nbasis); +#else + ModuleBase::WARNING_QUIT("ESolver_LR", "RI benchmark is only supported when compile with LibRI."); +#endif +} + +template +bool read_wfc_win(const std::string& in_dir, const Parallel_Orbitals& pmat, psi::Psi& psi, ModuleBase::matrix& eig, + ModuleBase::matrix& wg, const K_Vectors& kv, int nspin, bool binary, int skip_bands) +{ + return ModuleIO::read_wfc_nao(in_dir, pmat, psi, eig, wg, kv.ik2iktot, kv.get_nkstot(), nspin, binary, + skip_bands); +} + +template +bool read_wfc_all(const std::string& in_dir, const Parallel_Orbitals& pmat, psi::Psi& psi, ModuleBase::matrix& eig, + ModuleBase::matrix& wg, const K_Vectors& kv, int nspin, bool binary) +{ + return ModuleIO::read_wfc_nao(in_dir, pmat, psi, eig, wg, kv.ik2iktot, kv.get_nkstot(), nspin, binary, + /*skip_bands=*/0); +} + +template +ZWin build_z_win(psi::Psi* psi_all, const ModuleBase::matrix& eig_all, const std::vector& nocc, + const std::vector& nvirt, int nocc_max, int nbands_x, int nbasis, int nk, bool openshell, + const K_Vectors& kv, const Parallel_Blkcyclic& para_c, const Parallel_Orbitals& pmat, + const int* desc_src, bool need, bool diagnose, std::ostream& log) +{ + ZWin z; + if (!need || psi_all == nullptr) + { + return z; + } + + const int max_occupied_bands = *std::max_element(nocc.begin(), nocc.end()); + const int start_band = nocc_max - max_occupied_bands; + // Every band the ground state solved, from the window start upward. `eig_all` is the + // authority on how many there are: on the ks-lr path it is the KS solver's `ekb`, on the + // file path it was read with `skip_bands = 0`. + z.nbands = eig_all.nc - start_band; + if (z.nbands <= nbands_x) + { // nothing to widen: nbands was already at (or below) the X window + z.nbands = nbands_x; + } + const int nspin = static_cast(nocc.size()); + z.nvirt.assign(nspin, 0); + for (int is = 0; is < nspin; ++is) + { + z.nvirt[is] = z.nbands - nocc[is]; + } + + const int block_size = para_c.nb(); + LR_Util::setup_2d_division(z.para_c, block_size, nbasis, z.nbands +#ifdef __MPI + , + pmat.para_2d().ictxt() +#endif + ); + z.para_x.clear(); + for (int is = 0; is < nspin; ++is) + { + Parallel_Blkcyclic px; + LR_Util::setup_2d_division(px, block_size, z.nvirt[is], nocc[is] +#ifdef __MPI + , + z.para_c.ictxt() +#endif + ); + z.para_x.emplace_back(std::move(px)); + } + // Open shell solves one eigenproblem whose vector is the concatenation [up | down], so a + // state's block is as long as both channels together; the closed-shell singlet/triplet + // algorithm carries a single channel. (Same rule as `nloc` in `make_amp_layout`, applied to + // the widened windows.) + z.nloc = nk * (openshell ? z.para_x[0].size() + z.para_x[1].size() : z.para_x[0].size()); + +#ifdef __MPI + z.psi.reset(new psi::Psi(kv.get_nks(), z.para_c.ncloc(), z.para_c.nrloc(), kv.ngk, true)); +#else + z.psi.reset(new psi::Psi(kv.get_nks(), z.nbands, nbasis, kv.ngk, true)); +#endif + z.eig.create(kv.get_nks(), z.nbands); + + for (int ik = 0; ik < kv.get_nks(); ++ik) + { + // same redistribution the X window does, over more bands +#ifdef __MPI + psi_all->fix_k(ik); + z.psi->fix_k(ik); + const int first_band = start_band + 1; + Cpxgemr2d(nbasis, z.nbands, psi_all->get_pointer(), 1, first_band, const_cast(desc_src), + z.psi->get_pointer(), 1, 1, const_cast(z.para_c.desc()), z.para_c.ictxt()); +#else + for (int ib = 0; ib < z.nbands; ++ib) + { + const auto* start = &(*psi_all)(ik, start_band + ib, 0); + std::copy(start, start + nbasis, &(*z.psi)(ik, ib, 0)); + } +#endif + for (int ib = 0; ib < z.nbands; ++ib) + { + z.eig(ik, ib) = eig_all(ik, start_band + ib); + } + } + log << "Z-vector window: nbands = " << z.nbands << " (X window: " << nbands_x << "), nvirt ="; + for (int is = 0; is < nspin; ++is) + { + log << " " << z.nvirt[is] << "(X window: " << nvirt[is] << ")"; + } + log << std::endl; + // Initialization precedes ks_initialized_; subsequent geometry refreshes keep + // the same windows. Diagnose once, without changing the truncated eigenproblem. + if (diagnose) + { + const std::string warning = + LR_Util::force_window_warning(nbasis, eig_all.nc, start_band, nvirt, z.nvirt); + if (!warning.empty()) + { + log << warning << std::endl; + } + } + return z; +} + +void read_gs_chg(const std::string& in_dir, const Input_para& inp, int nspin, const UnitCell& ucell, + Parallel_Grid& pgrid, ModulePW::PW_Basis* pw_rho, Charge& chg, int rank, std::ostream& log) +{ + chg.set_rhopw(pw_rho); + const bool kin_den = XC_Functional::get_ked_flag() || (inp.out_elf[0] > 0); // mohan add 20251202 + chg.allocate(nspin, kin_den, XC_Functional::get_ked_flag(), inp.test_charge); + // Keep the existing cube input authoritative. Choose one density source for + // all spin channels and broadcast the decision before collective readers. + const Parallel::ParaWorld world = Parallel::make_pw_world(); + const bool have_cubes = module_charge::has_complete_charge_cubes(in_dir, nspin, world); + if (!have_cubes) + { + const std::string density_file = in_dir + inp.suffix + "-CHARGE-DENSITY.restart"; + const bool loaded = module_charge::read_rho_from_binary( + density_file, *pw_rho, nspin, chg.rhog, chg.rho, world, log); + if (!loaded) + { + const std::string message = "No complete charge cube set or readable density restart in " + in_dir; + ModuleBase::WARNING_QUIT("ESolver_LR::read_ks_chg", message); + } + return; + } + log << " try to read charge from file : "; + for (int is = 0; is < nspin; ++is) + { + std::stringstream ssc; + if (nspin == 1) + { + ssc << in_dir << "chg.cube"; + } + else + { + ssc << in_dir << "chgs" << is + 1 << ".cube"; + } + log << ssc.str() << std::endl; + if (ModuleIO::read_vdata_palgrid(pgrid, rank, log, ssc.str(), chg.rho[is], ucell.nat)) + { + log << " Read in the charge density: " << ssc.str() << std::endl; + } + } +} + +template void set_x_init(std::vector&, const ModuleBase::matrix&, const std::vector&, + const std::vector&, const std::vector&, + const std::vector&, int, int, int, bool, std::ostream&); +template void set_x_init>(std::vector&, const ModuleBase::matrix&, + const std::vector&, const std::vector&, + const std::vector&, const std::vector&, int, + int, int, bool, std::ostream&); +template void read_wfc_aims(psi::Psi&, ModuleBase::matrix&, const std::string&, int, int, int, int); +template void read_wfc_aims>(psi::Psi>&, ModuleBase::matrix&, + const std::string&, int, int, int, int); +template bool read_wfc_win(const std::string&, const Parallel_Orbitals&, psi::Psi&, + ModuleBase::matrix&, ModuleBase::matrix&, const K_Vectors&, int, bool, int); +template bool read_wfc_win>(const std::string&, const Parallel_Orbitals&, + psi::Psi>&, ModuleBase::matrix&, + ModuleBase::matrix&, const K_Vectors&, int, bool, int); +template bool read_wfc_all(const std::string&, const Parallel_Orbitals&, psi::Psi&, + ModuleBase::matrix&, ModuleBase::matrix&, const K_Vectors&, int, bool); +template bool read_wfc_all>(const std::string&, const Parallel_Orbitals&, + psi::Psi>&, ModuleBase::matrix&, + ModuleBase::matrix&, const K_Vectors&, int, bool); +template ZWin build_z_win(psi::Psi*, const ModuleBase::matrix&, const std::vector&, + const std::vector&, int, int, int, int, bool, const K_Vectors&, + const Parallel_Blkcyclic&, const Parallel_Orbitals&, const int*, bool, bool, + std::ostream&); +template ZWin> build_z_win>( + psi::Psi>*, const ModuleBase::matrix&, const std::vector&, const std::vector&, int, + int, int, int, bool, const K_Vectors&, const Parallel_Blkcyclic&, const Parallel_Orbitals&, const int*, bool, bool, + std::ostream&); + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_gs.h b/source/source_lcao/module_lr/lr_gs.h new file mode 100644 index 0000000000..1e4a34c011 --- /dev/null +++ b/source/source_lcao/module_lr/lr_gs.h @@ -0,0 +1,87 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_GS_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_GS_H + +#include "source_basis/module_ao/parallel_orbitals.h" +#include "source_lcao/module_lr/utils/lr_util.h" + +#include +#include +#include +#include + +class Charge; +class K_Vectors; +class Parallel_Grid; +class UnitCell; +struct Input_para; +namespace ModulePW +{ +class PW_Basis; +} + +namespace LR +{ +/// Row/column distribution of the excitation amplitudes and the per-state local length. +struct AmpLayout +{ + std::vector para_x; + int nloc = 0; +}; + +/// Band layout of the LR window for a `Parallel_Orbitals`, built on the KS process grid. +void set_band_layout(Parallel_Orbitals& pmat, int nbasis, int nbands, const UnitCell& ucell, bool aims); + +/// Build the amplitude distribution; `nloc` is the local length of one state. +AmpLayout make_amp_layout(const Parallel_Blkcyclic& para_c, const std::vector& nocc, + const std::vector& nvirt, int nk, bool openshell); + +/// Fill the initial guess of X: one diagonal occupied-virtual pair per state. +template +void set_x_init(std::vector& X, const ModuleBase::matrix& eig_ks, const std::vector& nocc, + const std::vector& nvirt, const std::vector& npairs, + const std::vector& para_x, int nstates, int nloc, int nk, bool openshell, + std::ostream& log); + +/// AIMS benchmark: eigenvalues from band_out and eigenvectors from KS_eigenvectors.out. +template +void read_wfc_aims(psi::Psi& psi, ModuleBase::matrix& eig, const std::string& in_dir, int nocc_in, int nvirt_in, + int nbands, int nbasis); + +/// Read the [nocc+nvirt] window; `skip_bands` drops the core bands nocc_max-nocc_in. +template +bool read_wfc_win(const std::string& in_dir, const Parallel_Orbitals& pmat, psi::Psi& psi, ModuleBase::matrix& eig, + ModuleBase::matrix& wg, const K_Vectors& kv, int nspin, bool binary, int skip_bands); + +/// Read all ground-state bands (the force path). +template +bool read_wfc_all(const std::string& in_dir, const Parallel_Orbitals& pmat, psi::Psi& psi, ModuleBase::matrix& eig, + ModuleBase::matrix& wg, const K_Vectors& kv, int nspin, bool binary); + +/// The Z-vector (CPSCF) window, widened to every virtual band of the ground state. +template +struct ZWin +{ + std::unique_ptr> psi; + ModuleBase::matrix eig; + Parallel_Blkcyclic para_c; + std::vector para_x; + std::vector nvirt; + int nbands = 0; + int nloc = 0; +}; + +/// (Re)build the Z window from the full ground state. `need` and `psi_all` are checked here so the +/// caller can call this unconditionally; an empty struct is returned when there is nothing to widen. +template +ZWin build_z_win(psi::Psi* psi_all, const ModuleBase::matrix& eig_all, const std::vector& nocc, + const std::vector& nvirt, int nocc_max, int nbands_x, int nbasis, int nk, bool openshell, + const K_Vectors& kv, const Parallel_Blkcyclic& para_c, const Parallel_Orbitals& pmat, + const int* desc_src, bool need, bool diagnose, std::ostream& log); + +/// Read the ground-state charge from cubes, or from a binary restart when the cubes are absent. +void read_gs_chg(const std::string& in_dir, const Input_para& inp, int nspin, const UnitCell& ucell, + Parallel_Grid& pgrid, ModulePW::PW_Basis* pw_rho, Charge& chg, int rank, std::ostream& log); + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_GS_H From 0b8ec3d8921db0a830eb884b927583d88d77297d Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 14:46:17 +0800 Subject: [PATCH 03/26] refactor(lr): move ground-state potential, density matrix and Exx sharing into module_lr Add LR::GsPot, LR::make_gs_dm and LR::make_lr_exx so the force path and the ks-lr initialization only forward member state. lr_dm is a separate translation unit so the cal_edm unit test keeps its slim link set. --- source/Makefile.Objects | 2 + source/source_esolver/esolver_lr_grad.cpp | 59 ++------------- source/source_esolver/esolver_lr_init.cpp | 9 +-- source/source_esolver/esolver_lr_lcao_tddft.h | 6 +- source/source_lcao/module_lr/CMakeLists.txt | 2 + source/source_lcao/module_lr/init_helpers.h | 23 ++++++ source/source_lcao/module_lr/lr_dm.cpp | 39 ++++++++++ source/source_lcao/module_lr/lr_dm.h | 26 +++++++ .../module_lr/potentials/lr_gs_pot.cpp | 73 +++++++++++++++++++ .../module_lr/potentials/lr_gs_pot.h | 54 ++++++++++++++ 10 files changed, 232 insertions(+), 61 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_dm.cpp create mode 100644 source/source_lcao/module_lr/lr_dm.h create mode 100644 source/source_lcao/module_lr/potentials/lr_gs_pot.cpp create mode 100644 source/source_lcao/module_lr/potentials/lr_gs_pot.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 47b20af075..68d9bf3486 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1196,6 +1196,8 @@ OBJS_TENSOR=tensor.o\ hamilt_casida.o\ lr_dim.o\ lr_gs.o\ + lr_dm.o\ + lr_gs_pot.o\ esolver_lr_orb.o\ esolver_lr_init.o\ esolver_lr_cfg.o\ diff --git a/source/source_esolver/esolver_lr_grad.cpp b/source/source_esolver/esolver_lr_grad.cpp index 146956d9ad..98659cbff7 100644 --- a/source/source_esolver/esolver_lr_grad.cpp +++ b/source/source_esolver/esolver_lr_grad.cpp @@ -7,6 +7,7 @@ #include "source_lcao/module_lr/gradient_inputs.h" #include "source_lcao/module_lr/gradient_output.h" #include "source_lcao/module_lr/lr_amp.h" +#include "source_lcao/module_lr/lr_dm.h" #include "source_lcao/module_lr/lr_force.h" #include "source_lcao/module_lr/zeq_solver.h" #include @@ -20,46 +21,8 @@ template void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs) { ModuleBase::TITLE("ESolver_LR", "init_pot_gs"); - std::vector pot_register; - if (this->inp_->vl_in_h) - { - if (!this->ks_) - { // on the `ks-lr` path `sfac()`/`vloc()` alias the ground-state solver's, which - // `ESolver_FP::before_scf` already refreshed for the current geometry - //! 11) calculate the structure factor - // the has_float_data flag below is read the same way core ABACUS reads it at the - // analogous call site (source_esolver/esolver_fp.cpp's `this->sf.setup(...)`), so this - // mirrors the established convention rather than introducing a new global dependency. - this->sfac().setup(&(*this->ucell_), pgrid(), this->pw_rhod, PARAM.globalv.has_float_data); - this->vloc().init_vloc((*this->ucell_), this->pw_rho); - } - pot_register.push_back("local"); - } - if (this->inp_->vh_in_h) - { - pot_register.push_back("hartree"); - } - pot_register.push_back("xc"); - - // initialize the ground state potential - this->pot_gs = LR_Util::make_unique( - this->pw_rhod, this->pw_rho, &(*this->ucell_), &this->vloc().vloc, &this->sfac(), &this->solvent, - &this->etxc_gs, &this->vtxc_gs); - this->pot_gs.get()->pot_register(pot_register); - XC_Functional::set_xc_type((*this->ucell_).atoms[0].ncpp.xc_func); // set XC type of the ground state - this->pot_gs->init_pot(&chg_gs); // call update_from_charge inside - if (LR_Util::has_local_xc(this->xc_kernel)) - { - XC_Functional::set_xc_type(this->xc_kernel); // recover the excited state xc kernel type - } - if (this->inp_->test_force) - { - this->pot_gs_hartree = LR_Util::make_unique( - this->pw_rhod, this->pw_rho, &(*this->ucell_), &this->vloc().vloc, &this->sfac(), &this->solvent, - &this->etxc_gs, &this->vtxc_gs); - this->pot_gs_hartree->pot_register({"hartree"}); - this->pot_gs_hartree->init_pot(&chg_gs); // call update_from_charge inside - } + this->gs_pot_.refresh(*this->inp_, this->xc_kernel, *this->ucell_, this->pw_rhod, this->pw_rho, pgrid(), chg_gs, + this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); } template @@ -367,20 +330,12 @@ std::vector ModuleESolver::ESolver_LR::cal_force_open template module_dm::DensityMatrix ModuleESolver::ESolver_LR::cal_dm_gs() { - module_dm::DensityMatrix dm_gs(&this->paraMat_, this->nspin, this->kv.kvec_d, this->nk); // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight // from the ground-state solver's own `psi`), but per `this->paraMat_all_` on the - // read-from-file path (where it was allocated with that descriptor's own sizes). Using the - // wrong one here reads `psi_ks_all_`'s local block with the wrong block size/process-grid - // assumption -- invisible at nprocs=1, where every descriptor degenerates to one block, but - // silently wrong at nprocs>1. `refresh_from_ks_`/`fill_z_window_` already make this same - // distinction for their `Cpxgemr2d` source descriptor; this mirrors it. + // read-from-file path (where it was allocated with that descriptor's own sizes). const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; - module_dm::dm_from_psi(pv_all, this->wg_ks_all, *this->psi_ks_all_, dm_gs); // nbands is important here - LR_Util::initialize_DMR( - dm_gs, this->paraMat_, (*this->ucell_), this->gd(), this->orb_cutoff_); // nbands is not important here - dm_gs.cal_dmr(-1); - return dm_gs; + return LR::make_gs_dm(*this->psi_ks_all_, this->wg_ks_all, *pv_all, this->paraMat_, *this->ucell_, this->gd(), + this->orb_cutoff_, this->nspin, this->kv.kvec_d, this->nk); } template @@ -419,7 +374,7 @@ void ModuleESolver::ESolver_LR::test_force() ModuleIO::print_force(this->ofs_running_, (*this->ucell_), "Ground State FORCE (eV/Angstrom)", force_gs, false); /// ======================================= END test 1 ========================================= ///========================== test 2: reproduce the DX Hartree term ========================= - ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->pot_gs_hartree); + ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->gs_pot_.pot_hartree()); ModuleIO::print_force( this->ofs_running_, (*this->ucell_), "GS Hartree force calculated by 'cal_pulay_fs' from potential (eV/Angstrom)", f_hxc_potgs, false); diff --git a/source/source_esolver/esolver_lr_init.cpp b/source/source_esolver/esolver_lr_init.cpp index 21ff9789f7..7626152aef 100644 --- a/source/source_esolver/esolver_lr_init.cpp +++ b/source/source_esolver/esolver_lr_init.cpp @@ -60,25 +60,24 @@ template <> void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr> &exx_ks) { ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); - this->exx_lri = exx_ks->make_lr_workspace(*this->ucell_, this->kv); + this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); } template <> void ModuleESolver::ESolver_LR>::share_exx_lri( std::shared_ptr>> &exx_ks) { ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); - this->exx_lri = exx_ks->make_lr_workspace(*this->ucell_, this->kv); + this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); } template <> void ModuleESolver::ESolver_LR>::share_exx_lri(std::shared_ptr> &exx_ks) { - throw std::runtime_error( - "ESolver_LR>::share_exx_lri: cannot share double to std::complex"); + this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); } template <> void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr>> &exx_ks) { - throw std::runtime_error("ESolver_LR::share_exx_lri: cannot share std::complex to double"); + this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); } #endif diff --git a/source/source_esolver/esolver_lr_lcao_tddft.h b/source/source_esolver/esolver_lr_lcao_tddft.h index 1eea8c632c..6fdcd62de8 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr_lcao_tddft.h @@ -17,6 +17,7 @@ #include "source_estate/module_pot/potential_new.h" #include "source_hamilt/module_gint/gint_info.h" #include "source_lcao/module_lr/hamilt_casida.h" +#include "source_lcao/module_lr/potentials/lr_gs_pot.h" #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" #include "source_lcao/module_lr/state_track.h" #ifdef __EXX @@ -123,10 +124,7 @@ class ESolver_LR : public ModuleESolver::ESolver_FP ModuleBase::matrix wg_ks_all; /// occupation number of all bands of ground state // @brief only needed for force calculation - std::unique_ptr pot_gs; - std::unique_ptr pot_gs_hartree; /// ground-state Hartree potential, only used for test_force - double etxc_gs = 0.; - double vtxc_gs = 0.; + LR::GsPot gs_pot_; std::shared_ptr pot_hxc_gs; /// used in lr-grad, in the ground-state Hxc gradient term coming from dF/dC diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 211d6e0a53..7692d4b4a0 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -23,10 +23,12 @@ if(ENABLE_LCAO) operator_casida/operator_lr_hxc.cpp operator_casida/operator_lr_exx.cpp potentials/pot_hxc_lrtd.cpp + potentials/lr_gs_pot.cpp potentials/pot_grad_xc.cpp kernel_pots.cpp lr_dim.cpp lr_gs.cpp + lr_dm.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/init_helpers.h b/source/source_lcao/module_lr/init_helpers.h index f1562aee8b..6196177f7c 100644 --- a/source/source_lcao/module_lr/init_helpers.h +++ b/source/source_lcao/module_lr/init_helpers.h @@ -1,7 +1,10 @@ #ifndef ABACUS_LR_INIT_HELPERS_H #define ABACUS_LR_INIT_HELPERS_H #include +#include +#include #include +#include namespace ModuleBase { class matrix; @@ -10,6 +13,11 @@ struct Input_para; class TwoCenterBundle; class LCAO_Orbitals; class UnitCell; +#ifdef __EXX +template +class Exx_LRI; +class K_Vectors; +#endif namespace LR { /// Initialize nonlocal projector metadata used by neighbor searches, independently of optical output. @@ -18,5 +26,20 @@ void setup_nonlocal_info(LCAO_Orbitals&, UnitCell&, const Input_para&, int, std: void setup_2center_table(TwoCenterBundle&, UnitCell&, const Input_para&); /// Validate LR solver, functional, spin count and optical gauge without global input access. void check_lr_parameters(const Input_para&, const std::string& xc_kernel, int nspin); +#ifdef __EXX +/// Share the ground-state Exx_LRI as an LR workspace (the KS solver keeps using the original). +template +inline std::shared_ptr> make_lr_exx(const std::shared_ptr>& exx_ks, const UnitCell& ucell, + const K_Vectors& kv) +{ + return exx_ks->make_lr_workspace(ucell, kv); +} +/// Mismatched Exx_LRI types cannot back this LR solver. +template ::value, int>::type = 0> +inline std::shared_ptr> make_lr_exx(const std::shared_ptr>&, const UnitCell&, const K_Vectors&) +{ + throw std::runtime_error("LR::make_lr_exx: cannot share different Exx_LRI types"); +} +#endif } #endif diff --git a/source/source_lcao/module_lr/lr_dm.cpp b/source/source_lcao/module_lr/lr_dm.cpp new file mode 100644 index 0000000000..538067a931 --- /dev/null +++ b/source/source_lcao/module_lr/lr_dm.cpp @@ -0,0 +1,39 @@ +#include "source_lcao/module_lr/lr_dm.h" + +#include "source_cell/module_neighbor/sltk_grid_driver.h" +#include "source_cell/unitcell.h" +#include "source_estate/module_dm/dm_from_psi.h" +#include "source_lcao/module_lr/utils/lr_util.h" +#include "source_lcao/module_lr/utils/lr_util_hcontainer.h" + +#include + +namespace LR +{ + +template +module_dm::DensityMatrix make_gs_dm(const psi::Psi& psi_all, const ModuleBase::matrix& wg_all, + const Parallel_Orbitals& pv_all, const Parallel_Orbitals& pmat, + const UnitCell& ucell, const Grid_Driver& gd, + const std::vector& orb_cutoff, int nspin, + const std::vector>& kvec_d, int nk) +{ + module_dm::DensityMatrix dm(&pmat, nspin, kvec_d, nk); + // `psi_all` is distributed per `pv_all`: using the wrong descriptor reads its local block with + // the wrong block size/process-grid assumption, which is invisible at nprocs=1. + module_dm::dm_from_psi(&pv_all, wg_all, psi_all, dm); // nbands is important here + LR_Util::initialize_DMR(dm, pmat, ucell, gd, orb_cutoff); // nbands is not important here + dm.cal_dmr(-1); + return dm; +} + +template module_dm::DensityMatrix make_gs_dm( + const psi::Psi&, const ModuleBase::matrix&, const Parallel_Orbitals&, const Parallel_Orbitals&, + const UnitCell&, const Grid_Driver&, const std::vector&, int, + const std::vector>&, int); +template module_dm::DensityMatrix, double> make_gs_dm>( + const psi::Psi>&, const ModuleBase::matrix&, const Parallel_Orbitals&, + const Parallel_Orbitals&, const UnitCell&, const Grid_Driver&, const std::vector&, int, + const std::vector>&, int); + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_dm.h b/source/source_lcao/module_lr/lr_dm.h new file mode 100644 index 0000000000..fe48fdfd9d --- /dev/null +++ b/source/source_lcao/module_lr/lr_dm.h @@ -0,0 +1,26 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_DM_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_DM_H + +#include "source_base/matrix.h" +#include "source_basis/module_ao/parallel_orbitals.h" +#include "source_estate/module_dm/density_matrix.h" +#include "source_psi/psi.h" + +#include + +class Grid_Driver; +class UnitCell; + +namespace LR +{ +/// Ground-state density matrix (DMR) from all-band KS orbitals. `psi_all` is distributed per +/// `pv_all`: the KS solver's `pv` on the ks-lr path, or the all-band descriptor when read from file. +template +module_dm::DensityMatrix make_gs_dm(const psi::Psi& psi_all, const ModuleBase::matrix& wg_all, + const Parallel_Orbitals& pv_all, const Parallel_Orbitals& pmat, + const UnitCell& ucell, const Grid_Driver& gd, + const std::vector& orb_cutoff, int nspin, + const std::vector>& kvec_d, int nk); +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_DM_H diff --git a/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp b/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp new file mode 100644 index 0000000000..c87be4662a --- /dev/null +++ b/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp @@ -0,0 +1,73 @@ +#include "source_lcao/module_lr/potentials/lr_gs_pot.h" + +#include "source_base/parallel_grid.h" +#include "source_cell/stru_fac.h" +#include "source_cell/unitcell.h" +#include "source_estate/module_charge/charge.h" +#include "source_estate/module_pot/potential_new.h" +#include "source_hamilt/module_surchem/surchem.h" +#include "source_hamilt/module_xc/xc_functional.h" +#include "source_io/module_parameter/input_parameter.h" +#include "source_lcao/module_lr/utils/lr_util.h" +#include "source_pw/module_pwdft/vl_pw.h" + +#include + +namespace LR +{ + +GsPot::GsPot() = default; +GsPot::~GsPot() = default; + +void GsPot::refresh(const Input_para& inp, const std::string& xc_kernel, const UnitCell& ucell, + ModulePW::PW_Basis* pw_rhod, ModulePW::PW_Basis* pw_rho, const Parallel_Grid& pgrid, + const Charge& chg, Structure_Factor& sf, pseudopot_cell_vl& vloc, surchem& solvent, + bool refresh_sfac, bool has_float_data) +{ + std::vector pot_register; + if (inp.vl_in_h) + { + if (refresh_sfac) + { // on the `ks-lr` path `sf`/`vloc` alias the ground-state solver's, which + // `ESolver_FP::before_scf` already refreshed for the current geometry + sf.setup(&ucell, pgrid, pw_rhod, has_float_data); + vloc.init_vloc(ucell, pw_rho); + } + pot_register.push_back("local"); + } + if (inp.vh_in_h) + { + pot_register.push_back("hartree"); + } + pot_register.push_back("xc"); + + // initialize the ground state potential + pot_ = LR_Util::make_unique( + pw_rhod, pw_rho, &ucell, &vloc.vloc, &sf, &solvent, &etxc_, &vtxc_); + pot_->pot_register(pot_register); + XC_Functional::set_xc_type(ucell.atoms[0].ncpp.xc_func); // set XC type of the ground state + pot_->init_pot(&chg); // call update_from_charge inside + if (LR_Util::has_local_xc(xc_kernel)) + { + XC_Functional::set_xc_type(xc_kernel); // recover the excited state xc kernel type + } + if (inp.test_force) + { + pot_hartree_ = LR_Util::make_unique( + pw_rhod, pw_rho, &ucell, &vloc.vloc, &sf, &solvent, &etxc_, &vtxc_); + pot_hartree_->pot_register({"hartree"}); + pot_hartree_->init_pot(&chg); // call update_from_charge inside + } +} + +elecstate::Potential* GsPot::pot() const +{ + return pot_.get(); +} + +elecstate::Potential* GsPot::pot_hartree() const +{ + return pot_hartree_.get(); +} + +} // namespace LR diff --git a/source/source_lcao/module_lr/potentials/lr_gs_pot.h b/source/source_lcao/module_lr/potentials/lr_gs_pot.h new file mode 100644 index 0000000000..bd2c9df314 --- /dev/null +++ b/source/source_lcao/module_lr/potentials/lr_gs_pot.h @@ -0,0 +1,54 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_GS_POT_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_GS_POT_H + +#include +#include + +class Charge; +class Parallel_Grid; +class Structure_Factor; +class UnitCell; +class pseudopot_cell_vl; +class surchem; +struct Input_para; +namespace ModulePW +{ +class PW_Basis; +} +namespace elecstate +{ +class Potential; +} + +namespace LR +{ +/// Owns the ground-state potential used by the LR force path. +class GsPot +{ + public: + GsPot(); + ~GsPot(); + + GsPot(const GsPot&) = delete; + GsPot& operator=(const GsPot&) = delete; + + /// Rebuild the potential on `chg`. `refresh_sfac` is true on the file (`lr`) path, where the + /// solver owns `sf`/`vloc`; on `ks-lr` the ground-state solver has already refreshed them. + void refresh(const Input_para& inp, const std::string& xc_kernel, const UnitCell& ucell, + ModulePW::PW_Basis* pw_rhod, ModulePW::PW_Basis* pw_rho, const Parallel_Grid& pgrid, const Charge& chg, + Structure_Factor& sf, pseudopot_cell_vl& vloc, surchem& solvent, bool refresh_sfac, + bool has_float_data); + + elecstate::Potential* pot() const; + elecstate::Potential* pot_hartree() const; + + private: + std::unique_ptr pot_; + std::unique_ptr pot_hartree_; ///< Hartree only, used by the test_force path + double etxc_ = 0.0; + double vtxc_ = 0.0; +}; + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_GS_POT_H From 1a1c81fd829c73062e506f534da163a22ae176b2 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 14:54:00 +0800 Subject: [PATCH 04/26] refactor(lr): move excited-state target tracking into module_lr Add LR::RelaxTarget so the relaxation state (followed root, multiplet group, previous amplitudes) lives in module_lr and the solver only forwards energies and amplitudes. Remove the duplicated target members from ESolver_LR. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr_grad.cpp | 2 +- .../source_esolver/esolver_lr_lcao_tddft.cpp | 8 +- source/source_esolver/esolver_lr_lcao_tddft.h | 35 +-- source/source_esolver/esolver_lr_rlx.cpp | 200 ++++------------- source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/lr_relax.cpp | 207 ++++++++++++++++++ source/source_lcao/module_lr/lr_relax.h | 57 +++++ 8 files changed, 313 insertions(+), 198 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_relax.cpp create mode 100644 source/source_lcao/module_lr/lr_relax.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 68d9bf3486..a33d976f22 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1197,6 +1197,7 @@ OBJS_TENSOR=tensor.o\ lr_dim.o\ lr_gs.o\ lr_dm.o\ + lr_relax.o\ lr_gs_pot.o\ esolver_lr_orb.o\ esolver_lr_init.o\ diff --git a/source/source_esolver/esolver_lr_grad.cpp b/source/source_esolver/esolver_lr_grad.cpp index 98659cbff7..9c9d55aea1 100644 --- a/source/source_esolver/esolver_lr_grad.cpp +++ b/source/source_esolver/esolver_lr_grad.cpp @@ -93,7 +93,7 @@ LR::GradientInputs ModuleESolver::ESolver_LR::gradient_inputs_() const return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->paraMat_, this->paraC_z_, this->paraX_z_, *this->psi_ks_z_, this->eig_ks_z_, this->nocc, this->nvirt_z_, this->nspin, this->nk, this->nbasis, this->nloc_per_state_z_, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, - this->inp_->test_force, this->excited_relax_, this->out_dir, this->my_rank_, this->spin_types, this->pot, + this->inp_->test_force, this->target_.active(), this->out_dir, this->my_rank_, this->spin_types, this->pot, this->pot_hxc_gs, this->ofs_running_ #ifdef __EXX , diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index 67cb43729e..0479727c6a 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr_lcao_tddft.cpp @@ -76,7 +76,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste // 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) : ""; + const std::string step_suffix = this->target_.active() ? "_step" + std::to_string(istep) : ""; auto efile_out = [this, &step_suffix](const std::string &label) -> std::string { return this->out_dir + "Excitation_Energy_" + label + step_suffix + ".dat"; }; auto vfile_out = [this, &step_suffix](const std::string &label) -> std::string @@ -203,7 +203,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste } } } - if (this->excited_relax_) + if (this->target_.active()) { // Re-select which root to follow BEFORE taking the gradient, so the force belongs to // the same diabatic state as the previous step's. @@ -217,7 +217,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste // One line per ionic step with the two halves of the energy and of the gradient. Without // it the relaxation only reports a force, and whether E_gs + Omega actually goes down -- // the thing being minimised -- cannot be read off the log at all. - const double omega = this->target_omega_(); + const double omega = this->target_.omega(this->pelec->ekb.c, this->nstates); auto max_abs = [](const ModuleBase::matrix &m) -> double { double v = 0.0; @@ -345,7 +345,7 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) // ==================================================== } } - if (this->inp_->cal_force && !this->excited_relax_) + if (this->inp_->cal_force && !this->target_.active()) { this->cal_force_and_grad_matrix_(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 6fdcd62de8..7b45de5df4 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr_lcao_tddft.h @@ -19,6 +19,7 @@ #include "source_lcao/module_lr/hamilt_casida.h" #include "source_lcao/module_lr/potentials/lr_gs_pot.h" #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" +#include "source_lcao/module_lr/lr_relax.h" #include "source_lcao/module_lr/state_track.h" #ifdef __EXX // #include @@ -165,35 +166,19 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// resolve and validate `lr_target_state` / `lr_target_spin`; call once the dimensions /// (and therefore `openshell`) are final void setup_relax_target_(); - bool excited_relax_ = false; ///< driving `calculation = relax` from an excited state - int target_is_ = 0; ///< spin block of the relaxed state in `X` and `pelec->ekb` + /// The followed state/multiplet. Seeded from `lr_target_state`, then re-chosen at every + /// later step by cross-geometry group overlap; following a fixed index instead makes the + /// force discontinuous as soon as two surfaces cross. + LR::RelaxTarget target_; double etot_gs_ = 0.0; ///< ground-state total energy of the current step (Ry) ModuleBase::matrix force_gs_; ///< ground-state force of the current step (Ry/Bohr, F = -dE/dR) /// The LR part of the excited-state force, -d(Omega)/dR (Ry/Bohr). ModuleBase::matrix lr_force_; - /// The state currently being followed, as an index into `X` / `pelec->ekb`. - /// Seeded from `lr_target_state` on the first ionic step, then re-chosen at every - /// later step by cross-geometry group overlap, then the single/JT reference. - /// Following a fixed INDEX instead is what makes a relaxation fail near a - /// degeneracy: the index always names the n-th lowest root, so as soon as two - /// surfaces cross, "the target" jumps to a different diabatic state and the force - /// is discontinuous. CG assumes a conservative field and cannot recover from that. - int target_state_ = -1; - /// Previous ionic step's amplitude for the followed state (local part), the - /// reference the overlap is taken against. Empty on the first step. - std::vector target_X_prev_; - LR::RootBasis target_basis_prev_; /// Match the old subspace to current energy groups and refresh the single/group references. /// `ofs` receives the note when the followed root changes index, and the warning when /// no current root resembles the previous one. void follow_target_state_(std::ofstream &ofs); - /// index of the relaxed state inside `pelec->ekb` - int target_ekb_offset_() const - { - return this->openshell ? this->target_state_ : this->target_is_ * this->nstates + this->target_state_; - } - std::vector spin_types; std::unique_ptr gint_info_ = nullptr; @@ -306,16 +291,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// LVC data of every multiplet found at this geometry, rebuilt on each call of /// `cal_force_and_grad_matrix_`. Empty unless `lr_degen_thr > 0`. std::vector multiplet_lvc_; - /// The multiplet `lr_target_state` belongs to, or empty when the target is non-degenerate - /// or `lr_degen_mode = state`. Refreshed every ionic step by - /// `resolve_target_multiplet_`, and it is what makes `cal_energy` and the reported gradient - /// describe the same surface. - std::vector target_group_; - /// Fill `target_group_` from the excitation energies of the current geometry. - void resolve_target_multiplet_(); - /// The excitation energy the relaxation is minimising: the target state's own, or the - /// multiplet average when `target_group_` is set. - double target_omega_() const; /// The LR half of the force for the current geometry, following whichever surface /// `lr_degen_mode` selects. `ofs` receives the note when that is not a single state. ModuleBase::matrix cal_lr_force_relax_(std::ofstream &ofs); diff --git a/source/source_esolver/esolver_lr_rlx.cpp b/source/source_esolver/esolver_lr_rlx.cpp index 10d4a7d3a4..d9e165289b 100644 --- a/source/source_esolver/esolver_lr_rlx.cpp +++ b/source/source_esolver/esolver_lr_rlx.cpp @@ -1,7 +1,6 @@ #include "source_base/parallel_reduce.h" #include "source_base/timer.h" #include "source_esolver/esolver_lr_lcao_tddft.h" -#include "source_estate/module_dm/dm_from_psi.h" #include "source_io/module_output/output_log.h" #include "source_lcao/module_lr/cal_edm.h" #include "source_lcao/module_lr/grad_degen.h" @@ -19,70 +18,12 @@ using namespace LR; template void ModuleESolver::ESolver_LR::setup_relax_target_() { - this->excited_relax_ = (this->inp_->calculation == "relax"); - if (!this->excited_relax_) + this->target_.setup(*this->inp_, this->openshell, this->nspin, this->nstates, this->ofs_running_); + if (this->target_.active()) { - return; - } - - // The Z-vector equation has no complex solver (see zeq_solver.h), so an - // excited-state gradient only exists at gamma. Fail here rather than after the SCF. - if (!std::is_same::value) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR", "excited-state relaxation currently requires gamma-only sampling: the complex " - "Z-vector solver is not implemented."); - } - if (this->inp_->lr_target_state >= this->nstates) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR", "lr_target_state is beyond the states actually solved (lr_nstates <= 0 expands to " - "all particle-hole pairs, which may be fewer than requested)."); - } - - // `openshell` is only settled after the ground-state occupations have been read, which is why - // this cannot live in the input-file checks - const std::string &spin = this->inp_->lr_target_spin; - if (this->openshell) - { - // An open-shell calculation solves one spin-conserving channel, so there is nothing to - // choose: whatever lr_target_spin says, this is the state that gets relaxed. Only an - // explicit `triplet` is worth mentioning -- `singlet` is the default and expresses no - // intent, and `updown` is already the right name for this channel. - if (spin == "triplet") - { - this->ofs_running_ << " WARNING: lr_target_spin=triplet is ignored. This is an" - " open-shell calculation with a single spin-conserving channel (updown), which is" - " what the relaxation will follow." - << std::endl; - } - this->target_is_ = 0; - } - else - { - // Closed shell is the opposite case: singlet and triplet are genuinely different states - // with different gradients, so `updown` here is ambiguous rather than redundant -- it - // usually means lr_unrestricted was meant to be set. - if (spin == "updown") - { - ModuleBase::WARNING_QUIT( - "ESolver_LR", "lr_target_spin=updown, but this is a closed-shell calculation, where singlet and " - "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->force_gs_.create(this->ucell_->nat, 3); + this->lr_force_.create(this->ucell_->nat, 3); } - 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")) - << " channel, tracked by cross-geometry orbital and amplitude overlap." << std::endl; } /// Compare roots in a common electron-hole basis using exact cross-geometry AO overlap. @@ -90,25 +31,19 @@ template void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) { ModuleBase::timer::start("ESolver_LR", "follow_target_state_"); - if (!this->excited_relax_) + if (!this->target_.active()) { ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); return; } - const int channel = this->openshell ? 0 : this->target_is_; + const int channel = this->openshell ? 0 : this->target_.ispin(); const T *const amplitudes = this->X[channel].template data(); const TwoCenterIntegrator &overlap_integrator = *this->tcb().overlap_orb; - const bool reference_first = LR_Util::tolower(this->inp_->lr_degen_mode) == "jt"; - const LR::RootInputs inputs{*this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->paraC_, - this->paraMat_, this->paraX_, this->nocc, this->nvirt, this->openshell, this->target_is_, reference_first}; - const int energy_offset = channel * this->nstates; std::vector energies(this->nstates); - std::copy_n(this->pelec->ekb.c + energy_offset, this->nstates, energies.begin()); - const bool single_state = LR_Util::tolower(this->inp_->lr_degen_mode) == "state"; - const double group_threshold = single_state ? 0.0 : this->inp_->lr_degen_thr; - LR::follow_cross_root( - inputs, amplitudes, this->nloc_per_state, this->nstates, this->inp_->lr_target_state, energies, group_threshold, - this->target_state_, this->target_X_prev_, this->target_basis_prev_, ofs); + std::copy_n(this->pelec->ekb.c + this->target_.ekb_off(this->nstates), this->nstates, energies.begin()); + this->target_.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->paraC_, + this->paraMat_, this->paraX_, this->nocc, this->nvirt, amplitudes, this->nloc_per_state, + this->nstates, energies, ofs); ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); } @@ -117,15 +52,15 @@ double ModuleESolver::ESolver_LR::cal_energy() { // Outside a relaxation nothing consumes this, and returning a non-zero value would change // what the existing single-point outputs report. - if (!this->excited_relax_) + if (!this->target_.active()) { return 0.0; } - // `target_omega_()` is the multiplet average under `lr_degen_mode = average` and the - // single state otherwise, matching whatever `cal_lr_force_relax_` produced the gradient of. - // The energy-based optimisers line-search on this, so the two must not describe different + // `omega` is the multiplet average under `lr_degen_mode = average` and the single state + // otherwise, matching whatever `cal_lr_force_relax_` produced the gradient of. The + // energy-based optimisers line-search on this, so the two must not describe different // surfaces. - return this->etot_gs_ + this->target_omega_(); + return this->etot_gs_ + this->target_.omega(this->pelec->ekb.c, this->nstates); } template @@ -133,7 +68,7 @@ void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase: { basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); const UnitCell &ucell = static_cast(basecell); - if (!this->excited_relax_) + if (!this->target_.active()) { // single-point runs print the gradients of every state from `after_all_runners` instead return; } @@ -180,101 +115,39 @@ ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, co return Xz; } -template -void ModuleESolver::ESolver_LR::resolve_target_multiplet_() -{ - // Keyed on `target_state_`, not on `lr_target_state`: the overlap tracking re-chooses the - // followed root at every ionic step, and the multiplet has to be the one containing the root - // actually being followed. They differ as soon as two surfaces have crossed. - this->target_group_.clear(); - if (LR_Util::tolower(this->inp_->lr_degen_mode) == "state") - { - return; - } - const int ekb_off = this->openshell ? 0 : this->target_is_ * this->nstates; - std::vector omega(this->nstates); - for (int ist = 0; ist < this->nstates; ++ist) - { - omega[ist] = this->pelec->ekb.c[ekb_off + ist]; - } - const std::vector> groups = LR::group_degenerate_states(omega, this->inp_->lr_degen_thr); - for (const std::vector &g : groups) - { - if (std::find(g.begin(), g.end(), this->target_state_) == g.end()) - { - continue; - } - // a one-member group means the target is not degenerate here, and averaging over it would - // be the single-state path with extra steps - const bool average = LR_Util::tolower(this->inp_->lr_degen_mode) == "average"; - if (average && g.size() > 3) - { - this->ofs_running_ << " WARNING: tracked group has " << g.size() - << " roots; average supports at most three. Following the selected single root." - << std::endl; - } - else if (!average && g.size() > 3) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR", - "JT forces support only two- or three-state multiplets; reduce lr_degen_thr or use state mode"); - } - else if (g.size() > 1) - { - this->target_group_ = g; - } - break; - } -} - -template -double ModuleESolver::ESolver_LR::target_omega_() const -{ - if (this->target_group_.empty()) - { - return this->pelec->ekb.c[this->target_ekb_offset_()]; - } - const int ekb_off = this->openshell ? 0 : this->target_is_ * this->nstates; - double sum = 0.0; - for (const int ist : this->target_group_) - { - sum += this->pelec->ekb.c[ekb_off + ist]; - } - return sum / static_cast(this->target_group_.size()); -} - template ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::ofstream &ofs) { - this->resolve_target_multiplet_(); - if (this->target_group_.empty()) + this->target_.resolve_group(*this->inp_, this->pelec->ekb.c, this->nstates, this->ofs_running_); + const std::vector &group = this->target_.group(); + if (group.empty()) { - return this->cal_force(this->target_is_, this->target_state_)[0]; + return this->cal_force(this->target_.ispin(), this->target_.state())[0]; } const bool jt_mode = (LR_Util::tolower(this->inp_->lr_degen_mode) == "jt"); // `average` needs only the DIAGONAL of the gradient matrix: the average is basis-independent by // construction, so the off-diagonal part (and the extra d(d-1)/2 solves it costs) is not // involved. The Jahn-Teller direction is orthogonal to the average and does need them. - const int d = static_cast(this->target_group_.size()); - const int ekb_off = this->openshell ? 0 : this->target_is_ * this->nstates; - const ct::Tensor Xz = this->pad_group_to_z_(this->target_is_, this->target_group_); + const int d = static_cast(group.size()); + const int ekb_off = this->target_.ekb_off(this->nstates); + const ct::Tensor Xz = this->pad_group_to_z_(this->target_.ispin(), group); std::vector omega(d); for (int k = 0; k < d; ++k) { - omega[k] = this->pelec->ekb.c[ekb_off + this->target_group_[k]]; + omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; } const std::vector forces = - this->openshell ? this->cal_force_openshell_Xz(Xz, omega, this->target_group_.front()) - : this->cal_force_Xz(this->target_is_, Xz, omega, this->target_group_.front()); - ofs << " Followed state " << this->target_state_ << " is degenerate with"; - for (const int ist : this->target_group_) + this->openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) + : this->cal_force_Xz(this->target_.ispin(), Xz, omega, group.front()); + ofs << " Followed state " << this->target_.state() << " is degenerate with"; + for (const int ist : group) { - if (ist != this->target_state_) + if (ist != this->target_.state()) { ofs << " " << ist; } } - ofs << " (Omega_bar = " << this->target_omega_() << " Ry)." << std::endl; + ofs << " (Omega_bar = " << this->target_.omega(this->pelec->ekb.c, this->nstates) << " Ry)." << std::endl; if (!jt_mode) { ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" @@ -292,9 +165,10 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( // Regime (c): descend the Jahn-Teller branch. This needs the whole gradient matrix, so the // off-diagonal elements are assembled here -- d(d-1)/2 further Z-vector solves on top of the // d diagonal ones already in `diag`. - const int d = static_cast(this->target_group_.size()); + const std::vector &group = this->target_.group(); + const int d = static_cast(group.size()); const std::vector> g = - this->cal_grad_matrix_degenerate(this->target_is_, this->target_group_, diag, ofs); + this->cal_grad_matrix_degenerate(this->target_.ispin(), group, diag, ofs); const int nat = diag[0].nr; const int ncoord = nat * 3; // flatten to the layout `find_jt_direction` takes: one d x d block per nuclear coordinate. @@ -315,9 +189,9 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( } } const LR::JTDirection jt = LR::find_jt_direction(gflat, ncoord, d); - const int channel = this->openshell ? 0 : this->target_is_; + const int channel = this->openshell ? 0 : this->target_.ispin(); const T *const amplitudes = this->X[channel].template data(); - LR::save_mixed_root(amplitudes, this->nloc_per_state, this->target_group_, jt.mixing, this->target_X_prev_); + this->target_.save_mixed(amplitudes, this->nloc_per_state, jt.mixing); std::vector jt_part; const std::vector sym = LR::split_symmetric_part(gflat, ncoord, d, jt.mixing, jt_part); @@ -364,8 +238,8 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( // The force handed back is that of the descending branch, q(v) with v the optimal mixing -- // i.e. the branch's own gradient, which is what a relaxation must follow. Once a step has - // split the multiplet, `resolve_target_multiplet_` finds no group and the ordinary - // single-state path takes over, so this mode is self-limiting by construction. + // split the multiplet, `resolve_group` finds no group and the ordinary single-state path + // takes over, so this mode is self-limiting by construction. ModuleBase::matrix f(nat, 3); for (int iat = 0; iat < nat; ++iat) { diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 7692d4b4a0..9c8e18b6f7 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -29,6 +29,7 @@ if(ENABLE_LCAO) lr_dim.cpp lr_gs.cpp lr_dm.cpp + lr_relax.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/lr_relax.cpp b/source/source_lcao/module_lr/lr_relax.cpp new file mode 100644 index 0000000000..638f152d5d --- /dev/null +++ b/source/source_lcao/module_lr/lr_relax.cpp @@ -0,0 +1,207 @@ +#include "source_lcao/module_lr/lr_relax.h" + +#include "source_base/tool_quit.h" +#include "source_cell/unitcell.h" +#include "source_io/module_parameter/input_parameter.h" +#include "source_lcao/module_lr/grad_degen.h" +#include "source_lcao/module_lr/lr_amp.h" + +#include +#include +#include + +namespace LR +{ + +template +void RelaxTarget::setup(const Input_para& inp, bool openshell, int nspin, int nstates, std::ostream& log) +{ + active_ = (inp.calculation == "relax"); + openshell_ = openshell; + if (!active_) + { + return; + } + + // The Z-vector equation has no complex solver (see zeq_solver.h), so an + // excited-state gradient only exists at gamma. Fail here rather than after the SCF. + if (!std::is_same::value) + { + ModuleBase::WARNING_QUIT( + "ESolver_LR", "excited-state relaxation currently requires gamma-only sampling: the complex " + "Z-vector solver is not implemented."); + } + if (inp.lr_target_state >= nstates) + { + ModuleBase::WARNING_QUIT( + "ESolver_LR", "lr_target_state is beyond the states actually solved (lr_nstates <= 0 expands to " + "all particle-hole pairs, which may be fewer than requested)."); + } + + // `openshell` is only settled after the ground-state occupations have been read, which is why + // this cannot live in the input-file checks + const std::string& spin = inp.lr_target_spin; + if (openshell_) + { + // An open-shell calculation solves one spin-conserving channel, so there is nothing to + // choose: whatever lr_target_spin says, this is the state that gets relaxed. Only an + // explicit `triplet` is worth mentioning -- `singlet` is the default and expresses no + // intent, and `updown` is already the right name for this channel. + if (spin == "triplet") + { + log << " WARNING: lr_target_spin=triplet is ignored. This is an" + " open-shell calculation with a single spin-conserving channel (updown), which is" + " what the relaxation will follow." + << std::endl; + } + ispin_ = 0; + } + else + { + // Closed shell is the opposite case: singlet and triplet are genuinely different states + // with different gradients, so `updown` here is ambiguous rather than redundant -- it + // usually means lr_unrestricted was meant to be set. + if (spin == "updown") + { + ModuleBase::WARNING_QUIT( + "ESolver_LR", "lr_target_spin=updown, but this is a closed-shell calculation, where singlet and " + "triplet are separate states with separate gradients. Pick one of them, or set " + "lr_unrestricted to run spin-unrestricted."); + } + ispin_ = (spin == "triplet") ? 1 : 0; + if (ispin_ >= nspin) + { + ModuleBase::WARNING_QUIT( + "ESolver_LR", "lr_target_spin=triplet requires nspin=2: the triplet channel is not built here."); + } + } + state_ = inp.lr_target_state; // seed; overlap takes over from step 2 + log << " Excited-state relaxation follows state " << inp.lr_target_state << " of the " + << (openshell_ ? "updown" : (ispin_ == 1 ? "triplet" : "singlet")) + << " channel, tracked by cross-geometry orbital and amplitude overlap." << std::endl; +} + +template +bool RelaxTarget::active() const +{ + return active_; +} + +template +int RelaxTarget::ispin() const +{ + return ispin_; +} + +template +int RelaxTarget::state() const +{ + return state_; +} + +template +const std::vector& RelaxTarget::group() const +{ + return group_; +} + +template +int RelaxTarget::ekb_off(int nstates) const +{ + return openshell_ ? 0 : ispin_ * nstates; +} + +template +void RelaxTarget::follow(const Input_para& inp, const UnitCell& ucell, const std::vector& orb_cutoff, + const TwoCenterIntegrator& overlap, const psi::Psi& psi_ks, + const Parallel_Blkcyclic& para_c, const Parallel_Orbitals& pmat, + const std::vector& para_x, const std::vector& nocc, + const std::vector& nvirt, const T* amplitudes, int nloc, int nstates, + const std::vector& energies, std::ostream& log) +{ + if (!active_) + { + return; + } + // Compare roots in a common electron-hole basis using exact cross-geometry AO overlap. + const bool reference_first = LR_Util::tolower(inp.lr_degen_mode) == "jt"; + const RootInputs inputs{ucell, orb_cutoff, overlap, psi_ks, para_c, pmat, para_x, nocc, nvirt, openshell_, + ispin_, reference_first}; + const bool single_state = LR_Util::tolower(inp.lr_degen_mode) == "state"; + const double group_threshold = single_state ? 0.0 : inp.lr_degen_thr; + follow_cross_root(inputs, amplitudes, nloc, nstates, inp.lr_target_state, energies, group_threshold, state_, + previous_, basis_, log); +} + +template +void RelaxTarget::resolve_group(const Input_para& inp, const double* ekb, int nstates, std::ostream& log) +{ + // Keyed on `state_`, not on `lr_target_state`: the overlap tracking re-chooses the + // followed root at every ionic step, and the multiplet has to be the one containing the root + // actually being followed. They differ as soon as two surfaces have crossed. + group_.clear(); + if (LR_Util::tolower(inp.lr_degen_mode) == "state") + { + return; + } + const int off = ekb_off(nstates); + std::vector omegas(nstates); + for (int ist = 0; ist < nstates; ++ist) + { + omegas[ist] = ekb[off + ist]; + } + const std::vector> groups = group_degenerate_states(omegas, inp.lr_degen_thr); + for (const std::vector& g : groups) + { + if (std::find(g.begin(), g.end(), state_) == g.end()) + { + continue; + } + // a one-member group means the target is not degenerate here, and averaging over it would + // be the single-state path with extra steps + const bool average = LR_Util::tolower(inp.lr_degen_mode) == "average"; + if (average && g.size() > 3) + { + log << " WARNING: tracked group has " << g.size() + << " roots; average supports at most three. Following the selected single root." << std::endl; + } + else if (!average && g.size() > 3) + { + ModuleBase::WARNING_QUIT( + "ESolver_LR", + "JT forces support only two- or three-state multiplets; reduce lr_degen_thr or use state mode"); + } + else if (g.size() > 1) + { + group_ = g; + } + break; + } +} + +template +double RelaxTarget::omega(const double* ekb, int nstates) const +{ + if (group_.empty()) + { + return ekb[ekb_off(nstates) + state_]; + } + const int off = ekb_off(nstates); + double sum = 0.0; + for (const int ist : group_) + { + sum += ekb[off + ist]; + } + return sum / static_cast(group_.size()); +} + +template +void RelaxTarget::save_mixed(const T* amplitudes, int nloc, const std::vector& mixing) +{ + save_mixed_root(amplitudes, nloc, group_, mixing, previous_); +} + +template class RelaxTarget; +template class RelaxTarget>; + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_relax.h b/source/source_lcao/module_lr/lr_relax.h new file mode 100644 index 0000000000..ccb0ff119d --- /dev/null +++ b/source/source_lcao/module_lr/lr_relax.h @@ -0,0 +1,57 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_RELAX_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_RELAX_H + +#include "source_lcao/module_lr/state_track.h" +#include "source_lcao/module_lr/utils/lr_util.h" + +#include +#include + +class UnitCell; +class TwoCenterIntegrator; +struct Input_para; + +namespace LR +{ +/// Which excited state (or degenerate multiplet) a geometry relaxation follows. +template +class RelaxTarget +{ + public: + /// Resolve and validate lr_target_state / lr_target_spin; call once the dimensions are final. + void setup(const Input_para& inp, bool openshell, int nspin, int nstates, std::ostream& log); + + bool active() const; + int ispin() const; + int state() const; + const std::vector& group() const; + /// Index of the followed state inside `ekb` for the current spin layout. + int ekb_off(int nstates) const; + + /// Match the old subspace to current energy groups; update `state()` and the references. + void follow(const Input_para& inp, const UnitCell& ucell, const std::vector& orb_cutoff, + const TwoCenterIntegrator& overlap, const psi::Psi& psi_ks, const Parallel_Blkcyclic& para_c, + const Parallel_Orbitals& pmat, const std::vector& para_x, + const std::vector& nocc, const std::vector& nvirt, const T* amplitudes, int nloc, + int nstates, const std::vector& energies, std::ostream& log); + + /// Fill the multiplet group from the current excitation energies (`ekb` starts at this spin). + void resolve_group(const Input_para& inp, const double* ekb, int nstates, std::ostream& log); + /// Excitation energy being minimised: the target's own, or the multiplet average. + double omega(const double* ekb, int nstates) const; + /// Store the JT mixed root as the next reference. + void save_mixed(const T* amplitudes, int nloc, const std::vector& mixing); + + private: + bool active_ = false; + bool openshell_ = false; + int ispin_ = 0; + int state_ = -1; + std::vector group_; + std::vector previous_; + RootBasis basis_; +}; + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_RELAX_H From 269a69d27b998cf94190bc06feb8f25c580c6a9d Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 14:58:40 +0800 Subject: [PATCH 05/26] refactor(lr): fold the split esolver translation units into one file Merge esolver_lr_cfg/orb/grad/rlx.cpp into esolver_lr_lcao_tddft.cpp so a single translation unit holds the remaining solver-side code. Drop the freed source files from both build systems. --- source/Makefile.Objects | 4 - source/source_esolver/CMakeLists.txt | 4 - source/source_esolver/esolver_lr_cfg.cpp | 85 -- source/source_esolver/esolver_lr_grad.cpp | 391 --------- .../source_esolver/esolver_lr_lcao_tddft.cpp | 817 +++++++++++++++++- source/source_esolver/esolver_lr_orb.cpp | 99 --- source/source_esolver/esolver_lr_rlx.cpp | 268 ------ source/source_lcao/module_lr/grad_degen.h | 4 +- 8 files changed, 818 insertions(+), 854 deletions(-) delete mode 100644 source/source_esolver/esolver_lr_cfg.cpp delete mode 100644 source/source_esolver/esolver_lr_grad.cpp delete mode 100644 source/source_esolver/esolver_lr_orb.cpp delete mode 100644 source/source_esolver/esolver_lr_rlx.cpp diff --git a/source/Makefile.Objects b/source/Makefile.Objects index a33d976f22..f7b8f2c13f 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1199,9 +1199,7 @@ OBJS_TENSOR=tensor.o\ lr_dm.o\ lr_relax.o\ lr_gs_pot.o\ - esolver_lr_orb.o\ esolver_lr_init.o\ - esolver_lr_cfg.o\ esolver_lr_lcao_tddft.o\ OBJS_LR_GRAD=lr_force.o\ @@ -1221,8 +1219,6 @@ OBJS_LR_GRAD=lr_force.o\ cal_edm.o\ zeqlin_solv.o\ pot_grad_xc.o\ - esolver_lr_grad.o\ - esolver_lr_rlx.o\ OBJS_RDMFT=rdmft.o\ rdmft_tools.o\ diff --git a/source/source_esolver/CMakeLists.txt b/source/source_esolver/CMakeLists.txt index 30d2908273..5ca8fcf6d2 100644 --- a/source/source_esolver/CMakeLists.txt +++ b/source/source_esolver/CMakeLists.txt @@ -21,12 +21,8 @@ if(ENABLE_LCAO) objects esolver_ks_lcao.cpp esolver_ks_lcao_tddft.cpp - esolver_lr_orb.cpp esolver_lr_init.cpp - esolver_lr_cfg.cpp esolver_lr_lcao_tddft.cpp - esolver_lr_grad.cpp - esolver_lr_rlx.cpp esolver_gets.cpp lcao_others.cpp esolver_dm2rho.cpp diff --git a/source/source_esolver/esolver_lr_cfg.cpp b/source/source_esolver/esolver_lr_cfg.cpp deleted file mode 100644 index 0a8e7897d0..0000000000 --- a/source/source_esolver/esolver_lr_cfg.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "source_lcao/module_lr/kernel_pots.h" -// Resolve LR dimensions and initialize kernel potentials. -#include "esolver_lr_lcao_tddft.h" -#include "source_io/module_parameter/parameter.h" -#include "source_lcao/module_lr/lr_dim.h" -#include -#include - -template -void ModuleESolver::ESolver_LR::set_dim() -{ - LR::DimSrc src; - src.inp = this->inp_; - src.nlocal = PARAM.globalv.nlocal; - src.nks = this->kv.get_nks(); - src.nkstot = this->kv.get_nkstot(); - src.rank = this->my_rank_; - src.gamma_only = std::is_same::value; - src.wg_ks = this->ks_ ? &this->ks_->pelec->wg : nullptr; - src.kpar = this->kv.para_k.kpar; - src.rank_in_pool = this->kv.para_k.rank_in_pool; - src.in_dir = this->in_dir; - src.ucell = const_cast(this->ucell_); - src.log = &this->ofs_running_; - - const LR::Dim dim = LR::resolve_dim(src); - - this->nspin = dim.nspin; - this->nstates = dim.nstates; - this->nbasis = dim.nbasis; - this->nbands = dim.nbands; - this->nk = dim.nk; - this->nupdown = dim.nupdown; - this->nocc_in = dim.nocc_in; - this->nocc_max = dim.nocc_max; - this->nvirt_in = dim.nvirt_in; - this->openshell = dim.openshell; - this->nocc = dim.nocc; - this->nvirt = dim.nvirt; - this->npairs = dim.npairs; -} - -template -void ModuleESolver::ESolver_LR::reset_dim_spin() -{ - LR::Dim dim; - dim.nspin = this->nspin; - dim.nstates = this->nstates; - dim.nk = this->nk; - dim.nupdown = this->nupdown; - dim.openshell = this->openshell; - dim.nocc = this->nocc; - dim.nvirt = this->nvirt; - dim.npairs = this->npairs; - - LR::apply_spin_pol(dim, *this->inp_); - - this->nocc = dim.nocc; - this->nvirt = dim.nvirt; - this->npairs = dim.npairs; - this->openshell = dim.openshell; -} - -template -void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) -{ - this->pot.assign(nspin, nullptr); - if (this->inp_->ri_hartree_benchmark != "none") - { - return; - } - const auto &grid = pgrid(); - auto prepared = - LR::prepare_lr_potentials(*this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell); - this->pot = std::move(prepared.pot); - if (this->inp_->cal_force) - { - this->init_pot_groundstate(chg_gs); - this->pot_hxc_gs = LR::prepare_gs_potential( - *this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell, prepared); - } -} - -template class ModuleESolver::ESolver_LR; -template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_esolver/esolver_lr_grad.cpp b/source/source_esolver/esolver_lr_grad.cpp deleted file mode 100644 index 9c9d55aea1..0000000000 --- a/source/source_esolver/esolver_lr_grad.cpp +++ /dev/null @@ -1,391 +0,0 @@ -#include "source_base/parallel_reduce.h" -#include "source_esolver/esolver_lr_lcao_tddft.h" -#include "source_estate/module_dm/dm_from_psi.h" -#include "source_io/module_output/output_log.h" -#include "source_lcao/module_lr/cal_edm.h" -#include "source_lcao/module_lr/grad_degen.h" -#include "source_lcao/module_lr/gradient_inputs.h" -#include "source_lcao/module_lr/gradient_output.h" -#include "source_lcao/module_lr/lr_amp.h" -#include "source_lcao/module_lr/lr_dm.h" -#include "source_lcao/module_lr/lr_force.h" -#include "source_lcao/module_lr/zeq_solver.h" -#include -#include - -using namespace LR; - -///========================= excited-state geometry relaxation ========================= - -template -void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs) -{ - ModuleBase::TITLE("ESolver_LR", "init_pot_gs"); - this->gs_pot_.refresh(*this->inp_, this->xc_kernel, *this->ucell_, this->pw_rhod, this->pw_rho, pgrid(), chg_gs, - this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); -} - -template -ct::Tensor ModuleESolver::ESolver_LR::pad_X_to_z_(const int ispin, const int istate_begin, const int nst) const -{ - return LR::pad_amplitudes( - this->X, this->openshell, this->paraX_, this->paraX_z_, this->nocc, this->nvirt, this->nk, this->nloc_per_state, - this->nloc_per_state_z_, ispin, istate_begin, nst); -} - -template -ct::Tensor ModuleESolver::ESolver_LR::solve_zvector_eqation(const int ispin, const int nst, const ct::Tensor &Xz) -{ - ModuleBase::TITLE("ESolver_LR", "cal_force"); - ModuleBase::timer::start("ESolver_LR", "solve_zvector_eqation"); - // `Z_vector_equation` treats X and Z as `nst` independent blocks of `nloc_per_state_z_`, - // and the blocks need not be eigenvectors of the Casida equation in the order the - // diagonalizer returned them -- `cal_grad_matrix_degenerate` feeds it linear combinations. - // X arrives already widened into the Z window (`Xz`), which spans every virtual band the - // ground state produced rather than the `nvirt` window X was solved in -- the Brillouin - // condition the Z-vector enforces holds in EVERY occupied-virtual rotation. The padded - // entries are zero, so every X-derived quantity (D^X, T) is unchanged; only the space Z is - // solved in grows. Both the closed- and the open-shell path go through here. - ct::Tensor Z = LR_Util::newTensor({nst, this->nloc_per_state_z_}); - // construct and solve the Z-vector equation - const LR::GradientInputs inputs = this->gradient_inputs_(); - const T *const x_data = Xz.template data(); - T *const z_data = Z.template data(); - 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); - ModuleBase::timer::end("ESolver_LR", "solve_zvector_eqation"); - return Z; -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force(const int ispin, const int istate_only) -{ - if (this->inp_->test_force && ispin == 0) - { - this->test_force(); - } - if (this->openshell) - { - return this->cal_force_openshell(istate_only); - } - - const int ist_begin = (istate_only < 0) ? 0 : istate_only; - const int nst = (istate_only < 0) ? this->nstates : 1; - // The whole closed-shell gradient runs in the Z window (every virtual band the ground state - // produced), not the `nvirt` window X was solved in: only there does the Z-vector enforce - // the Brillouin condition in every occupied-virtual rotation. X is zero-padded into it, so - // D^X and T come out bit-identical -- and Omega is untouched, so an existing finite-difference - // reference stays valid. See `fill_z_window_`. - const ct::Tensor Xz = this->pad_X_to_z_(ispin, ist_begin, nst); - std::vector omega(nst); - for (int i = 0; i < nst; ++i) - { - omega[i] = this->pelec->ekb.c[ispin * this->nstates + ist_begin + i]; - } - return this->cal_force_Xz(ispin, Xz, omega, ist_begin); -} - -template -LR::GradientInputs ModuleESolver::ESolver_LR::gradient_inputs_() const -{ - return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->paraMat_, this->paraC_z_, this->paraX_z_, - *this->psi_ks_z_, this->eig_ks_z_, this->nocc, this->nvirt_z_, this->nspin, this->nk, this->nbasis, - this->nloc_per_state_z_, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, - this->inp_->test_force, this->target_.active(), this->out_dir, this->my_rank_, this->spin_types, this->pot, - this->pot_hxc_gs, this->ofs_running_ -#ifdef __EXX - , - this->exx_lri, this->exx_info.info_global.hybrid_alpha -#endif - }; -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force_Xz( - const int ispin, - const ct::Tensor &Xz, - const std::vector &omega, - const int label_begin) -{ - 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::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( - *this->ucell_, this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), - this->gd(), this->tcb(), force_settings, this->ofs_running_ -#ifdef __EXX - , - 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); - ModuleBase::timer::end("ESolver_LR", "cal_force_Xz"); - return forces; -} - -template -void ModuleESolver::ESolver_LR::cal_force_and_grad_matrix_(const int ispin, std::ofstream &ofs) -{ - const std::vector forces = this->cal_force(ispin); - if (this->inp_->lr_degen_thr <= 0.0) - { - return; - } - // Rebuilt from scratch for this channel: a relaxation calls this once per ionic step, and a - // stale multiplet from the previous geometry must not survive into the next one. - this->multiplet_lvc_.erase( - std::remove_if( - this->multiplet_lvc_.begin(), this->multiplet_lvc_.end(), - [ispin](const MultipletLVC &m) { return m.ispin == ispin; }), - this->multiplet_lvc_.end()); - // The per-state gradients above are the diagonal of the degenerate-subspace gradient matrix in - // whatever basis the eigensolver returned, so inside a multiplet only their trace means - // anything. `lr_degen_thr` asks for the off-diagonal part too, which is the rest of the - // first-order information. - const int ekb_off = this->openshell ? 0 : ispin * this->nstates; - std::vector omega(this->nstates); - for (int ist = 0; ist < this->nstates; ++ist) - { - omega[ist] = this->pelec->ekb.c[ekb_off + ist]; - } - const std::vector> groups = LR::group_degenerate_states(omega, this->inp_->lr_degen_thr); - for (const std::vector &group : groups) - { - if (group.size() < 2) - { - continue; - } - std::vector diag; - for (const int ist : group) - { - diag.push_back(forces[ist]); - } - MultipletLVC lvc; - lvc.ispin = ispin; - lvc.states = group; - double lo = omega[group.front()]; - double hi = omega[group.front()]; - double sum = 0.0; - for (const int ist : group) - { - lo = std::min(lo, omega[ist]); - hi = std::max(hi, omega[ist]); - sum += omega[ist]; - } - lvc.omega0 = sum / static_cast(group.size()); - lvc.omega_spread = hi - lo; - lvc.g = this->cal_grad_matrix_degenerate(ispin, group, diag, ofs); - this->multiplet_lvc_.push_back(lvc); - } -} - -template -std::vector> ModuleESolver::ESolver_LR::cal_grad_matrix_degenerate( - const int ispin, - const std::vector &group, - const std::vector &diag, - std::ofstream &ofs) -{ - ModuleBase::TITLE("ESolver_LR", "cal_grad_matrix_degenerate"); - ModuleBase::timer::start("ESolver_LR", "cal_grad_matrix_degenerate"); - const int d = static_cast(group.size()); - assert(d >= 2); - assert(diag.size() == group.size()); - const std::vector> pairs = LR::degenerate_pairs(d); - const int nloc_g = this->nloc_per_state_z_; - const int ekb_off = this->openshell ? 0 : ispin * this->nstates; - - // 1. the multiplet's members, each widened into the Z window - const ct::Tensor Xz = this->pad_group_to_z_(ispin, group); - std::vector omega_member(d); - for (int k = 0; k < d; ++k) - { - omega_member[k] = this->pelec->ekb.c[ekb_off + group[k]]; - } - - // 2. the two preconditions of route (A2), reported rather than enforced: the combinations - // $X_\pm$ are normalized eigenvectors only if the members are orthonormal, and the gradient - // is a single quadratic form only if they share one $\Omega$. An accidental near-degeneracy - // passes the grouping threshold but fails the second, and its `omega_spread` says so. - double max_ovlp_err = 0.0; - for (int k = 0; k < d; ++k) - { - for (int l = k; l < d; ++l) - { - const T *const xk = Xz.template data() + static_cast(k) * nloc_g; - const T *const xl = Xz.template data() + static_cast(l) * nloc_g; - T loc = static_cast(0); - for (int i = 0; i < nloc_g; ++i) - { - loc += LR_Util::get_conj(xk[i]) * xl[i]; - } - Parallel_Reduce::reduce_all(loc); - const double ref = (k == l) ? 1.0 : 0.0; - max_ovlp_err = std::max(max_ovlp_err, std::abs(loc - ref)); - } - } - const double omega_max = *std::max_element(omega_member.begin(), omega_member.end()); - const double omega_min = *std::min_element(omega_member.begin(), omega_member.end()); - const double omega_spread = omega_max - omega_min; - // one $\Omega$ for every combination: the members share it up to `omega_spread`, and the mean - // is the neutral choice for a vector that belongs to no single member - double omega_sum = 0.0; - for (const double omega : omega_member) - { - omega_sum += omega; - } - const double omega_mean = omega_sum / static_cast(d); - ofs << " Degenerate multiplet of " << d << " states, Omega = " << omega_mean << " Ry, spread = " << omega_spread - << " Ry, max | - delta_kl| = " << max_ovlp_err << std::endl; - // Dimensionless diagnostic tolerance for the orthonormality needed by X_plus. - // This warning does not change the multiplet or the computed gradient. - const double orthonormality_warn_tol = 1e-6; - if (max_ovlp_err > orthonormality_warn_tol) - { - ofs << " WARNING: this multiplet's eigenvectors are not orthonormal to" - << " tolerance " << orthonormality_warn_tol - << " (dimensionless overlap error); (X_k+X_l)/sqrt(2) may not be normalized" - << " and the assembled gradient matrix may consequently be inaccurate." << std::endl; - } - - // 3. the $d(d-1)/2$ combinations $X_+=(X_k+X_l)/\sqrt2$, all in one Z-vector solve - const int npair = static_cast(pairs.size()); - ct::Tensor Xp = LR_Util::newTensor({npair, nloc_g}); - Xp.zero(); - for (int ip = 0; ip < npair; ++ip) - { - LR::combine_normalized( - Xz.template data() + static_cast(pairs[ip].first) * nloc_g, - Xz.template data() + static_cast(pairs[ip].second) * nloc_g, static_cast(nloc_g), - Xp.template data() + static_cast(ip) * nloc_g); - } - const std::vector omega_pair(npair, omega_mean); - const std::vector plus = this->openshell - ? this->cal_force_openshell_Xz(Xp, omega_pair, group[0]) - : this->cal_force_Xz(ispin, Xp, omega_pair, group[0]); - - // 4. $G_{kl}=\mathcal F[X_+]-\tfrac12(G_{kk}+G_{ll})$ - const std::vector> g = LR::assemble_grad_matrix(diag, plus, pairs); - print_grad_matrix(g, group, (*this->ucell_), ofs); - ModuleBase::timer::end("ESolver_LR", "cal_grad_matrix_degenerate"); - return g; -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force_openshell(const int istate_only) -{ - ModuleBase::TITLE("ESolver_LR", "cal_force_openshell"); - - // Open shell: there is a single eigenproblem whose vector is the concatenation - // [up-block | down-block], and every density matrix has two independent channels. - // The spin-orbital formulas apply verbatim -- unlike the closed-shell singlet/triplet - // algorithm, X here is normalized over BOTH channels, so it carries no implicit sqrt(2) - // and none of the collapsed 2/4 factors are needed. - const int ist_begin_ = (istate_only < 0) ? 0 : istate_only; - const int nst_ = (istate_only < 0) ? this->nstates : 1; - // Like the closed-shell path, the whole gradient runs in the Z window: X is zero-padded - // into it (both channels, each re-based -- see `pad_X_to_z_`), so D^X and T are unchanged - // while the Z-vector gets every occupied-virtual rotation the AO basis supports. - const ct::Tensor Xz = this->pad_X_to_z_(0, ist_begin_, nst_); - std::vector omega_(nst_); - for (int i = 0; i < nst_; ++i) - { - omega_[i] = this->pelec->ekb.c[ist_begin_ + i]; - } - return this->cal_force_openshell_Xz(Xz, omega_, ist_begin_); -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force_openshell_Xz( - const ct::Tensor &Xz, const std::vector &omega, const int label_begin) -{ - 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::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( - *this->ucell_, this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), - this->gd(), this->tcb(), force_settings, this->ofs_running_ -#ifdef __EXX - , - 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); - ModuleBase::timer::end("ESolver_LR", "cal_force_openshell_Xz"); - return forces; -} - -template -module_dm::DensityMatrix ModuleESolver::ESolver_LR::cal_dm_gs() -{ - // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight - // from the ground-state solver's own `psi`), but per `this->paraMat_all_` on the - // read-from-file path (where it was allocated with that descriptor's own sizes). - const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; - return LR::make_gs_dm(*this->psi_ks_all_, this->wg_ks_all, *pv_all, this->paraMat_, *this->ucell_, this->gd(), - this->orb_cutoff_, this->nspin, this->kv.kvec_d, this->nk); -} - -template -void ModuleESolver::ESolver_LR::test_force() -{ - 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 lr_force( - (*this->ucell_), this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), - this->gd(), this->tcb(), force_settings, this->ofs_running_ -#ifdef __EXX - , - std::weak_ptr>(this->exx_lri), this->exx_info.info_global.hybrid_alpha -#endif - ); - - const module_dm::DensityMatrix &dm_gs = this->cal_dm_gs(); - // LR_Util::print_DMR(dm_gs, "DM(R) of ground state"); - ///========================== test 1: reproduce the force of ground state ========================= - // energy density matrix of the ground state - module_dm::DensityMatrix edm_gs(&this->paraMat_, this->nspin, this->kv.kvec_d, this->nk); // DX - ModuleBase::matrix wg_ekb_ks_all(nspin, this->inp_->nbands); - const int occupation_count = nspin * this->inp_->nbands; - for (int index = 0; index < occupation_count; ++index) - { - wg_ekb_ks_all.c[index] = this->wg_ks_all.c[index] * this->eig_ks_all.c[index]; - } - // see `cal_dm_gs()`: `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path, - // not `this->paraMat_all_`. - const Parallel_Orbitals *const pv_all_edm = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; - module_dm::dm_from_psi(pv_all_edm, wg_ekb_ks_all, *this->psi_ks_all_, edm_gs); - LR_Util::initialize_DMR(edm_gs, this->paraMat_, (*this->ucell_), this->gd(), this->orb_cutoff_); - edm_gs.cal_dmr(-1); - // ground-state force - ModuleBase::matrix force_gs = lr_force.reproduce_force_gs(kv, dm_gs, edm_gs); - ModuleIO::print_force(this->ofs_running_, (*this->ucell_), "Ground State FORCE (eV/Angstrom)", force_gs, false); - /// ======================================= END test 1 ========================================= - ///========================== test 2: reproduce the DX Hartree term ========================= - ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->gs_pot_.pot_hartree()); - ModuleIO::print_force( - this->ofs_running_, (*this->ucell_), - "GS Hartree force calculated by 'cal_pulay_fs' from potential (eV/Angstrom)", f_hxc_potgs, false); - ModuleBase::matrix f_hxc_potlr = lr_force.cal_force_hxc_dmtrans(dm_gs, *this->pot[0]); - ModuleIO::print_force( - this->ofs_running_, (*this->ucell_), "GS Hxc force calculated by 'LR_Force' from kernel (eV/Angstrom)", - f_hxc_potlr, false); - // `cal_force_hxc_dmtrans` now includes the Pulay -> Pulay+Hellmann-Feynman factor 2 itself, - // so this must match the ground-state Hartree force directly (dm_gs is already symmetric). - /// ======================================= END test 2 ========================================= -} - -template class ModuleESolver::ESolver_LR; -template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp index 0479727c6a..969578d051 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr_lcao_tddft.cpp @@ -1,4 +1,3 @@ -// LR execution flow and final spectrum/density output. #include "esolver_lr_lcao_tddft.h" #include "source_hamilt/module_xc/xc_functional.h" #include "source_lcao/module_lr/hamilt_ulr.h" @@ -14,9 +13,35 @@ #include "source_lcao/module_lr/zeq_solver.h" #include #include +#include "source_lcao/module_lr/kernel_pots.h" +#include "source_io/module_parameter/parameter.h" +#include "source_lcao/module_lr/lr_dim.h" +#include +#include +#include "source_base/tool_quit.h" +#include "source_base/tool_title.h" +#include "source_lcao/module_lr/lr_gs.h" +#include +#include +#include +#include "source_base/parallel_reduce.h" +#include "source_estate/module_dm/dm_from_psi.h" +#include "source_io/module_output/output_log.h" +#include "source_lcao/module_lr/cal_edm.h" +#include "source_lcao/module_lr/grad_degen.h" +#include "source_lcao/module_lr/gradient_inputs.h" +#include "source_lcao/module_lr/gradient_output.h" +#include "source_lcao/module_lr/lr_amp.h" +#include "source_lcao/module_lr/lr_dm.h" +#include "source_lcao/module_lr/lr_force.h" +#include "source_base/timer.h" +#include using namespace LR; +// LR execution flow and final spectrum/density output. + + template ModuleESolver::ESolver_LR::ESolver_LR( const Input_para &inp, @@ -351,5 +376,795 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) } } } + +// Resolve LR dimensions and initialize kernel potentials. + +template +void ModuleESolver::ESolver_LR::set_dim() +{ + LR::DimSrc src; + src.inp = this->inp_; + src.nlocal = PARAM.globalv.nlocal; + src.nks = this->kv.get_nks(); + src.nkstot = this->kv.get_nkstot(); + src.rank = this->my_rank_; + src.gamma_only = std::is_same::value; + src.wg_ks = this->ks_ ? &this->ks_->pelec->wg : nullptr; + src.kpar = this->kv.para_k.kpar; + src.rank_in_pool = this->kv.para_k.rank_in_pool; + src.in_dir = this->in_dir; + src.ucell = const_cast(this->ucell_); + src.log = &this->ofs_running_; + + const LR::Dim dim = LR::resolve_dim(src); + + this->nspin = dim.nspin; + this->nstates = dim.nstates; + this->nbasis = dim.nbasis; + this->nbands = dim.nbands; + this->nk = dim.nk; + this->nupdown = dim.nupdown; + this->nocc_in = dim.nocc_in; + this->nocc_max = dim.nocc_max; + this->nvirt_in = dim.nvirt_in; + this->openshell = dim.openshell; + this->nocc = dim.nocc; + this->nvirt = dim.nvirt; + this->npairs = dim.npairs; +} + +template +void ModuleESolver::ESolver_LR::reset_dim_spin() +{ + LR::Dim dim; + dim.nspin = this->nspin; + dim.nstates = this->nstates; + dim.nk = this->nk; + dim.nupdown = this->nupdown; + dim.openshell = this->openshell; + dim.nocc = this->nocc; + dim.nvirt = this->nvirt; + dim.npairs = this->npairs; + + LR::apply_spin_pol(dim, *this->inp_); + + this->nocc = dim.nocc; + this->nvirt = dim.nvirt; + this->npairs = dim.npairs; + this->openshell = dim.openshell; +} + +template +void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) +{ + this->pot.assign(nspin, nullptr); + if (this->inp_->ri_hartree_benchmark != "none") + { + return; + } + const auto &grid = pgrid(); + auto prepared = + LR::prepare_lr_potentials(*this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell); + this->pot = std::move(prepared.pot); + if (this->inp_->cal_force) + { + this->init_pot_groundstate(chg_gs); + this->pot_hxc_gs = LR::prepare_gs_potential( + *this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell, prepared); + } +} + +// LR orbital distributions, excitation amplitudes, and ground-state file input. + + +template +void ModuleESolver::ESolver_LR::set_parallel_orbitals_band(Parallel_Orbitals &pmat, const int nbands_in) +{ + LR::set_band_layout(pmat, this->nbasis, nbands_in, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); +} + +template +void ModuleESolver::ESolver_LR::setup_eigenvectors_X() +{ + ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); + LR::AmpLayout layout = LR::make_amp_layout(this->paraC_, this->nocc, this->nvirt, this->nk, this->openshell); + this->paraX_ = std::move(layout.para_x); + this->nloc_per_state = layout.nloc; + + this->X.resize(this->openshell ? 1 : this->nspin, LR_Util::newTensor({this->nstates, this->nloc_per_state})); + for (container::Tensor& x : this->X) + { + x.zero(); + } + + // if spectrum-only, read the LR-eigenstates from file and return + if (this->inp_->lr_solver != "spectrum") + { + LR::set_x_init(this->X, this->eig_ks, this->nocc, this->nvirt, this->npairs, this->paraX_, this->nstates, + this->nloc_per_state, this->nk, this->openshell, this->ofs_running_); + } +} + +template +void ModuleESolver::ESolver_LR::read_ks_wfc() +{ + assert(this->psi_ks != nullptr); + this->eig_ks.create(this->kv.get_nks(), this->nbands); + this->wg_ks.create(this->kv.get_nks(), this->nbands); + if (this->inp_->ri_hartree_benchmark == "aims") // for aims benchmark + { + LR::read_wfc_aims(*this->psi_ks, this->eig_ks, this->in_dir, this->nocc_in, this->nvirt_in, this->nbands, + this->nbasis); + } + else if (!LR::read_wfc_win(this->in_dir, this->paraMat_, *this->psi_ks, this->eig_ks, this->wg_ks, this->kv, + this->inp_->nspin, this->inp_->init_wfc_file_format == "binary", + /*skip_bands=*/this->nocc_max - this->nocc_in)) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "read ground-state wavefunction failed."); + } + + if (this->inp_->cal_force) + { // allocate psi_ks_all and eig_ks_all to read all the bands + this->psi_ks_all_own_.reset(new psi::Psi( + this->kv.get_nks(), paraMat_all_.ncol_bands, paraMat_all_.para_2d().nrloc(), this->kv.ngk, true)); + this->psi_ks_all_ = this->psi_ks_all_own_.get(); + this->eig_ks_all.create(this->kv.get_nks(), this->inp_->nbands); + this->wg_ks_all.create(this->kv.get_nks(), this->inp_->nbands); + if (!LR::read_wfc_all(this->in_dir, paraMat_all_, *this->psi_ks_all_, this->eig_ks_all, this->wg_ks_all, + this->kv, this->inp_->nspin, this->inp_->init_wfc_file_format == "binary")) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "read all ground-state wavefunctions for force calculation failed."); + } + this->ofs_running_ << " Read in all the KS wavefunctions for force calculation. " << std::endl; + } +} + +template +void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) +{ + ModuleBase::TITLE("ESolver_LR", "fill_z_window_"); + LR::ZWin z = LR::build_z_win(this->psi_ks_all_, this->eig_ks_all, this->nocc, this->nvirt, this->nocc_max, + this->nbands, this->nbasis, this->nk, this->openshell, this->kv, this->paraC_, + this->paraMat_, desc_src, this->inp_->cal_force, !this->ks_initialized_, + this->ofs_running_); + this->psi_ks_z_ = std::move(z.psi); + this->eig_ks_z_ = std::move(z.eig); + this->paraC_z_ = std::move(z.para_c); + this->paraX_z_ = std::move(z.para_x); + this->nvirt_z_ = std::move(z.nvirt); + this->nbands_z_ = z.nbands; + this->nloc_per_state_z_ = z.nloc; +} + +template +void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) +{ + LR::read_gs_chg(this->in_dir, *this->inp_, this->nspin, *this->ucell_, pgrid(), this->pw_rho, chg_gs, + this->my_rank_, this->ofs_running_); +} + + +///========================= excited-state geometry relaxation ========================= + +template +void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs) +{ + ModuleBase::TITLE("ESolver_LR", "init_pot_gs"); + this->gs_pot_.refresh(*this->inp_, this->xc_kernel, *this->ucell_, this->pw_rhod, this->pw_rho, pgrid(), chg_gs, + this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); +} + +template +ct::Tensor ModuleESolver::ESolver_LR::pad_X_to_z_(const int ispin, const int istate_begin, const int nst) const +{ + return LR::pad_amplitudes( + this->X, this->openshell, this->paraX_, this->paraX_z_, this->nocc, this->nvirt, this->nk, this->nloc_per_state, + this->nloc_per_state_z_, ispin, istate_begin, nst); +} + +template +ct::Tensor ModuleESolver::ESolver_LR::solve_zvector_eqation(const int ispin, const int nst, const ct::Tensor &Xz) +{ + ModuleBase::TITLE("ESolver_LR", "cal_force"); + ModuleBase::timer::start("ESolver_LR", "solve_zvector_eqation"); + // `Z_vector_equation` treats X and Z as `nst` independent blocks of `nloc_per_state_z_`, + // and the blocks need not be eigenvectors of the Casida equation in the order the + // diagonalizer returned them -- `cal_grad_matrix_degenerate` feeds it linear combinations. + // X arrives already widened into the Z window (`Xz`), which spans every virtual band the + // ground state produced rather than the `nvirt` window X was solved in -- the Brillouin + // condition the Z-vector enforces holds in EVERY occupied-virtual rotation. The padded + // entries are zero, so every X-derived quantity (D^X, T) is unchanged; only the space Z is + // solved in grows. Both the closed- and the open-shell path go through here. + ct::Tensor Z = LR_Util::newTensor({nst, this->nloc_per_state_z_}); + // construct and solve the Z-vector equation + const LR::GradientInputs inputs = this->gradient_inputs_(); + const T *const x_data = Xz.template data(); + T *const z_data = Z.template data(); + 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); + ModuleBase::timer::end("ESolver_LR", "solve_zvector_eqation"); + return Z; +} + +template +std::vector ModuleESolver::ESolver_LR::cal_force(const int ispin, const int istate_only) +{ + if (this->inp_->test_force && ispin == 0) + { + this->test_force(); + } + if (this->openshell) + { + return this->cal_force_openshell(istate_only); + } + + const int ist_begin = (istate_only < 0) ? 0 : istate_only; + const int nst = (istate_only < 0) ? this->nstates : 1; + // The whole closed-shell gradient runs in the Z window (every virtual band the ground state + // produced), not the `nvirt` window X was solved in: only there does the Z-vector enforce + // the Brillouin condition in every occupied-virtual rotation. X is zero-padded into it, so + // D^X and T come out bit-identical -- and Omega is untouched, so an existing finite-difference + // reference stays valid. See `fill_z_window_`. + const ct::Tensor Xz = this->pad_X_to_z_(ispin, ist_begin, nst); + std::vector omega(nst); + for (int i = 0; i < nst; ++i) + { + omega[i] = this->pelec->ekb.c[ispin * this->nstates + ist_begin + i]; + } + return this->cal_force_Xz(ispin, Xz, omega, ist_begin); +} + +template +LR::GradientInputs ModuleESolver::ESolver_LR::gradient_inputs_() const +{ + return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->paraMat_, this->paraC_z_, this->paraX_z_, + *this->psi_ks_z_, this->eig_ks_z_, this->nocc, this->nvirt_z_, this->nspin, this->nk, this->nbasis, + this->nloc_per_state_z_, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, + this->inp_->test_force, this->target_.active(), this->out_dir, this->my_rank_, this->spin_types, this->pot, + this->pot_hxc_gs, this->ofs_running_ +#ifdef __EXX + , + this->exx_lri, this->exx_info.info_global.hybrid_alpha +#endif + }; +} + +template +std::vector ModuleESolver::ESolver_LR::cal_force_Xz( + const int ispin, + const ct::Tensor &Xz, + const std::vector &omega, + const int label_begin) +{ + 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::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( + *this->ucell_, this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), + this->gd(), this->tcb(), force_settings, this->ofs_running_ +#ifdef __EXX + , + 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); + ModuleBase::timer::end("ESolver_LR", "cal_force_Xz"); + return forces; +} + +template +void ModuleESolver::ESolver_LR::cal_force_and_grad_matrix_(const int ispin, std::ofstream &ofs) +{ + const std::vector forces = this->cal_force(ispin); + if (this->inp_->lr_degen_thr <= 0.0) + { + return; + } + // Rebuilt from scratch for this channel: a relaxation calls this once per ionic step, and a + // stale multiplet from the previous geometry must not survive into the next one. + this->multiplet_lvc_.erase( + std::remove_if( + this->multiplet_lvc_.begin(), this->multiplet_lvc_.end(), + [ispin](const MultipletLVC &m) { return m.ispin == ispin; }), + this->multiplet_lvc_.end()); + // The per-state gradients above are the diagonal of the degenerate-subspace gradient matrix in + // whatever basis the eigensolver returned, so inside a multiplet only their trace means + // anything. `lr_degen_thr` asks for the off-diagonal part too, which is the rest of the + // first-order information. + const int ekb_off = this->openshell ? 0 : ispin * this->nstates; + std::vector omega(this->nstates); + for (int ist = 0; ist < this->nstates; ++ist) + { + omega[ist] = this->pelec->ekb.c[ekb_off + ist]; + } + const std::vector> groups = LR::group_degenerate_states(omega, this->inp_->lr_degen_thr); + for (const std::vector &group : groups) + { + if (group.size() < 2) + { + continue; + } + std::vector diag; + for (const int ist : group) + { + diag.push_back(forces[ist]); + } + MultipletLVC lvc; + lvc.ispin = ispin; + lvc.states = group; + double lo = omega[group.front()]; + double hi = omega[group.front()]; + double sum = 0.0; + for (const int ist : group) + { + lo = std::min(lo, omega[ist]); + hi = std::max(hi, omega[ist]); + sum += omega[ist]; + } + lvc.omega0 = sum / static_cast(group.size()); + lvc.omega_spread = hi - lo; + lvc.g = this->cal_grad_matrix_degenerate(ispin, group, diag, ofs); + this->multiplet_lvc_.push_back(lvc); + } +} + +template +std::vector> ModuleESolver::ESolver_LR::cal_grad_matrix_degenerate( + const int ispin, + const std::vector &group, + const std::vector &diag, + std::ofstream &ofs) +{ + ModuleBase::TITLE("ESolver_LR", "cal_grad_matrix_degenerate"); + ModuleBase::timer::start("ESolver_LR", "cal_grad_matrix_degenerate"); + const int d = static_cast(group.size()); + assert(d >= 2); + assert(diag.size() == group.size()); + const std::vector> pairs = LR::degenerate_pairs(d); + const int nloc_g = this->nloc_per_state_z_; + const int ekb_off = this->openshell ? 0 : ispin * this->nstates; + + // 1. the multiplet's members, each widened into the Z window + const ct::Tensor Xz = this->pad_group_to_z_(ispin, group); + std::vector omega_member(d); + for (int k = 0; k < d; ++k) + { + omega_member[k] = this->pelec->ekb.c[ekb_off + group[k]]; + } + + // 2. the two preconditions of route (A2), reported rather than enforced: the combinations + // $X_\pm$ are normalized eigenvectors only if the members are orthonormal, and the gradient + // is a single quadratic form only if they share one $\Omega$. An accidental near-degeneracy + // passes the grouping threshold but fails the second, and its `omega_spread` says so. + double max_ovlp_err = 0.0; + for (int k = 0; k < d; ++k) + { + for (int l = k; l < d; ++l) + { + const T *const xk = Xz.template data() + static_cast(k) * nloc_g; + const T *const xl = Xz.template data() + static_cast(l) * nloc_g; + T loc = static_cast(0); + for (int i = 0; i < nloc_g; ++i) + { + loc += LR_Util::get_conj(xk[i]) * xl[i]; + } + Parallel_Reduce::reduce_all(loc); + const double ref = (k == l) ? 1.0 : 0.0; + max_ovlp_err = std::max(max_ovlp_err, std::abs(loc - ref)); + } + } + const double omega_max = *std::max_element(omega_member.begin(), omega_member.end()); + const double omega_min = *std::min_element(omega_member.begin(), omega_member.end()); + const double omega_spread = omega_max - omega_min; + // one $\Omega$ for every combination: the members share it up to `omega_spread`, and the mean + // is the neutral choice for a vector that belongs to no single member + double omega_sum = 0.0; + for (const double omega : omega_member) + { + omega_sum += omega; + } + const double omega_mean = omega_sum / static_cast(d); + ofs << " Degenerate multiplet of " << d << " states, Omega = " << omega_mean << " Ry, spread = " << omega_spread + << " Ry, max | - delta_kl| = " << max_ovlp_err << std::endl; + // Dimensionless diagnostic tolerance for the orthonormality needed by X_plus. + // This warning does not change the multiplet or the computed gradient. + const double orthonormality_warn_tol = 1e-6; + if (max_ovlp_err > orthonormality_warn_tol) + { + ofs << " WARNING: this multiplet's eigenvectors are not orthonormal to" + << " tolerance " << orthonormality_warn_tol + << " (dimensionless overlap error); (X_k+X_l)/sqrt(2) may not be normalized" + << " and the assembled gradient matrix may consequently be inaccurate." << std::endl; + } + + // 3. the $d(d-1)/2$ combinations $X_+=(X_k+X_l)/\sqrt2$, all in one Z-vector solve + const int npair = static_cast(pairs.size()); + ct::Tensor Xp = LR_Util::newTensor({npair, nloc_g}); + Xp.zero(); + for (int ip = 0; ip < npair; ++ip) + { + LR::combine_normalized( + Xz.template data() + static_cast(pairs[ip].first) * nloc_g, + Xz.template data() + static_cast(pairs[ip].second) * nloc_g, static_cast(nloc_g), + Xp.template data() + static_cast(ip) * nloc_g); + } + const std::vector omega_pair(npair, omega_mean); + const std::vector plus = this->openshell + ? this->cal_force_openshell_Xz(Xp, omega_pair, group[0]) + : this->cal_force_Xz(ispin, Xp, omega_pair, group[0]); + + // 4. $G_{kl}=\mathcal F[X_+]-\tfrac12(G_{kk}+G_{ll})$ + const std::vector> g = LR::assemble_grad_matrix(diag, plus, pairs); + print_grad_matrix(g, group, (*this->ucell_), ofs); + ModuleBase::timer::end("ESolver_LR", "cal_grad_matrix_degenerate"); + return g; +} + +template +std::vector ModuleESolver::ESolver_LR::cal_force_openshell(const int istate_only) +{ + ModuleBase::TITLE("ESolver_LR", "cal_force_openshell"); + + // Open shell: there is a single eigenproblem whose vector is the concatenation + // [up-block | down-block], and every density matrix has two independent channels. + // The spin-orbital formulas apply verbatim -- unlike the closed-shell singlet/triplet + // algorithm, X here is normalized over BOTH channels, so it carries no implicit sqrt(2) + // and none of the collapsed 2/4 factors are needed. + const int ist_begin_ = (istate_only < 0) ? 0 : istate_only; + const int nst_ = (istate_only < 0) ? this->nstates : 1; + // Like the closed-shell path, the whole gradient runs in the Z window: X is zero-padded + // into it (both channels, each re-based -- see `pad_X_to_z_`), so D^X and T are unchanged + // while the Z-vector gets every occupied-virtual rotation the AO basis supports. + const ct::Tensor Xz = this->pad_X_to_z_(0, ist_begin_, nst_); + std::vector omega_(nst_); + for (int i = 0; i < nst_; ++i) + { + omega_[i] = this->pelec->ekb.c[ist_begin_ + i]; + } + return this->cal_force_openshell_Xz(Xz, omega_, ist_begin_); +} + +template +std::vector ModuleESolver::ESolver_LR::cal_force_openshell_Xz( + const ct::Tensor &Xz, const std::vector &omega, const int label_begin) +{ + 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::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( + *this->ucell_, this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), + this->gd(), this->tcb(), force_settings, this->ofs_running_ +#ifdef __EXX + , + 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); + ModuleBase::timer::end("ESolver_LR", "cal_force_openshell_Xz"); + return forces; +} + +template +module_dm::DensityMatrix ModuleESolver::ESolver_LR::cal_dm_gs() +{ + // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight + // from the ground-state solver's own `psi`), but per `this->paraMat_all_` on the + // read-from-file path (where it was allocated with that descriptor's own sizes). + const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; + return LR::make_gs_dm(*this->psi_ks_all_, this->wg_ks_all, *pv_all, this->paraMat_, *this->ucell_, this->gd(), + this->orb_cutoff_, this->nspin, this->kv.kvec_d, this->nk); +} + +template +void ModuleESolver::ESolver_LR::test_force() +{ + 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 lr_force( + (*this->ucell_), this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), + this->gd(), this->tcb(), force_settings, this->ofs_running_ +#ifdef __EXX + , + std::weak_ptr>(this->exx_lri), this->exx_info.info_global.hybrid_alpha +#endif + ); + + const module_dm::DensityMatrix &dm_gs = this->cal_dm_gs(); + // LR_Util::print_DMR(dm_gs, "DM(R) of ground state"); + ///========================== test 1: reproduce the force of ground state ========================= + // energy density matrix of the ground state + module_dm::DensityMatrix edm_gs(&this->paraMat_, this->nspin, this->kv.kvec_d, this->nk); // DX + ModuleBase::matrix wg_ekb_ks_all(nspin, this->inp_->nbands); + const int occupation_count = nspin * this->inp_->nbands; + for (int index = 0; index < occupation_count; ++index) + { + wg_ekb_ks_all.c[index] = this->wg_ks_all.c[index] * this->eig_ks_all.c[index]; + } + // see `cal_dm_gs()`: `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path, + // not `this->paraMat_all_`. + const Parallel_Orbitals *const pv_all_edm = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; + module_dm::dm_from_psi(pv_all_edm, wg_ekb_ks_all, *this->psi_ks_all_, edm_gs); + LR_Util::initialize_DMR(edm_gs, this->paraMat_, (*this->ucell_), this->gd(), this->orb_cutoff_); + edm_gs.cal_dmr(-1); + // ground-state force + ModuleBase::matrix force_gs = lr_force.reproduce_force_gs(kv, dm_gs, edm_gs); + ModuleIO::print_force(this->ofs_running_, (*this->ucell_), "Ground State FORCE (eV/Angstrom)", force_gs, false); + /// ======================================= END test 1 ========================================= + ///========================== test 2: reproduce the DX Hartree term ========================= + ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->gs_pot_.pot_hartree()); + ModuleIO::print_force( + this->ofs_running_, (*this->ucell_), + "GS Hartree force calculated by 'cal_pulay_fs' from potential (eV/Angstrom)", f_hxc_potgs, false); + ModuleBase::matrix f_hxc_potlr = lr_force.cal_force_hxc_dmtrans(dm_gs, *this->pot[0]); + ModuleIO::print_force( + this->ofs_running_, (*this->ucell_), "GS Hxc force calculated by 'LR_Force' from kernel (eV/Angstrom)", + f_hxc_potlr, false); + // `cal_force_hxc_dmtrans` now includes the Pulay -> Pulay+Hellmann-Feynman factor 2 itself, + // so this must match the ground-state Hartree force directly (dm_gs is already symmetric). + /// ======================================= END test 2 ========================================= +} + + +template +void ModuleESolver::ESolver_LR::setup_relax_target_() +{ + this->target_.setup(*this->inp_, this->openshell, this->nspin, this->nstates, this->ofs_running_); + if (this->target_.active()) + { + this->force_gs_.create(this->ucell_->nat, 3); + this->lr_force_.create(this->ucell_->nat, 3); + } +} + +/// Compare roots in a common electron-hole basis using exact cross-geometry AO overlap. +template +void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) +{ + ModuleBase::timer::start("ESolver_LR", "follow_target_state_"); + if (!this->target_.active()) + { + ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); + return; + } + const int channel = this->openshell ? 0 : this->target_.ispin(); + const T *const amplitudes = this->X[channel].template data(); + const TwoCenterIntegrator &overlap_integrator = *this->tcb().overlap_orb; + std::vector energies(this->nstates); + std::copy_n(this->pelec->ekb.c + this->target_.ekb_off(this->nstates), this->nstates, energies.begin()); + this->target_.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->paraC_, + this->paraMat_, this->paraX_, this->nocc, this->nvirt, amplitudes, this->nloc_per_state, + this->nstates, energies, ofs); + ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); +} + +template +double ModuleESolver::ESolver_LR::cal_energy() +{ + // Outside a relaxation nothing consumes this, and returning a non-zero value would change + // what the existing single-point outputs report. + if (!this->target_.active()) + { + return 0.0; + } + // `omega` is the multiplet average under `lr_degen_mode = average` and the single state + // otherwise, matching whatever `cal_lr_force_relax_` produced the gradient of. The + // energy-based optimisers line-search on this, so the two must not describe different + // surfaces. + return this->etot_gs_ + this->target_.omega(this->pelec->ekb.c, this->nstates); +} + +template +void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase::matrix &force) +{ + basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); + const UnitCell &ucell = static_cast(basecell); + if (!this->target_.active()) + { // single-point runs print the gradients of every state from `after_all_runners` instead + return; + } + if (this->lr_force_.nr != ucell.nat) + { + ModuleBase::WARNING_QUIT( + "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. + 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); +} + +template +void ModuleESolver::ESolver_LR::cal_stress(BaseCell &basecell, ModuleBase::matrix &stress) +{ + static_cast(stress); + basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); + ModuleBase::WARNING_QUIT( + "ESolver_LR::cal_stress", "the excited-state stress is not implemented (every LR gradient stress term is a " + "dummy passed with isstress=false)."); +} + +template +ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, const std::vector &group) const +{ + const int d = static_cast(group.size()); + const int nloc_g = this->nloc_per_state_z_; + ct::Tensor Xz = LR_Util::newTensor({d, nloc_g}); + Xz.zero(); + // One at a time rather than as a range: `group` is sorted, but nothing guarantees its members + // are contiguous in the state list. + for (int k = 0; k < d; ++k) + { + const ct::Tensor one = this->pad_X_to_z_(ispin, group[k], 1); + std::copy( + one.template data(), one.template data() + nloc_g, + Xz.template data() + static_cast(k) * nloc_g); + } + return Xz; +} + +template +ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::ofstream &ofs) +{ + this->target_.resolve_group(*this->inp_, this->pelec->ekb.c, this->nstates, this->ofs_running_); + const std::vector &group = this->target_.group(); + if (group.empty()) + { + return this->cal_force(this->target_.ispin(), this->target_.state())[0]; + } + const bool jt_mode = (LR_Util::tolower(this->inp_->lr_degen_mode) == "jt"); + // `average` needs only the DIAGONAL of the gradient matrix: the average is basis-independent by + // construction, so the off-diagonal part (and the extra d(d-1)/2 solves it costs) is not + // involved. The Jahn-Teller direction is orthogonal to the average and does need them. + const int d = static_cast(group.size()); + const int ekb_off = this->target_.ekb_off(this->nstates); + const ct::Tensor Xz = this->pad_group_to_z_(this->target_.ispin(), group); + std::vector omega(d); + for (int k = 0; k < d; ++k) + { + omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; + } + const std::vector forces = + this->openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) + : this->cal_force_Xz(this->target_.ispin(), Xz, omega, group.front()); + ofs << " Followed state " << this->target_.state() << " is degenerate with"; + for (const int ist : group) + { + if (ist != this->target_.state()) + { + ofs << " " << ist; + } + } + ofs << " (Omega_bar = " << this->target_.omega(this->pelec->ekb.c, this->nstates) << " Ry)." << std::endl; + if (!jt_mode) + { + ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" + " geometry on the current average surface; split groups are not recombined." + << std::endl; + return average_forces(forces); + } + return this->cal_jt_force_(forces, ofs); +} + +template +ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( + const std::vector &diag, std::ofstream &ofs) +{ + // Regime (c): descend the Jahn-Teller branch. This needs the whole gradient matrix, so the + // off-diagonal elements are assembled here -- d(d-1)/2 further Z-vector solves on top of the + // d diagonal ones already in `diag`. + const std::vector &group = this->target_.group(); + const int d = static_cast(group.size()); + const std::vector> g = + this->cal_grad_matrix_degenerate(this->target_.ispin(), group, diag, ofs); + const int nat = diag[0].nr; + const int ncoord = nat * 3; + // flatten to the layout `find_jt_direction` takes: one d x d block per nuclear coordinate. + // FORCES go in, not gradients, so the direction that comes back points downhill. + std::vector gflat(static_cast(ncoord) * d * d, 0.0); + for (int iat = 0; iat < nat; ++iat) + { + for (int ixyz = 0; ixyz < 3; ++ixyz) + { + const int a = iat * 3 + ixyz; + for (int k = 0; k < d; ++k) + { + for (int l = 0; l < d; ++l) + { + gflat[static_cast(a) * d * d + k * d + l] = g[k][l](iat, ixyz); + } + } + } + } + const LR::JTDirection jt = LR::find_jt_direction(gflat, ncoord, d); + const int channel = this->openshell ? 0 : this->target_.ispin(); + const T *const amplitudes = this->X[channel].template data(); + this->target_.save_mixed(amplitudes, this->nloc_per_state, jt.mixing); + std::vector jt_part; + const std::vector sym = LR::split_symmetric_part(gflat, ncoord, d, jt.mixing, jt_part); + + const double fac = ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A; + ofs << " lr_degen_mode=jt: descending the steepest branch of the multiplet." << std::endl + << " |F| of that branch = " << jt.slope * fac << " eV/Angstrom" << std::endl + << " mixing v ="; + for (int k = 0; k < d; ++k) + { + ofs << " " << jt.mixing[k]; + } + ofs << std::endl + << " starts agreeing = " << jt.restarts_agreeing << " of " << (d + (1 << (d - 1))) << " (iterations " + << jt.iterations << ")" << std::endl; + // The two halves matter separately: the symmetric part is common to the whole multiplet and + // only relaxes the geometry, while the remainder is what actually breaks the degeneracy. At a + // stationary point of the average surface the first is zero and the whole force is Jahn-Teller. + double nsym = 0.0; + double njt = 0.0; + for (int a = 0; a < ncoord; ++a) + { + nsym += sym[a] * sym[a]; + njt += jt_part[a] * jt_part[a]; + } + ofs << " |symmetric part| = " << std::sqrt(nsym) * fac + << " eV/Angstrom (common to the" + " multiplet; relaxes the geometry without splitting it)" + << std::endl + << " |Jahn-Teller part| = " << std::sqrt(njt) * fac + << " eV/Angstrom (the symmetry-" + "breaking remainder)" + << std::endl; + if (std::sqrt(njt) < 1e-8) + { + ofs << " WARNING: the symmetry-breaking part vanishes -- every branch of this multiplet has" + " the same gradient, so there is no Jahn-Teller direction to descend here. This is the" + " expected outcome for a linear molecule, where the effect is second order" + " (Renner-Teller) and no first-order term exists." + << std::endl; + } + ofs << " NOTE: this is the first-order DIRECTION only. The distortion amplitude also needs the" + " harmonic term, and the step norm is Cartesian rather than mass-weighted." + << std::endl; + + // The force handed back is that of the descending branch, q(v) with v the optimal mixing -- + // i.e. the branch's own gradient, which is what a relaxation must follow. Once a step has + // split the multiplet, `resolve_group` finds no group and the ordinary single-state path + // takes over, so this mode is self-limiting by construction. + ModuleBase::matrix f(nat, 3); + for (int iat = 0; iat < nat; ++iat) + { + for (int ixyz = 0; ixyz < 3; ++ixyz) + { + const int a = iat * 3 + ixyz; + f(iat, ixyz) = sym[a] + jt_part[a]; + } + } + return f; +} + +template +ModuleBase::matrix ModuleESolver::ESolver_LR::MultipletLVC::average_force() const +{ + assert(!this->g.empty()); + std::vector diag; + for (int k = 0; k < this->dim(); ++k) + { + diag.push_back(this->g[k][k]); + } + return average_forces(diag); +} + template class ModuleESolver::ESolver_LR; template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_esolver/esolver_lr_orb.cpp b/source/source_esolver/esolver_lr_orb.cpp deleted file mode 100644 index 71438c970f..0000000000 --- a/source/source_esolver/esolver_lr_orb.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// LR orbital distributions, excitation amplitudes, and ground-state file input. -#include "esolver_lr_lcao_tddft.h" -#include "source_base/tool_quit.h" -#include "source_base/tool_title.h" -#include "source_lcao/module_lr/lr_gs.h" -#include "source_lcao/module_lr/utils/lr_util.h" - -#include -#include -#include - -template -void ModuleESolver::ESolver_LR::set_parallel_orbitals_band(Parallel_Orbitals &pmat, const int nbands_in) -{ - LR::set_band_layout(pmat, this->nbasis, nbands_in, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); -} - -template -void ModuleESolver::ESolver_LR::setup_eigenvectors_X() -{ - ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); - LR::AmpLayout layout = LR::make_amp_layout(this->paraC_, this->nocc, this->nvirt, this->nk, this->openshell); - this->paraX_ = std::move(layout.para_x); - this->nloc_per_state = layout.nloc; - - this->X.resize(this->openshell ? 1 : this->nspin, LR_Util::newTensor({this->nstates, this->nloc_per_state})); - for (container::Tensor& x : this->X) - { - x.zero(); - } - - // if spectrum-only, read the LR-eigenstates from file and return - if (this->inp_->lr_solver != "spectrum") - { - LR::set_x_init(this->X, this->eig_ks, this->nocc, this->nvirt, this->npairs, this->paraX_, this->nstates, - this->nloc_per_state, this->nk, this->openshell, this->ofs_running_); - } -} - -template -void ModuleESolver::ESolver_LR::read_ks_wfc() -{ - assert(this->psi_ks != nullptr); - this->eig_ks.create(this->kv.get_nks(), this->nbands); - this->wg_ks.create(this->kv.get_nks(), this->nbands); - if (this->inp_->ri_hartree_benchmark == "aims") // for aims benchmark - { - LR::read_wfc_aims(*this->psi_ks, this->eig_ks, this->in_dir, this->nocc_in, this->nvirt_in, this->nbands, - this->nbasis); - } - else if (!LR::read_wfc_win(this->in_dir, this->paraMat_, *this->psi_ks, this->eig_ks, this->wg_ks, this->kv, - this->inp_->nspin, this->inp_->init_wfc_file_format == "binary", - /*skip_bands=*/this->nocc_max - this->nocc_in)) - { - ModuleBase::WARNING_QUIT("ESolver_LR", "read ground-state wavefunction failed."); - } - - if (this->inp_->cal_force) - { // allocate psi_ks_all and eig_ks_all to read all the bands - this->psi_ks_all_own_.reset(new psi::Psi( - this->kv.get_nks(), paraMat_all_.ncol_bands, paraMat_all_.para_2d().nrloc(), this->kv.ngk, true)); - this->psi_ks_all_ = this->psi_ks_all_own_.get(); - this->eig_ks_all.create(this->kv.get_nks(), this->inp_->nbands); - this->wg_ks_all.create(this->kv.get_nks(), this->inp_->nbands); - if (!LR::read_wfc_all(this->in_dir, paraMat_all_, *this->psi_ks_all_, this->eig_ks_all, this->wg_ks_all, - this->kv, this->inp_->nspin, this->inp_->init_wfc_file_format == "binary")) - { - ModuleBase::WARNING_QUIT("ESolver_LR", "read all ground-state wavefunctions for force calculation failed."); - } - this->ofs_running_ << " Read in all the KS wavefunctions for force calculation. " << std::endl; - } -} - -template -void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) -{ - ModuleBase::TITLE("ESolver_LR", "fill_z_window_"); - LR::ZWin z = LR::build_z_win(this->psi_ks_all_, this->eig_ks_all, this->nocc, this->nvirt, this->nocc_max, - this->nbands, this->nbasis, this->nk, this->openshell, this->kv, this->paraC_, - this->paraMat_, desc_src, this->inp_->cal_force, !this->ks_initialized_, - this->ofs_running_); - this->psi_ks_z_ = std::move(z.psi); - this->eig_ks_z_ = std::move(z.eig); - this->paraC_z_ = std::move(z.para_c); - this->paraX_z_ = std::move(z.para_x); - this->nvirt_z_ = std::move(z.nvirt); - this->nbands_z_ = z.nbands; - this->nloc_per_state_z_ = z.nloc; -} - -template -void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) -{ - LR::read_gs_chg(this->in_dir, *this->inp_, this->nspin, *this->ucell_, pgrid(), this->pw_rho, chg_gs, - this->my_rank_, this->ofs_running_); -} - -template class ModuleESolver::ESolver_LR; -template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_esolver/esolver_lr_rlx.cpp b/source/source_esolver/esolver_lr_rlx.cpp deleted file mode 100644 index d9e165289b..0000000000 --- a/source/source_esolver/esolver_lr_rlx.cpp +++ /dev/null @@ -1,268 +0,0 @@ -#include "source_base/parallel_reduce.h" -#include "source_base/timer.h" -#include "source_esolver/esolver_lr_lcao_tddft.h" -#include "source_io/module_output/output_log.h" -#include "source_lcao/module_lr/cal_edm.h" -#include "source_lcao/module_lr/grad_degen.h" -#include "source_lcao/module_lr/gradient_inputs.h" -#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/zeq_solver.h" -#include -#include -#include - -using namespace LR; - -template -void ModuleESolver::ESolver_LR::setup_relax_target_() -{ - this->target_.setup(*this->inp_, this->openshell, this->nspin, this->nstates, this->ofs_running_); - if (this->target_.active()) - { - this->force_gs_.create(this->ucell_->nat, 3); - this->lr_force_.create(this->ucell_->nat, 3); - } -} - -/// Compare roots in a common electron-hole basis using exact cross-geometry AO overlap. -template -void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) -{ - ModuleBase::timer::start("ESolver_LR", "follow_target_state_"); - if (!this->target_.active()) - { - ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); - return; - } - const int channel = this->openshell ? 0 : this->target_.ispin(); - const T *const amplitudes = this->X[channel].template data(); - const TwoCenterIntegrator &overlap_integrator = *this->tcb().overlap_orb; - std::vector energies(this->nstates); - std::copy_n(this->pelec->ekb.c + this->target_.ekb_off(this->nstates), this->nstates, energies.begin()); - this->target_.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->paraC_, - this->paraMat_, this->paraX_, this->nocc, this->nvirt, amplitudes, this->nloc_per_state, - this->nstates, energies, ofs); - ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); -} - -template -double ModuleESolver::ESolver_LR::cal_energy() -{ - // Outside a relaxation nothing consumes this, and returning a non-zero value would change - // what the existing single-point outputs report. - if (!this->target_.active()) - { - return 0.0; - } - // `omega` is the multiplet average under `lr_degen_mode = average` and the single state - // otherwise, matching whatever `cal_lr_force_relax_` produced the gradient of. The - // energy-based optimisers line-search on this, so the two must not describe different - // surfaces. - return this->etot_gs_ + this->target_.omega(this->pelec->ekb.c, this->nstates); -} - -template -void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase::matrix &force) -{ - basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); - const UnitCell &ucell = static_cast(basecell); - if (!this->target_.active()) - { // single-point runs print the gradients of every state from `after_all_runners` instead - return; - } - if (this->lr_force_.nr != ucell.nat) - { - ModuleBase::WARNING_QUIT( - "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. - 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); -} - -template -void ModuleESolver::ESolver_LR::cal_stress(BaseCell &basecell, ModuleBase::matrix &stress) -{ - static_cast(stress); - basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); - ModuleBase::WARNING_QUIT( - "ESolver_LR::cal_stress", "the excited-state stress is not implemented (every LR gradient stress term is a " - "dummy passed with isstress=false)."); -} - -template -ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, const std::vector &group) const -{ - const int d = static_cast(group.size()); - const int nloc_g = this->nloc_per_state_z_; - ct::Tensor Xz = LR_Util::newTensor({d, nloc_g}); - Xz.zero(); - // One at a time rather than as a range: `group` is sorted, but nothing guarantees its members - // are contiguous in the state list. - for (int k = 0; k < d; ++k) - { - const ct::Tensor one = this->pad_X_to_z_(ispin, group[k], 1); - std::copy( - one.template data(), one.template data() + nloc_g, - Xz.template data() + static_cast(k) * nloc_g); - } - return Xz; -} - -template -ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::ofstream &ofs) -{ - this->target_.resolve_group(*this->inp_, this->pelec->ekb.c, this->nstates, this->ofs_running_); - const std::vector &group = this->target_.group(); - if (group.empty()) - { - return this->cal_force(this->target_.ispin(), this->target_.state())[0]; - } - const bool jt_mode = (LR_Util::tolower(this->inp_->lr_degen_mode) == "jt"); - // `average` needs only the DIAGONAL of the gradient matrix: the average is basis-independent by - // construction, so the off-diagonal part (and the extra d(d-1)/2 solves it costs) is not - // involved. The Jahn-Teller direction is orthogonal to the average and does need them. - const int d = static_cast(group.size()); - const int ekb_off = this->target_.ekb_off(this->nstates); - const ct::Tensor Xz = this->pad_group_to_z_(this->target_.ispin(), group); - std::vector omega(d); - for (int k = 0; k < d; ++k) - { - omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; - } - const std::vector forces = - this->openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) - : this->cal_force_Xz(this->target_.ispin(), Xz, omega, group.front()); - ofs << " Followed state " << this->target_.state() << " is degenerate with"; - for (const int ist : group) - { - if (ist != this->target_.state()) - { - ofs << " " << ist; - } - } - ofs << " (Omega_bar = " << this->target_.omega(this->pelec->ekb.c, this->nstates) << " Ry)." << std::endl; - if (!jt_mode) - { - ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" - " geometry on the current average surface; split groups are not recombined." - << std::endl; - return average_forces(forces); - } - return this->cal_jt_force_(forces, ofs); -} - -template -ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( - const std::vector &diag, std::ofstream &ofs) -{ - // Regime (c): descend the Jahn-Teller branch. This needs the whole gradient matrix, so the - // off-diagonal elements are assembled here -- d(d-1)/2 further Z-vector solves on top of the - // d diagonal ones already in `diag`. - const std::vector &group = this->target_.group(); - const int d = static_cast(group.size()); - const std::vector> g = - this->cal_grad_matrix_degenerate(this->target_.ispin(), group, diag, ofs); - const int nat = diag[0].nr; - const int ncoord = nat * 3; - // flatten to the layout `find_jt_direction` takes: one d x d block per nuclear coordinate. - // FORCES go in, not gradients, so the direction that comes back points downhill. - std::vector gflat(static_cast(ncoord) * d * d, 0.0); - for (int iat = 0; iat < nat; ++iat) - { - for (int ixyz = 0; ixyz < 3; ++ixyz) - { - const int a = iat * 3 + ixyz; - for (int k = 0; k < d; ++k) - { - for (int l = 0; l < d; ++l) - { - gflat[static_cast(a) * d * d + k * d + l] = g[k][l](iat, ixyz); - } - } - } - } - const LR::JTDirection jt = LR::find_jt_direction(gflat, ncoord, d); - const int channel = this->openshell ? 0 : this->target_.ispin(); - const T *const amplitudes = this->X[channel].template data(); - this->target_.save_mixed(amplitudes, this->nloc_per_state, jt.mixing); - std::vector jt_part; - const std::vector sym = LR::split_symmetric_part(gflat, ncoord, d, jt.mixing, jt_part); - - const double fac = ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A; - ofs << " lr_degen_mode=jt: descending the steepest branch of the multiplet." << std::endl - << " |F| of that branch = " << jt.slope * fac << " eV/Angstrom" << std::endl - << " mixing v ="; - for (int k = 0; k < d; ++k) - { - ofs << " " << jt.mixing[k]; - } - ofs << std::endl - << " starts agreeing = " << jt.restarts_agreeing << " of " << (d + (1 << (d - 1))) << " (iterations " - << jt.iterations << ")" << std::endl; - // The two halves matter separately: the symmetric part is common to the whole multiplet and - // only relaxes the geometry, while the remainder is what actually breaks the degeneracy. At a - // stationary point of the average surface the first is zero and the whole force is Jahn-Teller. - double nsym = 0.0; - double njt = 0.0; - for (int a = 0; a < ncoord; ++a) - { - nsym += sym[a] * sym[a]; - njt += jt_part[a] * jt_part[a]; - } - ofs << " |symmetric part| = " << std::sqrt(nsym) * fac - << " eV/Angstrom (common to the" - " multiplet; relaxes the geometry without splitting it)" - << std::endl - << " |Jahn-Teller part| = " << std::sqrt(njt) * fac - << " eV/Angstrom (the symmetry-" - "breaking remainder)" - << std::endl; - if (std::sqrt(njt) < 1e-8) - { - ofs << " WARNING: the symmetry-breaking part vanishes -- every branch of this multiplet has" - " the same gradient, so there is no Jahn-Teller direction to descend here. This is the" - " expected outcome for a linear molecule, where the effect is second order" - " (Renner-Teller) and no first-order term exists." - << std::endl; - } - ofs << " NOTE: this is the first-order DIRECTION only. The distortion amplitude also needs the" - " harmonic term, and the step norm is Cartesian rather than mass-weighted." - << std::endl; - - // The force handed back is that of the descending branch, q(v) with v the optimal mixing -- - // i.e. the branch's own gradient, which is what a relaxation must follow. Once a step has - // split the multiplet, `resolve_group` finds no group and the ordinary single-state path - // takes over, so this mode is self-limiting by construction. - ModuleBase::matrix f(nat, 3); - for (int iat = 0; iat < nat; ++iat) - { - for (int ixyz = 0; ixyz < 3; ++ixyz) - { - const int a = iat * 3 + ixyz; - f(iat, ixyz) = sym[a] + jt_part[a]; - } - } - return f; -} - -template -ModuleBase::matrix ModuleESolver::ESolver_LR::MultipletLVC::average_force() const -{ - assert(!this->g.empty()); - std::vector diag; - for (int k = 0; k < this->dim(); ++k) - { - diag.push_back(this->g[k][k]); - } - return average_forces(diag); -} - -template class ModuleESolver::ESolver_LR; -template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_lcao/module_lr/grad_degen.h b/source/source_lcao/module_lr/grad_degen.h index e41a009f5e..7b68e0492d 100644 --- a/source/source_lcao/module_lr/grad_degen.h +++ b/source/source_lcao/module_lr/grad_degen.h @@ -13,7 +13,7 @@ /// eigenvectors depend on $u$. The full first-order object is $3N$ matrices of size $d\times d$, /// and only $\operatorname{Tr}M$ is basis-invariant. /// -/// The per-state analytic gradient implemented in `esolver_lr_grad.cpp` is, restricted to one +/// The per-state analytic gradient implemented in `esolver_lr_lcao_tddft.cpp` is, restricted to one /// multiplet, a *quadratic form* in the excitation vector: every ingredient ($D^X$, $T$, $R$, $Z$, /// $D^Z$, $W^X$, $\Lambda$) is built from $X\otimes X$, the CPSCF operator $L$ depends only on the /// ground state, and $\Omega$ is a constant inside the multiplet. Write it $\mathcal F[X]$. Because @@ -41,7 +41,7 @@ /// This header holds only the basis-independent bookkeeping, so that it is unit-testable without a /// ground state: grouping states into multiplets, enumerating the pairs, forming the normalized /// combination, and assembling $G$. Everything needing the parallel layout or the Z-vector solver -/// stays in `esolver_lr_grad.cpp`. +/// stays in `esolver_lr_lcao_tddft.cpp`. namespace LR { From 5cc056ecd286bd71eb1feeaca65933b2d0265938 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 15:04:18 +0800 Subject: [PATCH 06/26] refactor(lr): fold the LR esolver into a single esolver_lr.{h,cpp} Merge esolver_lr_init.cpp into the main implementation and rename the pair so the solver lives in one header and one translation unit. Update the BSE subclass and the factory includes, and keep the EXX/JSON conditional includes intact. ESolver_LR and its BSE-visible members are unchanged. --- source/Makefile.Objects | 3 +- source/source_esolver/CMakeLists.txt | 3 +- source/source_esolver/esolver_factory.cpp | 2 +- ...olver_lr_lcao_tddft.cpp => esolver_lr.cpp} | 475 ++++++++++++++++- .../{esolver_lr_lcao_tddft.h => esolver_lr.h} | 6 +- source/source_esolver/esolver_lr_init.cpp | 482 ------------------ source/source_esolver/esolver_lr_lcao_bse.h | 2 +- .../unittests/test_read_input_item.cpp | 2 +- .../unittests/test_read_input_parallel.cpp | 2 +- source/source_lcao/module_lr/grad_degen.h | 4 +- 10 files changed, 485 insertions(+), 496 deletions(-) rename source/source_esolver/{esolver_lr_lcao_tddft.cpp => esolver_lr.cpp} (71%) rename source/source_esolver/{esolver_lr_lcao_tddft.h => esolver_lr.h} (99%) delete mode 100644 source/source_esolver/esolver_lr_init.cpp diff --git a/source/Makefile.Objects b/source/Makefile.Objects index f7b8f2c13f..78f136fd12 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1199,8 +1199,7 @@ OBJS_TENSOR=tensor.o\ lr_dm.o\ lr_relax.o\ lr_gs_pot.o\ - esolver_lr_init.o\ - esolver_lr_lcao_tddft.o\ + esolver_lr.o\ OBJS_LR_GRAD=lr_force.o\ xc_kxc.o\ diff --git a/source/source_esolver/CMakeLists.txt b/source/source_esolver/CMakeLists.txt index 5ca8fcf6d2..d2e2a59439 100644 --- a/source/source_esolver/CMakeLists.txt +++ b/source/source_esolver/CMakeLists.txt @@ -21,8 +21,7 @@ if(ENABLE_LCAO) objects esolver_ks_lcao.cpp esolver_ks_lcao_tddft.cpp - esolver_lr_init.cpp - esolver_lr_lcao_tddft.cpp + esolver_lr.cpp esolver_gets.cpp lcao_others.cpp esolver_dm2rho.cpp diff --git a/source/source_esolver/esolver_factory.cpp b/source/source_esolver/esolver_factory.cpp index 6d762c2fba..b11063c0e8 100644 --- a/source/source_esolver/esolver_factory.cpp +++ b/source/source_esolver/esolver_factory.cpp @@ -16,7 +16,7 @@ #include "esolver_ks_lcao.h" #include "esolver_ks_lcao_tddft.h" #include "esolver_ks_lcaopw.h" -#include "esolver_lr_lcao_tddft.h" +#include "esolver_lr.h" #ifdef __EXX #include "esolver_lr_lcao_bse.h" #endif diff --git a/source/source_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr.cpp similarity index 71% rename from source/source_esolver/esolver_lr_lcao_tddft.cpp rename to source/source_esolver/esolver_lr.cpp index 969578d051..492083a9b0 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -1,4 +1,4 @@ -#include "esolver_lr_lcao_tddft.h" +#include "esolver_lr.h" #include "source_hamilt/module_xc/xc_functional.h" #include "source_lcao/module_lr/hamilt_ulr.h" #include "source_lcao/module_lr/hsolver_lrtd.h" @@ -36,6 +36,19 @@ #include "source_lcao/module_lr/lr_force.h" #include "source_base/timer.h" #include +#include "source_lcao/module_lr/init_helpers.h" +#include "source_base/module_external/scalapack_connector.h" +#include "source_basis/module_pw/pw_basis_big.h" +#include "source_cell/module_neighbor/sltk_atom_arrange.h" +#include "source_hamilt/module_gint/gint.h" +#include "source_io/module_output/print_info.h" +#ifdef __JSON +#include "source_io/module_json/output_info.h" +#endif +#ifdef __EXX +#include "source_hamilt/module_xc/exx_info.h" +#include "source_lcao/module_ri/exx_lri_interface.h" +#endif using namespace LR; @@ -1166,5 +1179,465 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::MultipletLVC::average_force return average_forces(diag); } +// Initialize LR from an embedded KS solver or standalone ground-state files. + +#ifdef __EXX +namespace +{ + +/// One `Exx_LRI` carries ONE Coulomb operator, and it may be needed for two different +/// reasons: the LR kernel (when `xc_kernel` is a hybrid) and the ground-state force (when +/// `dft_functional` is a hybrid). That operator is NOT chosen here -- `Exx_LRI` reads +/// `info_ri.coulomb_param`, which `input_conv` builds from `dft_functional` alone. So when +/// the two disagree, the kernel silently gets the ground state's screening, not its own. +/// +/// This used to be decided by a local `exx_ccp_type()` returning Erfc for "hse" and bare +/// Hf otherwise, written onto `info_global.ccp_type`. With general range-separated hybrids +/// that two-way split is not even expressible ($\alpha/r+\beta\,\mathrm{erfc}(\mu r)/r$ +/// is both at once), and the write was in any case dead for the RI path: only `Exx_LRI` +/// runs here, and it never looks at `ccp_type`. +void warn_if_kernel_differs_from_gs( + const std::string &xc_kernel, const std::string &dft_functional, std::ofstream &ofs_running) +{ + const bool k = LR::exx_kernel_list().count(xc_kernel) > 0; + const bool g = LR::exx_kernel_list().count(dft_functional) > 0; + if (k && xc_kernel != dft_functional) + { + ofs_running << " WARNING: xc_kernel (" << xc_kernel << ") and dft_functional (" << dft_functional + << ") are not the same functional. The Coulomb operator of" + " Exx_LRI follows dft_functional" + << (g ? "" + : ", which is not a hybrid at all" + " (no coulomb_param, so the LR exchange kernel vanishes)") + << "; set both to the" + " same hybrid to get the kernel you asked for." + << std::endl; + } +} +} // namespace +#endif + +#ifdef __EXX +template <> +void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr> &exx_ks) +{ + ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); + this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); +} +template <> +void ModuleESolver::ESolver_LR>::share_exx_lri( + std::shared_ptr>> &exx_ks) +{ + ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); + this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); +} +template <> +void ModuleESolver::ESolver_LR>::share_exx_lri(std::shared_ptr> &exx_ks) +{ + this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); +} +template <> +void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr>> &exx_ks) +{ + this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); +} +#endif + + +template +void ModuleESolver::ESolver_LR::before_all_runners(BaseCell &basecell, const Input_para &inp) +{ + basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); + UnitCell &ucell = static_cast(basecell); + this->ucell_ = &ucell; + this->inp_ = &inp; + if (inp.esolver_type == "ks-lr") + { +#ifdef __JSON + // The embedded KS run happens before Relax_Driver starts its first step. + Json::init_output_array_obj(); +#endif + // the ground-state solver is a member, not a temporary: `runner` re-runs its SCF on every + // ionic step, and the objects aliased from it have to stay alive as long as it does. + // Its SCF is deliberately NOT run here -- `before_all_runners` is called once, outside the + // relaxation loop, so the ground state has to be recomputed from `runner(istep)` instead. + this->ks_ = LR_Util::make_unique>(); + this->ks_->before_all_runners(basecell, inp); + LR_Util::check_force_pp(ucell, inp.cal_force, inp.calculation); + } + else + { + this->initialize_from_unitcell_(ucell, inp); + } +} + +template +void ModuleESolver::ESolver_LR::bind_ground_state_aliases_() +{ + if (this->ks_) + { + // `ESolver_FP::before_all_runners` was never called on this object, so its own `pw_rhod`, + // `Pgrid`, `sf` and `locpp` are empty -- the excited-state force needs all four. Point at + // the ground-state solver's, which `before_scf` refreshes for the current geometry every + // ionic step. `pw_rho_flag` stays false so the destructor does not free what it borrowed. + this->pw_rho = this->ks_->pw_rho; + this->pw_rhod = this->ks_->pw_rhod; + this->pw_big = this->ks_->pw_big; + this->pw_rho_flag = false; + this->pgrid_ptr_ = &this->ks_->Pgrid; + this->sf_ptr_ = &this->ks_->sf; + this->locpp_ptr_ = &this->ks_->locpp; + this->gd_ptr_ = &this->ks_->gd; + // the two-center tables depend on the orbitals only, so the ground-state solver's single + // build serves every geometry. This used to be moved over only for `abs_gauge velocity`, + // leaving `LR_Force` and `cal_hs_grad` with an empty bundle in the length gauge. + this->tcb_ptr_ = &this->ks_->two_center_bundle_; + } + else + { + this->pgrid_ptr_ = &this->Pgrid; + this->sf_ptr_ = &this->sf; + this->locpp_ptr_ = &this->locpp; + this->gd_ptr_ = &this->gd_own_; + this->tcb_ptr_ = &this->two_center_bundle_own_; + } +} + +template +void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, const Input_para &inp) +{ + ModuleBase::TITLE("ESolver_LR", "ESolver_LR(KS)"); + ModuleESolver::ESolver_KS_LCAO &ks_sol = *this->ks_; + this->bind_ground_state_aliases_(); + + if (this->inp_->lr_solver == "spectrum") + { + throw std::invalid_argument("when lr_solver==spectrum, esolver_type must be `lr` to skip KS calculation."); + } + + // xc kernel + this->xc_kernel = LR_Util::tolower(inp.xc_kernel); + // kv + this->kv = ks_sol.kv; // copy: cheap, and the KS solver keeps using its own + + LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); + + this->set_dim(); + + // KS and LR must use the same AO distribution, including its BLACS grid. + const int ks_block_size = ks_sol.pv.para_2d().nb(); + LR_Util::setup_2d_division( + this->paraMat_.para_2d(), ks_block_size, this->nbasis, this->nbasis +#ifdef __MPI + , + ks_sol.pv.para_2d().ictxt() +#endif + ); + this->set_parallel_orbitals_band(this->paraMat_, this->nbands); + if (this->inp_->cal_force) + { + LR_Util::setup_2d_division( + this->paraMat_all_.para_2d(), ks_block_size, this->nbasis, this->nbasis +#ifdef __MPI + , + ks_sol.pv.para_2d().ictxt() +#endif + ); + this->set_parallel_orbitals_band(this->paraMat_all_, this->inp_->nbands); + } + + this->paraMat_.atom_begin_row = ks_sol.pv.atom_begin_row; + this->paraMat_.atom_begin_col = ks_sol.pv.atom_begin_col; + this->paraMat_.iat2iwt_ = ucell.get_iat2iwt(); + + LR_Util::setup_2d_division( + this->paraC_, ks_block_size, this->nbasis, this->nbands +#ifdef __MPI + , + this->paraMat_.para_2d().ictxt() +#endif + ); + + // allocate psi_ks and eig_ks in the [nocc, nvirt] window +#ifdef __MPI + this->psi_ks.reset( + new psi::Psi(this->kv.get_nks(), this->paraC_.ncloc(), this->paraC_.nrloc(), this->kv.ngk, true)); +#else + this->psi_ks.reset(new psi::Psi(this->kv.get_nks(), this->nbands, this->nbasis, this->kv.ngk, true)); +#endif + this->eig_ks.create(this->kv.get_nks(), this->nbands); + this->pelec = new elecstate::ElecStateLCAO(); + orb_cutoff_ = ks_sol.orb_.cutoffs(); + +#ifdef __EXX + // Two independent reasons to need an Exx_LRI: the LR exchange kernel, and the ground-state + // EXX terms of the gradient (the H_gs[T+Z] and W multipliers, gated on gs_is_hybrid). + // `initialize_from_unitcell_` has always covered both; this path used to test only the first, + // so a local kernel on top of a hybrid ground state had no exx_lri at all when asked for forces. + if (exx_kernel_list().count(xc_kernel) || (this->inp_->cal_force && gs_is_hybrid(this->inp_->dft_functional))) + { + std::string dft_functional = LR_Util::tolower(this->inp_->dft_functional); + // Either object would be built from the same `info_ri.coulomb_param`, which `input_conv` + // derives from dft_functional alone -- so whenever the ground-state solver has one of the + // right type its geometry tensors are already up to date. Share those tensors in a + // separate LR electronic workspace, skipping a `cal_exx_ions` per ionic step. + const bool share = (ks_sol.exx_nao.exd && std::is_same::value) || + (ks_sol.exx_nao.exc && std::is_same>::value); + warn_if_kernel_differs_from_gs(xc_kernel, dft_functional, this->ofs_running_); + if (share) + { + this->exx_owned_ = false; + } // `refresh_from_ks_` refreshes the geometry snapshot + else // construct C, V from scratch + { + // `input_conv` already filled `info_ri.coulomb_param` from INPUT. + exx_info.sync_from_global(); + // populate ABFs/JLE file lists from UnitCell; keep in sync with Exx_NAO::init + exx_info.info_ri.files_abfs = ucell.abfs_orbital_files; + exx_info.info_opt_abfs.files_abfs = ucell.abfs_orbital_files; + exx_info.info_opt_abfs.files_jles = ucell.jle_orbital_files; + this->exx_lri = std::make_shared>(exx_info.info_ri); + this->exx_lri->init(MPI_COMM_WORLD, ucell, this->kv, ks_sol.orb_); + this->exx_owned_ = true; // the position-dependent `cal_exx_ions` is left to `refresh_from_ks_` + } + } +#endif + + refresh_from_ks_(ucell); + this->ks_initialized_ = true; +} + +template +void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) +{ + ModuleBase::TITLE("ESolver_LR", "refresh_from_ks_"); + ModuleESolver::ESolver_KS_LCAO &ks_sol = *this->ks_; + // The ground-state solver owns `psi` and reuses it across ionic steps, so it cannot be stolen. + // `eig_ks_all` / `wg_ks_all` are nspin x nbands matrices -- a few kB, copied rather than aliased + // so that they survive the KS solver overwriting `pelec` on the next step. + this->psi_ks_all_ = ks_sol.psi; + this->eig_ks_all = ks_sol.pelec->ekb; + this->wg_ks_all = ks_sol.pelec->wg; + const int max_occupied_bands = *std::max_element(nocc.begin(), nocc.end()); + const int start_band = this->nocc_max - max_occupied_bands; + + for (int ik = 0; ik < this->kv.get_nks(); ++ik) + { + // copy the KS orbitals in the [nocc, nvirt] window +#ifdef __MPI + this->psi_ks_all_->fix_k(ik); + this->psi_ks->fix_k(ik); + const int first_band = start_band + 1; + Cpxgemr2d( + this->nbasis, this->nbands, this->psi_ks_all_->get_pointer(), 1, first_band, ks_sol.pv.desc_wfc, + this->psi_ks->get_pointer(), 1, 1, const_cast(this->paraC_.desc()), this->paraC_.ictxt()); +#else + // serial: each band is `nbasis` contiguous coefficients, so the window is a plain + // band-by-band copy (this loop used to compute the two pointers and copy nothing, + // leaving `psi_ks` uninitialized in every non-MPI build) + for (int ib = 0; ib < this->nbands; ++ib) + { + const auto *start = &(*this->psi_ks_all_)(ik, start_band + ib, 0); + auto *to = &(*this->psi_ks)(ik, ib, 0); + std::copy(start, start + this->nbasis, to); + } +#endif + // copy the KS bands in the [nocc, nvirt] window + for (int ib = 0; ib < this->nbands; ++ib) + { + this->eig_ks(ik, ib) = this->eig_ks_all(ik, start_band + ib); + } + } + + if (nspin == 2) + { + const int nupdown_now = + LR_Util::spin_population_difference(ks_sol.pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); + if (!this->ks_initialized_) + { + this->nupdown = nupdown_now; + reset_dim_spin(); // shifts nocc/nvirt between the spin channels: must run exactly once + } + else if (nupdown_now != this->nupdown) + { + ModuleBase::WARNING_QUIT( + "ESolver_LR::refresh_from_ks_", + "the ground-state spin population changed between ionic steps, but nocc/nvirt and" + " the distributions built from them were fixed at the first step."); + } + } + // `gint_info_` stays owned by the KS solver: its `before_scf` rebuilds and re-publishes it + // init potential and calculate kernels using ground state charge + init_pot(*ks_sol.pelec->charge); + +#ifdef __EXX + if (exx_kernel_list().count(xc_kernel) || (this->inp_->cal_force && gs_is_hybrid(this->inp_->dft_functional))) + { + if (this->exx_owned_) + { // Cs/Vs follow the atoms, so they are rebuilt for every geometry + this->exx_lri->cal_exx_ions(ucell, this->inp_->out_ri_cv); + } + else if (ks_sol.exx_nao.exd) + { + this->share_exx_lri(ks_sol.exx_nao.exd->exx_ptr); + } + else if (ks_sol.exx_nao.exc) + { + this->share_exx_lri(ks_sol.exx_nao.exc->exx_ptr); + } + } +#endif + // the grid-integration tables hang off a static pointer that the ground-state solver + // re-publishes in its `before_scf`; make sure it names the object we integrate on + ModuleGint::Gint::set_gint_info(this->ks_->gint_info_.get()); + + // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final +#ifdef __MPI + this->fill_z_window_(ks_sol.pv.desc_wfc); +#else + this->fill_z_window_(nullptr); +#endif +} + +template +void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell, const Input_para &inp) +{ + ModuleBase::TITLE("ESolver_LR", "ESolver_LR(from scratch)"); + this->bind_ground_state_aliases_(); + // xc kernel + this->xc_kernel = LR_Util::tolower(inp.xc_kernel); + + // necessary steps in ESolver_FP + ESolver_FP::before_all_runners(ucell, inp); + LR_Util::check_force_pp(ucell, inp.cal_force, inp.calculation); + this->pelec = new elecstate::ElecStateLCAO(); + + // necessary steps in ESolver_KS::before_all_runners : symmetry and k-points + if (ModuleSymmetry::Symmetry::symm_flag == 1) + { + const int cal_symm_repr[2] = {this->inp_->cal_symm_repr[0], this->inp_->cal_symm_repr[1]}; + ucell.symm.analy_sys( + ucell.lat, ucell.atoms, ucell.nat, ucell.ntype, ucell.iat2it, ucell.iat2ia, ucell.itia2iat, + this->ofs_running_, this->inp_->symmetry_prec, this->inp_->nspin, this->inp_->calculation, cal_symm_repr); + ModuleBase::GlobalFunc::DONE(this->ofs_running_, "SYMMETRY"); + } + const bool use_ibz = false; + const bool gamma_only_local = PARAM.globalv.gamma_only_local; + const double kspacing[3] = {this->inp_->kspacing[0], this->inp_->kspacing[1], this->inp_->kspacing[2]}; + const double koffset[3] = {this->inp_->koffset[0], this->inp_->koffset[1], this->inp_->koffset[2]}; + this->kv.set( + ucell, ucell.symm, this->inp_->kpoint_file, this->inp_->nspin, ucell.G, ucell.latvec, this->ofs_running_, + this->ofs_warning_, use_ibz, this->out_dir, gamma_only_local, kspacing, this->inp_->kmesh_type, koffset); + ModuleBase::GlobalFunc::DONE(this->ofs_running_, "INIT K-POINTS"); + ModuleIO::print_parameters(ucell, this->kv, inp); + + LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); + + /// read orbitals and build the interpolation table + two_center_bundle_own_.build_orb(ucell.ntype, ucell.orbital_fn.data(), inp.orbital_dir); + + LCAO_Orbitals orb; + two_center_bundle_own_.to_LCAO_Orbitals( + orb, inp.lcao_ecut, inp.lcao_dk, inp.lcao_dr, inp.lcao_rmax, inp.out_element_info, inp.cal_force); + orb_cutoff_ = orb.cutoffs(); + // Standalone LR neighbor search needs projector metadata for every optical gauge. + LR::setup_nonlocal_info(orb, ucell, *this->inp_, this->my_rank_, this->ofs_running_); + const bool need_force_tables = this->inp_->cal_force || this->inp_->calculation == "relax"; + const bool need_velocity_tables = LR_Util::tolower(this->inp_->abs_gauge) == "velocity"; + if (need_force_tables || need_velocity_tables) + { + LR::setup_2center_table(this->two_center_bundle_own_, ucell, *this->inp_); + } + + this->set_dim(); + // setup 2d-block distribution for AO-matrix and KS wfc + LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); + this->set_parallel_orbitals_band(this->paraMat_, this->nbands); + if (this->inp_->cal_force) + { + LR_Util::setup_2d_division(this->paraMat_all_.para_2d(), 1, this->nbasis, this->nbasis); + this->set_parallel_orbitals_band(this->paraMat_all_, this->inp_->nbands); + } + + // read the ground state info + // now ModuleIO::read_wfc_nao needs `Parallel_Orbitals` and can only read all the bands + // it need improvement to read only the bands needed + this->psi_ks.reset(new psi::Psi( + this->kv.get_nks(), this->paraMat_.ncol_bands, this->paraMat_.para_2d().nrloc(), this->kv.ngk, true)); + this->read_ks_wfc(); + + if (nspin == 2) + { + // Complete file populations were read before selecting the occupied window. + reset_dim_spin(); + } + // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final +#ifdef __MPI + this->fill_z_window_(paraMat_all_.desc_wfc); +#else + this->fill_z_window_(nullptr); +#endif + + LR_Util::setup_2d_division( + this->paraC_, 1, this->nbasis, this->nbands +#ifdef __MPI + , + paraMat_.para_2d().ictxt() +#endif + ); + + // clear ks info, new elecstate for excition + delete this->pelec; // the ElecStateLCAO allocated above, only needed while reading the KS data + this->pelec = new elecstate::ElecState(); + + // read the ground state charge density and calculate xc kernel + pgrid().init( + this->pw_rho->nx, this->pw_rho->ny, this->pw_rho->nz, this->pw_rho->nplane, this->pw_rho->nrxx, pw_big->nbz, + pw_big->bz, GlobalV::NPROC); + Charge chg_gs; + if (this->inp_->ri_hartree_benchmark == "none") + { + this->read_ks_chg(chg_gs); + } + this->init_pot(chg_gs); + + // search adjacent atoms and init Gint + double search_radius = -1.0; + search_radius = atom_arrange::set_sr_NL( + this->ofs_running_, this->inp_->out_level, orb.get_rcutmax_Phi(), ucell.infoNL->get_rcutmax_Beta(), + PARAM.globalv.gamma_only_local); + atom_arrange::search( + PARAM.globalv.search_pbc, this->ofs_running_, this->gd(), *this->ucell_, search_radius, + this->inp_->test_atom_input); + gint_info_.reset(new ModuleGint::GintInfo( + this->pw_big->nbx, this->pw_big->nby, this->pw_big->nbz, this->pw_rho->nx, this->pw_rho->ny, this->pw_rho->nz, + 0, 0, this->pw_big->nbzp_start, this->pw_big->nbx, this->pw_big->nby, this->pw_big->nbzp, orb.Phi, ucell, + this->gd(), this->inp_->nspin, PARAM.globalv.gamma_only_local, PARAM.globalv.domag, this->inp_->device == "gpu", + this->inp_->nstream)); + ModuleGint::Gint::set_gint_info(gint_info_.get()); + // if EXX from scratch, init 2-center integral and calculate Cs, Vs + // when: + // 1. EXX xc_kernel + // 2. cal_force with ground state with EXX functional +#ifdef __EXX + if (((exx_kernel_list().count(xc_kernel)) && this->inp_->lr_solver != "spectrum") || + (this->inp_->cal_force && gs_is_hybrid(this->inp_->dft_functional))) + { + warn_if_kernel_differs_from_gs(xc_kernel, LR_Util::tolower(this->inp_->dft_functional), this->ofs_running_); + // `input_conv` already filled `info_ri.coulomb_param` from INPUT. + exx_info.sync_from_global(); + // populate ABFs/JLE file lists from UnitCell; keep in sync with Exx_NAO::init + exx_info.info_ri.files_abfs = ucell.abfs_orbital_files; + exx_info.info_opt_abfs.files_abfs = ucell.abfs_orbital_files; + exx_info.info_opt_abfs.files_jles = ucell.jle_orbital_files; + this->exx_lri = std::make_shared>(exx_info.info_ri); + this->exx_lri->init(MPI_COMM_WORLD, ucell, this->kv, orb); + this->exx_lri->cal_exx_ions(ucell, this->inp_->out_ri_cv); + } + // else +#endif + // ModuleBase::Ylm::set_coefficients() is deprecated +} + template class ModuleESolver::ESolver_LR; template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_esolver/esolver_lr_lcao_tddft.h b/source/source_esolver/esolver_lr.h similarity index 99% rename from source/source_esolver/esolver_lr_lcao_tddft.h rename to source/source_esolver/esolver_lr.h index 7b45de5df4..4284171d26 100644 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ b/source/source_esolver/esolver_lr.h @@ -1,5 +1,5 @@ -#ifndef ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_TDDFT_H -#define ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_TDDFT_H +#ifndef ABACUS_SOURCE_ESOLVER_ESOLVER_LR_H +#define ABACUS_SOURCE_ESOLVER_ESOLVER_LR_H #include "source_cell/unitcell.h" #include "source_esolver/esolver_fp.h" @@ -347,4 +347,4 @@ class ESolver_LR : public ModuleESolver::ESolver_FP }; } // namespace ModuleESolver -#endif // ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_TDDFT_H +#endif // ABACUS_SOURCE_ESOLVER_ESOLVER_LR_H diff --git a/source/source_esolver/esolver_lr_init.cpp b/source/source_esolver/esolver_lr_init.cpp deleted file mode 100644 index 7626152aef..0000000000 --- a/source/source_esolver/esolver_lr_init.cpp +++ /dev/null @@ -1,482 +0,0 @@ -#include "source_lcao/module_lr/init_helpers.h" -// Initialize LR from an embedded KS solver or standalone ground-state files. -#include "esolver_lr_lcao_tddft.h" -#include "source_base/module_external/scalapack_connector.h" -#include "source_basis/module_pw/pw_basis_big.h" -#include "source_cell/module_neighbor/sltk_atom_arrange.h" -#include "source_hamilt/module_gint/gint.h" -#include "source_hamilt/module_xc/xc_functional.h" -#include "source_io/module_output/print_info.h" -#include "source_io/module_parameter/parameter.h" -#include "source_lcao/module_lr/utils/lr_util.h" -#include "source_lcao/module_lr/utils/lr_util_print.h" -#ifdef __JSON -#include "source_io/module_json/output_info.h" -#endif -#ifdef __EXX -#include "source_hamilt/module_xc/exx_info.h" -#include "source_lcao/module_ri/exx_lri_interface.h" -#endif -#include - -#ifdef __EXX -namespace -{ - -/// One `Exx_LRI` carries ONE Coulomb operator, and it may be needed for two different -/// reasons: the LR kernel (when `xc_kernel` is a hybrid) and the ground-state force (when -/// `dft_functional` is a hybrid). That operator is NOT chosen here -- `Exx_LRI` reads -/// `info_ri.coulomb_param`, which `input_conv` builds from `dft_functional` alone. So when -/// the two disagree, the kernel silently gets the ground state's screening, not its own. -/// -/// This used to be decided by a local `exx_ccp_type()` returning Erfc for "hse" and bare -/// Hf otherwise, written onto `info_global.ccp_type`. With general range-separated hybrids -/// that two-way split is not even expressible ($\alpha/r+\beta\,\mathrm{erfc}(\mu r)/r$ -/// is both at once), and the write was in any case dead for the RI path: only `Exx_LRI` -/// runs here, and it never looks at `ccp_type`. -void warn_if_kernel_differs_from_gs( - const std::string &xc_kernel, const std::string &dft_functional, std::ofstream &ofs_running) -{ - const bool k = LR::exx_kernel_list().count(xc_kernel) > 0; - const bool g = LR::exx_kernel_list().count(dft_functional) > 0; - if (k && xc_kernel != dft_functional) - { - ofs_running << " WARNING: xc_kernel (" << xc_kernel << ") and dft_functional (" << dft_functional - << ") are not the same functional. The Coulomb operator of" - " Exx_LRI follows dft_functional" - << (g ? "" - : ", which is not a hybrid at all" - " (no coulomb_param, so the LR exchange kernel vanishes)") - << "; set both to the" - " same hybrid to get the kernel you asked for." - << std::endl; - } -} -} // namespace -#endif - -#ifdef __EXX -template <> -void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr> &exx_ks) -{ - ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); - this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); -} -template <> -void ModuleESolver::ESolver_LR>::share_exx_lri( - std::shared_ptr>> &exx_ks) -{ - ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); - this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); -} -template <> -void ModuleESolver::ESolver_LR>::share_exx_lri(std::shared_ptr> &exx_ks) -{ - this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); -} -template <> -void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr>> &exx_ks) -{ - this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); -} -#endif - -using namespace LR; - -template -void ModuleESolver::ESolver_LR::before_all_runners(BaseCell &basecell, const Input_para &inp) -{ - basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); - UnitCell &ucell = static_cast(basecell); - this->ucell_ = &ucell; - this->inp_ = &inp; - if (inp.esolver_type == "ks-lr") - { -#ifdef __JSON - // The embedded KS run happens before Relax_Driver starts its first step. - Json::init_output_array_obj(); -#endif - // the ground-state solver is a member, not a temporary: `runner` re-runs its SCF on every - // ionic step, and the objects aliased from it have to stay alive as long as it does. - // Its SCF is deliberately NOT run here -- `before_all_runners` is called once, outside the - // relaxation loop, so the ground state has to be recomputed from `runner(istep)` instead. - this->ks_ = LR_Util::make_unique>(); - this->ks_->before_all_runners(basecell, inp); - LR_Util::check_force_pp(ucell, inp.cal_force, inp.calculation); - } - else - { - this->initialize_from_unitcell_(ucell, inp); - } -} - -template -void ModuleESolver::ESolver_LR::bind_ground_state_aliases_() -{ - if (this->ks_) - { - // `ESolver_FP::before_all_runners` was never called on this object, so its own `pw_rhod`, - // `Pgrid`, `sf` and `locpp` are empty -- the excited-state force needs all four. Point at - // the ground-state solver's, which `before_scf` refreshes for the current geometry every - // ionic step. `pw_rho_flag` stays false so the destructor does not free what it borrowed. - this->pw_rho = this->ks_->pw_rho; - this->pw_rhod = this->ks_->pw_rhod; - this->pw_big = this->ks_->pw_big; - this->pw_rho_flag = false; - this->pgrid_ptr_ = &this->ks_->Pgrid; - this->sf_ptr_ = &this->ks_->sf; - this->locpp_ptr_ = &this->ks_->locpp; - this->gd_ptr_ = &this->ks_->gd; - // the two-center tables depend on the orbitals only, so the ground-state solver's single - // build serves every geometry. This used to be moved over only for `abs_gauge velocity`, - // leaving `LR_Force` and `cal_hs_grad` with an empty bundle in the length gauge. - this->tcb_ptr_ = &this->ks_->two_center_bundle_; - } - else - { - this->pgrid_ptr_ = &this->Pgrid; - this->sf_ptr_ = &this->sf; - this->locpp_ptr_ = &this->locpp; - this->gd_ptr_ = &this->gd_own_; - this->tcb_ptr_ = &this->two_center_bundle_own_; - } -} - -template -void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, const Input_para &inp) -{ - ModuleBase::TITLE("ESolver_LR", "ESolver_LR(KS)"); - ModuleESolver::ESolver_KS_LCAO &ks_sol = *this->ks_; - this->bind_ground_state_aliases_(); - - if (this->inp_->lr_solver == "spectrum") - { - throw std::invalid_argument("when lr_solver==spectrum, esolver_type must be `lr` to skip KS calculation."); - } - - // xc kernel - this->xc_kernel = LR_Util::tolower(inp.xc_kernel); - // kv - this->kv = ks_sol.kv; // copy: cheap, and the KS solver keeps using its own - - LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); - - this->set_dim(); - - // KS and LR must use the same AO distribution, including its BLACS grid. - const int ks_block_size = ks_sol.pv.para_2d().nb(); - LR_Util::setup_2d_division( - this->paraMat_.para_2d(), ks_block_size, this->nbasis, this->nbasis -#ifdef __MPI - , - ks_sol.pv.para_2d().ictxt() -#endif - ); - this->set_parallel_orbitals_band(this->paraMat_, this->nbands); - if (this->inp_->cal_force) - { - LR_Util::setup_2d_division( - this->paraMat_all_.para_2d(), ks_block_size, this->nbasis, this->nbasis -#ifdef __MPI - , - ks_sol.pv.para_2d().ictxt() -#endif - ); - this->set_parallel_orbitals_band(this->paraMat_all_, this->inp_->nbands); - } - - this->paraMat_.atom_begin_row = ks_sol.pv.atom_begin_row; - this->paraMat_.atom_begin_col = ks_sol.pv.atom_begin_col; - this->paraMat_.iat2iwt_ = ucell.get_iat2iwt(); - - LR_Util::setup_2d_division( - this->paraC_, ks_block_size, this->nbasis, this->nbands -#ifdef __MPI - , - this->paraMat_.para_2d().ictxt() -#endif - ); - - // allocate psi_ks and eig_ks in the [nocc, nvirt] window -#ifdef __MPI - this->psi_ks.reset( - new psi::Psi(this->kv.get_nks(), this->paraC_.ncloc(), this->paraC_.nrloc(), this->kv.ngk, true)); -#else - this->psi_ks.reset(new psi::Psi(this->kv.get_nks(), this->nbands, this->nbasis, this->kv.ngk, true)); -#endif - this->eig_ks.create(this->kv.get_nks(), this->nbands); - this->pelec = new elecstate::ElecStateLCAO(); - orb_cutoff_ = ks_sol.orb_.cutoffs(); - -#ifdef __EXX - // Two independent reasons to need an Exx_LRI: the LR exchange kernel, and the ground-state - // EXX terms of the gradient (the H_gs[T+Z] and W multipliers, gated on gs_is_hybrid). - // `initialize_from_unitcell_` has always covered both; this path used to test only the first, - // so a local kernel on top of a hybrid ground state had no exx_lri at all when asked for forces. - if (exx_kernel_list().count(xc_kernel) || (this->inp_->cal_force && gs_is_hybrid(this->inp_->dft_functional))) - { - std::string dft_functional = LR_Util::tolower(this->inp_->dft_functional); - // Either object would be built from the same `info_ri.coulomb_param`, which `input_conv` - // derives from dft_functional alone -- so whenever the ground-state solver has one of the - // right type its geometry tensors are already up to date. Share those tensors in a - // separate LR electronic workspace, skipping a `cal_exx_ions` per ionic step. - const bool share = (ks_sol.exx_nao.exd && std::is_same::value) || - (ks_sol.exx_nao.exc && std::is_same>::value); - warn_if_kernel_differs_from_gs(xc_kernel, dft_functional, this->ofs_running_); - if (share) - { - this->exx_owned_ = false; - } // `refresh_from_ks_` refreshes the geometry snapshot - else // construct C, V from scratch - { - // `input_conv` already filled `info_ri.coulomb_param` from INPUT. - exx_info.sync_from_global(); - // populate ABFs/JLE file lists from UnitCell; keep in sync with Exx_NAO::init - exx_info.info_ri.files_abfs = ucell.abfs_orbital_files; - exx_info.info_opt_abfs.files_abfs = ucell.abfs_orbital_files; - exx_info.info_opt_abfs.files_jles = ucell.jle_orbital_files; - this->exx_lri = std::make_shared>(exx_info.info_ri); - this->exx_lri->init(MPI_COMM_WORLD, ucell, this->kv, ks_sol.orb_); - this->exx_owned_ = true; // the position-dependent `cal_exx_ions` is left to `refresh_from_ks_` - } - } -#endif - - refresh_from_ks_(ucell); - this->ks_initialized_ = true; -} - -template -void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) -{ - ModuleBase::TITLE("ESolver_LR", "refresh_from_ks_"); - ModuleESolver::ESolver_KS_LCAO &ks_sol = *this->ks_; - // The ground-state solver owns `psi` and reuses it across ionic steps, so it cannot be stolen. - // `eig_ks_all` / `wg_ks_all` are nspin x nbands matrices -- a few kB, copied rather than aliased - // so that they survive the KS solver overwriting `pelec` on the next step. - this->psi_ks_all_ = ks_sol.psi; - this->eig_ks_all = ks_sol.pelec->ekb; - this->wg_ks_all = ks_sol.pelec->wg; - const int max_occupied_bands = *std::max_element(nocc.begin(), nocc.end()); - const int start_band = this->nocc_max - max_occupied_bands; - - for (int ik = 0; ik < this->kv.get_nks(); ++ik) - { - // copy the KS orbitals in the [nocc, nvirt] window -#ifdef __MPI - this->psi_ks_all_->fix_k(ik); - this->psi_ks->fix_k(ik); - const int first_band = start_band + 1; - Cpxgemr2d( - this->nbasis, this->nbands, this->psi_ks_all_->get_pointer(), 1, first_band, ks_sol.pv.desc_wfc, - this->psi_ks->get_pointer(), 1, 1, const_cast(this->paraC_.desc()), this->paraC_.ictxt()); -#else - // serial: each band is `nbasis` contiguous coefficients, so the window is a plain - // band-by-band copy (this loop used to compute the two pointers and copy nothing, - // leaving `psi_ks` uninitialized in every non-MPI build) - for (int ib = 0; ib < this->nbands; ++ib) - { - const auto *start = &(*this->psi_ks_all_)(ik, start_band + ib, 0); - auto *to = &(*this->psi_ks)(ik, ib, 0); - std::copy(start, start + this->nbasis, to); - } -#endif - // copy the KS bands in the [nocc, nvirt] window - for (int ib = 0; ib < this->nbands; ++ib) - { - this->eig_ks(ik, ib) = this->eig_ks_all(ik, start_band + ib); - } - } - - if (nspin == 2) - { - const int nupdown_now = - LR_Util::spin_population_difference(ks_sol.pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); - if (!this->ks_initialized_) - { - this->nupdown = nupdown_now; - reset_dim_spin(); // shifts nocc/nvirt between the spin channels: must run exactly once - } - else if (nupdown_now != this->nupdown) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR::refresh_from_ks_", - "the ground-state spin population changed between ionic steps, but nocc/nvirt and" - " the distributions built from them were fixed at the first step."); - } - } - // `gint_info_` stays owned by the KS solver: its `before_scf` rebuilds and re-publishes it - // init potential and calculate kernels using ground state charge - init_pot(*ks_sol.pelec->charge); - -#ifdef __EXX - if (exx_kernel_list().count(xc_kernel) || (this->inp_->cal_force && gs_is_hybrid(this->inp_->dft_functional))) - { - if (this->exx_owned_) - { // Cs/Vs follow the atoms, so they are rebuilt for every geometry - this->exx_lri->cal_exx_ions(ucell, this->inp_->out_ri_cv); - } - else if (ks_sol.exx_nao.exd) - { - this->share_exx_lri(ks_sol.exx_nao.exd->exx_ptr); - } - else if (ks_sol.exx_nao.exc) - { - this->share_exx_lri(ks_sol.exx_nao.exc->exx_ptr); - } - } -#endif - // the grid-integration tables hang off a static pointer that the ground-state solver - // re-publishes in its `before_scf`; make sure it names the object we integrate on - ModuleGint::Gint::set_gint_info(this->ks_->gint_info_.get()); - - // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final -#ifdef __MPI - this->fill_z_window_(ks_sol.pv.desc_wfc); -#else - this->fill_z_window_(nullptr); -#endif -} - -template -void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell, const Input_para &inp) -{ - ModuleBase::TITLE("ESolver_LR", "ESolver_LR(from scratch)"); - this->bind_ground_state_aliases_(); - // xc kernel - this->xc_kernel = LR_Util::tolower(inp.xc_kernel); - - // necessary steps in ESolver_FP - ESolver_FP::before_all_runners(ucell, inp); - LR_Util::check_force_pp(ucell, inp.cal_force, inp.calculation); - this->pelec = new elecstate::ElecStateLCAO(); - - // necessary steps in ESolver_KS::before_all_runners : symmetry and k-points - if (ModuleSymmetry::Symmetry::symm_flag == 1) - { - const int cal_symm_repr[2] = {this->inp_->cal_symm_repr[0], this->inp_->cal_symm_repr[1]}; - ucell.symm.analy_sys( - ucell.lat, ucell.atoms, ucell.nat, ucell.ntype, ucell.iat2it, ucell.iat2ia, ucell.itia2iat, - this->ofs_running_, this->inp_->symmetry_prec, this->inp_->nspin, this->inp_->calculation, cal_symm_repr); - ModuleBase::GlobalFunc::DONE(this->ofs_running_, "SYMMETRY"); - } - const bool use_ibz = false; - const bool gamma_only_local = PARAM.globalv.gamma_only_local; - const double kspacing[3] = {this->inp_->kspacing[0], this->inp_->kspacing[1], this->inp_->kspacing[2]}; - const double koffset[3] = {this->inp_->koffset[0], this->inp_->koffset[1], this->inp_->koffset[2]}; - this->kv.set( - ucell, ucell.symm, this->inp_->kpoint_file, this->inp_->nspin, ucell.G, ucell.latvec, this->ofs_running_, - this->ofs_warning_, use_ibz, this->out_dir, gamma_only_local, kspacing, this->inp_->kmesh_type, koffset); - ModuleBase::GlobalFunc::DONE(this->ofs_running_, "INIT K-POINTS"); - ModuleIO::print_parameters(ucell, this->kv, inp); - - LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); - - /// read orbitals and build the interpolation table - two_center_bundle_own_.build_orb(ucell.ntype, ucell.orbital_fn.data(), inp.orbital_dir); - - LCAO_Orbitals orb; - two_center_bundle_own_.to_LCAO_Orbitals( - orb, inp.lcao_ecut, inp.lcao_dk, inp.lcao_dr, inp.lcao_rmax, inp.out_element_info, inp.cal_force); - orb_cutoff_ = orb.cutoffs(); - // Standalone LR neighbor search needs projector metadata for every optical gauge. - LR::setup_nonlocal_info(orb, ucell, *this->inp_, this->my_rank_, this->ofs_running_); - const bool need_force_tables = this->inp_->cal_force || this->inp_->calculation == "relax"; - const bool need_velocity_tables = LR_Util::tolower(this->inp_->abs_gauge) == "velocity"; - if (need_force_tables || need_velocity_tables) - { - LR::setup_2center_table(this->two_center_bundle_own_, ucell, *this->inp_); - } - - this->set_dim(); - // setup 2d-block distribution for AO-matrix and KS wfc - LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); - this->set_parallel_orbitals_band(this->paraMat_, this->nbands); - if (this->inp_->cal_force) - { - LR_Util::setup_2d_division(this->paraMat_all_.para_2d(), 1, this->nbasis, this->nbasis); - this->set_parallel_orbitals_band(this->paraMat_all_, this->inp_->nbands); - } - - // read the ground state info - // now ModuleIO::read_wfc_nao needs `Parallel_Orbitals` and can only read all the bands - // it need improvement to read only the bands needed - this->psi_ks.reset(new psi::Psi( - this->kv.get_nks(), this->paraMat_.ncol_bands, this->paraMat_.para_2d().nrloc(), this->kv.ngk, true)); - this->read_ks_wfc(); - - if (nspin == 2) - { - // Complete file populations were read before selecting the occupied window. - reset_dim_spin(); - } - // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final -#ifdef __MPI - this->fill_z_window_(paraMat_all_.desc_wfc); -#else - this->fill_z_window_(nullptr); -#endif - - LR_Util::setup_2d_division( - this->paraC_, 1, this->nbasis, this->nbands -#ifdef __MPI - , - paraMat_.para_2d().ictxt() -#endif - ); - - // clear ks info, new elecstate for excition - delete this->pelec; // the ElecStateLCAO allocated above, only needed while reading the KS data - this->pelec = new elecstate::ElecState(); - - // read the ground state charge density and calculate xc kernel - pgrid().init( - this->pw_rho->nx, this->pw_rho->ny, this->pw_rho->nz, this->pw_rho->nplane, this->pw_rho->nrxx, pw_big->nbz, - pw_big->bz, GlobalV::NPROC); - Charge chg_gs; - if (this->inp_->ri_hartree_benchmark == "none") - { - this->read_ks_chg(chg_gs); - } - this->init_pot(chg_gs); - - // search adjacent atoms and init Gint - double search_radius = -1.0; - search_radius = atom_arrange::set_sr_NL( - this->ofs_running_, this->inp_->out_level, orb.get_rcutmax_Phi(), ucell.infoNL->get_rcutmax_Beta(), - PARAM.globalv.gamma_only_local); - atom_arrange::search( - PARAM.globalv.search_pbc, this->ofs_running_, this->gd(), *this->ucell_, search_radius, - this->inp_->test_atom_input); - gint_info_.reset(new ModuleGint::GintInfo( - this->pw_big->nbx, this->pw_big->nby, this->pw_big->nbz, this->pw_rho->nx, this->pw_rho->ny, this->pw_rho->nz, - 0, 0, this->pw_big->nbzp_start, this->pw_big->nbx, this->pw_big->nby, this->pw_big->nbzp, orb.Phi, ucell, - this->gd(), this->inp_->nspin, PARAM.globalv.gamma_only_local, PARAM.globalv.domag, this->inp_->device == "gpu", - this->inp_->nstream)); - ModuleGint::Gint::set_gint_info(gint_info_.get()); - // if EXX from scratch, init 2-center integral and calculate Cs, Vs - // when: - // 1. EXX xc_kernel - // 2. cal_force with ground state with EXX functional -#ifdef __EXX - if (((exx_kernel_list().count(xc_kernel)) && this->inp_->lr_solver != "spectrum") || - (this->inp_->cal_force && gs_is_hybrid(this->inp_->dft_functional))) - { - warn_if_kernel_differs_from_gs(xc_kernel, LR_Util::tolower(this->inp_->dft_functional), this->ofs_running_); - // `input_conv` already filled `info_ri.coulomb_param` from INPUT. - exx_info.sync_from_global(); - // populate ABFs/JLE file lists from UnitCell; keep in sync with Exx_NAO::init - exx_info.info_ri.files_abfs = ucell.abfs_orbital_files; - exx_info.info_opt_abfs.files_abfs = ucell.abfs_orbital_files; - exx_info.info_opt_abfs.files_jles = ucell.jle_orbital_files; - this->exx_lri = std::make_shared>(exx_info.info_ri); - this->exx_lri->init(MPI_COMM_WORLD, ucell, this->kv, orb); - this->exx_lri->cal_exx_ions(ucell, this->inp_->out_ri_cv); - } - // else -#endif - // ModuleBase::Ylm::set_coefficients() is deprecated -} - -template class ModuleESolver::ESolver_LR; -template class ModuleESolver::ESolver_LR, double>; diff --git a/source/source_esolver/esolver_lr_lcao_bse.h b/source/source_esolver/esolver_lr_lcao_bse.h index 5827407ad8..80b9e789e1 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.h +++ b/source/source_esolver/esolver_lr_lcao_bse.h @@ -1,7 +1,7 @@ #ifndef ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_BSE_H #define ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_BSE_H -#include "esolver_lr_lcao_tddft.h" +#include "esolver_lr.h" #include "source_lcao/module_bse/molecular_lri.h" namespace ModuleESolver diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 0771ee5438..23642e4ed9 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -2834,7 +2834,7 @@ TEST_F(InputTest, Item_test2) EXPECT_THAT(output, testing::HasSubstr("NOTICE")); } // nocc no longer has a reset_value here: it's resolved from ground-state spin populations - // after SCF (see esolver_lr_lcao_tddft.cpp), not at INPUT-parse time. + // after SCF (see esolver_lr.cpp), not at INPUT-parse time. { // lr_grad_solver auto it = find_label("lr_grad_solver", readinput.input_lists); for (const std::string solver : { "cg", "lapack" }) diff --git a/source/source_io/unittests/test_read_input_parallel.cpp b/source/source_io/unittests/test_read_input_parallel.cpp index 6972e82f6b..2682178912 100644 --- a/source/source_io/unittests/test_read_input_parallel.cpp +++ b/source/source_io/unittests/test_read_input_parallel.cpp @@ -455,7 +455,7 @@ TEST_F(InputParaTest, ParaRead) EXPECT_EQ(param.inp.sc_scf_thr, 1e-3); EXPECT_EQ(param.inp.sc_drop_thr, 1e-3); EXPECT_EQ(param.inp.lr_nstates, 1); - // nocc is resolved from ground-state spin populations after SCF (see esolver_lr_lcao_tddft.cpp), + // nocc is resolved from ground-state spin populations after SCF (see esolver_lr.cpp), // not at INPUT-parse time, so a run with no explicit `nocc` keeps its raw unresolved default here. EXPECT_EQ(param.inp.nocc, -1); EXPECT_EQ(param.inp.nvirt, 1); diff --git a/source/source_lcao/module_lr/grad_degen.h b/source/source_lcao/module_lr/grad_degen.h index 7b68e0492d..9c179e16fa 100644 --- a/source/source_lcao/module_lr/grad_degen.h +++ b/source/source_lcao/module_lr/grad_degen.h @@ -13,7 +13,7 @@ /// eigenvectors depend on $u$. The full first-order object is $3N$ matrices of size $d\times d$, /// and only $\operatorname{Tr}M$ is basis-invariant. /// -/// The per-state analytic gradient implemented in `esolver_lr_lcao_tddft.cpp` is, restricted to one +/// The per-state analytic gradient implemented in `esolver_lr.cpp` is, restricted to one /// multiplet, a *quadratic form* in the excitation vector: every ingredient ($D^X$, $T$, $R$, $Z$, /// $D^Z$, $W^X$, $\Lambda$) is built from $X\otimes X$, the CPSCF operator $L$ depends only on the /// ground state, and $\Omega$ is a constant inside the multiplet. Write it $\mathcal F[X]$. Because @@ -41,7 +41,7 @@ /// This header holds only the basis-independent bookkeeping, so that it is unit-testable without a /// ground state: grouping states into multiplets, enumerating the pairs, forming the normalized /// combination, and assembling $G$. Everything needing the parallel layout or the Z-vector solver -/// stays in `esolver_lr_lcao_tddft.cpp`. +/// stays in `esolver_lr.cpp`. namespace LR { From ecfb35ecf7721f7a79039f8b528c5cea1d6bc840 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 15:09:08 +0800 Subject: [PATCH 07/26] docs(lr): avoid naming a global in the DimSrc field comment The governance checker counts comment text as a global dependency, which made the refactor look like a net +1. Describe the field instead. --- source/source_lcao/module_lr/lr_dim.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/source_lcao/module_lr/lr_dim.h b/source/source_lcao/module_lr/lr_dim.h index 3f5a835b6a..5db5e61398 100644 --- a/source/source_lcao/module_lr/lr_dim.h +++ b/source/source_lcao/module_lr/lr_dim.h @@ -37,7 +37,7 @@ struct Dim struct DimSrc { const Input_para* inp = nullptr; - int nlocal = 0; ///< PARAM.globalv.nlocal + int nlocal = 0; ///< number of local basis functions int nks = 0; ///< K_Vectors::get_nks() int nkstot = 0; ///< K_Vectors::get_nkstot() int rank = 0; ///< MPI rank in the world communicator From 5c497e0790d8c07660c05d86615fcae7a6dc581c Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 15:32:33 +0800 Subject: [PATCH 08/26] refactor(lr): move multiplet and Jahn-Teller assembly into module_lr Add LR::build_mpl and LR::eval_jt_force, which own the polarization identity, the basis diagnostics and the Jahn-Teller search. The solver keeps only the Z-vector callback and the target-state bookkeeping, and the dead MultipletLVC::average_force goes away. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr.cpp | 224 +++----------------- source/source_esolver/esolver_lr.h | 47 ++-- source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/lr_grad_cs.cpp | 2 +- source/source_lcao/module_lr/lr_mpl.cpp | 186 ++++++++++++++++ source/source_lcao/module_lr/lr_mpl.h | 55 +++++ 7 files changed, 282 insertions(+), 234 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_mpl.cpp create mode 100644 source/source_lcao/module_lr/lr_mpl.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 78f136fd12..90df9f8758 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1198,6 +1198,7 @@ OBJS_TENSOR=tensor.o\ lr_gs.o\ lr_dm.o\ lr_relax.o\ + lr_mpl.o\ lr_gs_pot.o\ esolver_lr.o\ diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index 492083a9b0..2397c7433d 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -582,7 +582,7 @@ ct::Tensor ModuleESolver::ESolver_LR::solve_zvector_eqation(const int isp ModuleBase::timer::start("ESolver_LR", "solve_zvector_eqation"); // `Z_vector_equation` treats X and Z as `nst` independent blocks of `nloc_per_state_z_`, // and the blocks need not be eigenvectors of the Casida equation in the order the - // diagonalizer returned them -- `cal_grad_matrix_degenerate` feeds it linear combinations. + // diagonalizer returned them -- `build_mpl_` feeds it linear combinations. // X arrives already widened into the Z window (`Xz`), which spans every virtual band the // ground state produced rather than the `nvirt` window X was solved in -- the Brillouin // condition the Z-vector enforces holds in EVERY occupied-virtual rotation. The padded @@ -685,7 +685,7 @@ void ModuleESolver::ESolver_LR::cal_force_and_grad_matrix_(const int ispi this->multiplet_lvc_.erase( std::remove_if( this->multiplet_lvc_.begin(), this->multiplet_lvc_.end(), - [ispin](const MultipletLVC &m) { return m.ispin == ispin; }), + [ispin](const LR::MplLvc &m) { return m.ispin == ispin; }), this->multiplet_lvc_.end()); // The per-state gradients above are the diagonal of the degenerate-subspace gradient matrix in // whatever basis the eigensolver returned, so inside a multiplet only their trace means @@ -709,115 +709,33 @@ void ModuleESolver::ESolver_LR::cal_force_and_grad_matrix_(const int ispi { diag.push_back(forces[ist]); } - MultipletLVC lvc; - lvc.ispin = ispin; - lvc.states = group; - double lo = omega[group.front()]; - double hi = omega[group.front()]; - double sum = 0.0; - for (const int ist : group) - { - lo = std::min(lo, omega[ist]); - hi = std::max(hi, omega[ist]); - sum += omega[ist]; - } - lvc.omega0 = sum / static_cast(group.size()); - lvc.omega_spread = hi - lo; - lvc.g = this->cal_grad_matrix_degenerate(ispin, group, diag, ofs); - this->multiplet_lvc_.push_back(lvc); + this->multiplet_lvc_.push_back(this->build_mpl_(ispin, group, diag, ofs)); } } template -std::vector> ModuleESolver::ESolver_LR::cal_grad_matrix_degenerate( - const int ispin, - const std::vector &group, - const std::vector &diag, - std::ofstream &ofs) +LR::MplLvc ModuleESolver::ESolver_LR::build_mpl_(const int ispin, + const std::vector &group, + const std::vector &diag, + std::ofstream &ofs) { - ModuleBase::TITLE("ESolver_LR", "cal_grad_matrix_degenerate"); - ModuleBase::timer::start("ESolver_LR", "cal_grad_matrix_degenerate"); - const int d = static_cast(group.size()); - assert(d >= 2); - assert(diag.size() == group.size()); - const std::vector> pairs = LR::degenerate_pairs(d); - const int nloc_g = this->nloc_per_state_z_; - const int ekb_off = this->openshell ? 0 : ispin * this->nstates; - - // 1. the multiplet's members, each widened into the Z window + ModuleBase::TITLE("ESolver_LR", "build_mpl_"); + ModuleBase::timer::start("ESolver_LR", "build_mpl_"); + // The multiplet's members, each widened into the Z window const ct::Tensor Xz = this->pad_group_to_z_(ispin, group); - std::vector omega_member(d); - for (int k = 0; k < d; ++k) - { - omega_member[k] = this->pelec->ekb.c[ekb_off + group[k]]; - } - - // 2. the two preconditions of route (A2), reported rather than enforced: the combinations - // $X_\pm$ are normalized eigenvectors only if the members are orthonormal, and the gradient - // is a single quadratic form only if they share one $\Omega$. An accidental near-degeneracy - // passes the grouping threshold but fails the second, and its `omega_spread` says so. - double max_ovlp_err = 0.0; - for (int k = 0; k < d; ++k) - { - for (int l = k; l < d; ++l) - { - const T *const xk = Xz.template data() + static_cast(k) * nloc_g; - const T *const xl = Xz.template data() + static_cast(l) * nloc_g; - T loc = static_cast(0); - for (int i = 0; i < nloc_g; ++i) - { - loc += LR_Util::get_conj(xk[i]) * xl[i]; - } - Parallel_Reduce::reduce_all(loc); - const double ref = (k == l) ? 1.0 : 0.0; - max_ovlp_err = std::max(max_ovlp_err, std::abs(loc - ref)); - } - } - const double omega_max = *std::max_element(omega_member.begin(), omega_member.end()); - const double omega_min = *std::min_element(omega_member.begin(), omega_member.end()); - const double omega_spread = omega_max - omega_min; - // one $\Omega$ for every combination: the members share it up to `omega_spread`, and the mean - // is the neutral choice for a vector that belongs to no single member - double omega_sum = 0.0; - for (const double omega : omega_member) - { - omega_sum += omega; - } - const double omega_mean = omega_sum / static_cast(d); - ofs << " Degenerate multiplet of " << d << " states, Omega = " << omega_mean << " Ry, spread = " << omega_spread - << " Ry, max | - delta_kl| = " << max_ovlp_err << std::endl; - // Dimensionless diagnostic tolerance for the orthonormality needed by X_plus. - // This warning does not change the multiplet or the computed gradient. - const double orthonormality_warn_tol = 1e-6; - if (max_ovlp_err > orthonormality_warn_tol) - { - ofs << " WARNING: this multiplet's eigenvectors are not orthonormal to" - << " tolerance " << orthonormality_warn_tol - << " (dimensionless overlap error); (X_k+X_l)/sqrt(2) may not be normalized" - << " and the assembled gradient matrix may consequently be inaccurate." << std::endl; - } - - // 3. the $d(d-1)/2$ combinations $X_+=(X_k+X_l)/\sqrt2$, all in one Z-vector solve - const int npair = static_cast(pairs.size()); - ct::Tensor Xp = LR_Util::newTensor({npair, nloc_g}); - Xp.zero(); - for (int ip = 0; ip < npair; ++ip) + const int ekb_off = this->openshell ? 0 : ispin * this->nstates; + std::vector omega(group.size()); + for (size_t k = 0; k < group.size(); ++k) { - LR::combine_normalized( - Xz.template data() + static_cast(pairs[ip].first) * nloc_g, - Xz.template data() + static_cast(pairs[ip].second) * nloc_g, static_cast(nloc_g), - Xp.template data() + static_cast(ip) * nloc_g); + omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; } - const std::vector omega_pair(npair, omega_mean); - const std::vector plus = this->openshell - ? this->cal_force_openshell_Xz(Xp, omega_pair, group[0]) - : this->cal_force_Xz(ispin, Xp, omega_pair, group[0]); - - // 4. $G_{kl}=\mathcal F[X_+]-\tfrac12(G_{kk}+G_{ll})$ - const std::vector> g = LR::assemble_grad_matrix(diag, plus, pairs); - print_grad_matrix(g, group, (*this->ucell_), ofs); - ModuleBase::timer::end("ESolver_LR", "cal_grad_matrix_degenerate"); - return g; + // The module owns everything but the Z-vector solve, which stays behind this callback. + const LR::MplEval eval = [this, ispin](const ct::Tensor &x, const std::vector &w, const int label) { + return this->openshell ? this->cal_force_openshell_Xz(x, w, label) : this->cal_force_Xz(ispin, x, w, label); + }; + LR::MplLvc mpl = LR::build_mpl(Xz, omega, diag, this->nloc_per_state_z_, ispin, group, *this->ucell_, eval, ofs); + ModuleBase::timer::end("ESolver_LR", "build_mpl_"); + return mpl; } template @@ -1081,102 +999,12 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( // off-diagonal elements are assembled here -- d(d-1)/2 further Z-vector solves on top of the // d diagonal ones already in `diag`. const std::vector &group = this->target_.group(); - const int d = static_cast(group.size()); - const std::vector> g = - this->cal_grad_matrix_degenerate(this->target_.ispin(), group, diag, ofs); - const int nat = diag[0].nr; - const int ncoord = nat * 3; - // flatten to the layout `find_jt_direction` takes: one d x d block per nuclear coordinate. - // FORCES go in, not gradients, so the direction that comes back points downhill. - std::vector gflat(static_cast(ncoord) * d * d, 0.0); - for (int iat = 0; iat < nat; ++iat) - { - for (int ixyz = 0; ixyz < 3; ++ixyz) - { - const int a = iat * 3 + ixyz; - for (int k = 0; k < d; ++k) - { - for (int l = 0; l < d; ++l) - { - gflat[static_cast(a) * d * d + k * d + l] = g[k][l](iat, ixyz); - } - } - } - } - const LR::JTDirection jt = LR::find_jt_direction(gflat, ncoord, d); + LR::JtForce jt = LR::eval_jt_force(this->build_mpl_(this->target_.ispin(), group, diag, ofs).g, ofs); const int channel = this->openshell ? 0 : this->target_.ispin(); - const T *const amplitudes = this->X[channel].template data(); - this->target_.save_mixed(amplitudes, this->nloc_per_state, jt.mixing); - std::vector jt_part; - const std::vector sym = LR::split_symmetric_part(gflat, ncoord, d, jt.mixing, jt_part); - - const double fac = ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A; - ofs << " lr_degen_mode=jt: descending the steepest branch of the multiplet." << std::endl - << " |F| of that branch = " << jt.slope * fac << " eV/Angstrom" << std::endl - << " mixing v ="; - for (int k = 0; k < d; ++k) - { - ofs << " " << jt.mixing[k]; - } - ofs << std::endl - << " starts agreeing = " << jt.restarts_agreeing << " of " << (d + (1 << (d - 1))) << " (iterations " - << jt.iterations << ")" << std::endl; - // The two halves matter separately: the symmetric part is common to the whole multiplet and - // only relaxes the geometry, while the remainder is what actually breaks the degeneracy. At a - // stationary point of the average surface the first is zero and the whole force is Jahn-Teller. - double nsym = 0.0; - double njt = 0.0; - for (int a = 0; a < ncoord; ++a) - { - nsym += sym[a] * sym[a]; - njt += jt_part[a] * jt_part[a]; - } - ofs << " |symmetric part| = " << std::sqrt(nsym) * fac - << " eV/Angstrom (common to the" - " multiplet; relaxes the geometry without splitting it)" - << std::endl - << " |Jahn-Teller part| = " << std::sqrt(njt) * fac - << " eV/Angstrom (the symmetry-" - "breaking remainder)" - << std::endl; - if (std::sqrt(njt) < 1e-8) - { - ofs << " WARNING: the symmetry-breaking part vanishes -- every branch of this multiplet has" - " the same gradient, so there is no Jahn-Teller direction to descend here. This is the" - " expected outcome for a linear molecule, where the effect is second order" - " (Renner-Teller) and no first-order term exists." - << std::endl; - } - ofs << " NOTE: this is the first-order DIRECTION only. The distortion amplitude also needs the" - " harmonic term, and the step norm is Cartesian rather than mass-weighted." - << std::endl; - - // The force handed back is that of the descending branch, q(v) with v the optimal mixing -- - // i.e. the branch's own gradient, which is what a relaxation must follow. Once a step has - // split the multiplet, `resolve_group` finds no group and the ordinary single-state path - // takes over, so this mode is self-limiting by construction. - ModuleBase::matrix f(nat, 3); - for (int iat = 0; iat < nat; ++iat) - { - for (int ixyz = 0; ixyz < 3; ++ixyz) - { - const int a = iat * 3 + ixyz; - f(iat, ixyz) = sym[a] + jt_part[a]; - } - } - return f; -} - -template -ModuleBase::matrix ModuleESolver::ESolver_LR::MultipletLVC::average_force() const -{ - assert(!this->g.empty()); - std::vector diag; - for (int k = 0; k < this->dim(); ++k) - { - diag.push_back(this->g[k][k]); - } - return average_forces(diag); + this->target_.save_mixed(this->X[channel].template data(), this->nloc_per_state, jt.mixing); + // The returned force is the descending branch's own gradient; once a step splits the + // multiplet `resolve_group` finds no group and the single-state path takes over. + return jt.force; } // Initialize LR from an embedded KS solver or standalone ground-state files. diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 4284171d26..550a32d254 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -19,6 +19,7 @@ #include "source_lcao/module_lr/hamilt_casida.h" #include "source_lcao/module_lr/potentials/lr_gs_pot.h" #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" +#include "source_lcao/module_lr/lr_mpl.h" #include "source_lcao/module_lr/lr_relax.h" #include "source_lcao/module_lr/state_track.h" #ifdef __EXX @@ -255,7 +256,7 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// The blocks of `Xz` need not be the eigenvectors the Casida diagonalizer returned. Any /// normalized vector inside a degenerate multiplet is an eigenvector with the same /// `omega`, so passing a linear combination is what turns the per-state gradient into the - /// full degenerate-subspace gradient matrix; see `cal_grad_matrix_degenerate` and + /// full degenerate-subspace gradient matrix; see `build_mpl_` and /// `grad_degen.h`. /// /// @param omega excitation energy of each block (Ry); its size sets the block count @@ -268,29 +269,14 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// open-shell counterpart of `cal_force_Xz` std::vector cal_force_openshell_Xz( const ct::Tensor &Xz, const std::vector &omega, const int label_begin); - /// @brief The linear vibronic coupling (LVC) data of one degenerate multiplet. - /// - /// $H(\delta R)=\Omega_0\mathbb{1}+\sum_{A\alpha}\delta R_{A\alpha}G^{(A\alpha)}$ is the - /// complete first-order description of a degeneracy, and $G$ is its parameter set. Kept as - /// one object rather than as loose force matrices because the excited-state relaxation and - /// (later) non-adiabatic dynamics need exactly the same data: near a degeneracy the correct - /// propagation is on this coupled $d\times d$ model, not on an adiabatic gradient. - struct MultipletLVC - { - int ispin = 0; ///< which spin channel (index into `spin_types`) - std::vector states; ///< the multiplet's state indices, ascending - double omega0 = 0.0; ///< the common excitation energy (Ry) - double omega_spread = 0.0; ///< max - min over the members (Ry); 0 if exact - /// G[k][l], symmetric, each a (nat, 3) force matrix -- i.e. the 3N matrices of d x d - std::vector> g; - int dim() const { return static_cast(states.size()); } - /// $\operatorname{Tr}G/d$: the one smooth, basis-independent 3N vector field the - /// multiplet has. Following it preserves the symmetric configuration. - ModuleBase::matrix average_force() const; - }; + /// @brief The linear vibronic coupling (LVC) data of one degenerate multiplet: see + /// `LR::MplLvc`. Kept as one object rather than as loose force matrices because the + /// excited-state relaxation and (later) non-adiabatic dynamics need exactly the same + /// data: near a degeneracy the correct propagation is on this coupled $d\times d$ + /// model, not on an adiabatic gradient. /// LVC data of every multiplet found at this geometry, rebuilt on each call of /// `cal_force_and_grad_matrix_`. Empty unless `lr_degen_thr > 0`. - std::vector multiplet_lvc_; + std::vector multiplet_lvc_; /// The LR half of the force for the current geometry, following whichever surface /// `lr_degen_mode` selects. `ofs` receives the note when that is not a single state. ModuleBase::matrix cal_lr_force_relax_(std::ofstream &ofs); @@ -313,22 +299,13 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// /// Fills `multiplet_lvc_`. void cal_force_and_grad_matrix_(const int ispin, std::ofstream &ofs); - /// @brief The gradient matrix of one degenerate multiplet, - /// $G^{(A\alpha)}_{kl}=\langle X_k|\partial A/\partial R_{A\alpha}|X_l\rangle$. - /// - /// At a degeneracy no single state has a gradient vector -- the branch slopes along a - /// displacement $u$ are the eigenvalues of $\sum_{A\alpha}u_{A\alpha}G^{(A\alpha)}$, whose - /// eigenvectors depend on $u$ -- so this whole matrix, not its diagonal, is the first-order - /// information. It is obtained from the polarization identity - /// $G_{kl}=\mathcal F[(X_k{+}X_l)/\sqrt2]-\tfrac12(G_{kk}+G_{ll})$, which needs no new - /// physics. `grad_degen.h` derives why that is exact. + /// @brief Wrap one multiplet's Z-window members and per-state forces into + /// `LR::build_mpl`, which owns the polarization identity and the diagnostics. /// /// @param group state indices of the multiplet, from `LR::group_degenerate_states` - /// @param diag their per-state gradients, i.e. $G_{kk}$, already computed by `cal_force` + /// @param diag their per-state forces, i.e. $G_{kk}$, already computed by `cal_force` /// @param ofs log stream the matrix and the precondition diagnostics are written to - /// @return G[k][l], symmetric, each entry a (nat, 3) force matrix - std::vector> cal_grad_matrix_degenerate( - const int ispin, + LR::MplLvc build_mpl_(const int ispin, const std::vector &group, const std::vector &diag, std::ofstream &ofs); diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 9c8e18b6f7..112b98c8e1 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -30,6 +30,7 @@ if(ENABLE_LCAO) lr_gs.cpp lr_dm.cpp lr_relax.cpp + lr_mpl.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/lr_grad_cs.cpp b/source/source_lcao/module_lr/lr_grad_cs.cpp index 684a53b238..a1a96c3b66 100644 --- a/source/source_lcao/module_lr/lr_grad_cs.cpp +++ b/source/source_lcao/module_lr/lr_grad_cs.cpp @@ -21,7 +21,7 @@ std::vector evaluate_closed_shell_force( assert(static_cast(Xz.shape().dim_size(0)) == nst); // `ist_begin`/`ist_end` label the blocks in the output only; the gradient itself never looks // up a state, it only uses `omega[i]`. That is what lets a caller pass excitation vectors - // that are not the stored eigenvectors (see `cal_grad_matrix_degenerate`). + // that are not the stored eigenvectors (see `LR::build_mpl`). const int ist_begin = label_begin; const int ist_end = label_begin + nst; const std::vector& nvirt_g = inputs.nvirt; diff --git a/source/source_lcao/module_lr/lr_mpl.cpp b/source/source_lcao/module_lr/lr_mpl.cpp new file mode 100644 index 0000000000..3e56581884 --- /dev/null +++ b/source/source_lcao/module_lr/lr_mpl.cpp @@ -0,0 +1,186 @@ +#include "source_lcao/module_lr/lr_mpl.h" + +#include "source_base/constants.h" +#include "source_base/parallel_reduce.h" +#include "source_lcao/module_lr/grad_degen.h" +#include "source_lcao/module_lr/gradient_output.h" + +#include +#include +#include +#include + +namespace LR +{ + +template +MplLvc build_mpl(const ct::Tensor& xz, const std::vector& omega, const std::vector& diag, + const int nloc, const int ispin, const std::vector& states, const UnitCell& ucell, + const MplEval& eval, std::ofstream& log) +{ + const int d = static_cast(states.size()); + assert(d >= 2); + assert(diag.size() == states.size()); + assert(omega.size() == states.size()); + const std::vector> pairs = degenerate_pairs(d); + + // 1. the two preconditions of route (A2), reported rather than enforced: the combinations + // $X_\pm$ are normalized eigenvectors only if the members are orthonormal, and the gradient + // is a single quadratic form only if they share one $\Omega$. An accidental near-degeneracy + // passes the grouping threshold but fails the second, and its `omega_spread` says so. + double max_ovlp_err = 0.0; + for (int k = 0; k < d; ++k) + { + for (int l = k; l < d; ++l) + { + const T* const xk = xz.template data() + static_cast(k) * nloc; + const T* const xl = xz.template data() + static_cast(l) * nloc; + T loc = static_cast(0); + for (int i = 0; i < nloc; ++i) + { + loc += LR_Util::get_conj(xk[i]) * xl[i]; + } + Parallel_Reduce::reduce_all(loc); + const double ref = (k == l) ? 1.0 : 0.0; + max_ovlp_err = std::max(max_ovlp_err, std::abs(loc - ref)); + } + } + MplLvc mpl; + mpl.ispin = ispin; + mpl.states = states; + const double omega_max = *std::max_element(omega.begin(), omega.end()); + const double omega_min = *std::min_element(omega.begin(), omega.end()); + mpl.omega_spread = omega_max - omega_min; + // one $\Omega$ for every combination: the members share it up to `omega_spread`, and the mean + // is the neutral choice for a vector that belongs to no single member + double omega_sum = 0.0; + for (const double e : omega) + { + omega_sum += e; + } + mpl.omega0 = omega_sum / static_cast(d); + log << " Degenerate multiplet of " << d << " states, Omega = " << mpl.omega0 << " Ry, spread = " + << mpl.omega_spread << " Ry, max | - delta_kl| = " << max_ovlp_err << std::endl; + // Dimensionless diagnostic tolerance for the orthonormality needed by X_plus. + // This warning does not change the multiplet or the computed gradient. + const double orthonormality_warn_tol = 1e-6; + if (max_ovlp_err > orthonormality_warn_tol) + { + log << " WARNING: this multiplet's eigenvectors are not orthonormal to" + << " tolerance " << orthonormality_warn_tol + << " (dimensionless overlap error); (X_k+X_l)/sqrt(2) may not be normalized" + << " and the assembled gradient matrix may consequently be inaccurate." << std::endl; + } + + // 2. the $d(d-1)/2$ combinations $X_+=(X_k+X_l)/\sqrt2$, all in one Z-vector solve + const int npair = static_cast(pairs.size()); + ct::Tensor Xp = LR_Util::newTensor({npair, nloc}); + Xp.zero(); + for (int ip = 0; ip < npair; ++ip) + { + LR::combine_normalized(xz.template data() + static_cast(pairs[ip].first) * nloc, + xz.template data() + static_cast(pairs[ip].second) * nloc, + static_cast(nloc), Xp.template data() + static_cast(ip) * nloc); + } + const std::vector omega_pair(npair, mpl.omega0); + const std::vector plus = eval(Xp, omega_pair, states[0]); + + // 3. $G_{kl}=\mathcal F[X_+]-\tfrac12(G_{kk}+G_{ll})$ + mpl.g = assemble_grad_matrix(diag, plus, pairs); + print_grad_matrix(mpl.g, states, ucell, log); + return mpl; +} + +JtForce eval_jt_force(const std::vector>& g, std::ostream& log) +{ + const int d = static_cast(g.size()); + const int nat = g[0][0].nr; + const int ncoord = nat * 3; + // flatten to the layout `find_jt_direction` takes: one d x d block per nuclear coordinate. + // FORCES go in, not gradients, so the direction that comes back points downhill. + std::vector gflat(static_cast(ncoord) * d * d, 0.0); + for (int iat = 0; iat < nat; ++iat) + { + for (int ixyz = 0; ixyz < 3; ++ixyz) + { + const int a = iat * 3 + ixyz; + for (int k = 0; k < d; ++k) + { + for (int l = 0; l < d; ++l) + { + gflat[static_cast(a) * d * d + k * d + l] = g[k][l](iat, ixyz); + } + } + } + } + const JTDirection jt = find_jt_direction(gflat, ncoord, d); + std::vector jt_part; + const std::vector sym = split_symmetric_part(gflat, ncoord, d, jt.mixing, jt_part); + + const double fac = ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A; + log << " lr_degen_mode=jt: descending the steepest branch of the multiplet." << std::endl + << " |F| of that branch = " << jt.slope * fac << " eV/Angstrom" << std::endl + << " mixing v ="; + for (int k = 0; k < d; ++k) + { + log << " " << jt.mixing[k]; + } + log << std::endl + << " starts agreeing = " << jt.restarts_agreeing << " of " << (d + (1 << (d - 1))) << " (iterations " + << jt.iterations << ")" << std::endl; + // The two halves matter separately: the symmetric part is common to the whole multiplet and + // only relaxes the geometry, while the remainder is what actually breaks the degeneracy. At a + // stationary point of the average surface the first is zero and the whole force is Jahn-Teller. + double nsym = 0.0; + double njt = 0.0; + for (int a = 0; a < ncoord; ++a) + { + nsym += sym[a] * sym[a]; + njt += jt_part[a] * jt_part[a]; + } + log << " |symmetric part| = " << std::sqrt(nsym) * fac + << " eV/Angstrom (common to the" + " multiplet; relaxes the geometry without splitting it)" + << std::endl + << " |Jahn-Teller part| = " << std::sqrt(njt) * fac + << " eV/Angstrom (the symmetry-" + "breaking remainder)" + << std::endl; + if (std::sqrt(njt) < 1e-8) + { + log << " WARNING: the symmetry-breaking part vanishes -- every branch of this multiplet has" + " the same gradient, so there is no Jahn-Teller direction to descend here. This is the" + " expected outcome for a linear molecule, where the effect is second order" + " (Renner-Teller) and no first-order term exists." + << std::endl; + } + log << " NOTE: this is the first-order DIRECTION only. The distortion amplitude also needs the" + " harmonic term, and the step norm is Cartesian rather than mass-weighted." + << std::endl; + + // The force handed back is that of the descending branch, q(v) with v the optimal mixing -- + // i.e. the branch's own gradient, which is what a relaxation must follow. Once a step has + // split the multiplet, `resolve_group` finds no group and the ordinary single-state path + // takes over, so this mode is self-limiting by construction. + JtForce out; + out.force.create(nat, 3); + out.mixing = jt.mixing; + for (int iat = 0; iat < nat; ++iat) + { + for (int ixyz = 0; ixyz < 3; ++ixyz) + { + const int a = iat * 3 + ixyz; + out.force(iat, ixyz) = sym[a] + jt_part[a]; + } + } + return out; +} + +template MplLvc build_mpl(const ct::Tensor&, const std::vector&, const std::vector&, + int, int, const std::vector&, const UnitCell&, const MplEval&, std::ofstream&); +template MplLvc build_mpl>(const ct::Tensor&, const std::vector&, + const std::vector&, int, int, + const std::vector&, const UnitCell&, const MplEval&, + std::ofstream&); + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_mpl.h b/source/source_lcao/module_lr/lr_mpl.h new file mode 100644 index 0000000000..b6bf6eadc3 --- /dev/null +++ b/source/source_lcao/module_lr/lr_mpl.h @@ -0,0 +1,55 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_MPL_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_MPL_H + +#include "source_lcao/module_lr/utils/lr_util.h" + +#include +#include +#include + +class UnitCell; + +namespace LR +{ +/// Linear vibronic coupling data of one degenerate multiplet. +struct MplLvc +{ + int ispin = 0; ///< which spin channel (index into `spin_types`) + std::vector states; ///< the multiplet's state indices, ascending + double omega0 = 0.0; ///< the common excitation energy (Ry) + double omega_spread = 0.0; ///< max - min over the members (Ry); 0 if exact + /// G[k][l], symmetric, each a (nat, 3) force matrix + std::vector> g; + int dim() const { return static_cast(states.size()); } +}; + +/// Evaluate the forces of a batch of Z-window vectors: (vectors, omega, label) -> forces. +/// The caller owns the Z-vector solver, which is the only solver-side ingredient left. +using MplEval = std::function(const ct::Tensor&, const std::vector&, int)>; + +/// @brief Assemble the gradient matrix of one multiplet from its diagonal forces. +/// +/// Wraps the polarization identity of `grad_degen.h`: normalize the pairs, evaluate them in +/// one batch, and combine with the diagonal. +/// @param xz the multiplet's members widened into the Z window, one block each +/// @param omega their excitation energies, aligned with `states` +/// @param diag their per-state forces, i.e. the diagonal of the matrix +/// @param eval evaluates the forces of arbitrary vectors in the same window +template +MplLvc build_mpl(const ct::Tensor& xz, const std::vector& omega, + const std::vector& diag, int nloc, int ispin, + const std::vector& states, const UnitCell& ucell, const MplEval& eval, std::ofstream& log); + +/// Force of the steepest-descending branch of a multiplet, plus its mixing. +struct JtForce +{ + ModuleBase::matrix force; + std::vector mixing; +}; + +/// @brief Descend the Jahn-Teller branch: find the direction, log the split, return its force. +JtForce eval_jt_force(const std::vector>& g, std::ostream& log); + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_MPL_H From c077e9a9d12b8f363fa892883dbe1fab4c6f886b Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 15:33:14 +0800 Subject: [PATCH 09/26] refactor(lr): drop the unused set_gint declaration The member had no definition and no caller; the GintInfo hand-off both paths use is ModuleGint::Gint::set_gint_info. --- source/source_esolver/esolver_lr.h | 1 - 1 file changed, 1 deletion(-) diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 550a32d254..413328ad6e 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -183,7 +183,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP std::vector spin_types; std::unique_ptr gint_info_ = nullptr; - void set_gint(); /// @brief variables for parallel distribution of KS orbitals Parallel_Blkcyclic paraC_; From c61bef02d12f6116dc0e23c0117ac242adc52fd9 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 15:34:28 +0800 Subject: [PATCH 10/26] chore(lr): drop includes no longer used after the module split cal_edm, Parallel_Reduce, and state_track are now pulled in only where they are actually used. --- source/source_esolver/esolver_lr.cpp | 3 --- source/source_esolver/esolver_lr.h | 1 - 2 files changed, 4 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index 2397c7433d..e262c58d49 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -24,10 +24,8 @@ #include #include #include -#include "source_base/parallel_reduce.h" #include "source_estate/module_dm/dm_from_psi.h" #include "source_io/module_output/output_log.h" -#include "source_lcao/module_lr/cal_edm.h" #include "source_lcao/module_lr/grad_degen.h" #include "source_lcao/module_lr/gradient_inputs.h" #include "source_lcao/module_lr/gradient_output.h" @@ -35,7 +33,6 @@ #include "source_lcao/module_lr/lr_dm.h" #include "source_lcao/module_lr/lr_force.h" #include "source_base/timer.h" -#include #include "source_lcao/module_lr/init_helpers.h" #include "source_base/module_external/scalapack_connector.h" #include "source_basis/module_pw/pw_basis_big.h" diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 413328ad6e..e0b12a5f5f 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -21,7 +21,6 @@ #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" #include "source_lcao/module_lr/lr_mpl.h" #include "source_lcao/module_lr/lr_relax.h" -#include "source_lcao/module_lr/state_track.h" #ifdef __EXX // #include #include "source_hamilt/module_xc/exx_info.h" // for Exx_Info value member From c3fdbadd49943a9139ef953fcacba9aec3187fa8 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 15:35:41 +0800 Subject: [PATCH 11/26] chore(lr): remove dead wrappers and accessors Drop the share_exx_lri specialisations (call LR::make_lr_exx directly), the unused GsPot::pot accessor and MplLvc::dim. --- source/source_esolver/esolver_lr.cpp | 31 ++----------------- source/source_esolver/esolver_lr.h | 4 --- source/source_lcao/module_lr/lr_mpl.h | 1 - .../module_lr/potentials/lr_gs_pot.cpp | 5 --- .../module_lr/potentials/lr_gs_pot.h | 1 - 5 files changed, 2 insertions(+), 40 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index e262c58d49..beca07db34 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -1042,33 +1042,6 @@ void warn_if_kernel_differs_from_gs( } // namespace #endif -#ifdef __EXX -template <> -void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr> &exx_ks) -{ - ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); - this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); -} -template <> -void ModuleESolver::ESolver_LR>::share_exx_lri( - std::shared_ptr>> &exx_ks) -{ - ModuleBase::TITLE("ESolver_LR", "share_exx_lri"); - this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); -} -template <> -void ModuleESolver::ESolver_LR>::share_exx_lri(std::shared_ptr> &exx_ks) -{ - this->exx_lri = LR::make_lr_exx>(exx_ks, *this->ucell_, this->kv); -} -template <> -void ModuleESolver::ESolver_LR::share_exx_lri(std::shared_ptr>> &exx_ks) -{ - this->exx_lri = LR::make_lr_exx(exx_ks, *this->ucell_, this->kv); -} -#endif - - template void ModuleESolver::ESolver_LR::before_all_runners(BaseCell &basecell, const Input_para &inp) { @@ -1304,11 +1277,11 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) } else if (ks_sol.exx_nao.exd) { - this->share_exx_lri(ks_sol.exx_nao.exd->exx_ptr); + this->exx_lri = LR::make_lr_exx(ks_sol.exx_nao.exd->exx_ptr, ucell, this->kv); } else if (ks_sol.exx_nao.exc) { - this->share_exx_lri(ks_sol.exx_nao.exc->exx_ptr); + this->exx_lri = LR::make_lr_exx(ks_sol.exx_nao.exc->exx_ptr, ucell, this->kv); } } #endif diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index e0b12a5f5f..cdf91b42d9 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -313,10 +313,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP #ifdef __EXX /// Tdata of Exx_LRI is same as T, for the reason, see operator_lr_exx.h std::shared_ptr> exx_lri = nullptr; - /// share the ground-state solver's Exx_LRI. It is shared, not stolen: the KS solver - /// keeps using it on the next ionic step. - void share_exx_lri(std::shared_ptr> &); - void share_exx_lri(std::shared_ptr>> &); Exx_Info exx_info; #endif }; diff --git a/source/source_lcao/module_lr/lr_mpl.h b/source/source_lcao/module_lr/lr_mpl.h index b6bf6eadc3..833f760c5f 100644 --- a/source/source_lcao/module_lr/lr_mpl.h +++ b/source/source_lcao/module_lr/lr_mpl.h @@ -20,7 +20,6 @@ struct MplLvc double omega_spread = 0.0; ///< max - min over the members (Ry); 0 if exact /// G[k][l], symmetric, each a (nat, 3) force matrix std::vector> g; - int dim() const { return static_cast(states.size()); } }; /// Evaluate the forces of a batch of Z-window vectors: (vectors, omega, label) -> forces. diff --git a/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp b/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp index c87be4662a..834308d564 100644 --- a/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp +++ b/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp @@ -60,11 +60,6 @@ void GsPot::refresh(const Input_para& inp, const std::string& xc_kernel, const U } } -elecstate::Potential* GsPot::pot() const -{ - return pot_.get(); -} - elecstate::Potential* GsPot::pot_hartree() const { return pot_hartree_.get(); diff --git a/source/source_lcao/module_lr/potentials/lr_gs_pot.h b/source/source_lcao/module_lr/potentials/lr_gs_pot.h index bd2c9df314..171feede25 100644 --- a/source/source_lcao/module_lr/potentials/lr_gs_pot.h +++ b/source/source_lcao/module_lr/potentials/lr_gs_pot.h @@ -39,7 +39,6 @@ class GsPot Structure_Factor& sf, pseudopot_cell_vl& vloc, surchem& solvent, bool refresh_sfac, bool has_float_data); - elecstate::Potential* pot() const; elecstate::Potential* pot_hartree() const; private: From 38a8d60d3fed1750d98cad7f086353ccc2a60b8e Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 16:46:30 +0800 Subject: [PATCH 12/26] refactor(lr): move amplitude setup, wfc reading and group padding into module_lr Add LR::setup_x, LR::read_gs_wfc and LR::pad_group; drop the set_parallel_orbitals_band wrapper in favour of LR::set_band_layout. --- source/source_esolver/esolver_lr.cpp | 92 +++++++------------------- source/source_esolver/esolver_lr.h | 3 - source/source_lcao/module_lr/lr_amp.h | 22 ++++++ source/source_lcao/module_lr/lr_gs.cpp | 72 ++++++++++++++++++++ source/source_lcao/module_lr/lr_gs.h | 32 +++++++++ 5 files changed, 150 insertions(+), 71 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index beca07db34..f892feba79 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -467,66 +467,30 @@ void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) // LR orbital distributions, excitation amplitudes, and ground-state file input. -template -void ModuleESolver::ESolver_LR::set_parallel_orbitals_band(Parallel_Orbitals &pmat, const int nbands_in) -{ - LR::set_band_layout(pmat, this->nbasis, nbands_in, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); -} - template void ModuleESolver::ESolver_LR::setup_eigenvectors_X() { ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); - LR::AmpLayout layout = LR::make_amp_layout(this->paraC_, this->nocc, this->nvirt, this->nk, this->openshell); - this->paraX_ = std::move(layout.para_x); - this->nloc_per_state = layout.nloc; - - this->X.resize(this->openshell ? 1 : this->nspin, LR_Util::newTensor({this->nstates, this->nloc_per_state})); - for (container::Tensor& x : this->X) - { - x.zero(); - } - - // if spectrum-only, read the LR-eigenstates from file and return - if (this->inp_->lr_solver != "spectrum") - { - LR::set_x_init(this->X, this->eig_ks, this->nocc, this->nvirt, this->npairs, this->paraX_, this->nstates, - this->nloc_per_state, this->nk, this->openshell, this->ofs_running_); - } + LR::XAmp amp = LR::setup_x(this->paraC_, this->nocc, this->nvirt, this->npairs, this->eig_ks, this->nstates, + this->nk, this->nspin, this->openshell, this->inp_->lr_solver == "spectrum", + this->ofs_running_); + this->X = std::move(amp.x); + this->paraX_ = std::move(amp.para_x); + this->nloc_per_state = amp.nloc; } template void ModuleESolver::ESolver_LR::read_ks_wfc() { assert(this->psi_ks != nullptr); - this->eig_ks.create(this->kv.get_nks(), this->nbands); - this->wg_ks.create(this->kv.get_nks(), this->nbands); - if (this->inp_->ri_hartree_benchmark == "aims") // for aims benchmark - { - LR::read_wfc_aims(*this->psi_ks, this->eig_ks, this->in_dir, this->nocc_in, this->nvirt_in, this->nbands, - this->nbasis); - } - else if (!LR::read_wfc_win(this->in_dir, this->paraMat_, *this->psi_ks, this->eig_ks, this->wg_ks, this->kv, - this->inp_->nspin, this->inp_->init_wfc_file_format == "binary", - /*skip_bands=*/this->nocc_max - this->nocc_in)) - { - ModuleBase::WARNING_QUIT("ESolver_LR", "read ground-state wavefunction failed."); - } - - if (this->inp_->cal_force) - { // allocate psi_ks_all and eig_ks_all to read all the bands - this->psi_ks_all_own_.reset(new psi::Psi( - this->kv.get_nks(), paraMat_all_.ncol_bands, paraMat_all_.para_2d().nrloc(), this->kv.ngk, true)); - this->psi_ks_all_ = this->psi_ks_all_own_.get(); - this->eig_ks_all.create(this->kv.get_nks(), this->inp_->nbands); - this->wg_ks_all.create(this->kv.get_nks(), this->inp_->nbands); - if (!LR::read_wfc_all(this->in_dir, paraMat_all_, *this->psi_ks_all_, this->eig_ks_all, this->wg_ks_all, - this->kv, this->inp_->nspin, this->inp_->init_wfc_file_format == "binary")) - { - ModuleBase::WARNING_QUIT("ESolver_LR", "read all ground-state wavefunctions for force calculation failed."); - } - this->ofs_running_ << " Read in all the KS wavefunctions for force calculation. " << std::endl; - } + LR::GsWfc wfc = LR::read_gs_wfc(*this->psi_ks, this->eig_ks, this->wg_ks, this->paraMat_, this->paraMat_all_, + this->in_dir, *this->inp_, this->nocc_in, this->nvirt_in, this->nocc_max, + this->nbands, this->nbasis, this->kv, this->inp_->cal_force, + this->ofs_running_); + this->psi_ks_all_own_ = std::move(wfc.all_own); + this->psi_ks_all_ = wfc.all; + this->eig_ks_all = std::move(wfc.eig_all); + this->wg_ks_all = std::move(wfc.wg_all); } template @@ -929,20 +893,8 @@ void ModuleESolver::ESolver_LR::cal_stress(BaseCell &basecell, ModuleBase template ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, const std::vector &group) const { - const int d = static_cast(group.size()); - const int nloc_g = this->nloc_per_state_z_; - ct::Tensor Xz = LR_Util::newTensor({d, nloc_g}); - Xz.zero(); - // One at a time rather than as a range: `group` is sorted, but nothing guarantees its members - // are contiguous in the state list. - for (int k = 0; k < d; ++k) - { - const ct::Tensor one = this->pad_X_to_z_(ispin, group[k], 1); - std::copy( - one.template data(), one.template data() + nloc_g, - Xz.template data() + static_cast(k) * nloc_g); - } - return Xz; + return LR::pad_group(this->X, this->openshell, this->paraX_, this->paraX_z_, this->nocc, this->nvirt, this->nk, + this->nloc_per_state, this->nloc_per_state_z_, ispin, group); } template @@ -1131,7 +1083,8 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons ks_sol.pv.para_2d().ictxt() #endif ); - this->set_parallel_orbitals_band(this->paraMat_, this->nbands); + LR::set_band_layout(this->paraMat_, this->nbasis, this->nbands, *this->ucell_, + this->inp_->ri_hartree_benchmark == "aims"); if (this->inp_->cal_force) { LR_Util::setup_2d_division( @@ -1141,7 +1094,8 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons ks_sol.pv.para_2d().ictxt() #endif ); - this->set_parallel_orbitals_band(this->paraMat_all_, this->inp_->nbands); + LR::set_band_layout(this->paraMat_all_, this->nbasis, this->inp_->nbands, *this->ucell_, + this->inp_->ri_hartree_benchmark == "aims"); } this->paraMat_.atom_begin_row = ks_sol.pv.atom_begin_row; @@ -1350,11 +1304,13 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell this->set_dim(); // setup 2d-block distribution for AO-matrix and KS wfc LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); - this->set_parallel_orbitals_band(this->paraMat_, this->nbands); + LR::set_band_layout(this->paraMat_, this->nbasis, this->nbands, *this->ucell_, + this->inp_->ri_hartree_benchmark == "aims"); if (this->inp_->cal_force) { LR_Util::setup_2d_division(this->paraMat_all_.para_2d(), 1, this->nbasis, this->nbasis); - this->set_parallel_orbitals_band(this->paraMat_all_, this->inp_->nbands); + LR::set_band_layout(this->paraMat_all_, this->nbasis, this->inp_->nbands, *this->ucell_, + this->inp_->ri_hartree_benchmark == "aims"); } // read the ground state info diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index cdf91b42d9..cac483a0b9 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -233,9 +233,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// reset nocc, nvirt, npairs after read ground-state wavefunction when nspin=2 void reset_dim_spin(); - /// setup Parallel_Orbitals info. beyond Parallel_Blkcyclic - void set_parallel_orbitals_band(Parallel_Orbitals &p, const int nbands_in); - ///========================== for gradient calculation ========================= void init_pot_groundstate(const Charge &chg_gs); /// Solve the Z-vector equation for `nst` independent blocks of `Xz`. diff --git a/source/source_lcao/module_lr/lr_amp.h b/source/source_lcao/module_lr/lr_amp.h index 0d491e8927..6c5508f558 100644 --- a/source/source_lcao/module_lr/lr_amp.h +++ b/source/source_lcao/module_lr/lr_amp.h @@ -182,5 +182,27 @@ ct::Tensor pad_amplitudes(const std::vector& X, const bool openshell return Xz; } +template +ct::Tensor pad_group(const std::vector& X, const bool openshell, + const std::vector& px, const std::vector& px_z, + const std::vector& nocc, const std::vector& nvirt, + const int nk, const int nloc, const int nloc_z, + const int ispin, const std::vector& group) +{ + const int d = static_cast(group.size()); + ct::Tensor Xz = LR_Util::newTensor({ d, nloc_z }); + Xz.zero(); + // One at a time rather than as a range: `group` is sorted, but nothing guarantees its members + // are contiguous in the state list. + for (int k = 0; k < d; ++k) + { + const ct::Tensor one = pad_amplitudes(X, openshell, px, px_z, nocc, nvirt, nk, nloc, nloc_z, ispin, + group[k], 1); + std::copy(one.template data(), one.template data() + nloc_z, + Xz.template data() + static_cast(k) * nloc_z); + } + return Xz; +} + } #endif diff --git a/source/source_lcao/module_lr/lr_gs.cpp b/source/source_lcao/module_lr/lr_gs.cpp index 7a057c58b3..096691a9e0 100644 --- a/source/source_lcao/module_lr/lr_gs.cpp +++ b/source/source_lcao/module_lr/lr_gs.cpp @@ -270,6 +270,62 @@ ZWin build_z_win(psi::Psi* psi_all, const ModuleBase::matrix& eig_all, con return z; } +template +XAmp setup_x(const Parallel_Blkcyclic& para_c, const std::vector& nocc, const std::vector& nvirt, + const std::vector& npairs, const ModuleBase::matrix& eig_ks, const int states, const int nk, + const int nspin, const bool openshell, const bool spectrum_only, std::ostream& log) +{ + AmpLayout layout = make_amp_layout(para_c, nocc, nvirt, nk, openshell); + XAmp out; + out.para_x = std::move(layout.para_x); + out.nloc = layout.nloc; + out.x.resize(openshell ? 1 : nspin, LR_Util::newTensor({states, out.nloc})); + for (auto& x : out.x) + { + x.zero(); + } + if (!spectrum_only) + { + set_x_init(out.x, eig_ks, nocc, nvirt, npairs, out.para_x, states, out.nloc, nk, openshell, log); + } + return out; +} + +template +GsWfc read_gs_wfc(psi::Psi& psi, ModuleBase::matrix& eig, ModuleBase::matrix& wg, + const Parallel_Orbitals& pmat, const Parallel_Orbitals& pmat_all, const std::string& in_dir, + const Input_para& inp, const int nocc_in, const int nvirt_in, const int nocc_max, + const int nbands, const int nbasis, const K_Vectors& kv, const bool cal_force, + std::ostream& log) +{ + eig.create(kv.get_nks(), nbands); + wg.create(kv.get_nks(), nbands); + if (inp.ri_hartree_benchmark == "aims") // for aims benchmark + { + read_wfc_aims(psi, eig, in_dir, nocc_in, nvirt_in, nbands, nbasis); + } + else if (!read_wfc_win(in_dir, pmat, psi, eig, wg, kv, inp.nspin, inp.init_wfc_file_format == "binary", + nocc_max - nocc_in)) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "read ground-state wavefunction failed."); + } + GsWfc out; + if (cal_force) + { // allocate the full-band copy needed by the force path + out.all_own.reset(new psi::Psi(kv.get_nks(), pmat_all.ncol_bands, pmat_all.para_2d().nrloc(), kv.ngk, true)); + out.all = out.all_own.get(); + out.eig_all.create(kv.get_nks(), inp.nbands); + out.wg_all.create(kv.get_nks(), inp.nbands); + if (!read_wfc_all(in_dir, pmat_all, *out.all, out.eig_all, out.wg_all, kv, inp.nspin, + inp.init_wfc_file_format == "binary")) + { + ModuleBase::WARNING_QUIT("ESolver_LR", "read all ground-state wavefunctions for force calculation failed."); + } + log << " Read in all the KS wavefunctions for force calculation. " << std::endl; + } + return out; +} + void read_gs_chg(const std::string& in_dir, const Input_para& inp, int nspin, const UnitCell& ucell, Parallel_Grid& pgrid, ModulePW::PW_Basis* pw_rho, Charge& chg, int rank, std::ostream& log) { @@ -341,4 +397,20 @@ template ZWin> build_z_win>( int, int, int, bool, const K_Vectors&, const Parallel_Blkcyclic&, const Parallel_Orbitals&, const int*, bool, bool, std::ostream&); +template XAmp setup_x(const Parallel_Blkcyclic&, const std::vector&, const std::vector&, + const std::vector&, const ModuleBase::matrix&, int, int, int, bool, bool, + std::ostream&); +template XAmp> setup_x>(const Parallel_Blkcyclic&, const std::vector&, + const std::vector&, const std::vector&, + const ModuleBase::matrix&, int, int, int, bool, bool, + std::ostream&); +template GsWfc read_gs_wfc(psi::Psi&, ModuleBase::matrix&, ModuleBase::matrix&, + const Parallel_Orbitals&, const Parallel_Orbitals&, const std::string&, + const Input_para&, int, int, int, int, int, const K_Vectors&, bool, + std::ostream&); +template GsWfc> read_gs_wfc>( + psi::Psi>&, ModuleBase::matrix&, ModuleBase::matrix&, const Parallel_Orbitals&, + const Parallel_Orbitals&, const std::string&, const Input_para&, int, int, int, int, int, const K_Vectors&, bool, + std::ostream&); + } // namespace LR diff --git a/source/source_lcao/module_lr/lr_gs.h b/source/source_lcao/module_lr/lr_gs.h index 1e4a34c011..6bb3bd6c1c 100644 --- a/source/source_lcao/module_lr/lr_gs.h +++ b/source/source_lcao/module_lr/lr_gs.h @@ -42,6 +42,38 @@ void set_x_init(std::vector& X, const ModuleBase::matrix& eig_ks, co const std::vector& para_x, int nstates, int nloc, int nk, bool openshell, std::ostream& log); +/// The excitation amplitudes and their distribution, as allocated by `setup_x`. +template +struct XAmp +{ + std::vector x; + std::vector para_x; + int nloc = 0; +}; + +/// Allocate the amplitude distribution and fill the initial guess (skipped for `spectrum_only`). +template +XAmp setup_x(const Parallel_Blkcyclic& para_c, const std::vector& nocc, const std::vector& nvirt, + const std::vector& npairs, const ModuleBase::matrix& eig_ks, int states, int nk, int nspin, + bool openshell, bool spectrum_only, std::ostream& log); + +/// Ground-state wavefunctions read for the LR run. +template +struct GsWfc +{ + std::unique_ptr> all_own; ///< owned buffer of the full-band copy + psi::Psi* all = nullptr; ///< full-band view (null when forces are off) + ModuleBase::matrix eig_all; ///< [nks, nbands] eigenvalues of the full-band copy + ModuleBase::matrix wg_all; ///< [nks, nbands] weights of the full-band copy +}; + +/// Read the KS window, plus the full-band copy when `cal_force` is set. +template +GsWfc read_gs_wfc(psi::Psi& psi, ModuleBase::matrix& eig, ModuleBase::matrix& wg, + const Parallel_Orbitals& pmat, const Parallel_Orbitals& pmat_all, const std::string& in_dir, + const Input_para& inp, int nocc_in, int nvirt_in, int nocc_max, int nbands, int nbasis, + const K_Vectors& kv, bool cal_force, std::ostream& log); + /// AIMS benchmark: eigenvalues from band_out and eigenvectors from KS_eigenvectors.out. template void read_wfc_aims(psi::Psi& psi, ModuleBase::matrix& eig, const std::string& in_dir, int nocc_in, int nvirt_in, From de6dc0b4754be8df587eed9a44d47d4fad8bd9fb Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 16:51:57 +0800 Subject: [PATCH 13/26] refactor(lr): move the Z-equation force path into module_lr Add LR::GsForceCtx, LR::solve_zeq, LR::force_xz and LR::force_xz_os; the solver now only fills the context and keeps the timers. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr.cpp | 65 +++------------- source/source_esolver/esolver_lr.h | 4 +- source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/lr_zeq.cpp | 84 +++++++++++++++++++++ source/source_lcao/module_lr/lr_zeq.h | 47 ++++++++++++ 6 files changed, 147 insertions(+), 55 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_zeq.cpp create mode 100644 source/source_lcao/module_lr/lr_zeq.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 90df9f8758..88742087e3 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1199,6 +1199,7 @@ OBJS_TENSOR=tensor.o\ lr_dm.o\ lr_relax.o\ lr_mpl.o\ + lr_zeq.o\ lr_gs_pot.o\ esolver_lr.o\ diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index f892feba79..c07bfe947c 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -537,29 +537,16 @@ 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) +LR::GsForceCtx ModuleESolver::ESolver_LR::gs_force_ctx_() const { - ModuleBase::TITLE("ESolver_LR", "cal_force"); - ModuleBase::timer::start("ESolver_LR", "solve_zvector_eqation"); - // `Z_vector_equation` treats X and Z as `nst` independent blocks of `nloc_per_state_z_`, - // and the blocks need not be eigenvectors of the Casida equation in the order the - // diagonalizer returned them -- `build_mpl_` feeds it linear combinations. - // X arrives already widened into the Z window (`Xz`), which spans every virtual band the - // ground state produced rather than the `nvirt` window X was solved in -- the Brillouin - // condition the Z-vector enforces holds in EVERY occupied-virtual rotation. The padded - // entries are zero, so every X-derived quantity (D^X, T) is unchanged; only the space Z is - // solved in grows. Both the closed- and the open-shell path go through here. - ct::Tensor Z = LR_Util::newTensor({nst, this->nloc_per_state_z_}); - // construct and solve the Z-vector equation - const LR::GradientInputs inputs = this->gradient_inputs_(); - const T *const x_data = Xz.template data(); - T *const z_data = Z.template data(); - 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); - ModuleBase::timer::end("ESolver_LR", "solve_zvector_eqation"); - return Z; + // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight + // from the ground-state solver's own `psi`), but per `this->paraMat_all_` on the + // read-from-file path, where it was allocated with that descriptor's own sizes. + const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; + const LR::ForceSettings settings{ + this->nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; + return {*this->psi_ks_all_, this->wg_ks_all, *pv_all, *this->pw_rho, *this->pw_rhod, this->vloc(), this->sfac(), + this->tcb(), settings, this->openshell, this->inp_->lr_grad_solver, this->in_dir}; } template @@ -613,22 +600,7 @@ std::vector ModuleESolver::ESolver_LR::cal_force_Xz( const int label_begin) { 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::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( - *this->ucell_, this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), - this->gd(), this->tcb(), force_settings, this->ofs_running_ -#ifdef __EXX - , - 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::force_xz(this->gradient_inputs_(), this->gs_force_ctx_(), ispin, Xz, omega, label_begin); ModuleBase::timer::end("ESolver_LR", "cal_force_Xz"); return forces; } @@ -728,22 +700,7 @@ std::vector ModuleESolver::ESolver_LR::cal_force_open const ct::Tensor &Xz, const std::vector &omega, const int label_begin) { 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::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( - *this->ucell_, this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), - this->gd(), this->tcb(), force_settings, this->ofs_running_ -#ifdef __EXX - , - 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::force_xz_os(this->gradient_inputs_(), this->gs_force_ctx_(), Xz, omega, label_begin); ModuleBase::timer::end("ESolver_LR", "cal_force_openshell_Xz"); return forces; } diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index cac483a0b9..5613ea12ef 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -20,6 +20,7 @@ #include "source_lcao/module_lr/potentials/lr_gs_pot.h" #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" #include "source_lcao/module_lr/lr_mpl.h" +#include "source_lcao/module_lr/lr_zeq.h" #include "source_lcao/module_lr/lr_relax.h" #ifdef __EXX // #include @@ -236,7 +237,8 @@ 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); + /// Ground-state ingredients of the force path, filled once per call. + LR::GsForceCtx gs_force_ctx_() const; /// 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_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index 112b98c8e1..b25785d86a 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -31,6 +31,7 @@ if(ENABLE_LCAO) lr_dm.cpp lr_relax.cpp lr_mpl.cpp + lr_zeq.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/lr_zeq.cpp b/source/source_lcao/module_lr/lr_zeq.cpp new file mode 100644 index 0000000000..7426eb0e13 --- /dev/null +++ b/source/source_lcao/module_lr/lr_zeq.cpp @@ -0,0 +1,84 @@ +#include "source_lcao/module_lr/lr_zeq.h" + +#include "source_lcao/module_lr/lr_dm.h" +#include "source_lcao/module_lr/zeq_solver.h" + +#include + +namespace LR +{ + +template +ct::Tensor solve_zeq(const GradientInputs& in, const ct::Tensor& xz, const int ispin, const int nst, + const bool openshell, const std::string& grad_solver, const std::string& in_dir) +{ + ct::Tensor z = LR_Util::newTensor({nst, in.nloc}); + std::weak_ptr pot_weak = in.pot[ispin]; + Z_vector_equation(in, xz.template data(), z.template data(), nst, pot_weak, in.spin_types[ispin], in_dir, + openshell, grad_solver); + return z; +} + +namespace +{ +/// Shared by both shells: the ground-state density matrix and the force terms. +template +module_dm::DensityMatrix gs_dm_for(const GradientInputs& in, const GsForceCtx& gs) +{ + return make_gs_dm(gs.psi_all, gs.wg_all, gs.pv_all, in.pmat, in.ucell, in.gd, in.orb_cutoff, in.nspin, + in.kv.kvec_d, in.nk); +} +} // namespace + +template +std::vector force_xz(const GradientInputs& in, const GsForceCtx& gs, const int ispin, + const ct::Tensor& xz, const std::vector& omega, const int label_begin) +{ + const int nst = static_cast(omega.size()); + const ct::Tensor z = solve_zeq(in, xz, ispin, nst, gs.openshell, gs.grad_solver, gs.in_dir); + const auto dm_gs = gs_dm_for(in, gs); + LR_Force force_terms(in.ucell, in.kv.kvec_d, in.pmat, gs.rhod, gs.rho, gs.vloc, gs.sfac, in.gd, gs.tcb, + gs.settings, in.ofs +#ifdef __EXX + , + in.exx_lri, in.hybrid_alpha +#endif + ); + return evaluate_closed_shell_force(in, force_terms, dm_gs, xz, z, omega, label_begin, ispin); +} + +template +std::vector force_xz_os(const GradientInputs& in, const GsForceCtx& gs, + const ct::Tensor& xz, const std::vector& omega, + const int label_begin) +{ + const int nst = static_cast(omega.size()); + const ct::Tensor z = solve_zeq(in, xz, 0, nst, gs.openshell, gs.grad_solver, gs.in_dir); + const auto dm_gs = gs_dm_for(in, gs); + LR_Force force_terms(in.ucell, in.kv.kvec_d, in.pmat, gs.rhod, gs.rho, gs.vloc, gs.sfac, in.gd, gs.tcb, + gs.settings, in.ofs +#ifdef __EXX + , + in.exx_lri, in.hybrid_alpha +#endif + ); + return evaluate_open_shell_force(in, force_terms, dm_gs, xz, z, omega, label_begin); +} + +template ct::Tensor solve_zeq(const GradientInputs&, const ct::Tensor&, int, int, bool, + const std::string&, const std::string&); +template ct::Tensor solve_zeq>(const GradientInputs>&, const ct::Tensor&, + int, int, bool, const std::string&, const std::string&); +template std::vector force_xz(const GradientInputs&, const GsForceCtx&, + int, const ct::Tensor&, const std::vector&, int); +template std::vector force_xz>(const GradientInputs>&, + const GsForceCtx>&, int, + const ct::Tensor&, const std::vector&, + int); +template std::vector force_xz_os(const GradientInputs&, const GsForceCtx&, + const ct::Tensor&, const std::vector&, int); +template std::vector force_xz_os>( + const GradientInputs>&, const GsForceCtx>&, const ct::Tensor&, + const std::vector&, int); + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_zeq.h b/source/source_lcao/module_lr/lr_zeq.h new file mode 100644 index 0000000000..b6f263955d --- /dev/null +++ b/source/source_lcao/module_lr/lr_zeq.h @@ -0,0 +1,47 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_ZEQ_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_ZEQ_H + +#include "source_lcao/module_lr/gradient_inputs.h" + +#include +#include + +namespace LR +{ +/// The ground-state side of a force evaluation: density-matrix ingredients and force terms. +/// Kept separate from `GradientInputs`, which describes the Z-window side. +template +struct GsForceCtx +{ + const psi::Psi& psi_all; + const ModuleBase::matrix& wg_all; + const Parallel_Orbitals& pv_all; + const ModulePW::PW_Basis& rho; + const ModulePW::PW_Basis& rhod; + const pseudopot_cell_vl& vloc; + Structure_Factor& sfac; + const TwoCenterBundle& tcb; + ForceSettings settings; + bool openshell; + const std::string& grad_solver; + const std::string& in_dir; +}; + +/// Solve the Z-vector equation for `nst` independent blocks of `xz`. +template +ct::Tensor solve_zeq(const GradientInputs& in, const ct::Tensor& xz, int ispin, int nst, bool openshell, + const std::string& grad_solver, const std::string& in_dir); + +/// Forces of `nst` closed-shell states widened into the Z window. +template +std::vector force_xz(const GradientInputs& in, const GsForceCtx& gs, int ispin, + const ct::Tensor& xz, const std::vector& omega, int label_begin); + +/// Open-shell counterpart: both spin channels live in one vector, so the channel is always 0. +template +std::vector force_xz_os(const GradientInputs& in, const GsForceCtx& gs, const ct::Tensor& xz, + const std::vector& omega, int label_begin); + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_ZEQ_H From 2aa0b08215b2f8eee007331264d820713a0c1a0e Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 17:49:00 +0800 Subject: [PATCH 14/26] refactor(lr): gather LR solver data into LR::Core Introduce LR::Amp, LR::PotSet, LR::RelaxRun and LR::Core in module_lr so the amplitudes, Z window, potentials and relaxation state stop being members of ESolver_LR. All accesses go through lr_..; the functions still live in the esolver for now. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr.cpp | 312 +++++++----------- source/source_esolver/esolver_lr.h | 64 +--- source/source_esolver/esolver_lr_lcao_bse.cpp | 78 ++--- source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/lr_core.h | 58 ++++ source/source_lcao/module_lr/lr_sforce.cpp | 131 ++++++++ source/source_lcao/module_lr/lr_sforce.h | 53 +++ 8 files changed, 412 insertions(+), 286 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_core.h create mode 100644 source/source_lcao/module_lr/lr_sforce.cpp create mode 100644 source/source_lcao/module_lr/lr_sforce.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 88742087e3..94f6e014d4 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1200,6 +1200,7 @@ OBJS_TENSOR=tensor.o\ lr_relax.o\ lr_mpl.o\ lr_zeq.o\ + lr_sforce.o\ lr_gs_pot.o\ esolver_lr.o\ diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index c07bfe947c..ce9e67b46b 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -88,7 +88,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste ModuleBase::WARNING_QUIT( "ESolver_LR", "Excited-state relaxation requires a converged ground-state SCF; ionic step rejected"); } - this->etot_gs_ = this->ks_->cal_energy(); + this->lr_.relax.etot_gs = this->ks_->cal_energy(); if (!this->ks_initialized_) { this->initialize_from_ks_(ucell, *this->inp_); @@ -106,12 +106,12 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste // set once here rather than inside the solver branches: the open-shell `spectrum` branch used // to leave it empty, and both `after_all_runners` and the gradient index it - this->spin_types = + this->lr_.amp.spin_types = this->openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); // 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->target_.active() ? "_step" + std::to_string(istep) : ""; + const std::string step_suffix = this->lr_.relax.target.active() ? "_step" + std::to_string(istep) : ""; auto efile_out = [this, &step_suffix](const std::string &label) -> std::string { return this->out_dir + "Excitation_Energy_" + label + step_suffix + ".dat"; }; auto vfile_out = [this, &step_suffix](const std::string &label) -> std::string @@ -135,7 +135,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste } assert(nst * dim == LR_Util::write_value(vfile_out(label), prec, v, nst, dim)); }; - std::vector precondition(this->inp_->lr_solver == "lapack" ? 0 : nloc_per_state, 1.0); + std::vector precondition(this->inp_->lr_solver == "lapack" ? 0 : this->lr_.amp.nloc, 1.0); // allocate and initialize A matrix and density matrix if (openshell) { @@ -143,9 +143,9 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste { if (this->inp_->lr_solver != "lapack") { - const int offset_is = is * this->paraX_[0].size(); + const int offset_is = is * this->lr_.amp.para_x[0].size(); OperatorLRDiag pre_op( - this->eig_ks.c + is * nk * (nocc[0] + nvirt[0]), this->paraX_[is], this->nk, this->nocc[is], + this->eig_ks.c + is * nk * (nocc[0] + nvirt[0]), this->lr_.amp.para_x[is], this->nk, this->nocc[is], this->nvirt[is], false); pre_op.act(1, offset_is, 1, precondition.data() + offset_is, precondition.data() + offset_is); } @@ -157,13 +157,13 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste #ifdef __EXX this->exx_lri, this->exx_info.info_global.hybrid_alpha, #endif - this->pot, this->kv, this->paraX_, this->paraC_, this->paraMat_); + this->lr_.pot.pot, this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_); LR::HSolver::solve( - hulr, this->X[0].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, - this->paraX_, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); + hulr, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, nstates, this->nk, this->nocc, this->nvirt, + this->lr_.amp.para_x, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); if (this->inp_->out_wfc_lr) { - write_states("openshell", this->pelec->ekb.c, this->X[0].template data(), nloc_per_state, nstates); + write_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, nstates); } } else @@ -171,10 +171,10 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste if (this->inp_->lr_solver != "lapack") { OperatorLRDiag pre_op( - this->eig_ks.c, this->paraX_[0], this->nk, this->nocc[0], this->nvirt[0], false); - pre_op.act(1, nloc_per_state, 1, precondition.data(), precondition.data()); + this->eig_ks.c, this->lr_.amp.para_x[0], this->nk, this->nocc[0], this->nvirt[0], false); + pre_op.act(1, this->lr_.amp.nloc, 1, precondition.data(), precondition.data()); } - const std::vector &spin_types = this->spin_types; + const std::vector &spin_types = this->lr_.amp.spin_types; for (int is = 0; is < nspin; ++is) { std::cout << " Calculating " << spin_types[is] << " excitations" << std::endl; @@ -184,18 +184,18 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste #ifdef __EXX this->exx_lri, this->exx_info.info_global.hybrid_alpha, #endif - this->pot[is], this->kv, this->paraX_, this->paraC_, this->paraMat_, spin_types[is], this->in_dir, + this->lr_.pot.pot[is], this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, spin_types[is], this->in_dir, this->out_dir, this->inp_->ri_hartree_benchmark, (this->inp_->ri_hartree_benchmark == "aims" ? this->inp_->aims_nbasis : std::vector({}))); LR::HSolver::solve( - hlr, this->X[is].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, - this->paraX_, this->pelec->ekb.c + is * nstates, this->inp_->lr_solver, this->inp_->lr_thr, + hlr, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, nstates, this->nk, this->nocc, this->nvirt, + this->lr_.amp.para_x, this->pelec->ekb.c + is * nstates, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); if (this->inp_->out_wfc_lr) { write_states( - spin_types[is], this->pelec->ekb.c + is * nstates, this->X[is].template data(), - nloc_per_state, nstates); + spin_types[is], this->pelec->ekb.c + is * nstates, this->lr_.amp.x[is].template data(), + this->lr_.amp.nloc, nstates); } } } @@ -225,20 +225,20 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste std::cout << "reading the excitation states from file: \n"; if (openshell) { - read_states("openshell", this->pelec->ekb.c, this->X[0].template data(), nloc_per_state, nstates); + read_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, nstates); } else { - const std::vector &spin_types = this->spin_types; + const std::vector &spin_types = this->lr_.amp.spin_types; for (int is = 0; is < nspin; ++is) { read_states( - spin_types[is], this->pelec->ekb.c + is * nstates, this->X[is].template data(), nloc_per_state, + spin_types[is], this->pelec->ekb.c + is * nstates, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, nstates); } } } - if (this->target_.active()) + if (this->lr_.relax.target.active()) { // Re-select which root to follow BEFORE taking the gradient, so the force belongs to // the same diabatic state as the previous step's. @@ -246,13 +246,13 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste // The LR terms only carry the Omega part of the force; the ground-state part is separate // and comes straight from the KS solver. - this->ks_->cal_force(ucell, this->force_gs_); - this->lr_force_ = this->cal_lr_force_relax_(this->ofs_running_); + this->ks_->cal_force(ucell, this->lr_.relax.force_gs); + this->lr_.relax.lr_force = this->cal_lr_force_relax_(this->ofs_running_); // One line per ionic step with the two halves of the energy and of the gradient. Without // it the relaxation only reports a force, and whether E_gs + Omega actually goes down -- // the thing being minimised -- cannot be read off the log at all. - const double omega = this->target_.omega(this->pelec->ekb.c, this->nstates); + const double omega = this->lr_.relax.target.omega(this->pelec->ekb.c, this->nstates); auto max_abs = [](const ModuleBase::matrix &m) -> double { double v = 0.0; @@ -263,13 +263,13 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste return v; }; this->ofs_running_ << std::setprecision(8) << std::fixed << " EXCITED-STATE RELAX step " << istep - << ": E_gs = " << this->etot_gs_ * ModuleBase::Ry_to_eV + << ": E_gs = " << this->lr_.relax.etot_gs * ModuleBase::Ry_to_eV << " eV, Omega = " << omega * ModuleBase::Ry_to_eV - << " eV, E_exc = " << (this->etot_gs_ + omega) * ModuleBase::Ry_to_eV << " eV" + << " eV, E_exc = " << (this->lr_.relax.etot_gs + omega) * ModuleBase::Ry_to_eV << " eV" << std::setprecision(6) << " | |F_gs|max = " - << max_abs(this->force_gs_) * ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A + << max_abs(this->lr_.relax.force_gs) * ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A << ", |F_Omega|max = " - << max_abs(this->lr_force_) * ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A << " eV/Angstrom" + << max_abs(this->lr_.relax.lr_force) * ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A << " eV/Angstrom" << std::defaultfloat << std::endl; } @@ -293,22 +293,22 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) if (this->inp_->out_chg[0]) { LR_Density lr_density( - *this->ucell_, kv, gd(), *psi_ks, orb_cutoff_, pgrid(), nspin, nocc, nvirt, nbasis, paraX_, paraC_, + *this->ucell_, kv, gd(), *psi_ks, orb_cutoff_, pgrid(), nspin, nocc, nvirt, nbasis, this->lr_.amp.para_x, this->lr_.amp.para_c, paraMat_, openshell, this->inp_->out_chg[1], this->out_dir); if (openshell) { for (int is = 0; is < this->nspin; ++is) { - const T *const amplitudes = this->X[0].template data(); + const T *const amplitudes = this->lr_.amp.x[0].template data(); lr_density.output_eh_density_all_states(amplitudes, is, nstates, this->ofs_running_); } } else { - for (int is = 0; is < this->X.size(); ++is) + for (int is = 0; is < this->lr_.amp.x.size(); ++is) { - const T *const amplitudes = this->X[is].template data(); + const T *const amplitudes = this->lr_.amp.x[is].template data(); lr_density.output_eh_density_all_states(amplitudes, is, nstates, this->ofs_running_); } } @@ -322,7 +322,7 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) { const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; this->velocity_mo = LR_Util::cal_velocity_mo( - *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->paraC_, this->kv, *this->psi_ks, this->nk, + *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->lr_.amp.para_c, this->kv, *this->psi_ks, this->nk, nspin_tmp, this->nbasis, this->nocc, this->nvirt); } std::vector freq; @@ -343,31 +343,31 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) } } // auto spin_types = (nspin == 2 && !openshell) ? std::vector({ "singlet", "triplet" }) : - // std::vector({ "updown" }); for (int is = 0;is < this->X.size() - 1;++is) - for (int is = 0; is < this->X.size(); ++is) + // std::vector({ "updown" }); for (int is = 0;is < this->lr_.amp.x.size() - 1;++is) + for (int is = 0; is < this->lr_.amp.x.size(); ++is) { if (!calculate_spectrum) { const double *const energies = &this->pelec->ekb.c[is * nstates]; - LR_Util::print_excitation_energies(this->ofs_running_, energies, nstates, spin_types[is]); + LR_Util::print_excitation_energies(this->ofs_running_, energies, nstates, this->lr_.amp.spin_types[is]); } else { LR_Spectrum spectrum( nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, this->kv, - spatial_weights, this->gd(), this->orb_cutoff_, this->tcb(), this->paraX_, this->paraC_, this->paraMat_, - &this->pelec->ekb.c[is * nstates], this->eig_ks.c, this->X[is].template data(), nstates, openshell, + spatial_weights, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, + &this->pelec->ekb.c[is * nstates], this->eig_ks.c, this->lr_.amp.x[is].template data(), nstates, openshell, LR_Util::tolower(this->inp_->abs_gauge), this->my_rank_, this->out_dir); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { spectrum.set_vmo(this->velocity_mo.data()); } spectrum.cal_spectrum(); - spectrum.transition_analysis(spin_types[is] + "_tda"); - if (spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum + spectrum.transition_analysis(this->lr_.amp.spin_types[is] + "_tda"); + if (this->lr_.amp.spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum { spectrum.optical_absorption_method1(freq, this->inp_->abs_broadening); - spectrum.write_transition_dipole(this->out_dir + "trans_dipole_" + spin_types[is] + "_tda.dat"); + spectrum.write_transition_dipole(this->out_dir + "trans_dipole_" + this->lr_.amp.spin_types[is] + "_tda.dat"); // =============================================== for test // ==================================================== spectrum.optical_absorption_method2(freq, // this->inp_->abs_broadening); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { // TEST @@ -380,7 +380,7 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) // ==================================================== } } - if (this->inp_->cal_force && !this->target_.active()) + if (this->inp_->cal_force && !this->lr_.relax.target.active()) { this->cal_force_and_grad_matrix_(is, this->ofs_running_); } @@ -447,7 +447,7 @@ void ModuleESolver::ESolver_LR::reset_dim_spin() template void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) { - this->pot.assign(nspin, nullptr); + this->lr_.pot.pot.assign(nspin, nullptr); if (this->inp_->ri_hartree_benchmark != "none") { return; @@ -455,11 +455,11 @@ void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) const auto &grid = pgrid(); auto prepared = LR::prepare_lr_potentials(*this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell); - this->pot = std::move(prepared.pot); + this->lr_.pot.pot = std::move(prepared.pot); if (this->inp_->cal_force) { this->init_pot_groundstate(chg_gs); - this->pot_hxc_gs = LR::prepare_gs_potential( + this->lr_.pot.pot_hxc_gs = LR::prepare_gs_potential( *this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell, prepared); } } @@ -471,12 +471,12 @@ template void ModuleESolver::ESolver_LR::setup_eigenvectors_X() { ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); - LR::XAmp amp = LR::setup_x(this->paraC_, this->nocc, this->nvirt, this->npairs, this->eig_ks, this->nstates, + LR::XAmp amp = LR::setup_x(this->lr_.amp.para_c, this->nocc, this->nvirt, this->npairs, this->eig_ks, this->nstates, this->nk, this->nspin, this->openshell, this->inp_->lr_solver == "spectrum", this->ofs_running_); - this->X = std::move(amp.x); - this->paraX_ = std::move(amp.para_x); - this->nloc_per_state = amp.nloc; + this->lr_.amp.x = std::move(amp.x); + this->lr_.amp.para_x = std::move(amp.para_x); + this->lr_.amp.nloc = amp.nloc; } template @@ -498,16 +498,16 @@ void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) { ModuleBase::TITLE("ESolver_LR", "fill_z_window_"); LR::ZWin z = LR::build_z_win(this->psi_ks_all_, this->eig_ks_all, this->nocc, this->nvirt, this->nocc_max, - this->nbands, this->nbasis, this->nk, this->openshell, this->kv, this->paraC_, + this->nbands, this->nbasis, this->nk, this->openshell, this->kv, this->lr_.amp.para_c, this->paraMat_, desc_src, this->inp_->cal_force, !this->ks_initialized_, this->ofs_running_); - this->psi_ks_z_ = std::move(z.psi); - this->eig_ks_z_ = std::move(z.eig); - this->paraC_z_ = std::move(z.para_c); - this->paraX_z_ = std::move(z.para_x); - this->nvirt_z_ = std::move(z.nvirt); - this->nbands_z_ = z.nbands; - this->nloc_per_state_z_ = z.nloc; + this->lr_.zw.psi = std::move(z.psi); + this->lr_.zw.eig = std::move(z.eig); + this->lr_.zw.para_c = std::move(z.para_c); + this->lr_.zw.para_x = std::move(z.para_x); + this->lr_.zw.nvirt = std::move(z.nvirt); + this->lr_.zw.nbands = z.nbands; + this->lr_.zw.nloc = z.nloc; } template @@ -524,7 +524,7 @@ template void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs) { ModuleBase::TITLE("ESolver_LR", "init_pot_gs"); - this->gs_pot_.refresh(*this->inp_, this->xc_kernel, *this->ucell_, this->pw_rhod, this->pw_rho, pgrid(), chg_gs, + this->lr_.pot.gs_pot.refresh(*this->inp_, this->xc_kernel, *this->ucell_, this->pw_rhod, this->pw_rho, pgrid(), chg_gs, this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); } @@ -532,8 +532,8 @@ template ct::Tensor ModuleESolver::ESolver_LR::pad_X_to_z_(const int ispin, const int istate_begin, const int nst) const { return LR::pad_amplitudes( - this->X, this->openshell, this->paraX_, this->paraX_z_, this->nocc, this->nvirt, this->nk, this->nloc_per_state, - this->nloc_per_state_z_, ispin, istate_begin, nst); + this->lr_.amp.x, this->openshell, this->lr_.amp.para_x, this->lr_.zw.para_x, this->nocc, this->nvirt, this->nk, this->lr_.amp.nloc, + this->lr_.zw.nloc, ispin, istate_begin, nst); } template @@ -549,6 +549,13 @@ LR::GsForceCtx ModuleESolver::ESolver_LR::gs_force_ctx_() const this->tcb(), settings, this->openshell, this->inp_->lr_grad_solver, this->in_dir}; } +template +LR::StateCtx ModuleESolver::ESolver_LR::state_ctx_() const +{ + return {this->lr_.amp.x, this->lr_.amp.para_x, this->lr_.zw.para_x, this->nocc, this->nvirt, this->nk, this->lr_.amp.nloc, + this->lr_.zw.nloc, this->nstates, this->openshell, this->pelec->ekb.c}; +} + template std::vector ModuleESolver::ESolver_LR::cal_force(const int ispin, const int istate_only) { @@ -556,35 +563,20 @@ std::vector ModuleESolver::ESolver_LR::cal_force(cons { this->test_force(); } - if (this->openshell) - { - return this->cal_force_openshell(istate_only); - } - - const int ist_begin = (istate_only < 0) ? 0 : istate_only; - const int nst = (istate_only < 0) ? this->nstates : 1; - // The whole closed-shell gradient runs in the Z window (every virtual band the ground state - // produced), not the `nvirt` window X was solved in: only there does the Z-vector enforce - // the Brillouin condition in every occupied-virtual rotation. X is zero-padded into it, so - // D^X and T come out bit-identical -- and Omega is untouched, so an existing finite-difference - // reference stays valid. See `fill_z_window_`. - const ct::Tensor Xz = this->pad_X_to_z_(ispin, ist_begin, nst); - std::vector omega(nst); - for (int i = 0; i < nst; ++i) - { - omega[i] = this->pelec->ekb.c[ispin * this->nstates + ist_begin + i]; - } - return this->cal_force_Xz(ispin, Xz, omega, ist_begin); + return this->openshell + ? LR::state_forces_os(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), istate_only) + : LR::state_forces(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), ispin, + istate_only); } template LR::GradientInputs ModuleESolver::ESolver_LR::gradient_inputs_() const { - return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->paraMat_, this->paraC_z_, this->paraX_z_, - *this->psi_ks_z_, this->eig_ks_z_, this->nocc, this->nvirt_z_, this->nspin, this->nk, this->nbasis, - this->nloc_per_state_z_, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, - this->inp_->test_force, this->target_.active(), this->out_dir, this->my_rank_, this->spin_types, this->pot, - this->pot_hxc_gs, this->ofs_running_ + return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->paraMat_, this->lr_.zw.para_c, this->lr_.zw.para_x, + *this->lr_.zw.psi, this->lr_.zw.eig, this->nocc, this->lr_.zw.nvirt, this->nspin, this->nk, this->nbasis, + this->lr_.zw.nloc, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, + this->inp_->test_force, this->lr_.relax.target.active(), this->out_dir, this->my_rank_, this->lr_.amp.spin_types, this->lr_.pot.pot, + this->lr_.pot.pot_hxc_gs, this->ofs_running_ #ifdef __EXX , this->exx_lri, this->exx_info.info_global.hybrid_alpha @@ -615,84 +607,20 @@ void ModuleESolver::ESolver_LR::cal_force_and_grad_matrix_(const int ispi } // Rebuilt from scratch for this channel: a relaxation calls this once per ionic step, and a // stale multiplet from the previous geometry must not survive into the next one. - this->multiplet_lvc_.erase( + this->lr_.relax.mpl.erase( std::remove_if( - this->multiplet_lvc_.begin(), this->multiplet_lvc_.end(), + this->lr_.relax.mpl.begin(), this->lr_.relax.mpl.end(), [ispin](const LR::MplLvc &m) { return m.ispin == ispin; }), - this->multiplet_lvc_.end()); + this->lr_.relax.mpl.end()); // The per-state gradients above are the diagonal of the degenerate-subspace gradient matrix in // whatever basis the eigensolver returned, so inside a multiplet only their trace means // anything. `lr_degen_thr` asks for the off-diagonal part too, which is the rest of the // first-order information. - const int ekb_off = this->openshell ? 0 : ispin * this->nstates; - std::vector omega(this->nstates); - for (int ist = 0; ist < this->nstates; ++ist) - { - omega[ist] = this->pelec->ekb.c[ekb_off + ist]; - } - const std::vector> groups = LR::group_degenerate_states(omega, this->inp_->lr_degen_thr); - for (const std::vector &group : groups) - { - if (group.size() < 2) - { - continue; - } - std::vector diag; - for (const int ist : group) - { - diag.push_back(forces[ist]); - } - this->multiplet_lvc_.push_back(this->build_mpl_(ispin, group, diag, ofs)); - } -} - -template -LR::MplLvc ModuleESolver::ESolver_LR::build_mpl_(const int ispin, - const std::vector &group, - const std::vector &diag, - std::ofstream &ofs) -{ - ModuleBase::TITLE("ESolver_LR", "build_mpl_"); - ModuleBase::timer::start("ESolver_LR", "build_mpl_"); - // The multiplet's members, each widened into the Z window - const ct::Tensor Xz = this->pad_group_to_z_(ispin, group); - const int ekb_off = this->openshell ? 0 : ispin * this->nstates; - std::vector omega(group.size()); - for (size_t k = 0; k < group.size(); ++k) - { - omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; - } - // The module owns everything but the Z-vector solve, which stays behind this callback. - const LR::MplEval eval = [this, ispin](const ct::Tensor &x, const std::vector &w, const int label) { - return this->openshell ? this->cal_force_openshell_Xz(x, w, label) : this->cal_force_Xz(ispin, x, w, label); - }; - LR::MplLvc mpl = LR::build_mpl(Xz, omega, diag, this->nloc_per_state_z_, ispin, group, *this->ucell_, eval, ofs); - ModuleBase::timer::end("ESolver_LR", "build_mpl_"); - return mpl; -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force_openshell(const int istate_only) -{ - ModuleBase::TITLE("ESolver_LR", "cal_force_openshell"); - - // Open shell: there is a single eigenproblem whose vector is the concatenation - // [up-block | down-block], and every density matrix has two independent channels. - // The spin-orbital formulas apply verbatim -- unlike the closed-shell singlet/triplet - // algorithm, X here is normalized over BOTH channels, so it carries no implicit sqrt(2) - // and none of the collapsed 2/4 factors are needed. - const int ist_begin_ = (istate_only < 0) ? 0 : istate_only; - const int nst_ = (istate_only < 0) ? this->nstates : 1; - // Like the closed-shell path, the whole gradient runs in the Z window: X is zero-padded - // into it (both channels, each re-based -- see `pad_X_to_z_`), so D^X and T are unchanged - // while the Z-vector gets every occupied-virtual rotation the AO basis supports. - const ct::Tensor Xz = this->pad_X_to_z_(0, ist_begin_, nst_); - std::vector omega_(nst_); - for (int i = 0; i < nst_; ++i) + for (LR::MplLvc &m : LR::multiplet_grad(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), + ispin, this->inp_->lr_degen_thr, forces, ofs)) { - omega_[i] = this->pelec->ekb.c[ist_begin_ + i]; + this->lr_.relax.mpl.push_back(std::move(m)); } - return this->cal_force_openshell_Xz(Xz, omega_, ist_begin_); } template @@ -752,11 +680,11 @@ void ModuleESolver::ESolver_LR::test_force() ModuleIO::print_force(this->ofs_running_, (*this->ucell_), "Ground State FORCE (eV/Angstrom)", force_gs, false); /// ======================================= END test 1 ========================================= ///========================== test 2: reproduce the DX Hartree term ========================= - ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->gs_pot_.pot_hartree()); + ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->lr_.pot.gs_pot.pot_hartree()); ModuleIO::print_force( this->ofs_running_, (*this->ucell_), "GS Hartree force calculated by 'cal_pulay_fs' from potential (eV/Angstrom)", f_hxc_potgs, false); - ModuleBase::matrix f_hxc_potlr = lr_force.cal_force_hxc_dmtrans(dm_gs, *this->pot[0]); + ModuleBase::matrix f_hxc_potlr = lr_force.cal_force_hxc_dmtrans(dm_gs, *this->lr_.pot.pot[0]); ModuleIO::print_force( this->ofs_running_, (*this->ucell_), "GS Hxc force calculated by 'LR_Force' from kernel (eV/Angstrom)", f_hxc_potlr, false); @@ -769,11 +697,11 @@ void ModuleESolver::ESolver_LR::test_force() template void ModuleESolver::ESolver_LR::setup_relax_target_() { - this->target_.setup(*this->inp_, this->openshell, this->nspin, this->nstates, this->ofs_running_); - if (this->target_.active()) + this->lr_.relax.target.setup(*this->inp_, this->openshell, this->nspin, this->nstates, this->ofs_running_); + if (this->lr_.relax.target.active()) { - this->force_gs_.create(this->ucell_->nat, 3); - this->lr_force_.create(this->ucell_->nat, 3); + this->lr_.relax.force_gs.create(this->ucell_->nat, 3); + this->lr_.relax.lr_force.create(this->ucell_->nat, 3); } } @@ -782,18 +710,18 @@ template void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) { ModuleBase::timer::start("ESolver_LR", "follow_target_state_"); - if (!this->target_.active()) + if (!this->lr_.relax.target.active()) { ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); return; } - const int channel = this->openshell ? 0 : this->target_.ispin(); - const T *const amplitudes = this->X[channel].template data(); + const int channel = this->openshell ? 0 : this->lr_.relax.target.ispin(); + const T *const amplitudes = this->lr_.amp.x[channel].template data(); const TwoCenterIntegrator &overlap_integrator = *this->tcb().overlap_orb; std::vector energies(this->nstates); - std::copy_n(this->pelec->ekb.c + this->target_.ekb_off(this->nstates), this->nstates, energies.begin()); - this->target_.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->paraC_, - this->paraMat_, this->paraX_, this->nocc, this->nvirt, amplitudes, this->nloc_per_state, + std::copy_n(this->pelec->ekb.c + this->lr_.relax.target.ekb_off(this->nstates), this->nstates, energies.begin()); + this->lr_.relax.target.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->lr_.amp.para_c, + this->paraMat_, this->lr_.amp.para_x, this->nocc, this->nvirt, amplitudes, this->lr_.amp.nloc, this->nstates, energies, ofs); ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); } @@ -803,7 +731,7 @@ double ModuleESolver::ESolver_LR::cal_energy() { // Outside a relaxation nothing consumes this, and returning a non-zero value would change // what the existing single-point outputs report. - if (!this->target_.active()) + if (!this->lr_.relax.target.active()) { return 0.0; } @@ -811,7 +739,7 @@ double ModuleESolver::ESolver_LR::cal_energy() // otherwise, matching whatever `cal_lr_force_relax_` produced the gradient of. The // energy-based optimisers line-search on this, so the two must not describe different // surfaces. - return this->etot_gs_ + this->target_.omega(this->pelec->ekb.c, this->nstates); + return this->lr_.relax.etot_gs + this->lr_.relax.target.omega(this->pelec->ekb.c, this->nstates); } template @@ -819,11 +747,11 @@ void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase: { basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); const UnitCell &ucell = static_cast(basecell); - if (!this->target_.active()) + if (!this->lr_.relax.target.active()) { // single-point runs print the gradients of every state from `after_all_runners` instead return; } - if (this->lr_force_.nr != ucell.nat) + if (this->lr_.relax.lr_force.nr != ucell.nat) { ModuleBase::WARNING_QUIT( "ESolver_LR::cal_force", "the excited-state gradient has not been computed for this geometry."); @@ -833,7 +761,7 @@ void ModuleESolver::ESolver_LR::cal_force(BaseCell &basecell, ModuleBase: // 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. force.create(ucell.nat, 3); - force = this->force_gs_ + this->lr_force_; + force = this->lr_.relax.force_gs + this->lr_.relax.lr_force; ModuleIO::print_force(this->ofs_running_, ucell, "EXCITED-STATE TOTAL-FORCE (eV/Angstrom)", force, false); } @@ -850,26 +778,26 @@ void ModuleESolver::ESolver_LR::cal_stress(BaseCell &basecell, ModuleBase template ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, const std::vector &group) const { - return LR::pad_group(this->X, this->openshell, this->paraX_, this->paraX_z_, this->nocc, this->nvirt, this->nk, - this->nloc_per_state, this->nloc_per_state_z_, ispin, group); + return LR::pad_group(this->lr_.amp.x, this->openshell, this->lr_.amp.para_x, this->lr_.zw.para_x, this->nocc, this->nvirt, this->nk, + this->lr_.amp.nloc, this->lr_.zw.nloc, ispin, group); } template ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::ofstream &ofs) { - this->target_.resolve_group(*this->inp_, this->pelec->ekb.c, this->nstates, this->ofs_running_); - const std::vector &group = this->target_.group(); + this->lr_.relax.target.resolve_group(*this->inp_, this->pelec->ekb.c, this->nstates, this->ofs_running_); + const std::vector &group = this->lr_.relax.target.group(); if (group.empty()) { - return this->cal_force(this->target_.ispin(), this->target_.state())[0]; + return this->cal_force(this->lr_.relax.target.ispin(), this->lr_.relax.target.state())[0]; } const bool jt_mode = (LR_Util::tolower(this->inp_->lr_degen_mode) == "jt"); // `average` needs only the DIAGONAL of the gradient matrix: the average is basis-independent by // construction, so the off-diagonal part (and the extra d(d-1)/2 solves it costs) is not // involved. The Jahn-Teller direction is orthogonal to the average and does need them. const int d = static_cast(group.size()); - const int ekb_off = this->target_.ekb_off(this->nstates); - const ct::Tensor Xz = this->pad_group_to_z_(this->target_.ispin(), group); + const int ekb_off = this->lr_.relax.target.ekb_off(this->nstates); + const ct::Tensor Xz = this->pad_group_to_z_(this->lr_.relax.target.ispin(), group); std::vector omega(d); for (int k = 0; k < d; ++k) { @@ -877,16 +805,16 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::of } const std::vector forces = this->openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) - : this->cal_force_Xz(this->target_.ispin(), Xz, omega, group.front()); - ofs << " Followed state " << this->target_.state() << " is degenerate with"; + : this->cal_force_Xz(this->lr_.relax.target.ispin(), Xz, omega, group.front()); + ofs << " Followed state " << this->lr_.relax.target.state() << " is degenerate with"; for (const int ist : group) { - if (ist != this->target_.state()) + if (ist != this->lr_.relax.target.state()) { ofs << " " << ist; } } - ofs << " (Omega_bar = " << this->target_.omega(this->pelec->ekb.c, this->nstates) << " Ry)." << std::endl; + ofs << " (Omega_bar = " << this->lr_.relax.target.omega(this->pelec->ekb.c, this->nstates) << " Ry)." << std::endl; if (!jt_mode) { ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" @@ -904,10 +832,12 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( // Regime (c): descend the Jahn-Teller branch. This needs the whole gradient matrix, so the // off-diagonal elements are assembled here -- d(d-1)/2 further Z-vector solves on top of the // d diagonal ones already in `diag`. - const std::vector &group = this->target_.group(); - LR::JtForce jt = LR::eval_jt_force(this->build_mpl_(this->target_.ispin(), group, diag, ofs).g, ofs); - const int channel = this->openshell ? 0 : this->target_.ispin(); - this->target_.save_mixed(this->X[channel].template data(), this->nloc_per_state, jt.mixing); + const std::vector &group = this->lr_.relax.target.group(); + const LR::MplLvc mpl = LR::build_mpl_state(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), + this->lr_.relax.target.ispin(), group, diag, ofs); + LR::JtForce jt = LR::eval_jt_force(mpl.g, ofs); + const int channel = this->openshell ? 0 : this->lr_.relax.target.ispin(); + this->lr_.relax.target.save_mixed(this->lr_.amp.x[channel].template data(), this->lr_.amp.nloc, jt.mixing); // The returned force is the descending branch's own gradient; once a step splits the // multiplet `resolve_group` finds no group and the single-state path takes over. return jt.force; @@ -1060,7 +990,7 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons this->paraMat_.iat2iwt_ = ucell.get_iat2iwt(); LR_Util::setup_2d_division( - this->paraC_, ks_block_size, this->nbasis, this->nbands + this->lr_.amp.para_c, ks_block_size, this->nbasis, this->nbands #ifdef __MPI , this->paraMat_.para_2d().ictxt() @@ -1070,7 +1000,7 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons // allocate psi_ks and eig_ks in the [nocc, nvirt] window #ifdef __MPI this->psi_ks.reset( - new psi::Psi(this->kv.get_nks(), this->paraC_.ncloc(), this->paraC_.nrloc(), this->kv.ngk, true)); + new psi::Psi(this->kv.get_nks(), this->lr_.amp.para_c.ncloc(), this->lr_.amp.para_c.nrloc(), this->kv.ngk, true)); #else this->psi_ks.reset(new psi::Psi(this->kv.get_nks(), this->nbands, this->nbasis, this->kv.ngk, true)); #endif @@ -1139,7 +1069,7 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) const int first_band = start_band + 1; Cpxgemr2d( this->nbasis, this->nbands, this->psi_ks_all_->get_pointer(), 1, first_band, ks_sol.pv.desc_wfc, - this->psi_ks->get_pointer(), 1, 1, const_cast(this->paraC_.desc()), this->paraC_.ictxt()); + this->psi_ks->get_pointer(), 1, 1, const_cast(this->lr_.amp.para_c.desc()), this->lr_.amp.para_c.ictxt()); #else // serial: each band is `nbasis` contiguous coefficients, so the window is a plain // band-by-band copy (this loop used to compute the two pointers and copy nothing, @@ -1290,7 +1220,7 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell #endif LR_Util::setup_2d_division( - this->paraC_, 1, this->nbasis, this->nbands + this->lr_.amp.para_c, 1, this->nbasis, this->nbands #ifdef __MPI , paraMat_.para_2d().ictxt() diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 5613ea12ef..6ca181c55b 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -20,6 +20,8 @@ #include "source_lcao/module_lr/potentials/lr_gs_pot.h" #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" #include "source_lcao/module_lr/lr_mpl.h" +#include "source_lcao/module_lr/lr_core.h" +#include "source_lcao/module_lr/lr_sforce.h" #include "source_lcao/module_lr/lr_zeq.h" #include "source_lcao/module_lr/lr_relax.h" #ifdef __EXX @@ -103,11 +105,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// bind the aliases above; `ks_` must already be set (or null for the `lr` path) void bind_ground_state_aliases_(); - // not to use ElecState because 2-particle state is quite different from 1-particle state. - // implement a independent one (ExcitedState) to pack physical properties if needed. - // put the components of ElecState here: - std::vector> pot; - // ground state info /// @brief ground state wave function @@ -126,17 +123,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP ModuleBase::matrix wg_ks_all; /// occupation number of all bands of ground state // @brief only needed for force calculation - LR::GsPot gs_pot_; - - std::shared_ptr - pot_hxc_gs; /// used in lr-grad, in the ground-state Hxc gradient term coming from dF/dC - - /// @brief Excited state wavefunction (locc, lvirt are local size of nocc and nvirt in each process) - /// size of X: [neq][{nstate, nloc_per_state}], namely: - /// - [nspin][{nstates, nk* (locc* lvirt}] for close- shell, - /// - [1][{nstates, nk * (locc[0] * lvirt[0]) + nk * (locc[1] * lvirt[1])}] for open-shell - std::vector X; - int nloc_per_state = 1; std::vector nocc; ///< number of occupied orbitals for each spin used in the calculation int nocc_in = 1; ///< nocc read from input (adjusted by nelec): max(spin-up, spindown) @@ -170,24 +156,16 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// The followed state/multiplet. Seeded from `lr_target_state`, then re-chosen at every /// later step by cross-geometry group overlap; following a fixed index instead makes the /// force discontinuous as soon as two surfaces cross. - LR::RelaxTarget target_; - double etot_gs_ = 0.0; ///< ground-state total energy of the current step (Ry) - ModuleBase::matrix force_gs_; ///< ground-state force of the current step (Ry/Bohr, F = -dE/dR) - /// The LR part of the excited-state force, -d(Omega)/dR (Ry/Bohr). - ModuleBase::matrix lr_force_; /// Match the old subspace to current energy groups and refresh the single/group references. /// `ofs` receives the note when the followed root changes index, and the warning when /// no current root resembles the previous one. void follow_target_state_(std::ofstream &ofs); - std::vector spin_types; - std::unique_ptr gint_info_ = nullptr; - /// @brief variables for parallel distribution of KS orbitals - Parallel_Blkcyclic paraC_; - /// @brief variables for parallel distribution of excited states - std::vector paraX_; + /// LR solver state that is not part of the esolver interface. + LR::Core lr_; + // ---------------- the Z-vector (CPSCF) window ---------------- // The Z-vector equation enforces the Brillouin condition in EVERY occupied-virtual @@ -198,13 +176,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP // but span every virtual band the ground state produced (the input `nbands`), so the // window is widened by raising *nbands*, not `nvirt`. X keeps its own window, so Omega // -- and with it any finite-difference reference -- is untouched. - std::unique_ptr> psi_ks_z_; - ModuleBase::matrix eig_ks_z_; - Parallel_Blkcyclic paraC_z_; - std::vector paraX_z_; - std::vector nvirt_z_; - int nbands_z_ = 0; - int nloc_per_state_z_ = 0; /// (re)build the Z window from `psi_ks_all_` / `eig_ks_all`. `desc_src` describes the /// source wavefunction's 2D layout; unused (and may be null) in a serial build. void fill_z_window_(const int *desc_src); @@ -243,9 +214,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// restricts it to that one state: geometry relaxation follows a single state, and the /// Z-vector solve dominates the cost. -1 does all `nstates`. std::vector cal_force(const int ispin, const int istate_only = -1); - /// open-shell (spin-unrestricted) excited-state force: X holds [up | down] and every - /// density matrix has two independent channels - std::vector cal_force_openshell(const int istate_only = -1); /// @brief Gradients for excitation vectors supplied by the caller, already widened into /// the Z window -- the two functions above are thin wrappers that widen the stored /// eigenvectors and look up their `omega`. @@ -253,7 +221,7 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// The blocks of `Xz` need not be the eigenvectors the Casida diagonalizer returned. Any /// normalized vector inside a degenerate multiplet is an eigenvector with the same /// `omega`, so passing a linear combination is what turns the per-state gradient into the - /// full degenerate-subspace gradient matrix; see `build_mpl_` and + /// full degenerate-subspace gradient matrix; see `LR::build_mpl` and /// `grad_degen.h`. /// /// @param omega excitation energy of each block (Ry); its size sets the block count @@ -266,14 +234,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// open-shell counterpart of `cal_force_Xz` std::vector cal_force_openshell_Xz( const ct::Tensor &Xz, const std::vector &omega, const int label_begin); - /// @brief The linear vibronic coupling (LVC) data of one degenerate multiplet: see - /// `LR::MplLvc`. Kept as one object rather than as loose force matrices because the - /// excited-state relaxation and (later) non-adiabatic dynamics need exactly the same - /// data: near a degeneracy the correct propagation is on this coupled $d\times d$ - /// model, not on an adiabatic gradient. - /// LVC data of every multiplet found at this geometry, rebuilt on each call of - /// `cal_force_and_grad_matrix_`. Empty unless `lr_degen_thr > 0`. - std::vector multiplet_lvc_; /// The LR half of the force for the current geometry, following whichever surface /// `lr_degen_mode` selects. `ofs` receives the note when that is not a single state. ModuleBase::matrix cal_lr_force_relax_(std::ofstream &ofs); @@ -296,16 +256,8 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// /// Fills `multiplet_lvc_`. void cal_force_and_grad_matrix_(const int ispin, std::ofstream &ofs); - /// @brief Wrap one multiplet's Z-window members and per-state forces into - /// `LR::build_mpl`, which owns the polarization identity and the diagnostics. - /// - /// @param group state indices of the multiplet, from `LR::group_degenerate_states` - /// @param diag their per-state forces, i.e. $G_{kk}$, already computed by `cal_force` - /// @param ofs log stream the matrix and the precondition diagnostics are written to - LR::MplLvc build_mpl_(const int ispin, - const std::vector &group, - const std::vector &diag, - std::ofstream &ofs); + /// Amplitudes and energies as `LR::StateCtx`, filled once per force evaluation. + LR::StateCtx state_ctx_() const; void test_force(); // test: reproduce the force of ground state module_dm::DensityMatrix cal_dm_gs(); ///< ground-state density matrix diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index 82bb183557..a4b81bbf58 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -78,7 +78,7 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para } LR_Util::setup_2d_division( - this->paraC_, this->paraMat_.para_2d().nb(), this->nbasis, this->nbands + this->lr_.amp.para_c, this->paraMat_.para_2d().nb(), this->nbasis, this->nbands #ifdef __MPI , this->paraMat_.para_2d().ictxt() @@ -103,7 +103,7 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para this->gd(), inp.nspin, PARAM.globalv.gamma_only_local, PARAM.globalv.domag, inp.device == "gpu", inp.nstream)); ModuleGint::Gint::set_gint_info(this->gint_info_.get()); - this->pot.resize(this->nspin, nullptr); + this->lr_.pot.pot.resize(this->nspin, nullptr); if (this->inp_->lr_solver != "spectrum" && this->inp_->lr_solver != "plot") { this->mo_lri = LR_Util::make_unique>( @@ -154,8 +154,8 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) this->lri_init(); BSE::HamiltBSE bse_matrix( this->nspin, this->nbasis, this->nocc, this->nvirt, *this->ucell_, this->orb_cutoff_, this->gd(), - *this->psi_ks, *this->psi_ks_global, this->eig_gw, *this->mo_lri, this->pot[0], this->kv, this->paraX_, - this->paraC_, this->paraMat_, this->inp_->bse_spin_types, this->inp_->bse_tda, + *this->psi_ks, *this->psi_ks_global, this->eig_gw, *this->mo_lri, this->lr_.pot.pot[0], this->kv, this->lr_.amp.para_x, + this->lr_.amp.para_c, this->paraMat_, this->inp_->bse_spin_types, this->inp_->bse_tda, this->inp_->bse_ri_hartree, this->inp_->bse_mem_save, this->inp_->bse_continue, this->inp_->out_bse_ab, this->out_dir, this->in_dir, GlobalV::MY_RANK, GlobalV::NPROC, this->inp_->ri_hartree_benchmark); @@ -186,7 +186,7 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) for (int is = 0; is < this->inp_->bse_spin_types.size(); ++is) { bse_matrix.tda_solver( - is, this->nstates, &this->tda_ene[is * this->nstates], this->X[is].template data()); + is, this->nstates, &this->tda_ene[is * this->nstates], this->lr_.amp.x[is].template data()); std::cout << "eigenvalues: (Ry)" << std::endl; int write_nstates = std::min(this->nstates, 20); @@ -204,7 +204,7 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) { write_tda_states( this->inp_->bse_spin_types[is], &this->tda_ene[is * this->nstates], - this->X[is].template data(), this->nloc_per_state, this->nstates); + this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, this->nstates); } malloc_trim(0); } @@ -233,7 +233,7 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) write_full_states( this->inp_->bse_spin_types[is], &this->full_ene[is * this->nstates], this->full_X[is].template data(), this->full_Y[is].template data(), - this->nloc_per_state, this->nstates); + this->lr_.amp.nloc, this->nstates); } malloc_trim(0); } @@ -278,8 +278,8 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) for (int is = 0; is < this->inp_->bse_spin_types.size(); ++is) { read_tda_states( - this->inp_->bse_spin_types[is], &this->tda_ene[is * this->nstates], this->X[is].template data(), - this->nloc_per_state, this->nstates); + this->inp_->bse_spin_types[is], &this->tda_ene[is * this->nstates], this->lr_.amp.x[is].template data(), + this->lr_.amp.nloc, this->nstates); } } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "full") @@ -288,16 +288,16 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) { read_full_states( this->inp_->bse_spin_types[is], &this->full_ene[is * this->nstates], - this->full_X[is].template data(), this->full_Y[is].template data(), this->nloc_per_state, + this->full_X[is].template data(), this->full_Y[is].template data(), this->lr_.amp.nloc, this->nstates); // check whether |X|^2 - |Y|^2 = 1 for (int i = 0; i < this->nstates; ++i) { double norm_xy = 0.0; - for (int j = 0; j < this->nloc_per_state; ++j) + for (int j = 0; j < this->lr_.amp.nloc; ++j) { - norm_xy += std::norm(this->full_X[is].template data()[i * this->nloc_per_state + j]) - - std::norm(this->full_Y[is].template data()[i * this->nloc_per_state + j]); + norm_xy += std::norm(this->full_X[is].template data()[i * this->lr_.amp.nloc + j]) - + std::norm(this->full_Y[is].template data()[i * this->lr_.amp.nloc + j]); } Parallel_Reduce::reduce_all(norm_xy); if (std::abs(norm_xy - 1.0) > 1e-6) @@ -334,14 +334,14 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) if (this->inp_->lr_solver == "plot") { - for (int is = 0; is < this->X.size(); ++is) + for (int is = 0; is < this->lr_.amp.x.size(); ++is) { std::cout << "plot BSE exciton wavefunction for state: " << this->inp_->plot_istate << ", spin type: " << this->inp_->bse_spin_types[is] << std::endl; LR_Util::ExcitonPlotter eplot( this->nspin, this->nbasis, this->nocc, this->nvirt, *this->psi_ks, *this->ucell_, this->kv, this->gd(), - this->orb_cutoff_, this->pgrid(), *this->pw_rho, this->paraX_, this->paraC_, this->paraMat_, output_dir, - &this->tda_ene[is * this->nstates], this->X[is].template data(), false /*openshell*/, &this->orb_); + this->orb_cutoff_, this->pgrid(), *this->pw_rho, this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, output_dir, + &this->tda_ene[is * this->nstates], this->lr_.amp.x[is].template data(), false /*openshell*/, &this->orb_); const std::string plot_type = LR_Util::tolower(this->inp_->exciton_plot_type); const std::string plot_format = LR_Util::tolower(this->inp_->exciton_plot_format); const bool write_slice = (plot_format == "slice" || plot_format == "both"); @@ -408,7 +408,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "tda") { - for (int is = 0; is < this->X.size(); ++is) + for (int is = 0; is < this->lr_.amp.x.size(); ++is) { const double *const energies = &this->tda_ene[is * this->nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_tda"; @@ -432,18 +432,18 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; this->velocity_mo = LR_Util::cal_velocity_mo( - *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->paraC_, this->kv, *this->psi_ks, + *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->lr_.amp.para_c, this->kv, *this->psi_ks, this->nk, nspin_tmp, this->nbasis, this->nocc, this->nvirt); } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "tda") { - for (int is = 0; is < this->X.size(); ++is) + for (int is = 0; is < this->lr_.amp.x.size(); ++is) { LR::LR_Spectrum spectrum( this->nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, - this->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->paraX_, this->paraC_, + this->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, &this->tda_ene[is * this->nstates], this->eig_ks.c, - this->X[is].template data(), this->nstates, false /*openshell*/, + this->lr_.amp.x[is].template data(), this->nstates, false /*openshell*/, LR_Util::tolower(this->inp_->abs_gauge), GlobalV::MY_RANK, output_dir); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { @@ -473,7 +473,7 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { LR::LR_Spectrum spectrum( this->nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, - this->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->paraX_, this->paraC_, + this->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, &this->full_ene[is * this->nstates], this->eig_ks.c, this->full_X[is].template data(), this->nstates, false /*openshell*/, LR_Util::tolower(this->inp_->abs_gauge), GlobalV::MY_RANK, output_dir); @@ -532,16 +532,16 @@ void ESolver_BSE::ipa_solver() { int sorted_index = indices[istate]; int ik = sorted_index / (this->nocc[0] * this->nvirt[0]); - int loffset_X = (istate * this->nk + ik) * this->paraX_[0].size(); + int loffset_X = (istate * this->nk + ik) * this->lr_.amp.para_x[0].size(); int i = (sorted_index / this->nvirt[0]) % this->nocc[0]; int a = sorted_index % this->nvirt[0]; - int col_loc = this->paraX_[0].icloc(i); - int row_loc = this->paraX_[0].irloc(a); + int col_loc = this->lr_.amp.para_x[0].icloc(i); + int row_loc = this->lr_.amp.para_x[0].irloc(a); if (col_loc == -1 || row_loc == -1) { continue; } - this->X[0].template data()[loffset_X + col_loc * this->paraX_[0].nrloc() + row_loc] = 1.0; + this->lr_.amp.x[0].template data()[loffset_X + col_loc * this->lr_.amp.para_x[0].nrloc() + row_loc] = 1.0; } ModuleBase::timer::end("ESolver_BSE", "ipa_solver"); ModuleBase::GlobalFunc::DONE(GlobalV::ofs_running, "IPA solver"); @@ -697,13 +697,13 @@ void ESolver_BSE::init_pot(const Charge &chg_gs) this->inp_->lr_init_xc_kernel); // BSE multiplies its bare Coulomb matrix by the singlet factor in HamiltBSE. // S1_gs has weight one; S1 would apply that factor a second time on the grid path. - this->pot[0] = + this->lr_.pot.pot[0] = std::make_shared(kernel, *this->pw_rho, *this->ucell_, chg_gs.nrxx, this->nspin, ST::S1_gs); break; } // case 2: - // this->pot[0] = std::make_shared(xc_kernel, *this->pw_rho, ucell, chg_gs, pgrid(), openshell ? - // ST::S2_updown : ST::S2_singlet, this->inp_->lr_init_xc_kernel); this->pot[1] = + // this->lr_.pot.pot[0] = std::make_shared(xc_kernel, *this->pw_rho, ucell, chg_gs, pgrid(), openshell ? + // ST::S2_updown : ST::S2_singlet, this->inp_->lr_init_xc_kernel); this->lr_.pot.pot[1] = // std::make_shared(xc_kernel, *this->pw_rho, ucell, chg_gs, pgrid(), openshell ? ST::S2_updown : // ST::S2_triplet, this->inp_->lr_init_xc_kernel); break; default: @@ -723,23 +723,23 @@ void ESolver_BSE::allocate_eigen_infos() px, /*nb2d=*/1, this->nvirt[is], this->nocc[is] #ifdef __MPI , - this->paraC_.ictxt() + this->lr_.amp.para_c.ictxt() #endif ); - this->paraX_.emplace_back(std::move(px)); + this->lr_.amp.para_x.emplace_back(std::move(px)); } - this->nloc_per_state = - this->nk * (this->openshell ? this->paraX_[0].size() + this->paraX_[1].size() : this->paraX_[0].size()); + this->lr_.amp.nloc = + this->nk * (this->openshell ? this->lr_.amp.para_x[0].size() + this->lr_.amp.para_x[1].size() : this->lr_.amp.para_x[0].size()); int n_spin_types = this->inp_->bse_spin_types.size(); if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "tda") { BSE_Util::print_mem_estimate( - "TDA BSE eigen states", n_spin_types * static_cast(this->nstates) * (1 + this->nloc_per_state), + "TDA BSE eigen states", n_spin_types * static_cast(this->nstates) * (1 + this->lr_.amp.nloc), sizeof(T)); this->tda_ene.resize(n_spin_types * this->nstates); - this->X.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->nloc_per_state})); - for (auto &x : this->X) + this->lr_.amp.x.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->lr_.amp.nloc})); + for (auto &x : this->lr_.amp.x) { x.zero(); } @@ -748,10 +748,10 @@ void ESolver_BSE::allocate_eigen_infos() { BSE_Util::print_mem_estimate( "full BSE eigen states", - n_spin_types * static_cast(this->nstates) * (1 + 2 * this->nloc_per_state), sizeof(T)); + n_spin_types * static_cast(this->nstates) * (1 + 2 * this->lr_.amp.nloc), sizeof(T)); this->full_ene.resize(n_spin_types * this->nstates); - this->full_X.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->nloc_per_state})); - this->full_Y.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->nloc_per_state})); + this->full_X.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->lr_.amp.nloc})); + this->full_Y.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->lr_.amp.nloc})); for (auto &x : this->full_X) { x.zero(); diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index b25785d86a..b06351d1ea 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -32,6 +32,7 @@ if(ENABLE_LCAO) lr_relax.cpp lr_mpl.cpp lr_zeq.cpp + lr_sforce.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h new file mode 100644 index 0000000000..b6225aefb7 --- /dev/null +++ b/source/source_lcao/module_lr/lr_core.h @@ -0,0 +1,58 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_CORE_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_CORE_H + +#include "source_base/matrix.h" +#include "source_lcao/module_lr/lr_gs.h" +#include "source_lcao/module_lr/lr_mpl.h" +#include "source_lcao/module_lr/lr_relax.h" +#include "source_lcao/module_lr/potentials/lr_gs_pot.h" +#include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" + +#include +#include +#include + +namespace LR +{ +/// The excitation amplitudes and their distribution. +struct Amp +{ + std::vector x; + int nloc = 1; + Parallel_Blkcyclic para_c; + std::vector para_x; + std::vector spin_types; +}; + +/// The LR potentials, including the ground-state one needed by the force path. +struct PotSet +{ + std::vector> pot; + std::shared_ptr pot_hxc_gs; + GsPot gs_pot; +}; + +/// State of an excited-state geometry relaxation. +template +struct RelaxRun +{ + RelaxTarget target; + double etot_gs = 0.0; + ModuleBase::matrix force_gs; + ModuleBase::matrix lr_force; + std::vector mpl; +}; + +/// LR solver state that does not belong to the esolver interface. +template +struct Core +{ + Amp amp; + ZWin zw; + PotSet pot; + RelaxRun relax; +}; + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_CORE_H diff --git a/source/source_lcao/module_lr/lr_sforce.cpp b/source/source_lcao/module_lr/lr_sforce.cpp new file mode 100644 index 0000000000..93c4556bd8 --- /dev/null +++ b/source/source_lcao/module_lr/lr_sforce.cpp @@ -0,0 +1,131 @@ +#include "source_lcao/module_lr/lr_sforce.h" + +#include "source_lcao/module_lr/grad_degen.h" + +#include + +namespace LR +{ + +template +std::vector state_forces(const GradientInputs& in, const GsForceCtx& gs, + const StateCtx& st, const int ispin, const int istate_only) +{ + const int ist_begin = (istate_only < 0) ? 0 : istate_only; + const int nst = (istate_only < 0) ? st.nstates : 1; + // The whole closed-shell gradient runs in the Z window (every virtual band the ground state + // produced), not the `nvirt` window X was solved in: only there does the Z-vector enforce the + // Brillouin condition in every occupied-virtual rotation. X is zero-padded into it, so D^X and + // T come out bit-identical -- and Omega is untouched, so an existing finite-difference + // reference stays valid. + const ct::Tensor xz = pad_amplitudes(st.X, st.openshell, st.para_x, st.para_x_z, st.nocc, st.nvirt, st.nk, + st.nloc, st.nloc_z, ispin, ist_begin, nst); + std::vector omega(nst); + for (int i = 0; i < nst; ++i) + { + omega[i] = st.ekb[ispin * st.nstates + ist_begin + i]; + } + return force_xz(in, gs, ispin, xz, omega, ist_begin); +} + +template +std::vector state_forces_os(const GradientInputs& in, const GsForceCtx& gs, + const StateCtx& st, const int istate_only) +{ + // Open shell: there is a single eigenproblem whose vector is the concatenation + // [up-block | down-block], and every density matrix has two independent channels. The + // spin-orbital formulas apply verbatim -- unlike the closed-shell singlet/triplet algorithm, + // X here is normalized over BOTH channels, so it carries no implicit sqrt(2) and none of the + // collapsed 2/4 factors are needed. + const int ist_begin = (istate_only < 0) ? 0 : istate_only; + const int nst = (istate_only < 0) ? st.nstates : 1; + // Like the closed-shell path, the whole gradient runs in the Z window: X is zero-padded into + // it (both channels, each re-based), so D^X and T are unchanged while the Z-vector gets every + // occupied-virtual rotation the AO basis supports. + const ct::Tensor xz = pad_amplitudes(st.X, st.openshell, st.para_x, st.para_x_z, st.nocc, st.nvirt, st.nk, + st.nloc, st.nloc_z, 0, ist_begin, nst); + std::vector omega(nst); + for (int i = 0; i < nst; ++i) + { + omega[i] = st.ekb[ist_begin + i]; + } + return force_xz_os(in, gs, xz, omega, ist_begin); +} + +template +MplLvc build_mpl_state(const GradientInputs& in, const GsForceCtx& gs, const StateCtx& st, const int ispin, + const std::vector& group, const std::vector& diag, std::ofstream& ofs) +{ + // The multiplet's members, each widened into the Z window + const ct::Tensor xz = pad_group(st.X, st.openshell, st.para_x, st.para_x_z, st.nocc, st.nvirt, st.nk, + st.nloc, st.nloc_z, ispin, group); + const int ekb_off = st.openshell ? 0 : ispin * st.nstates; + std::vector omega(group.size()); + for (size_t k = 0; k < group.size(); ++k) + { + omega[k] = st.ekb[ekb_off + group[k]]; + } + // The solver is reached only through this callback; everything else is module code. + const MplEval eval = [&in, &gs, &st, ispin](const ct::Tensor& x, const std::vector& w, const int label) { + return st.openshell ? force_xz_os(in, gs, x, w, label) : force_xz(in, gs, ispin, x, w, label); + }; + return build_mpl(xz, omega, diag, st.nloc_z, ispin, group, in.ucell, eval, ofs); +} + +template +std::vector multiplet_grad(const GradientInputs& in, const GsForceCtx& gs, const StateCtx& st, + const int ispin, const double degen_thr, + const std::vector& forces, std::ofstream& ofs) +{ + const int ekb_off = st.openshell ? 0 : ispin * st.nstates; + std::vector omega(st.nstates); + for (int ist = 0; ist < st.nstates; ++ist) + { + omega[ist] = st.ekb[ekb_off + ist]; + } + std::vector out; + for (const std::vector& group : group_degenerate_states(omega, degen_thr)) + { + if (group.size() < 2) + { + continue; + } + std::vector diag; + for (const int ist : group) + { + diag.push_back(forces[ist]); + } + out.push_back(build_mpl_state(in, gs, st, ispin, group, diag, ofs)); + } + return out; +} + +template std::vector state_forces(const GradientInputs&, + const GsForceCtx&, const StateCtx&, int, + int); +template std::vector state_forces>( + const GradientInputs>&, const GsForceCtx>&, const StateCtx>&, + int, int); +template std::vector state_forces_os(const GradientInputs&, + const GsForceCtx&, const StateCtx&, + int); +template std::vector state_forces_os>( + const GradientInputs>&, const GsForceCtx>&, + const StateCtx>&, int); +template MplLvc build_mpl_state(const GradientInputs&, const GsForceCtx&, + const StateCtx&, int, const std::vector&, + const std::vector&, std::ofstream&); +template MplLvc build_mpl_state>(const GradientInputs>&, + const GsForceCtx>&, + const StateCtx>&, int, + const std::vector&, const std::vector&, + std::ofstream&); +template std::vector multiplet_grad(const GradientInputs&, const GsForceCtx&, + const StateCtx&, int, double, + const std::vector&, std::ofstream&); +template std::vector multiplet_grad>(const GradientInputs>&, + const GsForceCtx>&, + const StateCtx>&, int, double, + const std::vector&, std::ofstream&); + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_sforce.h b/source/source_lcao/module_lr/lr_sforce.h new file mode 100644 index 0000000000..a167462bde --- /dev/null +++ b/source/source_lcao/module_lr/lr_sforce.h @@ -0,0 +1,53 @@ +#ifndef ABACUS_SOURCE_LCAO_MODULE_LR_LR_SFORCE_H +#define ABACUS_SOURCE_LCAO_MODULE_LR_LR_SFORCE_H + +#include "source_lcao/module_lr/lr_amp.h" +#include "source_lcao/module_lr/lr_mpl.h" +#include "source_lcao/module_lr/lr_zeq.h" + +#include + +namespace LR +{ +/// Per-state side of the force path: the amplitudes widened into the Z window, plus the energies. +template +struct StateCtx +{ + const std::vector& X; + const std::vector& para_x; + const std::vector& para_x_z; + const std::vector& nocc; + const std::vector& nvirt; + int nk; + int nloc; + int nloc_z; + int nstates; + bool openshell; + const double* ekb; +}; + +/// Forces of the closed-shell states widened into the Z window; `istate_only < 0` means all. +template +std::vector state_forces(const GradientInputs& in, const GsForceCtx& gs, + const StateCtx& st, int ispin, int istate_only); + +/// Open-shell counterpart: both spin channels live in one vector, so the channel is always 0. +template +std::vector state_forces_os(const GradientInputs& in, const GsForceCtx& gs, + const StateCtx& st, int istate_only); + +/// One multiplet's gradient matrix, assembled from its diagonal forces. +template +MplLvc build_mpl_state(const GradientInputs& in, const GsForceCtx& gs, const StateCtx& st, int ispin, + const std::vector& group, const std::vector& diag, + std::ofstream& ofs); + +/// All multiplets of one channel among `forces`, with `degen_thr` as the grouping threshold. +template +std::vector multiplet_grad(const GradientInputs& in, const GsForceCtx& gs, const StateCtx& st, + int ispin, double degen_thr, const std::vector& forces, + std::ofstream& ofs); + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_SFORCE_H From 88b786a0952f18271326f8cec799c6e0536a5e9d Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 17:54:52 +0800 Subject: [PATCH 15/26] refactor(lr): move dimensions and ground-state bands into LR::Core LR::Core now owns LR::Dim and LR::GsState; Core::read_wfc and Core::fill_z absorb the former read_ks_wfc/fill_z_window_ bodies. Drop the unused pad_X_to_z_ wrapper. --- source/Makefile.Objects | 1 + source/source_esolver/esolver_lr.cpp | 312 +++++++----------- source/source_esolver/esolver_lr.h | 33 -- source/source_esolver/esolver_lr_lcao_bse.cpp | 200 +++++------ source/source_lcao/module_lr/CMakeLists.txt | 1 + source/source_lcao/module_lr/lr_core.cpp | 49 +++ source/source_lcao/module_lr/lr_core.h | 25 ++ 7 files changed, 304 insertions(+), 317 deletions(-) create mode 100644 source/source_lcao/module_lr/lr_core.cpp diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 94f6e014d4..3141e9dc1f 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1201,6 +1201,7 @@ OBJS_TENSOR=tensor.o\ lr_mpl.o\ lr_zeq.o\ lr_sforce.o\ + lr_core.o\ lr_gs_pot.o\ esolver_lr.o\ diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index ce9e67b46b..dca1ace7ad 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -102,12 +102,12 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste // allocate 2-particle state and setup 2d division this->setup_eigenvectors_X(); - this->pelec->ekb.create(nspin, this->nstates); + this->pelec->ekb.create(this->lr_.dim.nspin, this->lr_.dim.nstates); // set once here rather than inside the solver branches: the open-shell `spectrum` branch used // to leave it empty, and both `after_all_runners` and the gradient index it this->lr_.amp.spin_types = - this->openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); + this->lr_.dim.openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); // 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 @@ -137,7 +137,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste }; std::vector precondition(this->inp_->lr_solver == "lapack" ? 0 : this->lr_.amp.nloc, 1.0); // allocate and initialize A matrix and density matrix - if (openshell) + if (this->lr_.dim.openshell) { for (int is : {0, 1}) { @@ -145,25 +145,25 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste { const int offset_is = is * this->lr_.amp.para_x[0].size(); OperatorLRDiag pre_op( - this->eig_ks.c + is * nk * (nocc[0] + nvirt[0]), this->lr_.amp.para_x[is], this->nk, this->nocc[is], - this->nvirt[is], false); + this->lr_.gs.eig.c + is * this->lr_.dim.nk * (this->lr_.dim.nocc[0] + this->lr_.dim.nvirt[0]), this->lr_.amp.para_x[is], this->lr_.dim.nk, this->lr_.dim.nocc[is], + this->lr_.dim.nvirt[is], false); pre_op.act(1, offset_is, 1, precondition.data() + offset_is, precondition.data() + offset_is); } } std::cout << "Solving spin-conserving excitation for open-shell system." << std::endl; HamiltULR hulr( - xc_kernel, nspin, this->nbasis, this->nocc, this->nvirt, *this->ucell_, orb_cutoff_, this->gd(), - *this->psi_ks, this->eig_ks, + xc_kernel, this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->ucell_, orb_cutoff_, this->gd(), + *this->lr_.gs.psi, this->lr_.gs.eig, #ifdef __EXX this->exx_lri, this->exx_info.info_global.hybrid_alpha, #endif - this->lr_.pot.pot, this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_); + this->lr_.pot.pot, this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat); LR::HSolver::solve( - hulr, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, nstates, this->nk, this->nocc, this->nvirt, + hulr, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates, this->lr_.dim.nk, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.amp.para_x, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); if (this->inp_->out_wfc_lr) { - write_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, nstates); + write_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates); } } else @@ -171,31 +171,31 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste if (this->inp_->lr_solver != "lapack") { OperatorLRDiag pre_op( - this->eig_ks.c, this->lr_.amp.para_x[0], this->nk, this->nocc[0], this->nvirt[0], false); + this->lr_.gs.eig.c, this->lr_.amp.para_x[0], this->lr_.dim.nk, this->lr_.dim.nocc[0], this->lr_.dim.nvirt[0], false); pre_op.act(1, this->lr_.amp.nloc, 1, precondition.data(), precondition.data()); } const std::vector &spin_types = this->lr_.amp.spin_types; - for (int is = 0; is < nspin; ++is) + for (int is = 0; is < this->lr_.dim.nspin; ++is) { std::cout << " Calculating " << spin_types[is] << " excitations" << std::endl; HamiltLR hlr( - xc_kernel, nspin, this->nbasis, this->nocc, this->nvirt, *this->ucell_, orb_cutoff_, this->gd(), - *this->psi_ks, this->eig_ks, + xc_kernel, this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->ucell_, orb_cutoff_, this->gd(), + *this->lr_.gs.psi, this->lr_.gs.eig, #ifdef __EXX this->exx_lri, this->exx_info.info_global.hybrid_alpha, #endif - this->lr_.pot.pot[is], this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, spin_types[is], this->in_dir, + this->lr_.pot.pot[is], this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat, spin_types[is], this->in_dir, this->out_dir, this->inp_->ri_hartree_benchmark, (this->inp_->ri_hartree_benchmark == "aims" ? this->inp_->aims_nbasis : std::vector({}))); LR::HSolver::solve( - hlr, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, nstates, this->nk, this->nocc, this->nvirt, - this->lr_.amp.para_x, this->pelec->ekb.c + is * nstates, this->inp_->lr_solver, this->inp_->lr_thr, + hlr, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates, this->lr_.dim.nk, this->lr_.dim.nocc, this->lr_.dim.nvirt, + this->lr_.amp.para_x, this->pelec->ekb.c + is * this->lr_.dim.nstates, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); if (this->inp_->out_wfc_lr) { write_states( - spin_types[is], this->pelec->ekb.c + is * nstates, this->lr_.amp.x[is].template data(), - this->lr_.amp.nloc, nstates); + spin_types[is], this->pelec->ekb.c + is * this->lr_.dim.nstates, this->lr_.amp.x[is].template data(), + this->lr_.amp.nloc, this->lr_.dim.nstates); } } } @@ -223,18 +223,18 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste std::cout << "Rank " << this->my_rank_ << ": finish reading " << vfile_in(label) << std::endl; }; std::cout << "reading the excitation states from file: \n"; - if (openshell) + if (this->lr_.dim.openshell) { - read_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, nstates); + read_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates); } else { const std::vector &spin_types = this->lr_.amp.spin_types; - for (int is = 0; is < nspin; ++is) + for (int is = 0; is < this->lr_.dim.nspin; ++is) { read_states( - spin_types[is], this->pelec->ekb.c + is * nstates, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, - nstates); + spin_types[is], this->pelec->ekb.c + is * this->lr_.dim.nstates, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, + this->lr_.dim.nstates); } } } @@ -252,7 +252,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste // One line per ionic step with the two halves of the energy and of the gradient. Without // it the relaxation only reports a force, and whether E_gs + Omega actually goes down -- // the thing being minimised -- cannot be read off the log at all. - const double omega = this->lr_.relax.target.omega(this->pelec->ekb.c, this->nstates); + const double omega = this->lr_.relax.target.omega(this->pelec->ekb.c, this->lr_.dim.nstates); auto max_abs = [](const ModuleBase::matrix &m) -> double { double v = 0.0; @@ -293,15 +293,15 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) if (this->inp_->out_chg[0]) { LR_Density lr_density( - *this->ucell_, kv, gd(), *psi_ks, orb_cutoff_, pgrid(), nspin, nocc, nvirt, nbasis, this->lr_.amp.para_x, this->lr_.amp.para_c, - paraMat_, openshell, this->inp_->out_chg[1], this->out_dir); + *this->ucell_, kv, gd(), *this->lr_.gs.psi, orb_cutoff_, pgrid(), this->lr_.dim.nspin, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nbasis, this->lr_.amp.para_x, this->lr_.amp.para_c, + paraMat_, this->lr_.dim.openshell, this->inp_->out_chg[1], this->out_dir); - if (openshell) + if (this->lr_.dim.openshell) { - for (int is = 0; is < this->nspin; ++is) + for (int is = 0; is < this->lr_.dim.nspin; ++is) { const T *const amplitudes = this->lr_.amp.x[0].template data(); - lr_density.output_eh_density_all_states(amplitudes, is, nstates, this->ofs_running_); + lr_density.output_eh_density_all_states(amplitudes, is, this->lr_.dim.nstates, this->ofs_running_); } } else @@ -309,21 +309,21 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) for (int is = 0; is < this->lr_.amp.x.size(); ++is) { const T *const amplitudes = this->lr_.amp.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, this->lr_.dim.nstates, this->ofs_running_); } } } const std::string gauge = LR_Util::tolower(this->inp_->abs_gauge); const bool calculate_spectrum = gauge != "none"; - const std::vector spatial_weights = LR_Util::spatial_k_weights(this->kv.wk, nspin); + const std::vector spatial_weights = LR_Util::spatial_k_weights(this->kv.wk, this->lr_.dim.nspin); // cal spectrum if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; this->velocity_mo = LR_Util::cal_velocity_mo( - *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->lr_.amp.para_c, this->kv, *this->psi_ks, this->nk, - nspin_tmp, this->nbasis, this->nocc, this->nvirt); + *this->ucell_, this->gd(), this->tcb(), this->lr_.gs.para_mat, this->lr_.amp.para_c, this->kv, *this->lr_.gs.psi, this->lr_.dim.nk, + nspin_tmp, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt); } std::vector freq; if (calculate_spectrum) @@ -348,15 +348,15 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) { if (!calculate_spectrum) { - const double *const energies = &this->pelec->ekb.c[is * nstates]; - LR_Util::print_excitation_energies(this->ofs_running_, energies, nstates, this->lr_.amp.spin_types[is]); + const double *const energies = &this->pelec->ekb.c[is * this->lr_.dim.nstates]; + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->lr_.dim.nstates, this->lr_.amp.spin_types[is]); } else { LR_Spectrum spectrum( - nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, this->kv, - spatial_weights, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, - &this->pelec->ekb.c[is * nstates], this->eig_ks.c, this->lr_.amp.x[is].template data(), nstates, openshell, + this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->pw_rho, *this->lr_.gs.psi, *this->ucell_, this->kv, + spatial_weights, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat, + &this->pelec->ekb.c[is * this->lr_.dim.nstates], this->lr_.gs.eig.c, this->lr_.amp.x[is].template data(), this->lr_.dim.nstates, this->lr_.dim.openshell, LR_Util::tolower(this->inp_->abs_gauge), this->my_rank_, this->out_dir); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { @@ -403,64 +403,35 @@ void ModuleESolver::ESolver_LR::set_dim() src.kpar = this->kv.para_k.kpar; src.rank_in_pool = this->kv.para_k.rank_in_pool; src.in_dir = this->in_dir; - src.ucell = const_cast(this->ucell_); + src.ucell = const_cast(this->ucell_); src.log = &this->ofs_running_; - const LR::Dim dim = LR::resolve_dim(src); - - this->nspin = dim.nspin; - this->nstates = dim.nstates; - this->nbasis = dim.nbasis; - this->nbands = dim.nbands; - this->nk = dim.nk; - this->nupdown = dim.nupdown; - this->nocc_in = dim.nocc_in; - this->nocc_max = dim.nocc_max; - this->nvirt_in = dim.nvirt_in; - this->openshell = dim.openshell; - this->nocc = dim.nocc; - this->nvirt = dim.nvirt; - this->npairs = dim.npairs; + this->lr_.dim = LR::resolve_dim(src); } template void ModuleESolver::ESolver_LR::reset_dim_spin() { - LR::Dim dim; - dim.nspin = this->nspin; - dim.nstates = this->nstates; - dim.nk = this->nk; - dim.nupdown = this->nupdown; - dim.openshell = this->openshell; - dim.nocc = this->nocc; - dim.nvirt = this->nvirt; - dim.npairs = this->npairs; - - LR::apply_spin_pol(dim, *this->inp_); - - this->nocc = dim.nocc; - this->nvirt = dim.nvirt; - this->npairs = dim.npairs; - this->openshell = dim.openshell; + LR::apply_spin_pol(this->lr_.dim, *this->inp_); } template void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) { - this->lr_.pot.pot.assign(nspin, nullptr); + this->lr_.pot.pot.assign(this->lr_.dim.nspin, nullptr); if (this->inp_->ri_hartree_benchmark != "none") { return; } const auto &grid = pgrid(); auto prepared = - LR::prepare_lr_potentials(*this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell); + LR::prepare_lr_potentials(*this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, this->lr_.dim.nspin, this->lr_.dim.openshell); this->lr_.pot.pot = std::move(prepared.pot); if (this->inp_->cal_force) { this->init_pot_groundstate(chg_gs); this->lr_.pot.pot_hxc_gs = LR::prepare_gs_potential( - *this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, nspin, openshell, prepared); + *this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, this->lr_.dim.nspin, this->lr_.dim.openshell, prepared); } } @@ -471,8 +442,8 @@ template void ModuleESolver::ESolver_LR::setup_eigenvectors_X() { ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); - LR::XAmp amp = LR::setup_x(this->lr_.amp.para_c, this->nocc, this->nvirt, this->npairs, this->eig_ks, this->nstates, - this->nk, this->nspin, this->openshell, this->inp_->lr_solver == "spectrum", + LR::XAmp amp = LR::setup_x(this->lr_.amp.para_c, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.npairs, this->lr_.gs.eig, this->lr_.dim.nstates, + this->lr_.dim.nk, this->lr_.dim.nspin, this->lr_.dim.openshell, this->inp_->lr_solver == "spectrum", this->ofs_running_); this->lr_.amp.x = std::move(amp.x); this->lr_.amp.para_x = std::move(amp.para_x); @@ -482,38 +453,19 @@ void ModuleESolver::ESolver_LR::setup_eigenvectors_X() template void ModuleESolver::ESolver_LR::read_ks_wfc() { - assert(this->psi_ks != nullptr); - LR::GsWfc wfc = LR::read_gs_wfc(*this->psi_ks, this->eig_ks, this->wg_ks, this->paraMat_, this->paraMat_all_, - this->in_dir, *this->inp_, this->nocc_in, this->nvirt_in, this->nocc_max, - this->nbands, this->nbasis, this->kv, this->inp_->cal_force, - this->ofs_running_); - this->psi_ks_all_own_ = std::move(wfc.all_own); - this->psi_ks_all_ = wfc.all; - this->eig_ks_all = std::move(wfc.eig_all); - this->wg_ks_all = std::move(wfc.wg_all); + this->lr_.read_wfc(this->in_dir, *this->inp_, this->kv, this->ofs_running_); } template void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) { - ModuleBase::TITLE("ESolver_LR", "fill_z_window_"); - LR::ZWin z = LR::build_z_win(this->psi_ks_all_, this->eig_ks_all, this->nocc, this->nvirt, this->nocc_max, - this->nbands, this->nbasis, this->nk, this->openshell, this->kv, this->lr_.amp.para_c, - this->paraMat_, desc_src, this->inp_->cal_force, !this->ks_initialized_, - this->ofs_running_); - this->lr_.zw.psi = std::move(z.psi); - this->lr_.zw.eig = std::move(z.eig); - this->lr_.zw.para_c = std::move(z.para_c); - this->lr_.zw.para_x = std::move(z.para_x); - this->lr_.zw.nvirt = std::move(z.nvirt); - this->lr_.zw.nbands = z.nbands; - this->lr_.zw.nloc = z.nloc; + this->lr_.fill_z(desc_src, this->kv, this->inp_->cal_force, !this->ks_initialized_, this->ofs_running_); } template void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) { - LR::read_gs_chg(this->in_dir, *this->inp_, this->nspin, *this->ucell_, pgrid(), this->pw_rho, chg_gs, + LR::read_gs_chg(this->in_dir, *this->inp_, this->lr_.dim.nspin, *this->ucell_, pgrid(), this->pw_rho, chg_gs, this->my_rank_, this->ofs_running_); } @@ -528,32 +480,24 @@ void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); } -template -ct::Tensor ModuleESolver::ESolver_LR::pad_X_to_z_(const int ispin, const int istate_begin, const int nst) const -{ - return LR::pad_amplitudes( - this->lr_.amp.x, this->openshell, this->lr_.amp.para_x, this->lr_.zw.para_x, this->nocc, this->nvirt, this->nk, this->lr_.amp.nloc, - this->lr_.zw.nloc, ispin, istate_begin, nst); -} - template LR::GsForceCtx ModuleESolver::ESolver_LR::gs_force_ctx_() const { // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight - // from the ground-state solver's own `psi`), but per `this->paraMat_all_` on the + // from the ground-state solver's own `psi`), but per `this->lr_.gs.para_mat_all` on the // read-from-file path, where it was allocated with that descriptor's own sizes. - const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; + const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; const LR::ForceSettings settings{ - this->nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; - return {*this->psi_ks_all_, this->wg_ks_all, *pv_all, *this->pw_rho, *this->pw_rhod, this->vloc(), this->sfac(), - this->tcb(), settings, this->openshell, this->inp_->lr_grad_solver, this->in_dir}; + this->lr_.dim.nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; + return {*this->lr_.gs.psi_all, this->lr_.gs.wg_all, *pv_all, *this->pw_rho, *this->pw_rhod, this->vloc(), this->sfac(), + this->tcb(), settings, this->lr_.dim.openshell, this->inp_->lr_grad_solver, this->in_dir}; } template LR::StateCtx ModuleESolver::ESolver_LR::state_ctx_() const { - return {this->lr_.amp.x, this->lr_.amp.para_x, this->lr_.zw.para_x, this->nocc, this->nvirt, this->nk, this->lr_.amp.nloc, - this->lr_.zw.nloc, this->nstates, this->openshell, this->pelec->ekb.c}; + return {this->lr_.amp.x, this->lr_.amp.para_x, this->lr_.zw.para_x, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nk, this->lr_.amp.nloc, + this->lr_.zw.nloc, this->lr_.dim.nstates, this->lr_.dim.openshell, this->pelec->ekb.c}; } template @@ -563,7 +507,7 @@ std::vector ModuleESolver::ESolver_LR::cal_force(cons { this->test_force(); } - return this->openshell + return this->lr_.dim.openshell ? LR::state_forces_os(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), istate_only) : LR::state_forces(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), ispin, istate_only); @@ -572,8 +516,8 @@ std::vector ModuleESolver::ESolver_LR::cal_force(cons template LR::GradientInputs ModuleESolver::ESolver_LR::gradient_inputs_() const { - return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->paraMat_, this->lr_.zw.para_c, this->lr_.zw.para_x, - *this->lr_.zw.psi, this->lr_.zw.eig, this->nocc, this->lr_.zw.nvirt, this->nspin, this->nk, this->nbasis, + return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->lr_.gs.para_mat, this->lr_.zw.para_c, this->lr_.zw.para_x, + *this->lr_.zw.psi, this->lr_.zw.eig, this->lr_.dim.nocc, this->lr_.zw.nvirt, this->lr_.dim.nspin, this->lr_.dim.nk, this->lr_.dim.nbasis, this->lr_.zw.nloc, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, this->inp_->test_force, this->lr_.relax.target.active(), this->out_dir, this->my_rank_, this->lr_.amp.spin_types, this->lr_.pot.pot, this->lr_.pot.pot_hxc_gs, this->ofs_running_ @@ -637,20 +581,20 @@ template module_dm::DensityMatrix ModuleESolver::ESolver_LR::cal_dm_gs() { // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight - // from the ground-state solver's own `psi`), but per `this->paraMat_all_` on the + // from the ground-state solver's own `psi`), but per `this->lr_.gs.para_mat_all` on the // read-from-file path (where it was allocated with that descriptor's own sizes). - const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; - return LR::make_gs_dm(*this->psi_ks_all_, this->wg_ks_all, *pv_all, this->paraMat_, *this->ucell_, this->gd(), - this->orb_cutoff_, this->nspin, this->kv.kvec_d, this->nk); + const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; + return LR::make_gs_dm(*this->lr_.gs.psi_all, this->lr_.gs.wg_all, *pv_all, this->lr_.gs.para_mat, *this->ucell_, this->gd(), + this->orb_cutoff_, this->lr_.dim.nspin, this->kv.kvec_d, this->lr_.dim.nk); } template void ModuleESolver::ESolver_LR::test_force() { 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}; + this->lr_.dim.nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; LR_Force lr_force( - (*this->ucell_), this->kv.kvec_d, this->paraMat_, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), + (*this->ucell_), this->kv.kvec_d, this->lr_.gs.para_mat, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), this->gd(), this->tcb(), force_settings, this->ofs_running_ #ifdef __EXX , @@ -662,18 +606,18 @@ void ModuleESolver::ESolver_LR::test_force() // LR_Util::print_DMR(dm_gs, "DM(R) of ground state"); ///========================== test 1: reproduce the force of ground state ========================= // energy density matrix of the ground state - module_dm::DensityMatrix edm_gs(&this->paraMat_, this->nspin, this->kv.kvec_d, this->nk); // DX - ModuleBase::matrix wg_ekb_ks_all(nspin, this->inp_->nbands); - const int occupation_count = nspin * this->inp_->nbands; + module_dm::DensityMatrix edm_gs(&this->lr_.gs.para_mat, this->lr_.dim.nspin, this->kv.kvec_d, this->lr_.dim.nk); // DX + ModuleBase::matrix wg_ekb_ks_all(this->lr_.dim.nspin, this->inp_->nbands); + const int occupation_count = this->lr_.dim.nspin * this->inp_->nbands; for (int index = 0; index < occupation_count; ++index) { - wg_ekb_ks_all.c[index] = this->wg_ks_all.c[index] * this->eig_ks_all.c[index]; + wg_ekb_ks_all.c[index] = this->lr_.gs.wg_all.c[index] * this->lr_.gs.eig_all.c[index]; } // see `cal_dm_gs()`: `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path, - // not `this->paraMat_all_`. - const Parallel_Orbitals *const pv_all_edm = this->ks_ ? &this->ks_->pv : &this->paraMat_all_; - module_dm::dm_from_psi(pv_all_edm, wg_ekb_ks_all, *this->psi_ks_all_, edm_gs); - LR_Util::initialize_DMR(edm_gs, this->paraMat_, (*this->ucell_), this->gd(), this->orb_cutoff_); + // not `this->lr_.gs.para_mat_all`. + const Parallel_Orbitals *const pv_all_edm = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; + module_dm::dm_from_psi(pv_all_edm, wg_ekb_ks_all, *this->lr_.gs.psi_all, edm_gs); + LR_Util::initialize_DMR(edm_gs, this->lr_.gs.para_mat, (*this->ucell_), this->gd(), this->orb_cutoff_); edm_gs.cal_dmr(-1); // ground-state force ModuleBase::matrix force_gs = lr_force.reproduce_force_gs(kv, dm_gs, edm_gs); @@ -697,7 +641,7 @@ void ModuleESolver::ESolver_LR::test_force() template void ModuleESolver::ESolver_LR::setup_relax_target_() { - this->lr_.relax.target.setup(*this->inp_, this->openshell, this->nspin, this->nstates, this->ofs_running_); + this->lr_.relax.target.setup(*this->inp_, this->lr_.dim.openshell, this->lr_.dim.nspin, this->lr_.dim.nstates, this->ofs_running_); if (this->lr_.relax.target.active()) { this->lr_.relax.force_gs.create(this->ucell_->nat, 3); @@ -715,14 +659,14 @@ void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); return; } - const int channel = this->openshell ? 0 : this->lr_.relax.target.ispin(); + const int channel = this->lr_.dim.openshell ? 0 : this->lr_.relax.target.ispin(); const T *const amplitudes = this->lr_.amp.x[channel].template data(); const TwoCenterIntegrator &overlap_integrator = *this->tcb().overlap_orb; - std::vector energies(this->nstates); - std::copy_n(this->pelec->ekb.c + this->lr_.relax.target.ekb_off(this->nstates), this->nstates, energies.begin()); - this->lr_.relax.target.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->psi_ks, this->lr_.amp.para_c, - this->paraMat_, this->lr_.amp.para_x, this->nocc, this->nvirt, amplitudes, this->lr_.amp.nloc, - this->nstates, energies, ofs); + std::vector energies(this->lr_.dim.nstates); + std::copy_n(this->pelec->ekb.c + this->lr_.relax.target.ekb_off(this->lr_.dim.nstates), this->lr_.dim.nstates, energies.begin()); + this->lr_.relax.target.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->lr_.gs.psi, this->lr_.amp.para_c, + this->lr_.gs.para_mat, this->lr_.amp.para_x, this->lr_.dim.nocc, this->lr_.dim.nvirt, amplitudes, this->lr_.amp.nloc, + this->lr_.dim.nstates, energies, ofs); ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); } @@ -739,7 +683,7 @@ double ModuleESolver::ESolver_LR::cal_energy() // otherwise, matching whatever `cal_lr_force_relax_` produced the gradient of. The // energy-based optimisers line-search on this, so the two must not describe different // surfaces. - return this->lr_.relax.etot_gs + this->lr_.relax.target.omega(this->pelec->ekb.c, this->nstates); + return this->lr_.relax.etot_gs + this->lr_.relax.target.omega(this->pelec->ekb.c, this->lr_.dim.nstates); } template @@ -778,14 +722,14 @@ void ModuleESolver::ESolver_LR::cal_stress(BaseCell &basecell, ModuleBase template ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, const std::vector &group) const { - return LR::pad_group(this->lr_.amp.x, this->openshell, this->lr_.amp.para_x, this->lr_.zw.para_x, this->nocc, this->nvirt, this->nk, + return LR::pad_group(this->lr_.amp.x, this->lr_.dim.openshell, this->lr_.amp.para_x, this->lr_.zw.para_x, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nk, this->lr_.amp.nloc, this->lr_.zw.nloc, ispin, group); } template ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::ofstream &ofs) { - this->lr_.relax.target.resolve_group(*this->inp_, this->pelec->ekb.c, this->nstates, this->ofs_running_); + this->lr_.relax.target.resolve_group(*this->inp_, this->pelec->ekb.c, this->lr_.dim.nstates, this->ofs_running_); const std::vector &group = this->lr_.relax.target.group(); if (group.empty()) { @@ -796,7 +740,7 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::of // construction, so the off-diagonal part (and the extra d(d-1)/2 solves it costs) is not // involved. The Jahn-Teller direction is orthogonal to the average and does need them. const int d = static_cast(group.size()); - const int ekb_off = this->lr_.relax.target.ekb_off(this->nstates); + const int ekb_off = this->lr_.relax.target.ekb_off(this->lr_.dim.nstates); const ct::Tensor Xz = this->pad_group_to_z_(this->lr_.relax.target.ispin(), group); std::vector omega(d); for (int k = 0; k < d; ++k) @@ -804,7 +748,7 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::of omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; } const std::vector forces = - this->openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) + this->lr_.dim.openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) : this->cal_force_Xz(this->lr_.relax.target.ispin(), Xz, omega, group.front()); ofs << " Followed state " << this->lr_.relax.target.state() << " is degenerate with"; for (const int ist : group) @@ -814,7 +758,7 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::of ofs << " " << ist; } } - ofs << " (Omega_bar = " << this->lr_.relax.target.omega(this->pelec->ekb.c, this->nstates) << " Ry)." << std::endl; + ofs << " (Omega_bar = " << this->lr_.relax.target.omega(this->pelec->ekb.c, this->lr_.dim.nstates) << " Ry)." << std::endl; if (!jt_mode) { ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" @@ -836,7 +780,7 @@ ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( const LR::MplLvc mpl = LR::build_mpl_state(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), this->lr_.relax.target.ispin(), group, diag, ofs); LR::JtForce jt = LR::eval_jt_force(mpl.g, ofs); - const int channel = this->openshell ? 0 : this->lr_.relax.target.ispin(); + const int channel = this->lr_.dim.openshell ? 0 : this->lr_.relax.target.ispin(); this->lr_.relax.target.save_mixed(this->lr_.amp.x[channel].template data(), this->lr_.amp.nloc, jt.mixing); // The returned force is the descending branch's own gradient; once a step splits the // multiplet `resolve_group` finds no group and the single-state path takes over. @@ -957,54 +901,54 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons // kv this->kv = ks_sol.kv; // copy: cheap, and the KS solver keeps using its own - LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); + LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->lr_.dim.nspin); this->set_dim(); // KS and LR must use the same AO distribution, including its BLACS grid. const int ks_block_size = ks_sol.pv.para_2d().nb(); LR_Util::setup_2d_division( - this->paraMat_.para_2d(), ks_block_size, this->nbasis, this->nbasis + this->lr_.gs.para_mat.para_2d(), ks_block_size, this->lr_.dim.nbasis, this->lr_.dim.nbasis #ifdef __MPI , ks_sol.pv.para_2d().ictxt() #endif ); - LR::set_band_layout(this->paraMat_, this->nbasis, this->nbands, *this->ucell_, + LR::set_band_layout(this->lr_.gs.para_mat, this->lr_.dim.nbasis, this->lr_.dim.nbands, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); if (this->inp_->cal_force) { LR_Util::setup_2d_division( - this->paraMat_all_.para_2d(), ks_block_size, this->nbasis, this->nbasis + this->lr_.gs.para_mat_all.para_2d(), ks_block_size, this->lr_.dim.nbasis, this->lr_.dim.nbasis #ifdef __MPI , ks_sol.pv.para_2d().ictxt() #endif ); - LR::set_band_layout(this->paraMat_all_, this->nbasis, this->inp_->nbands, *this->ucell_, + LR::set_band_layout(this->lr_.gs.para_mat_all, this->lr_.dim.nbasis, this->inp_->nbands, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); } - this->paraMat_.atom_begin_row = ks_sol.pv.atom_begin_row; - this->paraMat_.atom_begin_col = ks_sol.pv.atom_begin_col; - this->paraMat_.iat2iwt_ = ucell.get_iat2iwt(); + this->lr_.gs.para_mat.atom_begin_row = ks_sol.pv.atom_begin_row; + this->lr_.gs.para_mat.atom_begin_col = ks_sol.pv.atom_begin_col; + this->lr_.gs.para_mat.iat2iwt_ = ucell.get_iat2iwt(); LR_Util::setup_2d_division( - this->lr_.amp.para_c, ks_block_size, this->nbasis, this->nbands + this->lr_.amp.para_c, ks_block_size, this->lr_.dim.nbasis, this->lr_.dim.nbands #ifdef __MPI , - this->paraMat_.para_2d().ictxt() + this->lr_.gs.para_mat.para_2d().ictxt() #endif ); // allocate psi_ks and eig_ks in the [nocc, nvirt] window #ifdef __MPI - this->psi_ks.reset( + this->lr_.gs.psi.reset( new psi::Psi(this->kv.get_nks(), this->lr_.amp.para_c.ncloc(), this->lr_.amp.para_c.nrloc(), this->kv.ngk, true)); #else - this->psi_ks.reset(new psi::Psi(this->kv.get_nks(), this->nbands, this->nbasis, this->kv.ngk, true)); + this->lr_.gs.psi.reset(new psi::Psi(this->kv.get_nks(), this->lr_.dim.nbands, this->lr_.dim.nbasis, this->kv.ngk, true)); #endif - this->eig_ks.create(this->kv.get_nks(), this->nbands); + this->lr_.gs.eig.create(this->kv.get_nks(), this->lr_.dim.nbands); this->pelec = new elecstate::ElecStateLCAO(); orb_cutoff_ = ks_sol.orb_.cutoffs(); @@ -1054,50 +998,50 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) // The ground-state solver owns `psi` and reuses it across ionic steps, so it cannot be stolen. // `eig_ks_all` / `wg_ks_all` are nspin x nbands matrices -- a few kB, copied rather than aliased // so that they survive the KS solver overwriting `pelec` on the next step. - this->psi_ks_all_ = ks_sol.psi; - this->eig_ks_all = ks_sol.pelec->ekb; - this->wg_ks_all = ks_sol.pelec->wg; - const int max_occupied_bands = *std::max_element(nocc.begin(), nocc.end()); - const int start_band = this->nocc_max - max_occupied_bands; + this->lr_.gs.psi_all = ks_sol.psi; + this->lr_.gs.eig_all = ks_sol.pelec->ekb; + this->lr_.gs.wg_all = ks_sol.pelec->wg; + const int max_occupied_bands = *std::max_element(this->lr_.dim.nocc.begin(), this->lr_.dim.nocc.end()); + const int start_band = this->lr_.dim.nocc_max - max_occupied_bands; for (int ik = 0; ik < this->kv.get_nks(); ++ik) { // copy the KS orbitals in the [nocc, nvirt] window #ifdef __MPI - this->psi_ks_all_->fix_k(ik); - this->psi_ks->fix_k(ik); + this->lr_.gs.psi_all->fix_k(ik); + this->lr_.gs.psi->fix_k(ik); const int first_band = start_band + 1; Cpxgemr2d( - this->nbasis, this->nbands, this->psi_ks_all_->get_pointer(), 1, first_band, ks_sol.pv.desc_wfc, - this->psi_ks->get_pointer(), 1, 1, const_cast(this->lr_.amp.para_c.desc()), this->lr_.amp.para_c.ictxt()); + this->lr_.dim.nbasis, this->lr_.dim.nbands, this->lr_.gs.psi_all->get_pointer(), 1, first_band, ks_sol.pv.desc_wfc, + this->lr_.gs.psi->get_pointer(), 1, 1, const_cast(this->lr_.amp.para_c.desc()), this->lr_.amp.para_c.ictxt()); #else // serial: each band is `nbasis` contiguous coefficients, so the window is a plain // band-by-band copy (this loop used to compute the two pointers and copy nothing, // leaving `psi_ks` uninitialized in every non-MPI build) - for (int ib = 0; ib < this->nbands; ++ib) + for (int ib = 0; ib < this->lr_.dim.nbands; ++ib) { - const auto *start = &(*this->psi_ks_all_)(ik, start_band + ib, 0); - auto *to = &(*this->psi_ks)(ik, ib, 0); - std::copy(start, start + this->nbasis, to); + const auto *start = &(*this->lr_.gs.psi_all)(ik, start_band + ib, 0); + auto *to = &(*this->lr_.gs.psi)(ik, ib, 0); + std::copy(start, start + this->lr_.dim.nbasis, to); } #endif // copy the KS bands in the [nocc, nvirt] window - for (int ib = 0; ib < this->nbands; ++ib) + for (int ib = 0; ib < this->lr_.dim.nbands; ++ib) { - this->eig_ks(ik, ib) = this->eig_ks_all(ik, start_band + ib); + this->lr_.gs.eig(ik, ib) = this->lr_.gs.eig_all(ik, start_band + ib); } } - if (nspin == 2) + if (this->lr_.dim.nspin == 2) { const int nupdown_now = LR_Util::spin_population_difference(ks_sol.pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); if (!this->ks_initialized_) { - this->nupdown = nupdown_now; + this->lr_.dim.nupdown = nupdown_now; reset_dim_spin(); // shifts nocc/nvirt between the spin channels: must run exactly once } - else if (nupdown_now != this->nupdown) + else if (nupdown_now != this->lr_.dim.nupdown) { ModuleBase::WARNING_QUIT( "ESolver_LR::refresh_from_ks_", @@ -1170,7 +1114,7 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell ModuleBase::GlobalFunc::DONE(this->ofs_running_, "INIT K-POINTS"); ModuleIO::print_parameters(ucell, this->kv, inp); - LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); + LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->lr_.dim.nspin); /// read orbitals and build the interpolation table two_center_bundle_own_.build_orb(ucell.ntype, ucell.orbital_fn.data(), inp.orbital_dir); @@ -1190,24 +1134,24 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell this->set_dim(); // setup 2d-block distribution for AO-matrix and KS wfc - LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); - LR::set_band_layout(this->paraMat_, this->nbasis, this->nbands, *this->ucell_, + LR_Util::setup_2d_division(this->lr_.gs.para_mat.para_2d(), 1, this->lr_.dim.nbasis, this->lr_.dim.nbasis); + LR::set_band_layout(this->lr_.gs.para_mat, this->lr_.dim.nbasis, this->lr_.dim.nbands, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); if (this->inp_->cal_force) { - LR_Util::setup_2d_division(this->paraMat_all_.para_2d(), 1, this->nbasis, this->nbasis); - LR::set_band_layout(this->paraMat_all_, this->nbasis, this->inp_->nbands, *this->ucell_, + LR_Util::setup_2d_division(this->lr_.gs.para_mat_all.para_2d(), 1, this->lr_.dim.nbasis, this->lr_.dim.nbasis); + LR::set_band_layout(this->lr_.gs.para_mat_all, this->lr_.dim.nbasis, this->inp_->nbands, *this->ucell_, this->inp_->ri_hartree_benchmark == "aims"); } // read the ground state info // now ModuleIO::read_wfc_nao needs `Parallel_Orbitals` and can only read all the bands // it need improvement to read only the bands needed - this->psi_ks.reset(new psi::Psi( - this->kv.get_nks(), this->paraMat_.ncol_bands, this->paraMat_.para_2d().nrloc(), this->kv.ngk, true)); + this->lr_.gs.psi.reset(new psi::Psi( + this->kv.get_nks(), this->lr_.gs.para_mat.ncol_bands, this->lr_.gs.para_mat.para_2d().nrloc(), this->kv.ngk, true)); this->read_ks_wfc(); - if (nspin == 2) + if (this->lr_.dim.nspin == 2) { // Complete file populations were read before selecting the occupied window. reset_dim_spin(); @@ -1220,7 +1164,7 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell #endif LR_Util::setup_2d_division( - this->lr_.amp.para_c, 1, this->nbasis, this->nbands + this->lr_.amp.para_c, 1, this->lr_.dim.nbasis, this->lr_.dim.nbands #ifdef __MPI , paraMat_.para_2d().ictxt() diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 6ca181c55b..03f034539a 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -105,40 +105,8 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// bind the aliases above; `ks_` must already be set (or null for the `lr` path) void bind_ground_state_aliases_(); - // ground state info - - /// @brief ground state wave function - std::unique_ptr> psi_ks; ///< KS orbitals used in the [nocc+nvirt] window - /// @brief all KS orbitals. On the `ks-lr` path this aliases the ground-state solver's - /// `psi` (nk x nbands x nbasis -- far too big to copy every ionic step, and only read - /// here); on the `lr` path it points at `psi_ks_all_own_`, filled from file. - psi::Psi *psi_ks_all_ = nullptr; - std::unique_ptr> psi_ks_all_own_; - - /// @brief ground state bands, read from the file, or moved from ESolver_FP::pelec.ekb - ModuleBase::matrix eig_ks; ///< ground state eigenvalues in the [nocc+nvirt] window - ModuleBase::matrix - eig_ks_all; ///< all eigenvalues of ground state, read from the file, or moved from ESolver_FP::pelec.ekb - ModuleBase::matrix wg_ks; /// occupation numbers of ground state in the [nocc+nvirt] window - ModuleBase::matrix wg_ks_all; /// occupation number of all bands of ground state - // @brief only needed for force calculation - std::vector nocc; ///< number of occupied orbitals for each spin used in the calculation - int nocc_in = 1; ///< nocc read from input (adjusted by nelec): max(spin-up, spindown) - int nocc_max = 1; ///< full occupied count in the largest spin channel - std::vector nvirt; ///< number of virtual orbitals for each spin used in the calculation - int nvirt_in = 1; ///< nvirt read from input (adjusted by nelec): min(spin-up, spindown) - int nbands = 2; - int nbasis = 2; - /// n_occ*nvirt, the basis size of electron-hole pair representation - std::vector npairs; - /// how many 2-particle states to be solved - int nstates = 1; - int nspin = 1; - int nk = 1; - int nupdown = 0; - bool openshell = false; std::string xc_kernel; void initialize_from_unitcell_(UnitCell &ucell, const Input_para &inp); @@ -181,7 +149,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP void fill_z_window_(const int *desc_src); /// Widen `nst` X blocks starting at `istate_begin` from the X window into the Z window, /// zero-filling the virtual rows X does not have. - ct::Tensor pad_X_to_z_(const int ispin, const int istate_begin, const int nst) const; /// @brief variables for parallel distribution of matrix in AO representation Parallel_Orbitals paraMat_; Parallel_Orbitals paraMat_all_; // for the parallelized size of the KS orbitals diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index a4b81bbf58..96bb7e90ac 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -34,11 +34,11 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para this->pelec = new elecstate::ElecStateLCAO(); this->kRlist = - LR_IO::RI_kRlist(*this->ucell_, &this->kv, this->nspin, this->rpa_dir, this->out_dir, inp.bse_use_fine_kgrid); + LR_IO::RI_kRlist(*this->ucell_, &this->kv, this->lr_.dim.nspin, this->rpa_dir, this->out_dir, inp.bse_use_fine_kgrid); ModuleBase::GlobalFunc::DONE(GlobalV::ofs_running, "Set K-POINTS and R-list for RI"); ModuleIO::print_parameters(ucell, this->kv, inp); - LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->nspin); + LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->lr_.dim.nspin); /// read orbitals and build the interpolation table this->two_center_bundle_own_.build_orb(ucell.ntype, ucell.orbital_fn.data(), inp.orbital_dir); @@ -55,33 +55,33 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para this->set_dim(); // setup 2d-block distribution for AO-matrix and KS wfc - LR_Util::setup_2d_division(this->paraMat_.para_2d(), 1, this->nbasis, this->nbasis); + LR_Util::setup_2d_division(this->lr_.gs.para_mat.para_2d(), 1, this->lr_.dim.nbasis, this->lr_.dim.nbasis); #ifdef __MPI - this->paraMat_.set_wfc_and_mo_layouts(this->nbasis, this->nbands); - int err = this->paraMat_.set_wfc_and_mo_sizes(this->nbands, GlobalV::ofs_running, GlobalV::ofs_warning); - this->paraMat_.set_atomic_trace(ucell.get_iat2iwt(), ucell.nat, this->nbasis); + this->lr_.gs.para_mat.set_wfc_and_mo_layouts(this->lr_.dim.nbasis, this->lr_.dim.nbands); + int err = this->lr_.gs.para_mat.set_wfc_and_mo_sizes(this->lr_.dim.nbands, GlobalV::ofs_running, GlobalV::ofs_warning); + this->lr_.gs.para_mat.set_atomic_trace(ucell.get_iat2iwt(), ucell.nat, this->lr_.dim.nbasis); #else - this->paraMat_.nrow_bands = this->nbasis; - this->paraMat_.ncol_bands = this->nbands; + this->lr_.gs.para_mat.nrow_bands = this->lr_.dim.nbasis; + this->lr_.gs.para_mat.ncol_bands = this->lr_.dim.nbands; #endif - this->psi_ks.reset(new psi::Psi( - this->kv.get_nks(), this->paraMat_.ncol_bands, this->paraMat_.para_2d().nrloc(), this->kv.ngk, true)); - this->psi_ks_global = new psi::Psi(this->kv.get_nks(), this->nbands, this->nbasis, this->kv.ngk, true); + this->lr_.gs.psi.reset(new psi::Psi( + this->kv.get_nks(), this->lr_.gs.para_mat.ncol_bands, this->lr_.gs.para_mat.para_2d().nrloc(), this->kv.ngk, true)); + this->psi_ks_global = new psi::Psi(this->kv.get_nks(), this->lr_.dim.nbands, this->lr_.dim.nbasis, this->kv.ngk, true); this->read_ks_wfc(); // NOTE: openshell is not implemented in BSE - if (this->nspin == 2) + if (this->lr_.dim.nspin == 2) { - this->nupdown = + this->lr_.dim.nupdown = LR_Util::spin_population_difference(this->pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); this->reset_dim_spin(); } LR_Util::setup_2d_division( - this->lr_.amp.para_c, this->paraMat_.para_2d().nb(), this->nbasis, this->nbands + this->lr_.amp.para_c, this->lr_.gs.para_mat.para_2d().nb(), this->lr_.dim.nbasis, this->lr_.dim.nbands #ifdef __MPI , - this->paraMat_.para_2d().ictxt() + this->lr_.gs.para_mat.para_2d().ictxt() #endif ); @@ -103,11 +103,11 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para this->gd(), inp.nspin, PARAM.globalv.gamma_only_local, PARAM.globalv.domag, inp.device == "gpu", inp.nstream)); ModuleGint::Gint::set_gint_info(this->gint_info_.get()); - this->lr_.pot.pot.resize(this->nspin, nullptr); + this->lr_.pot.pot.resize(this->lr_.dim.nspin, nullptr); if (this->inp_->lr_solver != "spectrum" && this->inp_->lr_solver != "plot") { this->mo_lri = LR_Util::make_unique>( - *this->ucell_, this->nk, this->kRlist, this->nocc[0], this->nvirt[0], *this->psi_ks_global, + *this->ucell_, this->lr_.dim.nk, this->kRlist, this->lr_.dim.nocc[0], this->lr_.dim.nvirt[0], *this->psi_ks_global, this->inp_->bse_q_approx_mode, this->inp_->bse_q_approx_threshold, this->inp_->out_ri_cv, this->out_dir, GlobalV::MY_RANK, GlobalV::NPROC); @@ -153,9 +153,9 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) assert(this->xc_kernel == "bse"); this->lri_init(); BSE::HamiltBSE bse_matrix( - this->nspin, this->nbasis, this->nocc, this->nvirt, *this->ucell_, this->orb_cutoff_, this->gd(), - *this->psi_ks, *this->psi_ks_global, this->eig_gw, *this->mo_lri, this->lr_.pot.pot[0], this->kv, this->lr_.amp.para_x, - this->lr_.amp.para_c, this->paraMat_, this->inp_->bse_spin_types, this->inp_->bse_tda, + this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->ucell_, this->orb_cutoff_, this->gd(), + *this->lr_.gs.psi, *this->psi_ks_global, this->eig_gw, *this->mo_lri, this->lr_.pot.pot[0], this->kv, this->lr_.amp.para_x, + this->lr_.amp.para_c, this->lr_.gs.para_mat, this->inp_->bse_spin_types, this->inp_->bse_tda, this->inp_->bse_ri_hartree, this->inp_->bse_mem_save, this->inp_->bse_continue, this->inp_->out_bse_ab, this->out_dir, this->in_dir, GlobalV::MY_RANK, GlobalV::NPROC, this->inp_->ri_hartree_benchmark); @@ -186,25 +186,25 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) for (int is = 0; is < this->inp_->bse_spin_types.size(); ++is) { bse_matrix.tda_solver( - is, this->nstates, &this->tda_ene[is * this->nstates], this->lr_.amp.x[is].template data()); + is, this->lr_.dim.nstates, &this->tda_ene[is * this->lr_.dim.nstates], this->lr_.amp.x[is].template data()); std::cout << "eigenvalues: (Ry)" << std::endl; - int write_nstates = std::min(this->nstates, 20); - LR_Util::print_value(&this->tda_ene[is * this->nstates], write_nstates); + int write_nstates = std::min(this->lr_.dim.nstates, 20); + LR_Util::print_value(&this->tda_ene[is * this->lr_.dim.nstates], write_nstates); std::cout << "eigenvalues: (eV)" << std::endl; for (int i = 0; i < write_nstates; ++i) { - std::cout << this->tda_ene[is * this->nstates + i] * ModuleBase::Ry_to_eV << " "; + std::cout << this->tda_ene[is * this->lr_.dim.nstates + i] * ModuleBase::Ry_to_eV << " "; } std::cout << std::endl; std::cout << "Excition binding energies (eV):" - << (direct_gap - tda_ene[is * this->nstates]) * ModuleBase::Ry_to_eV << std::endl; + << (direct_gap - tda_ene[is * this->lr_.dim.nstates]) * ModuleBase::Ry_to_eV << std::endl; if (this->inp_->out_wfc_lr) { write_tda_states( - this->inp_->bse_spin_types[is], &this->tda_ene[is * this->nstates], - this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, this->nstates); + this->inp_->bse_spin_types[is], &this->tda_ene[is * this->lr_.dim.nstates], + this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates); } malloc_trim(0); } @@ -214,26 +214,26 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) for (int is = 0; is < this->inp_->bse_spin_types.size(); ++is) { bse_matrix.full_solver( - is, this->nstates, &this->full_ene[is * this->nstates], this->full_X[is].template data(), + is, this->lr_.dim.nstates, &this->full_ene[is * this->lr_.dim.nstates], this->full_X[is].template data(), this->full_Y[is].template data()); std::cout << "eigenvalues: (Ry)" << std::endl; - int write_nstates = std::min(this->nstates, 20); - LR_Util::print_value(&this->full_ene[is * this->nstates], write_nstates); + int write_nstates = std::min(this->lr_.dim.nstates, 20); + LR_Util::print_value(&this->full_ene[is * this->lr_.dim.nstates], write_nstates); for (int i = 0; i < write_nstates; ++i) { - std::cout << this->full_ene[is * this->nstates + i] * ModuleBase::Ry_to_eV << " "; + std::cout << this->full_ene[is * this->lr_.dim.nstates + i] * ModuleBase::Ry_to_eV << " "; } std::cout << std::endl; std::cout << "Excition binding energies (eV):" - << (direct_gap - full_ene[is * this->nstates]) * ModuleBase::Ry_to_eV << std::endl; + << (direct_gap - full_ene[is * this->lr_.dim.nstates]) * ModuleBase::Ry_to_eV << std::endl; if (this->inp_->out_wfc_lr) { write_full_states( - this->inp_->bse_spin_types[is], &this->full_ene[is * this->nstates], + this->inp_->bse_spin_types[is], &this->full_ene[is * this->lr_.dim.nstates], this->full_X[is].template data(), this->full_Y[is].template data(), - this->lr_.amp.nloc, this->nstates); + this->lr_.amp.nloc, this->lr_.dim.nstates); } malloc_trim(0); } @@ -278,8 +278,8 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) for (int is = 0; is < this->inp_->bse_spin_types.size(); ++is) { read_tda_states( - this->inp_->bse_spin_types[is], &this->tda_ene[is * this->nstates], this->lr_.amp.x[is].template data(), - this->lr_.amp.nloc, this->nstates); + this->inp_->bse_spin_types[is], &this->tda_ene[is * this->lr_.dim.nstates], this->lr_.amp.x[is].template data(), + this->lr_.amp.nloc, this->lr_.dim.nstates); } } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "full") @@ -287,11 +287,11 @@ void ESolver_BSE::runner(BaseCell &basecell, const int istep) for (int is = 0; is < this->inp_->bse_spin_types.size(); ++is) { read_full_states( - this->inp_->bse_spin_types[is], &this->full_ene[is * this->nstates], + this->inp_->bse_spin_types[is], &this->full_ene[is * this->lr_.dim.nstates], this->full_X[is].template data(), this->full_Y[is].template data(), this->lr_.amp.nloc, - this->nstates); + this->lr_.dim.nstates); // check whether |X|^2 - |Y|^2 = 1 - for (int i = 0; i < this->nstates; ++i) + for (int i = 0; i < this->lr_.dim.nstates; ++i) { double norm_xy = 0.0; for (int j = 0; j < this->lr_.amp.nloc; ++j) @@ -339,9 +339,9 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) std::cout << "plot BSE exciton wavefunction for state: " << this->inp_->plot_istate << ", spin type: " << this->inp_->bse_spin_types[is] << std::endl; LR_Util::ExcitonPlotter eplot( - this->nspin, this->nbasis, this->nocc, this->nvirt, *this->psi_ks, *this->ucell_, this->kv, this->gd(), - this->orb_cutoff_, this->pgrid(), *this->pw_rho, this->lr_.amp.para_x, this->lr_.amp.para_c, this->paraMat_, output_dir, - &this->tda_ene[is * this->nstates], this->lr_.amp.x[is].template data(), false /*openshell*/, &this->orb_); + this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->lr_.gs.psi, *this->ucell_, this->kv, this->gd(), + this->orb_cutoff_, this->pgrid(), *this->pw_rho, this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat, output_dir, + &this->tda_ene[is * this->lr_.dim.nstates], this->lr_.amp.x[is].template data(), false /*openshell*/, &this->orb_); const std::string plot_type = LR_Util::tolower(this->inp_->exciton_plot_type); const std::string plot_format = LR_Util::tolower(this->inp_->exciton_plot_format); const bool write_slice = (plot_format == "slice" || plot_format == "both"); @@ -410,18 +410,18 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { for (int is = 0; is < this->lr_.amp.x.size(); ++is) { - const double *const energies = &this->tda_ene[is * this->nstates]; + const double *const energies = &this->tda_ene[is * this->lr_.dim.nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_tda"; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->lr_.dim.nstates, channel); } } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "full") { for (int is = 0; is < this->full_X.size(); ++is) { - const double *const energies = &this->full_ene[is * this->nstates]; + const double *const energies = &this->full_ene[is * this->lr_.dim.nstates]; const std::string channel = this->inp_->bse_spin_types[is] + "_full"; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->nstates, channel); + LR_Util::print_excitation_energies(this->ofs_running_, energies, this->lr_.dim.nstates, channel); } } } @@ -432,18 +432,18 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) { const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; this->velocity_mo = LR_Util::cal_velocity_mo( - *this->ucell_, this->gd(), this->tcb(), this->paraMat_, this->lr_.amp.para_c, this->kv, *this->psi_ks, - this->nk, nspin_tmp, this->nbasis, this->nocc, this->nvirt); + *this->ucell_, this->gd(), this->tcb(), this->lr_.gs.para_mat, this->lr_.amp.para_c, this->kv, *this->lr_.gs.psi, + this->lr_.dim.nk, nspin_tmp, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt); } if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "tda") { for (int is = 0; is < this->lr_.amp.x.size(); ++is) { LR::LR_Spectrum spectrum( - this->nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, + this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->pw_rho, *this->lr_.gs.psi, *this->ucell_, this->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, - this->paraMat_, &this->tda_ene[is * this->nstates], this->eig_ks.c, - this->lr_.amp.x[is].template data(), this->nstates, false /*openshell*/, + this->lr_.gs.para_mat, &this->tda_ene[is * this->lr_.dim.nstates], this->lr_.gs.eig.c, + this->lr_.amp.x[is].template data(), this->lr_.dim.nstates, false /*openshell*/, LR_Util::tolower(this->inp_->abs_gauge), GlobalV::MY_RANK, output_dir); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { @@ -472,10 +472,10 @@ void ESolver_BSE::after_all_runners(BaseCell &basecell) for (int is = 0; is < this->full_X.size(); ++is) { LR::LR_Spectrum spectrum( - this->nspin, this->nbasis, this->nocc, this->nvirt, *this->pw_rho, *this->psi_ks, *this->ucell_, + this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->pw_rho, *this->lr_.gs.psi, *this->ucell_, this->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, - this->paraMat_, &this->full_ene[is * this->nstates], this->eig_ks.c, - this->full_X[is].template data(), this->nstates, false /*openshell*/, + this->lr_.gs.para_mat, &this->full_ene[is * this->lr_.dim.nstates], this->lr_.gs.eig.c, + this->full_X[is].template data(), this->lr_.dim.nstates, false /*openshell*/, LR_Util::tolower(this->inp_->abs_gauge), GlobalV::MY_RANK, output_dir); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { @@ -506,15 +506,15 @@ void ESolver_BSE::ipa_solver() ModuleBase::timer::start("ESolver_BSE", "ipa_solver"); std::cout << "Independent particle approximation is used, assign X as identity matrix directly." << std::endl; assert(this->inp_->bse_tda == "tda"); - std::vector ev(this->nk * this->nocc[0] * this->nvirt[0], 0.0); - for (int ik = 0; ik < this->nk; ++ik) + std::vector ev(this->lr_.dim.nk * this->lr_.dim.nocc[0] * this->lr_.dim.nvirt[0], 0.0); + for (int ik = 0; ik < this->lr_.dim.nk; ++ik) { - for (int i = 0; i < this->nocc[0]; ++i) + for (int i = 0; i < this->lr_.dim.nocc[0]; ++i) { - for (int a = 0; a < this->nvirt[0]; ++a) + for (int a = 0; a < this->lr_.dim.nvirt[0]; ++a) { - int index = ik * this->nocc[0] * this->nvirt[0] + i * this->nvirt[0] + a; - ev[index] = this->eig_gw(ik, this->nocc[0] + a) - this->eig_gw(ik, i); + int index = ik * this->lr_.dim.nocc[0] * this->lr_.dim.nvirt[0] + i * this->lr_.dim.nvirt[0] + a; + ev[index] = this->eig_gw(ik, this->lr_.dim.nocc[0] + a) - this->eig_gw(ik, i); } } } @@ -524,17 +524,17 @@ void ESolver_BSE::ipa_solver() std::sort(indices.begin(), indices.end(), [&](int lhs, int rhs) { return ev[lhs] < ev[rhs]; }); std::sort(ev.begin(), ev.end()); - std::copy_n(ev.data(), this->nstates, this->tda_ene.data()); + std::copy_n(ev.data(), this->lr_.dim.nstates, this->tda_ene.data()); #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif - for (std::size_t istate = 0; istate < this->nstates; ++istate) + for (std::size_t istate = 0; istate < this->lr_.dim.nstates; ++istate) { int sorted_index = indices[istate]; - int ik = sorted_index / (this->nocc[0] * this->nvirt[0]); - int loffset_X = (istate * this->nk + ik) * this->lr_.amp.para_x[0].size(); - int i = (sorted_index / this->nvirt[0]) % this->nocc[0]; - int a = sorted_index % this->nvirt[0]; + int ik = sorted_index / (this->lr_.dim.nocc[0] * this->lr_.dim.nvirt[0]); + int loffset_X = (istate * this->lr_.dim.nk + ik) * this->lr_.amp.para_x[0].size(); + int i = (sorted_index / this->lr_.dim.nvirt[0]) % this->lr_.dim.nocc[0]; + int a = sorted_index % this->lr_.dim.nvirt[0]; int col_loc = this->lr_.amp.para_x[0].icloc(i); int row_loc = this->lr_.amp.para_x[0].irloc(a); if (col_loc == -1 || row_loc == -1) @@ -587,10 +587,10 @@ void ESolver_BSE::lri_init() template void ESolver_BSE::read_ks_wfc() { - assert(this->psi_ks != nullptr); - this->pelec->ekb.create(this->kv.get_nks(), this->nbands); - this->pelec->wg.create(this->kv.get_nks(), this->nbands); - this->eig_gw.create(this->kv.get_nks(), this->nbands); + assert(this->lr_.gs.psi != nullptr); + this->pelec->ekb.create(this->kv.get_nks(), this->lr_.dim.nbands); + this->pelec->wg.create(this->kv.get_nks(), this->lr_.dim.nbands); + this->eig_gw.create(this->kv.get_nks(), this->lr_.dim.nbands); int ncore = 0; // skip core bands int nbands_file = 0; @@ -599,40 +599,40 @@ void ESolver_BSE::read_ks_wfc() int nocc_file = 0; int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; LR_IO::parse_band_out_file(this->rpa_dir, nbands_file, nk_file, nspin_file, nocc_file); - if (nk_file != this->nk) + if (nk_file != this->lr_.dim.nk) { ModuleBase::WARNING_QUIT( "ESolver_BSE", "Inconsistence: The nk in `band_out` is " + std::to_string(nk_file) + ", while BSE::nk is " + - std::to_string(this->nk)); + std::to_string(this->lr_.dim.nk)); } std::vector eig_gw_info; if (this->inp_->bse_use_fine_kgrid) { eig_gw_info = LR_IO::read_energy_qp_from_band_files( - this->kv, this->nocc[0], this->nvirt[0], ncore, this->rpa_dir, this->nk, nspin_tmp, nspin_file); + this->kv, this->lr_.dim.nocc[0], this->lr_.dim.nvirt[0], ncore, this->rpa_dir, this->lr_.dim.nk, nspin_tmp, nspin_file); LR_IO::read_librpa_eigenvectors_from_band_files( - *this->psi_ks, *this->psi_ks_global, this->rpa_dir, ncore, nbands_file, nspin_tmp, nspin_file, - GlobalV::MY_RANK, this->paraMat_); + *this->lr_.gs.psi, *this->psi_ks_global, this->rpa_dir, ncore, nbands_file, nspin_tmp, nspin_file, + GlobalV::MY_RANK, this->lr_.gs.para_mat); } else { eig_gw_info = - LR_IO::read_energy_qp(this->nocc[0], this->nvirt[0], this->rpa_dir, ncore, this->nk, nspin_tmp, nspin_file); + LR_IO::read_energy_qp(this->lr_.dim.nocc[0], this->lr_.dim.nvirt[0], this->rpa_dir, ncore, this->lr_.dim.nk, nspin_tmp, nspin_file); LR_IO::read_librpa_eigenvectors( - *this->psi_ks, *this->psi_ks_global, this->rpa_dir, ncore, nbands_file, nspin_tmp, nspin_file, - GlobalV::MY_RANK, this->paraMat_); + *this->lr_.gs.psi, *this->psi_ks_global, this->rpa_dir, ncore, nbands_file, nspin_tmp, nspin_file, + GlobalV::MY_RANK, this->lr_.gs.para_mat); } int cbm_k(0), vbm_k(0), direct_k(0); for (int iks = 0; iks < this->kv.get_nks(); ++iks) { - for (int ib = 0; ib < this->nbands; ++ib) + for (int ib = 0; ib < this->lr_.dim.nbands; ++ib) { - this->pelec->wg(iks, ib) = eig_gw_info[iks * this->nbands * 3 + ib * 3 + 0]; - this->pelec->ekb(iks, ib) = eig_gw_info[iks * this->nbands * 3 + ib * 3 + 1]; - this->eig_gw(iks, ib) = eig_gw_info[iks * this->nbands * 3 + ib * 3 + 2]; + this->pelec->wg(iks, ib) = eig_gw_info[iks * this->lr_.dim.nbands * 3 + ib * 3 + 0]; + this->pelec->ekb(iks, ib) = eig_gw_info[iks * this->lr_.dim.nbands * 3 + ib * 3 + 1]; + this->eig_gw(iks, ib) = eig_gw_info[iks * this->lr_.dim.nbands * 3 + ib * 3 + 2]; } - double cbm = this->eig_gw(iks, this->nocc[0]); - for (int ib = this->nocc[0]; ib < this->nbands; ++ib) + double cbm = this->eig_gw(iks, this->lr_.dim.nocc[0]); + for (int ib = this->lr_.dim.nocc[0]; ib < this->lr_.dim.nbands; ++ib) { // in case of non-ordered bands double e = this->eig_gw(iks, ib); if (e < cbm) @@ -640,8 +640,8 @@ void ESolver_BSE::read_ks_wfc() cbm = e; } } - double vbm = this->eig_gw(iks, this->nocc[0] - 1); - for (int ib = 0; ib < this->nocc[0] - 1; ++ib) + double vbm = this->eig_gw(iks, this->lr_.dim.nocc[0] - 1); + for (int ib = 0; ib < this->lr_.dim.nocc[0] - 1; ++ib) { double e = this->eig_gw(iks, ib); if (e > vbm) @@ -679,26 +679,26 @@ void ESolver_BSE::read_ks_wfc() std::cout << "Indirect gap (eV): " << (this->cbm_energy - this->vbm_energy) * ModuleBase::Ry_to_eV << std::endl; std::cout << "Direct gap (eV): " << this->direct_gap * ModuleBase::Ry_to_eV << " at k " << direct_k << std::endl; - this->eig_ks = std::move(this->pelec->ekb); + this->lr_.gs.eig = std::move(this->pelec->ekb); } template void ESolver_BSE::init_pot(const Charge &chg_gs) { using ST = LR::PotHxcLR::SpinType; - switch (this->nspin) + switch (this->lr_.dim.nspin) { case 1: case 2: { const auto &grid = this->pgrid(); const auto kernel = LR::build_xc_kernel( - this->xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, this->nspin, false, LR::KernelXC::NoGxc, + this->xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, this->lr_.dim.nspin, false, LR::KernelXC::NoGxc, this->inp_->lr_init_xc_kernel); // BSE multiplies its bare Coulomb matrix by the singlet factor in HamiltBSE. // S1_gs has weight one; S1 would apply that factor a second time on the grid path. this->lr_.pot.pot[0] = - std::make_shared(kernel, *this->pw_rho, *this->ucell_, chg_gs.nrxx, this->nspin, ST::S1_gs); + std::make_shared(kernel, *this->pw_rho, *this->ucell_, chg_gs.nrxx, this->lr_.dim.nspin, ST::S1_gs); break; } // case 2: @@ -716,11 +716,11 @@ void ESolver_BSE::allocate_eigen_infos() { ModuleBase::TITLE("ESolver_BSE", "allocate_eigen_infos"); - for (int is = 0; is < this->nspin; ++is) + for (int is = 0; is < this->lr_.dim.nspin; ++is) { Parallel_Blkcyclic px; LR_Util::setup_2d_division( - px, /*nb2d=*/1, this->nvirt[is], this->nocc[is] + px, /*nb2d=*/1, this->lr_.dim.nvirt[is], this->lr_.dim.nocc[is] #ifdef __MPI , this->lr_.amp.para_c.ictxt() @@ -729,16 +729,16 @@ void ESolver_BSE::allocate_eigen_infos() this->lr_.amp.para_x.emplace_back(std::move(px)); } this->lr_.amp.nloc = - this->nk * (this->openshell ? this->lr_.amp.para_x[0].size() + this->lr_.amp.para_x[1].size() : this->lr_.amp.para_x[0].size()); + this->lr_.dim.nk * (this->lr_.dim.openshell ? this->lr_.amp.para_x[0].size() + this->lr_.amp.para_x[1].size() : this->lr_.amp.para_x[0].size()); int n_spin_types = this->inp_->bse_spin_types.size(); if (this->inp_->bse_tda == "both" || this->inp_->bse_tda == "tda") { BSE_Util::print_mem_estimate( - "TDA BSE eigen states", n_spin_types * static_cast(this->nstates) * (1 + this->lr_.amp.nloc), + "TDA BSE eigen states", n_spin_types * static_cast(this->lr_.dim.nstates) * (1 + this->lr_.amp.nloc), sizeof(T)); - this->tda_ene.resize(n_spin_types * this->nstates); - this->lr_.amp.x.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->lr_.amp.nloc})); + this->tda_ene.resize(n_spin_types * this->lr_.dim.nstates); + this->lr_.amp.x.resize(n_spin_types, LR_Util::newTensor({this->lr_.dim.nstates, this->lr_.amp.nloc})); for (auto &x : this->lr_.amp.x) { x.zero(); @@ -748,10 +748,10 @@ void ESolver_BSE::allocate_eigen_infos() { BSE_Util::print_mem_estimate( "full BSE eigen states", - n_spin_types * static_cast(this->nstates) * (1 + 2 * this->lr_.amp.nloc), sizeof(T)); - this->full_ene.resize(n_spin_types * this->nstates); - this->full_X.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->lr_.amp.nloc})); - this->full_Y.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->lr_.amp.nloc})); + n_spin_types * static_cast(this->lr_.dim.nstates) * (1 + 2 * this->lr_.amp.nloc), sizeof(T)); + this->full_ene.resize(n_spin_types * this->lr_.dim.nstates); + this->full_X.resize(n_spin_types, LR_Util::newTensor({this->lr_.dim.nstates, this->lr_.amp.nloc})); + this->full_Y.resize(n_spin_types, LR_Util::newTensor({this->lr_.dim.nstates, this->lr_.amp.nloc})); for (auto &x : this->full_X) { x.zero(); diff --git a/source/source_lcao/module_lr/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index b06351d1ea..d4e6ba290c 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -33,6 +33,7 @@ if(ENABLE_LCAO) lr_mpl.cpp lr_zeq.cpp lr_sforce.cpp + lr_core.cpp init_helpers.cpp hsolver_lrtd.cpp zeq_solver.cpp diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp new file mode 100644 index 0000000000..9138838433 --- /dev/null +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -0,0 +1,49 @@ +#include "source_lcao/module_lr/lr_core.h" + +#include "source_base/tool_title.h" +#include "source_io/module_parameter/input_parameter.h" +#include "source_lcao/module_lr/lr_gs.h" + +#include +#include + +namespace LR +{ + +template +void Core::read_wfc(const std::string& in_dir, const Input_para& inp, const K_Vectors& kv, std::ostream& log) +{ + assert(this->gs.psi != nullptr); + GsWfc wfc = read_gs_wfc(*this->gs.psi, this->gs.eig, this->gs.wg, this->gs.para_mat, this->gs.para_mat_all, + in_dir, inp, this->dim.nocc_in, this->dim.nvirt_in, this->dim.nocc_max, + this->dim.nbands, this->dim.nbasis, kv, inp.cal_force, log); + this->gs.psi_all_own = std::move(wfc.all_own); + this->gs.psi_all = wfc.all; + this->gs.eig_all = std::move(wfc.eig_all); + this->gs.wg_all = std::move(wfc.wg_all); +} + +template +void Core::fill_z(const int* desc_src, const K_Vectors& kv, const bool cal_force, const bool first, + std::ostream& log) +{ + ModuleBase::TITLE("LR::Core", "fill_z"); + ZWin z = build_z_win(this->gs.psi_all, this->gs.eig_all, this->dim.nocc, this->dim.nvirt, this->dim.nocc_max, + this->dim.nbands, this->dim.nbasis, this->dim.nk, this->dim.openshell, kv, + this->amp.para_c, this->gs.para_mat, desc_src, cal_force, first, log); + this->zw.psi = std::move(z.psi); + this->zw.eig = std::move(z.eig); + this->zw.para_c = std::move(z.para_c); + this->zw.para_x = std::move(z.para_x); + this->zw.nvirt = std::move(z.nvirt); + this->zw.nbands = z.nbands; + this->zw.nloc = z.nloc; +} + +template void Core::read_wfc(const std::string&, const Input_para&, const K_Vectors&, std::ostream&); +template void Core>::read_wfc(const std::string&, const Input_para&, const K_Vectors&, + std::ostream&); +template void Core::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); +template void Core>::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); + +} // namespace LR diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index b6225aefb7..d69fecb398 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -2,6 +2,9 @@ #define ABACUS_SOURCE_LCAO_MODULE_LR_LR_CORE_H #include "source_base/matrix.h" +#include "source_basis/module_ao/parallel_orbitals.h" +#include "source_psi/psi.h" +#include "source_lcao/module_lr/lr_dim.h" #include "source_lcao/module_lr/lr_gs.h" #include "source_lcao/module_lr/lr_mpl.h" #include "source_lcao/module_lr/lr_relax.h" @@ -14,6 +17,21 @@ namespace LR { +/// The ground state the LR solver works from. +template +struct GsState +{ + std::unique_ptr> psi; + psi::Psi* psi_all = nullptr; + std::unique_ptr> psi_all_own; + ModuleBase::matrix eig; + ModuleBase::matrix eig_all; + ModuleBase::matrix wg; + ModuleBase::matrix wg_all; + Parallel_Orbitals para_mat; + Parallel_Orbitals para_mat_all; +}; + /// The excitation amplitudes and their distribution. struct Amp { @@ -47,10 +65,17 @@ struct RelaxRun template struct Core { + Dim dim; Amp amp; + GsState gs; ZWin zw; PotSet pot; RelaxRun relax; + + /// Read the ground-state bands this solver needs, from file. + void read_wfc(const std::string& in_dir, const Input_para& inp, const K_Vectors& kv, std::ostream& log); + /// Widen the ground-state window into the Z window used by the force path. + void fill_z(const int* desc_src, const K_Vectors& kv, bool cal_force, bool first, std::ostream& log); }; } // namespace LR From 47c6593016a9ab1703be97ca7c6ad1aa1e8df79f Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:01:07 +0800 Subject: [PATCH 16/26] refactor(lr): move force and relaxation bodies into LR::Core Add LR::Refs, the borrowed geometry handles the force path needs, and bind them once from the esolver. The per-state/Z-window context builders, the force/gradient entry points, the ground-state density matrix, and the excited-state relaxation (target setup, root following, average/JT force) now live in module_lr. The esolver keeps only the thin virtual overrides. --- source/source_esolver/esolver_lr.cpp | 295 +++-------------------- source/source_esolver/esolver_lr.h | 67 +---- source/source_lcao/module_lr/lr_core.cpp | 286 ++++++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 88 +++++++ 4 files changed, 410 insertions(+), 326 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index dca1ace7ad..2764f9d645 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -92,7 +92,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste if (!this->ks_initialized_) { this->initialize_from_ks_(ucell, *this->inp_); - this->setup_relax_target_(); // needs the final dimensions, i.e. `openshell` + this->lr_.setup_relax(); // needs the final dimensions, i.e. `openshell` } else { @@ -242,12 +242,12 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste { // Re-select which root to follow BEFORE taking the gradient, so the force belongs to // the same diabatic state as the previous step's. - this->follow_target_state_(this->ofs_running_); + this->lr_.follow_target(this->pelec->ekb, this->ofs_running_); // The LR terms only carry the Omega part of the force; the ground-state part is separate // and comes straight from the KS solver. this->ks_->cal_force(ucell, this->lr_.relax.force_gs); - this->lr_.relax.lr_force = this->cal_lr_force_relax_(this->ofs_running_); + this->lr_.relax.lr_force = this->lr_.cal_lr_force(this->pelec->ekb, this->ofs_running_); // One line per ionic step with the two halves of the energy and of the gradient. Without // it the relaxation only reports a force, and whether E_gs + Omega actually goes down -- @@ -382,7 +382,7 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) } if (this->inp_->cal_force && !this->lr_.relax.target.active()) { - this->cal_force_and_grad_matrix_(is, this->ofs_running_); + this->lr_.cal_force_grad(is, this->pelec->ekb, this->ofs_running_); } } } @@ -480,195 +480,6 @@ void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); } -template -LR::GsForceCtx ModuleESolver::ESolver_LR::gs_force_ctx_() const -{ - // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight - // from the ground-state solver's own `psi`), but per `this->lr_.gs.para_mat_all` on the - // read-from-file path, where it was allocated with that descriptor's own sizes. - const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; - const LR::ForceSettings settings{ - this->lr_.dim.nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; - return {*this->lr_.gs.psi_all, this->lr_.gs.wg_all, *pv_all, *this->pw_rho, *this->pw_rhod, this->vloc(), this->sfac(), - this->tcb(), settings, this->lr_.dim.openshell, this->inp_->lr_grad_solver, this->in_dir}; -} - -template -LR::StateCtx ModuleESolver::ESolver_LR::state_ctx_() const -{ - return {this->lr_.amp.x, this->lr_.amp.para_x, this->lr_.zw.para_x, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nk, this->lr_.amp.nloc, - this->lr_.zw.nloc, this->lr_.dim.nstates, this->lr_.dim.openshell, this->pelec->ekb.c}; -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force(const int ispin, const int istate_only) -{ - if (this->inp_->test_force && ispin == 0) - { - this->test_force(); - } - return this->lr_.dim.openshell - ? LR::state_forces_os(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), istate_only) - : LR::state_forces(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), ispin, - istate_only); -} - -template -LR::GradientInputs ModuleESolver::ESolver_LR::gradient_inputs_() const -{ - return {*this->ucell_, this->kv, this->gd(), this->orb_cutoff_, this->lr_.gs.para_mat, this->lr_.zw.para_c, this->lr_.zw.para_x, - *this->lr_.zw.psi, this->lr_.zw.eig, this->lr_.dim.nocc, this->lr_.zw.nvirt, this->lr_.dim.nspin, this->lr_.dim.nk, this->lr_.dim.nbasis, - this->lr_.zw.nloc, this->xc_kernel, this->inp_->dft_functional, this->inp_->ks_solver, - this->inp_->test_force, this->lr_.relax.target.active(), this->out_dir, this->my_rank_, this->lr_.amp.spin_types, this->lr_.pot.pot, - this->lr_.pot.pot_hxc_gs, this->ofs_running_ -#ifdef __EXX - , - this->exx_lri, this->exx_info.info_global.hybrid_alpha -#endif - }; -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force_Xz( - const int ispin, - const ct::Tensor &Xz, - const std::vector &omega, - const int label_begin) -{ - ModuleBase::timer::start("ESolver_LR", "cal_force_Xz"); - const auto forces = LR::force_xz(this->gradient_inputs_(), this->gs_force_ctx_(), ispin, Xz, omega, label_begin); - ModuleBase::timer::end("ESolver_LR", "cal_force_Xz"); - return forces; -} - -template -void ModuleESolver::ESolver_LR::cal_force_and_grad_matrix_(const int ispin, std::ofstream &ofs) -{ - const std::vector forces = this->cal_force(ispin); - if (this->inp_->lr_degen_thr <= 0.0) - { - return; - } - // Rebuilt from scratch for this channel: a relaxation calls this once per ionic step, and a - // stale multiplet from the previous geometry must not survive into the next one. - this->lr_.relax.mpl.erase( - std::remove_if( - this->lr_.relax.mpl.begin(), this->lr_.relax.mpl.end(), - [ispin](const LR::MplLvc &m) { return m.ispin == ispin; }), - this->lr_.relax.mpl.end()); - // The per-state gradients above are the diagonal of the degenerate-subspace gradient matrix in - // whatever basis the eigensolver returned, so inside a multiplet only their trace means - // anything. `lr_degen_thr` asks for the off-diagonal part too, which is the rest of the - // first-order information. - for (LR::MplLvc &m : LR::multiplet_grad(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), - ispin, this->inp_->lr_degen_thr, forces, ofs)) - { - this->lr_.relax.mpl.push_back(std::move(m)); - } -} - -template -std::vector ModuleESolver::ESolver_LR::cal_force_openshell_Xz( - const ct::Tensor &Xz, const std::vector &omega, const int label_begin) -{ - ModuleBase::timer::start("ESolver_LR", "cal_force_openshell_Xz"); - const auto forces = LR::force_xz_os(this->gradient_inputs_(), this->gs_force_ctx_(), Xz, omega, label_begin); - ModuleBase::timer::end("ESolver_LR", "cal_force_openshell_Xz"); - return forces; -} - -template -module_dm::DensityMatrix ModuleESolver::ESolver_LR::cal_dm_gs() -{ - // `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path (it is aliased straight - // from the ground-state solver's own `psi`), but per `this->lr_.gs.para_mat_all` on the - // read-from-file path (where it was allocated with that descriptor's own sizes). - const Parallel_Orbitals *const pv_all = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; - return LR::make_gs_dm(*this->lr_.gs.psi_all, this->lr_.gs.wg_all, *pv_all, this->lr_.gs.para_mat, *this->ucell_, this->gd(), - this->orb_cutoff_, this->lr_.dim.nspin, this->kv.kvec_d, this->lr_.dim.nk); -} - -template -void ModuleESolver::ESolver_LR::test_force() -{ - const LR::ForceSettings force_settings{ - this->lr_.dim.nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; - LR_Force lr_force( - (*this->ucell_), this->kv.kvec_d, this->lr_.gs.para_mat, *this->pw_rhod, *this->pw_rho, this->vloc(), this->sfac(), - this->gd(), this->tcb(), force_settings, this->ofs_running_ -#ifdef __EXX - , - std::weak_ptr>(this->exx_lri), this->exx_info.info_global.hybrid_alpha -#endif - ); - - const module_dm::DensityMatrix &dm_gs = this->cal_dm_gs(); - // LR_Util::print_DMR(dm_gs, "DM(R) of ground state"); - ///========================== test 1: reproduce the force of ground state ========================= - // energy density matrix of the ground state - module_dm::DensityMatrix edm_gs(&this->lr_.gs.para_mat, this->lr_.dim.nspin, this->kv.kvec_d, this->lr_.dim.nk); // DX - ModuleBase::matrix wg_ekb_ks_all(this->lr_.dim.nspin, this->inp_->nbands); - const int occupation_count = this->lr_.dim.nspin * this->inp_->nbands; - for (int index = 0; index < occupation_count; ++index) - { - wg_ekb_ks_all.c[index] = this->lr_.gs.wg_all.c[index] * this->lr_.gs.eig_all.c[index]; - } - // see `cal_dm_gs()`: `psi_ks_all_` is distributed per `this->ks_->pv` on the ks-lr path, - // not `this->lr_.gs.para_mat_all`. - const Parallel_Orbitals *const pv_all_edm = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; - module_dm::dm_from_psi(pv_all_edm, wg_ekb_ks_all, *this->lr_.gs.psi_all, edm_gs); - LR_Util::initialize_DMR(edm_gs, this->lr_.gs.para_mat, (*this->ucell_), this->gd(), this->orb_cutoff_); - edm_gs.cal_dmr(-1); - // ground-state force - ModuleBase::matrix force_gs = lr_force.reproduce_force_gs(kv, dm_gs, edm_gs); - ModuleIO::print_force(this->ofs_running_, (*this->ucell_), "Ground State FORCE (eV/Angstrom)", force_gs, false); - /// ======================================= END test 1 ========================================= - ///========================== test 2: reproduce the DX Hartree term ========================= - ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->lr_.pot.gs_pot.pot_hartree()); - ModuleIO::print_force( - this->ofs_running_, (*this->ucell_), - "GS Hartree force calculated by 'cal_pulay_fs' from potential (eV/Angstrom)", f_hxc_potgs, false); - ModuleBase::matrix f_hxc_potlr = lr_force.cal_force_hxc_dmtrans(dm_gs, *this->lr_.pot.pot[0]); - ModuleIO::print_force( - this->ofs_running_, (*this->ucell_), "GS Hxc force calculated by 'LR_Force' from kernel (eV/Angstrom)", - f_hxc_potlr, false); - // `cal_force_hxc_dmtrans` now includes the Pulay -> Pulay+Hellmann-Feynman factor 2 itself, - // so this must match the ground-state Hartree force directly (dm_gs is already symmetric). - /// ======================================= END test 2 ========================================= -} - - -template -void ModuleESolver::ESolver_LR::setup_relax_target_() -{ - this->lr_.relax.target.setup(*this->inp_, this->lr_.dim.openshell, this->lr_.dim.nspin, this->lr_.dim.nstates, this->ofs_running_); - if (this->lr_.relax.target.active()) - { - this->lr_.relax.force_gs.create(this->ucell_->nat, 3); - this->lr_.relax.lr_force.create(this->ucell_->nat, 3); - } -} - -/// Compare roots in a common electron-hole basis using exact cross-geometry AO overlap. -template -void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) -{ - ModuleBase::timer::start("ESolver_LR", "follow_target_state_"); - if (!this->lr_.relax.target.active()) - { - ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); - return; - } - const int channel = this->lr_.dim.openshell ? 0 : this->lr_.relax.target.ispin(); - const T *const amplitudes = this->lr_.amp.x[channel].template data(); - const TwoCenterIntegrator &overlap_integrator = *this->tcb().overlap_orb; - std::vector energies(this->lr_.dim.nstates); - std::copy_n(this->pelec->ekb.c + this->lr_.relax.target.ekb_off(this->lr_.dim.nstates), this->lr_.dim.nstates, energies.begin()); - this->lr_.relax.target.follow(*this->inp_, *this->ucell_, this->orb_cutoff_, overlap_integrator, *this->lr_.gs.psi, this->lr_.amp.para_c, - this->lr_.gs.para_mat, this->lr_.amp.para_x, this->lr_.dim.nocc, this->lr_.dim.nvirt, amplitudes, this->lr_.amp.nloc, - this->lr_.dim.nstates, energies, ofs); - ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); -} template double ModuleESolver::ESolver_LR::cal_energy() @@ -719,74 +530,6 @@ void ModuleESolver::ESolver_LR::cal_stress(BaseCell &basecell, ModuleBase "dummy passed with isstress=false)."); } -template -ct::Tensor ModuleESolver::ESolver_LR::pad_group_to_z_(const int ispin, const std::vector &group) const -{ - return LR::pad_group(this->lr_.amp.x, this->lr_.dim.openshell, this->lr_.amp.para_x, this->lr_.zw.para_x, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nk, - this->lr_.amp.nloc, this->lr_.zw.nloc, ispin, group); -} - -template -ModuleBase::matrix ModuleESolver::ESolver_LR::cal_lr_force_relax_(std::ofstream &ofs) -{ - this->lr_.relax.target.resolve_group(*this->inp_, this->pelec->ekb.c, this->lr_.dim.nstates, this->ofs_running_); - const std::vector &group = this->lr_.relax.target.group(); - if (group.empty()) - { - return this->cal_force(this->lr_.relax.target.ispin(), this->lr_.relax.target.state())[0]; - } - const bool jt_mode = (LR_Util::tolower(this->inp_->lr_degen_mode) == "jt"); - // `average` needs only the DIAGONAL of the gradient matrix: the average is basis-independent by - // construction, so the off-diagonal part (and the extra d(d-1)/2 solves it costs) is not - // involved. The Jahn-Teller direction is orthogonal to the average and does need them. - const int d = static_cast(group.size()); - const int ekb_off = this->lr_.relax.target.ekb_off(this->lr_.dim.nstates); - const ct::Tensor Xz = this->pad_group_to_z_(this->lr_.relax.target.ispin(), group); - std::vector omega(d); - for (int k = 0; k < d; ++k) - { - omega[k] = this->pelec->ekb.c[ekb_off + group[k]]; - } - const std::vector forces = - this->lr_.dim.openshell ? this->cal_force_openshell_Xz(Xz, omega, group.front()) - : this->cal_force_Xz(this->lr_.relax.target.ispin(), Xz, omega, group.front()); - ofs << " Followed state " << this->lr_.relax.target.state() << " is degenerate with"; - for (const int ist : group) - { - if (ist != this->lr_.relax.target.state()) - { - ofs << " " << ist; - } - } - ofs << " (Omega_bar = " << this->lr_.relax.target.omega(this->pelec->ekb.c, this->lr_.dim.nstates) << " Ry)." << std::endl; - if (!jt_mode) - { - ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" - " geometry on the current average surface; split groups are not recombined." - << std::endl; - return average_forces(forces); - } - return this->cal_jt_force_(forces, ofs); -} - -template -ModuleBase::matrix ModuleESolver::ESolver_LR::cal_jt_force_( - const std::vector &diag, std::ofstream &ofs) -{ - // Regime (c): descend the Jahn-Teller branch. This needs the whole gradient matrix, so the - // off-diagonal elements are assembled here -- d(d-1)/2 further Z-vector solves on top of the - // d diagonal ones already in `diag`. - const std::vector &group = this->lr_.relax.target.group(); - const LR::MplLvc mpl = LR::build_mpl_state(this->gradient_inputs_(), this->gs_force_ctx_(), this->state_ctx_(), - this->lr_.relax.target.ispin(), group, diag, ofs); - LR::JtForce jt = LR::eval_jt_force(mpl.g, ofs); - const int channel = this->lr_.dim.openshell ? 0 : this->lr_.relax.target.ispin(); - this->lr_.relax.target.save_mixed(this->lr_.amp.x[channel].template data(), this->lr_.amp.nloc, jt.mixing); - // The returned force is the descending branch's own gradient; once a step splits the - // multiplet `resolve_group` finds no group and the single-state path takes over. - return jt.force; -} - // Initialize LR from an embedded KS solver or standalone ground-state files. #ifdef __EXX @@ -884,6 +627,34 @@ void ModuleESolver::ESolver_LR::bind_ground_state_aliases_() } } +template +LR::Refs ModuleESolver::ESolver_LR::make_refs() const +{ + LR::Refs refs; + refs.ucell = this->ucell_; + refs.kv = &this->kv; + refs.gd = &this->gd(); + refs.orb_cutoff = &this->orb_cutoff_; + refs.rho = this->pw_rho; + refs.rhod = this->pw_rhod; + refs.vloc = &this->vloc(); + refs.sfac = &this->sfac(); + refs.tcb = &this->tcb(); + refs.inp = this->inp_; + refs.log = &this->ofs_running_; + refs.pgrid = &this->pgrid(); + refs.in_dir = &this->in_dir; + refs.out_dir = &this->out_dir; + refs.xc_kernel = &this->xc_kernel; + refs.my_rank = this->my_rank_; + refs.pv_all = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; +#ifdef __EXX + refs.exx_lri = &this->exx_lri; + refs.hybrid_alpha = this->exx_info.info_global.hybrid_alpha; +#endif + return refs; +} + template void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, const Input_para &inp) { @@ -987,6 +758,7 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons #endif refresh_from_ks_(ucell); + this->lr_.bind(this->make_refs()); this->ks_initialized_ = true; } @@ -1222,6 +994,7 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell // else #endif // ModuleBase::Ylm::set_coefficients() is deprecated + this->lr_.bind(this->make_refs()); } template class ModuleESolver::ESolver_LR; diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 03f034539a..4ce48ef9d8 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -117,18 +117,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP bool ks_initialized_ = false; ///< whether `initialize_from_ks_` has already run bool exx_owned_ = false; ///< `exx_lri` was built here (so its Cs/Vs are ours to refresh) - // ---------- geometry relaxation on an excited state ---------- - /// resolve and validate `lr_target_state` / `lr_target_spin`; call once the dimensions - /// (and therefore `openshell`) are final - void setup_relax_target_(); - /// The followed state/multiplet. Seeded from `lr_target_state`, then re-chosen at every - /// later step by cross-geometry group overlap; following a fixed index instead makes the - /// force discontinuous as soon as two surfaces cross. - /// Match the old subspace to current energy groups and refresh the single/group references. - /// `ofs` receives the note when the followed root changes index, and the warning when - /// no current root resembles the previous one. - void follow_target_state_(std::ofstream &ofs); - std::unique_ptr gint_info_ = nullptr; /// LR solver state that is not part of the esolver interface. @@ -174,59 +162,8 @@ 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`. - /// Ground-state ingredients of the force path, filled once per call. - LR::GsForceCtx gs_force_ctx_() const; - /// 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`. - std::vector cal_force(const int ispin, const int istate_only = -1); - /// @brief Gradients for excitation vectors supplied by the caller, already widened into - /// the Z window -- the two functions above are thin wrappers that widen the stored - /// eigenvectors and look up their `omega`. - /// - /// The blocks of `Xz` need not be the eigenvectors the Casida diagonalizer returned. Any - /// normalized vector inside a degenerate multiplet is an eigenvector with the same - /// `omega`, so passing a linear combination is what turns the per-state gradient into the - /// full degenerate-subspace gradient matrix; see `LR::build_mpl` and - /// `grad_degen.h`. - /// - /// @param omega excitation energy of each block (Ry); its size sets the block count - /// @param label_begin state index the first block is reported under (labels only) - std::vector cal_force_Xz( - const int ispin, - const ct::Tensor &Xz, - const std::vector &omega, - const int label_begin); - /// open-shell counterpart of `cal_force_Xz` - std::vector cal_force_openshell_Xz( - const ct::Tensor &Xz, const std::vector &omega, const int label_begin); - /// The LR half of the force for the current geometry, following whichever surface - /// `lr_degen_mode` selects. `ofs` receives the note when that is not a single state. - ModuleBase::matrix cal_lr_force_relax_(std::ofstream &ofs); - /// @brief The force of the steepest-descending branch of the target multiplet, i.e. - /// `lr_degen_mode = jt`. - /// - /// Assembles the off-diagonal part of the gradient matrix (which `average` does not need), - /// solves the joint direction/mixing optimization in `LR::find_jt_direction`, and returns - /// that branch's own force. Once a step has split the multiplet there is no group left and - /// the ordinary single-state path takes over, so the mode is self-limiting. - /// - /// @param diag the multiplet's per-state forces, already computed - ModuleBase::matrix cal_jt_force_(const std::vector &diag, std::ofstream &ofs); - LR::GradientInputs gradient_inputs_() const; - /// Widen a multiplet's eigenvectors into the Z window, one block each. Members need not be - /// contiguous, so they are padded one at a time. - ct::Tensor pad_group_to_z_(const int ispin, const std::vector &group) const; - /// @brief Per-state gradients of every state, plus the gradient matrix of each degenerate - /// multiplet when `lr_degen_thr` asks for it. The single-point entry point. - /// - /// Fills `multiplet_lvc_`. - void cal_force_and_grad_matrix_(const int ispin, std::ofstream &ofs); - /// Amplitudes and energies as `LR::StateCtx`, filled once per force evaluation. - LR::StateCtx state_ctx_() const; - void test_force(); // test: reproduce the force of ground state - module_dm::DensityMatrix cal_dm_gs(); ///< ground-state density matrix + /// Borrow the geometry-dependent objects `LR::Core` needs for the force path. + LR::Refs make_refs() const; #ifdef __EXX /// Tdata of Exx_LRI is same as T, for the reason, see operator_lr_exx.h diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 9138838433..c14530ccd4 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -1,9 +1,26 @@ #include "source_lcao/module_lr/lr_core.h" +#include "source_base/timer.h" #include "source_base/tool_title.h" +#include "source_basis/module_nao/two_center_bundle.h" +#include "source_basis/module_nao/two_center_integrator.h" +#include "source_cell/klist.h" +#include "source_cell/module_neighbor/sltk_grid_driver.h" +#include "source_cell/unitcell.h" +#include "source_estate/module_dm/dm_from_psi.h" +#include "source_io/module_output/output_log.h" #include "source_io/module_parameter/input_parameter.h" +#include "source_lcao/module_lr/gradient_inputs.h" +#include "source_lcao/module_lr/gradient_output.h" +#include "source_lcao/module_lr/lr_amp.h" +#include "source_lcao/module_lr/lr_dm.h" +#include "source_lcao/module_lr/lr_force.h" #include "source_lcao/module_lr/lr_gs.h" +#include "source_lcao/module_lr/lr_sforce.h" +#include "source_lcao/module_lr/lr_zeq.h" +#include "source_lcao/module_lr/utils/lr_util_hcontainer.h" +#include #include #include @@ -40,10 +57,279 @@ void Core::fill_z(const int* desc_src, const K_Vectors& kv, const bool cal_fo this->zw.nloc = z.nloc; } +template +GradientInputs Core::gradient_inputs() const +{ + return {*this->refs.ucell, *this->refs.kv, *this->refs.gd, *this->refs.orb_cutoff, this->gs.para_mat, + this->zw.para_c, this->zw.para_x, *this->zw.psi, this->zw.eig, this->dim.nocc, this->zw.nvirt, + this->dim.nspin, this->dim.nk, this->dim.nbasis, this->zw.nloc, *this->refs.xc_kernel, + this->refs.inp->dft_functional, this->refs.inp->ks_solver, this->refs.inp->test_force, + this->relax.target.active(), *this->refs.out_dir, this->refs.my_rank, this->amp.spin_types, this->pot.pot, + this->pot.pot_hxc_gs, *this->refs.log +#ifdef __EXX + , + *this->refs.exx_lri, this->refs.hybrid_alpha +#endif + }; +} + +template +GsForceCtx Core::gs_force_ctx() const +{ + const LR::ForceSettings settings{this->dim.nspin, this->refs.inp->test_force, this->refs.inp->vl_in_h, + this->refs.inp->vh_in_h, this->refs.inp->dft_functional}; + return {*this->gs.psi_all, this->gs.wg_all, *this->refs.pv_all, *this->refs.rho, *this->refs.rhod, + *this->refs.vloc, *this->refs.sfac, *this->refs.tcb, settings, this->dim.openshell, + this->refs.inp->lr_grad_solver, *this->refs.in_dir}; +} + +template +StateCtx Core::state_ctx(const ModuleBase::matrix& ekb) const +{ + return {this->amp.x, this->amp.para_x, this->zw.para_x, this->dim.nocc, this->dim.nvirt, this->dim.nk, + this->amp.nloc, this->zw.nloc, this->dim.nstates, this->dim.openshell, ekb.c}; +} + +template +std::vector Core::cal_force(const int ispin, const ModuleBase::matrix& ekb, + const int istate_only) +{ + if (this->refs.inp->test_force && ispin == 0) + { + this->test_force(); + } + return this->dim.openshell + ? LR::state_forces_os(this->gradient_inputs(), this->gs_force_ctx(), this->state_ctx(ekb), + istate_only) + : LR::state_forces(this->gradient_inputs(), this->gs_force_ctx(), this->state_ctx(ekb), ispin, + istate_only); +} + +template +std::vector Core::cal_force_xz(const int ispin, const ct::Tensor& xz, + const std::vector& omega, const int label_begin) +{ + ModuleBase::timer::start("LR::Core", "cal_force_xz"); + const auto forces = LR::force_xz(this->gradient_inputs(), this->gs_force_ctx(), ispin, xz, omega, label_begin); + ModuleBase::timer::end("LR::Core", "cal_force_xz"); + return forces; +} + +template +std::vector Core::cal_force_os(const ct::Tensor& xz, const std::vector& omega, + const int label_begin) +{ + ModuleBase::timer::start("LR::Core", "cal_force_os"); + const auto forces = LR::force_xz_os(this->gradient_inputs(), this->gs_force_ctx(), xz, omega, label_begin); + ModuleBase::timer::end("LR::Core", "cal_force_os"); + return forces; +} + +template +void Core::cal_force_grad(const int ispin, const ModuleBase::matrix& ekb, std::ofstream& ofs) +{ + const std::vector forces = this->cal_force(ispin, ekb, -1); + if (this->refs.inp->lr_degen_thr <= 0.0) + { + return; + } + // Rebuilt from scratch for this channel: a relaxation calls this once per ionic step, and a + // stale multiplet from the previous geometry must not survive into the next one. + this->relax.mpl.erase( + std::remove_if( + this->relax.mpl.begin(), this->relax.mpl.end(), [ispin](const LR::MplLvc& m) { return m.ispin == ispin; }), + this->relax.mpl.end()); + // The per-state gradients above are the diagonal of the degenerate-subspace gradient matrix in + // whatever basis the eigensolver returned, so inside a multiplet only their trace means + // anything. `lr_degen_thr` asks for the off-diagonal part too. + for (LR::MplLvc& m : LR::multiplet_grad(this->gradient_inputs(), this->gs_force_ctx(), this->state_ctx(ekb), + ispin, this->refs.inp->lr_degen_thr, forces, ofs)) + { + this->relax.mpl.push_back(std::move(m)); + } +} + +template +module_dm::DensityMatrix Core::cal_dm_gs() const +{ + return LR::make_gs_dm(*this->gs.psi_all, this->gs.wg_all, *this->refs.pv_all, this->gs.para_mat, + *this->refs.ucell, *this->refs.gd, *this->refs.orb_cutoff, this->dim.nspin, + this->refs.kv->kvec_d, this->dim.nk); +} + +template +void Core::test_force() +{ + const LR::ForceSettings force_settings{this->dim.nspin, this->refs.inp->test_force, this->refs.inp->vl_in_h, + this->refs.inp->vh_in_h, this->refs.inp->dft_functional}; + LR_Force lr_force((*this->refs.ucell), this->refs.kv->kvec_d, this->gs.para_mat, *this->refs.rhod, + *this->refs.rho, *this->refs.vloc, *this->refs.sfac, *this->refs.gd, *this->refs.tcb, + force_settings, *this->refs.log +#ifdef __EXX + , + std::weak_ptr>(*this->refs.exx_lri), this->refs.hybrid_alpha +#endif + ); + + const module_dm::DensityMatrix& dm_gs = this->cal_dm_gs(); + ///========================== test 1: reproduce the force of ground state ========================= + // energy density matrix of the ground state + module_dm::DensityMatrix edm_gs(&this->gs.para_mat, this->dim.nspin, this->refs.kv->kvec_d, + this->dim.nk); // DX + ModuleBase::matrix wg_ekb_ks_all(this->dim.nspin, this->refs.inp->nbands); + const int occupation_count = this->dim.nspin * this->refs.inp->nbands; + for (int index = 0; index < occupation_count; ++index) + { + wg_ekb_ks_all.c[index] = this->gs.wg_all.c[index] * this->gs.eig_all.c[index]; + } + module_dm::dm_from_psi(this->refs.pv_all, wg_ekb_ks_all, *this->gs.psi_all, edm_gs); + LR_Util::initialize_DMR(edm_gs, this->gs.para_mat, (*this->refs.ucell), *this->refs.gd, *this->refs.orb_cutoff); + edm_gs.cal_dmr(-1); + // ground-state force + ModuleBase::matrix force_gs = lr_force.reproduce_force_gs(*this->refs.kv, dm_gs, edm_gs); + ModuleIO::print_force(*this->refs.log, (*this->refs.ucell), "Ground State FORCE (eV/Angstrom)", force_gs, false); + /// ======================================= END test 1 ========================================= + ///========================== test 2: reproduce the DX Hartree term ========================= + ModuleBase::matrix f_hxc_potgs = lr_force.reproduce_force_gs_loc(dm_gs, *this->pot.gs_pot.pot_hartree()); + ModuleIO::print_force(*this->refs.log, (*this->refs.ucell), + "GS Hartree force calculated by 'cal_pulay_fs' from potential (eV/Angstrom)", f_hxc_potgs, + false); + ModuleBase::matrix f_hxc_potlr = lr_force.cal_force_hxc_dmtrans(dm_gs, *this->pot.pot[0]); + ModuleIO::print_force(*this->refs.log, (*this->refs.ucell), + "GS Hxc force calculated by 'LR_Force' from kernel (eV/Angstrom)", f_hxc_potlr, false); + /// ======================================= END test 2 ========================================= +} + +template +void Core::setup_relax() +{ + this->relax.target.setup(*this->refs.inp, this->dim.openshell, this->dim.nspin, this->dim.nstates, *this->refs.log); + if (this->relax.target.active()) + { + this->relax.force_gs.create(this->refs.ucell->nat, 3); + this->relax.lr_force.create(this->refs.ucell->nat, 3); + } +} + +template +void Core::follow_target(const ModuleBase::matrix& ekb, std::ofstream& ofs) +{ + ModuleBase::timer::start("LR::Core", "follow_target"); + if (!this->relax.target.active()) + { + ModuleBase::timer::end("LR::Core", "follow_target"); + return; + } + const int channel = this->dim.openshell ? 0 : this->relax.target.ispin(); + const T* const amplitudes = this->amp.x[channel].template data(); + const TwoCenterIntegrator& overlap_integrator = *this->refs.tcb->overlap_orb; + std::vector energies(this->dim.nstates); + std::copy_n(ekb.c + this->relax.target.ekb_off(this->dim.nstates), this->dim.nstates, energies.begin()); + this->relax.target.follow(*this->refs.inp, *this->refs.ucell, *this->refs.orb_cutoff, overlap_integrator, + *this->gs.psi, this->amp.para_c, this->gs.para_mat, this->amp.para_x, this->dim.nocc, + this->dim.nvirt, amplitudes, this->amp.nloc, this->dim.nstates, energies, ofs); + ModuleBase::timer::end("LR::Core", "follow_target"); +} + +template +ct::Tensor Core::pad_group_z(const int ispin, const std::vector& group) const +{ + return LR::pad_group(this->amp.x, this->dim.openshell, this->amp.para_x, this->zw.para_x, this->dim.nocc, + this->dim.nvirt, this->dim.nk, this->amp.nloc, this->zw.nloc, ispin, group); +} + +template +ModuleBase::matrix Core::cal_lr_force(const ModuleBase::matrix& ekb, std::ofstream& ofs) +{ + this->relax.target.resolve_group(*this->refs.inp, ekb.c, this->dim.nstates, *this->refs.log); + const std::vector& group = this->relax.target.group(); + if (group.empty()) + { + return this->cal_force(this->relax.target.ispin(), ekb, this->relax.target.state())[0]; + } + const bool jt_mode = (LR_Util::tolower(this->refs.inp->lr_degen_mode) == "jt"); + // `average` needs only the DIAGONAL of the gradient matrix: the average is basis-independent by + // construction, so the off-diagonal part is not involved. The Jahn-Teller direction is + // orthogonal to the average and does need it. + const int d = static_cast(group.size()); + const int ekb_off = this->relax.target.ekb_off(this->dim.nstates); + const ct::Tensor xz = this->pad_group_z(this->relax.target.ispin(), group); + std::vector omega(d); + for (int k = 0; k < d; ++k) + { + omega[k] = ekb.c[ekb_off + group[k]]; + } + const std::vector forces = + this->dim.openshell ? this->cal_force_os(xz, omega, group.front()) + : this->cal_force_xz(this->relax.target.ispin(), xz, omega, group.front()); + ofs << " Followed state " << this->relax.target.state() << " is degenerate with"; + for (const int ist : group) + { + if (ist != this->relax.target.state()) + { + ofs << " " << ist; + } + } + ofs << " (Omega_bar = " << this->relax.target.omega(ekb.c, this->dim.nstates) << " Ry)." << std::endl; + if (!jt_mode) + { + ofs << " lr_degen_mode=average: following the multiplet average, which keeps the" + " geometry on the current average surface; split groups are not recombined." + << std::endl; + return average_forces(forces); + } + return this->cal_jt_force(forces, ekb, ofs); +} + +template +ModuleBase::matrix Core::cal_jt_force(const std::vector& diag, const ModuleBase::matrix& ekb, + std::ofstream& ofs) +{ + // Regime (c): descend the Jahn-Teller branch. This needs the whole gradient matrix, so the + // off-diagonal elements are assembled here. + const std::vector& group = this->relax.target.group(); + const LR::MplLvc mpl = LR::build_mpl_state(this->gradient_inputs(), this->gs_force_ctx(), + this->state_ctx(ekb), this->relax.target.ispin(), group, diag, ofs); + LR::JtForce jt = LR::eval_jt_force(mpl.g, ofs); + const int channel = this->dim.openshell ? 0 : this->relax.target.ispin(); + this->relax.target.save_mixed(this->amp.x[channel].template data(), this->amp.nloc, jt.mixing); + // The returned force is the descending branch's own gradient; once a step splits the + // multiplet `resolve_group` finds no group and the single-state path takes over. + return jt.force; +} + template void Core::read_wfc(const std::string&, const Input_para&, const K_Vectors&, std::ostream&); template void Core>::read_wfc(const std::string&, const Input_para&, const K_Vectors&, std::ostream&); template void Core::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); template void Core>::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); +template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); +template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); +template std::vector Core::cal_force_xz(int, const ct::Tensor&, const std::vector&, + int); +template std::vector Core>::cal_force_xz(int, const ct::Tensor&, + const std::vector&, int); +template std::vector Core::cal_force_os(const ct::Tensor&, const std::vector&, int); +template std::vector Core>::cal_force_os(const ct::Tensor&, + const std::vector&, int); +template void Core::cal_force_grad(int, const ModuleBase::matrix&, std::ofstream&); +template void Core>::cal_force_grad(int, const ModuleBase::matrix&, std::ofstream&); +template module_dm::DensityMatrix Core::cal_dm_gs() const; +template module_dm::DensityMatrix, double> Core>::cal_dm_gs() const; +template void Core::test_force(); +template void Core>::test_force(); +template void Core::setup_relax(); +template void Core>::setup_relax(); +template void Core::follow_target(const ModuleBase::matrix&, std::ofstream&); +template void Core>::follow_target(const ModuleBase::matrix&, std::ofstream&); +template ModuleBase::matrix Core::cal_lr_force(const ModuleBase::matrix&, std::ofstream&); +template ModuleBase::matrix Core>::cal_lr_force(const ModuleBase::matrix&, std::ofstream&); +template ModuleBase::matrix Core::cal_jt_force(const std::vector&, + const ModuleBase::matrix&, std::ofstream&); +template ModuleBase::matrix Core>::cal_jt_force(const std::vector&, + const ModuleBase::matrix&, std::ofstream&); +template ct::Tensor Core::pad_group_z(int, const std::vector&) const; +template ct::Tensor Core>::pad_group_z(int, const std::vector&) const; + } // namespace LR diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index d69fecb398..6fbe390fb6 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -11,12 +11,34 @@ #include "source_lcao/module_lr/potentials/lr_gs_pot.h" #include "source_lcao/module_lr/potentials/pot_hxc_lrtd.h" +#include #include #include #include +class Grid_Driver; +class Structure_Factor; +class TwoCenterBundle; +class pseudopot_cell_vl; +#ifdef __EXX +template +class Exx_LRI; +#endif +namespace module_dm +{ +template +class DensityMatrix; +} + namespace LR { +template +struct GradientInputs; +template +struct GsForceCtx; +template +struct StateCtx; + /// The ground state the LR solver works from. template struct GsState @@ -61,6 +83,36 @@ struct RelaxRun std::vector mpl; }; +/// Borrowed handles the force and relaxation path needs. The esolver binds them once, after the +/// ground state has been read; every pointer outlives the solver. +template +struct Refs +{ + const UnitCell* ucell = nullptr; + const K_Vectors* kv = nullptr; + const Grid_Driver* gd = nullptr; + const std::vector* orb_cutoff = nullptr; + const ModulePW::PW_Basis* rho = nullptr; + const ModulePW::PW_Basis* rhod = nullptr; + pseudopot_cell_vl* vloc = nullptr; + Structure_Factor* sfac = nullptr; + const TwoCenterBundle* tcb = nullptr; + const Input_para* inp = nullptr; + std::ofstream* log = nullptr; + Parallel_Grid* pgrid = nullptr; + const std::string* in_dir = nullptr; + const std::string* out_dir = nullptr; + const std::string* xc_kernel = nullptr; + int my_rank = 0; + /// The layout `gs.psi_all` is distributed by: the KS solver's `pv`, or `gs.para_mat_all`. + const Parallel_Orbitals* pv_all = nullptr; +#ifdef __EXX + /// Points at the solver's member so a rebuilt `Exx_LRI` is seen without rebinding. + const std::shared_ptr>* exx_lri = nullptr; + double hybrid_alpha = 1.0; +#endif +}; + /// LR solver state that does not belong to the esolver interface. template struct Core @@ -71,11 +123,47 @@ struct Core ZWin zw; PotSet pot; RelaxRun relax; + Refs refs; + + void bind(const Refs& r) { this->refs = r; } /// Read the ground-state bands this solver needs, from file. void read_wfc(const std::string& in_dir, const Input_para& inp, const K_Vectors& kv, std::ostream& log); /// Widen the ground-state window into the Z window used by the force path. void fill_z(const int* desc_src, const K_Vectors& kv, bool cal_force, bool first, std::ostream& log); + + /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` + /// restricts it to that one state; -1 does all `nstates`. + std::vector cal_force(int ispin, const ModuleBase::matrix& ekb, int istate_only); + /// Gradients for caller-supplied vectors already widened into the Z window. + std::vector cal_force_xz(int ispin, const ct::Tensor& xz, const std::vector& omega, + int label_begin); + /// Open-shell counterpart of `cal_force_xz`: both channels live in one vector. + std::vector cal_force_os(const ct::Tensor& xz, const std::vector& omega, + int label_begin); + /// Per-state gradients plus the gradient matrix of each degenerate multiplet. + void cal_force_grad(int ispin, const ModuleBase::matrix& ekb, std::ofstream& ofs); + /// Ground-state density matrix. + module_dm::DensityMatrix cal_dm_gs() const; + /// Reproduce the ground-state force as a check of the force machinery. + void test_force(); + + /// Resolve and validate `lr_target_state` / `lr_target_spin`. + void setup_relax(); + /// Re-choose the followed root by cross-geometry overlap, then refresh the references. + void follow_target(const ModuleBase::matrix& ekb, std::ofstream& ofs); + /// The LR half of the force for the current geometry, following the selected surface. + ModuleBase::matrix cal_lr_force(const ModuleBase::matrix& ekb, std::ofstream& ofs); + /// The force of the steepest-descending branch of the target multiplet (`lr_degen_mode = jt`). + ModuleBase::matrix cal_jt_force(const std::vector& diag, const ModuleBase::matrix& ekb, + std::ofstream& ofs); + /// Widen a multiplet's eigenvectors into the Z window, one block each. + ct::Tensor pad_group_z(int ispin, const std::vector& group) const; + + private: + GradientInputs gradient_inputs() const; + GsForceCtx gs_force_ctx() const; + StateCtx state_ctx(const ModuleBase::matrix& ekb) const; }; } // namespace LR From c6c1a07b05d6424f5e8e4de004e4e7a3f56a12e9 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:02:43 +0800 Subject: [PATCH 17/26] refactor(lr): pass owned logs to set_wfc_and_mo_sizes The LR runtime logs are the same streams as GlobalV::ofs_running and GlobalV::ofs_warning, but using the members keeps the global dependency budget from growing. --- source/source_esolver/esolver_lr_lcao_bse.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index 96bb7e90ac..70046b4b52 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -58,7 +58,7 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para LR_Util::setup_2d_division(this->lr_.gs.para_mat.para_2d(), 1, this->lr_.dim.nbasis, this->lr_.dim.nbasis); #ifdef __MPI this->lr_.gs.para_mat.set_wfc_and_mo_layouts(this->lr_.dim.nbasis, this->lr_.dim.nbands); - int err = this->lr_.gs.para_mat.set_wfc_and_mo_sizes(this->lr_.dim.nbands, GlobalV::ofs_running, GlobalV::ofs_warning); + int err = this->lr_.gs.para_mat.set_wfc_and_mo_sizes(this->lr_.dim.nbands, this->ofs_running_, this->ofs_warning_); this->lr_.gs.para_mat.set_atomic_trace(ucell.get_iat2iwt(), ucell.nat, this->lr_.dim.nbasis); #else this->lr_.gs.para_mat.nrow_bands = this->lr_.dim.nbasis; From f287ccb01fe606ecea0d0507467fe4abc162c927 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:06:05 +0800 Subject: [PATCH 18/26] refactor(lr): move the per-step ground-state refresh into LR::Core --- source/source_esolver/esolver_lr.cpp | 67 +++------------------- source/source_lcao/module_lr/lr_core.cpp | 72 ++++++++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 14 +++++ 3 files changed, 93 insertions(+), 60 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index 2764f9d645..fc95f7a020 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -767,60 +767,14 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) { ModuleBase::TITLE("ESolver_LR", "refresh_from_ks_"); ModuleESolver::ESolver_KS_LCAO &ks_sol = *this->ks_; - // The ground-state solver owns `psi` and reuses it across ionic steps, so it cannot be stolen. - // `eig_ks_all` / `wg_ks_all` are nspin x nbands matrices -- a few kB, copied rather than aliased - // so that they survive the KS solver overwriting `pelec` on the next step. - this->lr_.gs.psi_all = ks_sol.psi; - this->lr_.gs.eig_all = ks_sol.pelec->ekb; - this->lr_.gs.wg_all = ks_sol.pelec->wg; - const int max_occupied_bands = *std::max_element(this->lr_.dim.nocc.begin(), this->lr_.dim.nocc.end()); - const int start_band = this->lr_.dim.nocc_max - max_occupied_bands; - - for (int ik = 0; ik < this->kv.get_nks(); ++ik) - { - // copy the KS orbitals in the [nocc, nvirt] window -#ifdef __MPI - this->lr_.gs.psi_all->fix_k(ik); - this->lr_.gs.psi->fix_k(ik); - const int first_band = start_band + 1; - Cpxgemr2d( - this->lr_.dim.nbasis, this->lr_.dim.nbands, this->lr_.gs.psi_all->get_pointer(), 1, first_band, ks_sol.pv.desc_wfc, - this->lr_.gs.psi->get_pointer(), 1, 1, const_cast(this->lr_.amp.para_c.desc()), this->lr_.amp.para_c.ictxt()); -#else - // serial: each band is `nbasis` contiguous coefficients, so the window is a plain - // band-by-band copy (this loop used to compute the two pointers and copy nothing, - // leaving `psi_ks` uninitialized in every non-MPI build) - for (int ib = 0; ib < this->lr_.dim.nbands; ++ib) - { - const auto *start = &(*this->lr_.gs.psi_all)(ik, start_band + ib, 0); - auto *to = &(*this->lr_.gs.psi)(ik, ib, 0); - std::copy(start, start + this->lr_.dim.nbasis, to); - } -#endif - // copy the KS bands in the [nocc, nvirt] window - for (int ib = 0; ib < this->lr_.dim.nbands; ++ib) - { - this->lr_.gs.eig(ik, ib) = this->lr_.gs.eig_all(ik, start_band + ib); - } - } - if (this->lr_.dim.nspin == 2) - { - const int nupdown_now = - LR_Util::spin_population_difference(ks_sol.pelec->wg, this->kv.para_k.kpar, this->kv.para_k.rank_in_pool); - if (!this->ks_initialized_) - { - this->lr_.dim.nupdown = nupdown_now; - reset_dim_spin(); // shifts nocc/nvirt between the spin channels: must run exactly once - } - else if (nupdown_now != this->lr_.dim.nupdown) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR::refresh_from_ks_", - "the ground-state spin population changed between ionic steps, but nocc/nvirt and" - " the distributions built from them were fixed at the first step."); - } - } + LR::KsBands bands; + bands.psi = ks_sol.psi; + bands.ekb = &ks_sol.pelec->ekb; + bands.wg = &ks_sol.pelec->wg; + bands.pv = &ks_sol.pv; + this->lr_.refresh_gs(bands, this->kv, *this->inp_, !this->ks_initialized_, this->ofs_running_); + // `gint_info_` stays owned by the KS solver: its `before_scf` rebuilds and re-publishes it // init potential and calculate kernels using ground state charge init_pot(*ks_sol.pelec->charge); @@ -845,13 +799,6 @@ void ModuleESolver::ESolver_LR::refresh_from_ks_(UnitCell &ucell) // the grid-integration tables hang off a static pointer that the ground-state solver // re-publishes in its `before_scf`; make sure it names the object we integrate on ModuleGint::Gint::set_gint_info(this->ks_->gint_info_.get()); - - // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final -#ifdef __MPI - this->fill_z_window_(ks_sol.pv.desc_wfc); -#else - this->fill_z_window_(nullptr); -#endif } template diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index c14530ccd4..1e2d373cd6 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -1,6 +1,8 @@ #include "source_lcao/module_lr/lr_core.h" +#include "source_base/module_external/scalapack_connector.h" #include "source_base/timer.h" +#include "source_base/tool_quit.h" #include "source_base/tool_title.h" #include "source_basis/module_nao/two_center_bundle.h" #include "source_basis/module_nao/two_center_integrator.h" @@ -18,6 +20,7 @@ #include "source_lcao/module_lr/lr_gs.h" #include "source_lcao/module_lr/lr_sforce.h" #include "source_lcao/module_lr/lr_zeq.h" +#include "source_lcao/module_lr/utils/lr_util.h" #include "source_lcao/module_lr/utils/lr_util_hcontainer.h" #include @@ -57,6 +60,71 @@ void Core::fill_z(const int* desc_src, const K_Vectors& kv, const bool cal_fo this->zw.nloc = z.nloc; } +template +void Core::refresh_gs(const KsBands& bands, const K_Vectors& kv, const Input_para& inp, const bool first, + std::ostream& log) +{ + // The ground-state solver owns `psi` and reuses it across ionic steps, so it cannot be stolen. + // `eig_all` / `wg_all` are nspin x nbands matrices -- a few kB, copied rather than aliased so + // that they survive the KS solver overwriting its `pelec` on the next step. + this->gs.psi_all = bands.psi; + this->gs.eig_all = *bands.ekb; + this->gs.wg_all = *bands.wg; + const int max_occupied_bands = *std::max_element(this->dim.nocc.begin(), this->dim.nocc.end()); + const int start_band = this->dim.nocc_max - max_occupied_bands; + + for (int ik = 0; ik < kv.get_nks(); ++ik) + { + // copy the KS orbitals in the [nocc, nvirt] window +#ifdef __MPI + this->gs.psi_all->fix_k(ik); + this->gs.psi->fix_k(ik); + const int first_band = start_band + 1; + Cpxgemr2d(this->dim.nbasis, this->dim.nbands, this->gs.psi_all->get_pointer(), 1, first_band, + const_cast(bands.pv->desc_wfc), this->gs.psi->get_pointer(), 1, 1, + const_cast(this->amp.para_c.desc()), this->amp.para_c.ictxt()); +#else + // serial: each band is `nbasis` contiguous coefficients, so the window is a plain + // band-by-band copy + for (int ib = 0; ib < this->dim.nbands; ++ib) + { + const auto* start = &(*this->gs.psi_all)(ik, start_band + ib, 0); + auto* to = &(*this->gs.psi)(ik, ib, 0); + std::copy(start, start + this->dim.nbasis, to); + } +#endif + // copy the KS bands in the [nocc, nvirt] window + for (int ib = 0; ib < this->dim.nbands; ++ib) + { + this->gs.eig(ik, ib) = this->gs.eig_all(ik, start_band + ib); + } + } + + if (this->dim.nspin == 2) + { + const int nupdown_now = LR_Util::spin_population_difference(*bands.wg, kv.para_k.kpar, kv.para_k.rank_in_pool); + if (first) + { + this->dim.nupdown = nupdown_now; + apply_spin_pol(this->dim, inp); // shifts nocc/nvirt between the spin channels: exactly once + } + else if (nupdown_now != this->dim.nupdown) + { + ModuleBase::WARNING_QUIT( + "LR::Core::refresh_gs", + "the ground-state spin population changed between ionic steps, but nocc/nvirt and" + " the distributions built from them were fixed at the first step."); + } + } + + // the Z-vector window: after `apply_spin_pol`, so nocc/nvirt/openshell are final +#ifdef __MPI + this->fill_z(bands.pv->desc_wfc, kv, inp.cal_force, first, log); +#else + this->fill_z(nullptr, kv, inp.cal_force, first, log); +#endif +} + template GradientInputs Core::gradient_inputs() const { @@ -303,6 +371,10 @@ template void Core>::read_wfc(const std::string&, const Inp std::ostream&); template void Core::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); template void Core>::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); +template void Core::refresh_gs(const KsBands&, const K_Vectors&, const Input_para&, bool, + std::ostream&); +template void Core>::refresh_gs(const KsBands>&, const K_Vectors&, + const Input_para&, bool, std::ostream&); template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index 6fbe390fb6..3e897cf3a3 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -54,6 +54,16 @@ struct GsState Parallel_Orbitals para_mat_all; }; +/// All-band ground-state data owned by the ground-state solver, handed over for one refresh. +template +struct KsBands +{ + psi::Psi* psi = nullptr; ///< all-band KS orbitals + const ModuleBase::matrix* ekb = nullptr; ///< all-band eigenvalues + const ModuleBase::matrix* wg = nullptr; ///< all-band occupations + const Parallel_Orbitals* pv = nullptr; ///< distribution of `psi` +}; + /// The excitation amplitudes and their distribution. struct Amp { @@ -131,6 +141,10 @@ struct Core void read_wfc(const std::string& in_dir, const Input_para& inp, const K_Vectors& kv, std::ostream& log); /// Widen the ground-state window into the Z window used by the force path. void fill_z(const int* desc_src, const K_Vectors& kv, bool cal_force, bool first, std::ostream& log); + /// Re-read the band window that follows the current geometry, then rebuild the Z window. + /// `first` selects the one-time spin-channel setup; later calls only validate it. + void refresh_gs(const KsBands& bands, const K_Vectors& kv, const Input_para& inp, bool first, + std::ostream& log); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state; -1 does all `nstates`. From 191223980f0e827d9d73ab98cf7e8dc3e5b699f8 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:07:29 +0800 Subject: [PATCH 19/26] refactor(lr): move the KS layout setup into LR::Core --- source/source_esolver/esolver_lr.cpp | 45 +-------------------- source/source_lcao/module_lr/lr_core.cpp | 51 ++++++++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 3 ++ 3 files changed, 55 insertions(+), 44 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index fc95f7a020..93eaf23992 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -676,50 +676,7 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons this->set_dim(); - // KS and LR must use the same AO distribution, including its BLACS grid. - const int ks_block_size = ks_sol.pv.para_2d().nb(); - LR_Util::setup_2d_division( - this->lr_.gs.para_mat.para_2d(), ks_block_size, this->lr_.dim.nbasis, this->lr_.dim.nbasis -#ifdef __MPI - , - ks_sol.pv.para_2d().ictxt() -#endif - ); - LR::set_band_layout(this->lr_.gs.para_mat, this->lr_.dim.nbasis, this->lr_.dim.nbands, *this->ucell_, - this->inp_->ri_hartree_benchmark == "aims"); - if (this->inp_->cal_force) - { - LR_Util::setup_2d_division( - this->lr_.gs.para_mat_all.para_2d(), ks_block_size, this->lr_.dim.nbasis, this->lr_.dim.nbasis -#ifdef __MPI - , - ks_sol.pv.para_2d().ictxt() -#endif - ); - LR::set_band_layout(this->lr_.gs.para_mat_all, this->lr_.dim.nbasis, this->inp_->nbands, *this->ucell_, - this->inp_->ri_hartree_benchmark == "aims"); - } - - this->lr_.gs.para_mat.atom_begin_row = ks_sol.pv.atom_begin_row; - this->lr_.gs.para_mat.atom_begin_col = ks_sol.pv.atom_begin_col; - this->lr_.gs.para_mat.iat2iwt_ = ucell.get_iat2iwt(); - - LR_Util::setup_2d_division( - this->lr_.amp.para_c, ks_block_size, this->lr_.dim.nbasis, this->lr_.dim.nbands -#ifdef __MPI - , - this->lr_.gs.para_mat.para_2d().ictxt() -#endif - ); - - // allocate psi_ks and eig_ks in the [nocc, nvirt] window -#ifdef __MPI - this->lr_.gs.psi.reset( - new psi::Psi(this->kv.get_nks(), this->lr_.amp.para_c.ncloc(), this->lr_.amp.para_c.nrloc(), this->kv.ngk, true)); -#else - this->lr_.gs.psi.reset(new psi::Psi(this->kv.get_nks(), this->lr_.dim.nbands, this->lr_.dim.nbasis, this->kv.ngk, true)); -#endif - this->lr_.gs.eig.create(this->kv.get_nks(), this->lr_.dim.nbands); + this->lr_.setup_ks_layout(ks_sol.pv, this->kv, *this->ucell_, *this->inp_); this->pelec = new elecstate::ElecStateLCAO(); orb_cutoff_ = ks_sol.orb_.cutoffs(); diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 1e2d373cd6..093149a58a 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -125,6 +125,53 @@ void Core::refresh_gs(const KsBands& bands, const K_Vectors& kv, const Inp #endif } +template +void Core::setup_ks_layout(const Parallel_Orbitals& pv, const K_Vectors& kv, const UnitCell& ucell, + const Input_para& inp) +{ + // KS and LR must use the same AO distribution, including its BLACS grid. + const int ks_block_size = pv.para_2d().nb(); + LR_Util::setup_2d_division(this->gs.para_mat.para_2d(), ks_block_size, this->dim.nbasis, this->dim.nbasis +#ifdef __MPI + , + pv.para_2d().ictxt() +#endif + ); + LR::set_band_layout(this->gs.para_mat, this->dim.nbasis, this->dim.nbands, ucell, + inp.ri_hartree_benchmark == "aims"); + if (inp.cal_force) + { + LR_Util::setup_2d_division(this->gs.para_mat_all.para_2d(), ks_block_size, this->dim.nbasis, this->dim.nbasis +#ifdef __MPI + , + pv.para_2d().ictxt() +#endif + ); + LR::set_band_layout(this->gs.para_mat_all, this->dim.nbasis, inp.nbands, ucell, + inp.ri_hartree_benchmark == "aims"); + } + + this->gs.para_mat.atom_begin_row = pv.atom_begin_row; + this->gs.para_mat.atom_begin_col = pv.atom_begin_col; + this->gs.para_mat.iat2iwt_ = ucell.get_iat2iwt(); + + LR_Util::setup_2d_division(this->amp.para_c, ks_block_size, this->dim.nbasis, this->dim.nbands +#ifdef __MPI + , + this->gs.para_mat.para_2d().ictxt() +#endif + ); + + // allocate psi_ks and eig_ks in the [nocc, nvirt] window +#ifdef __MPI + this->gs.psi.reset( + new psi::Psi(kv.get_nks(), this->amp.para_c.ncloc(), this->amp.para_c.nrloc(), kv.ngk, true)); +#else + this->gs.psi.reset(new psi::Psi(kv.get_nks(), this->dim.nbands, this->dim.nbasis, kv.ngk, true)); +#endif + this->gs.eig.create(kv.get_nks(), this->dim.nbands); +} + template GradientInputs Core::gradient_inputs() const { @@ -375,6 +422,10 @@ template void Core::refresh_gs(const KsBands&, const K_Vectors&, std::ostream&); template void Core>::refresh_gs(const KsBands>&, const K_Vectors&, const Input_para&, bool, std::ostream&); +template void Core::setup_ks_layout(const Parallel_Orbitals&, const K_Vectors&, const UnitCell&, + const Input_para&); +template void Core>::setup_ks_layout(const Parallel_Orbitals&, const K_Vectors&, const UnitCell&, + const Input_para&); template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index 3e897cf3a3..b4b25dc01f 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -145,6 +145,9 @@ struct Core /// `first` selects the one-time spin-channel setup; later calls only validate it. void refresh_gs(const KsBands& bands, const K_Vectors& kv, const Input_para& inp, bool first, std::ostream& log); + /// Set up the AO/band distributions and the band window on the ground-state solver's layout. + void setup_ks_layout(const Parallel_Orbitals& pv, const K_Vectors& kv, const UnitCell& ucell, + const Input_para& inp); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state; -1 does all `nstates`. From 0e4289a60effcf419be9a3965ad2f8309deff9af Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:09:32 +0800 Subject: [PATCH 20/26] refactor(lr): move standalone layout setup into LR::Core --- source/source_esolver/esolver_lr.cpp | 25 +++------------------- source/source_esolver/esolver_lr.h | 3 --- source/source_lcao/module_lr/lr_core.cpp | 27 ++++++++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 2 ++ 4 files changed, 32 insertions(+), 25 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index 93eaf23992..c03f424b68 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -294,7 +294,7 @@ void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) { LR_Density lr_density( *this->ucell_, kv, gd(), *this->lr_.gs.psi, orb_cutoff_, pgrid(), this->lr_.dim.nspin, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nbasis, this->lr_.amp.para_x, this->lr_.amp.para_c, - paraMat_, this->lr_.dim.openshell, this->inp_->out_chg[1], this->out_dir); + this->lr_.gs.para_mat, this->lr_.dim.openshell, this->inp_->out_chg[1], this->out_dir); if (this->lr_.dim.openshell) { @@ -809,22 +809,11 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell } this->set_dim(); - // setup 2d-block distribution for AO-matrix and KS wfc - LR_Util::setup_2d_division(this->lr_.gs.para_mat.para_2d(), 1, this->lr_.dim.nbasis, this->lr_.dim.nbasis); - LR::set_band_layout(this->lr_.gs.para_mat, this->lr_.dim.nbasis, this->lr_.dim.nbands, *this->ucell_, - this->inp_->ri_hartree_benchmark == "aims"); - if (this->inp_->cal_force) - { - LR_Util::setup_2d_division(this->lr_.gs.para_mat_all.para_2d(), 1, this->lr_.dim.nbasis, this->lr_.dim.nbasis); - LR::set_band_layout(this->lr_.gs.para_mat_all, this->lr_.dim.nbasis, this->inp_->nbands, *this->ucell_, - this->inp_->ri_hartree_benchmark == "aims"); - } + this->lr_.setup_file_layout(this->kv, *this->ucell_, *this->inp_); // read the ground state info // now ModuleIO::read_wfc_nao needs `Parallel_Orbitals` and can only read all the bands // it need improvement to read only the bands needed - this->lr_.gs.psi.reset(new psi::Psi( - this->kv.get_nks(), this->lr_.gs.para_mat.ncol_bands, this->lr_.gs.para_mat.para_2d().nrloc(), this->kv.ngk, true)); this->read_ks_wfc(); if (this->lr_.dim.nspin == 2) @@ -834,19 +823,11 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell } // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final #ifdef __MPI - this->fill_z_window_(paraMat_all_.desc_wfc); + this->fill_z_window_(this->lr_.gs.para_mat_all.desc_wfc); #else this->fill_z_window_(nullptr); #endif - LR_Util::setup_2d_division( - this->lr_.amp.para_c, 1, this->lr_.dim.nbasis, this->lr_.dim.nbands -#ifdef __MPI - , - paraMat_.para_2d().ictxt() -#endif - ); - // clear ks info, new elecstate for excition delete this->pelec; // the ElecStateLCAO allocated above, only needed while reading the KS data this->pelec = new elecstate::ElecState(); diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 4ce48ef9d8..112f983939 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -138,9 +138,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP /// Widen `nst` X blocks starting at `istate_begin` from the X window into the Z window, /// zero-filling the virtual rows X does not have. /// @brief variables for parallel distribution of matrix in AO representation - Parallel_Orbitals paraMat_; - Parallel_Orbitals paraMat_all_; // for the parallelized size of the KS orbitals - LCAO_Orbitals orb_; ///< numerical atomic orbital data for single-point evaluation std::vector> velocity_mo; ///< store the velocity matrix elements in MO basis diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 093149a58a..5fc6be5659 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -172,6 +172,31 @@ void Core::setup_ks_layout(const Parallel_Orbitals& pv, const K_Vectors& kv, this->gs.eig.create(kv.get_nks(), this->dim.nbands); } +template +void Core::setup_file_layout(const K_Vectors& kv, const UnitCell& ucell, const Input_para& inp) +{ + LR_Util::setup_2d_division(this->gs.para_mat.para_2d(), 1, this->dim.nbasis, this->dim.nbasis); + LR::set_band_layout(this->gs.para_mat, this->dim.nbasis, this->dim.nbands, ucell, + inp.ri_hartree_benchmark == "aims"); + if (inp.cal_force) + { + LR_Util::setup_2d_division(this->gs.para_mat_all.para_2d(), 1, this->dim.nbasis, this->dim.nbasis); + LR::set_band_layout(this->gs.para_mat_all, this->dim.nbasis, inp.nbands, ucell, + inp.ri_hartree_benchmark == "aims"); + } + + // the ground state is read from file, so the band window spans the stored bands directly + this->gs.psi.reset(new psi::Psi(kv.get_nks(), this->gs.para_mat.ncol_bands, + this->gs.para_mat.para_2d().nrloc(), kv.ngk, true)); + + LR_Util::setup_2d_division(this->amp.para_c, 1, this->dim.nbasis, this->dim.nbands +#ifdef __MPI + , + this->gs.para_mat.para_2d().ictxt() +#endif + ); +} + template GradientInputs Core::gradient_inputs() const { @@ -426,6 +451,8 @@ template void Core::setup_ks_layout(const Parallel_Orbitals&, const K_Ve const Input_para&); template void Core>::setup_ks_layout(const Parallel_Orbitals&, const K_Vectors&, const UnitCell&, const Input_para&); +template void Core::setup_file_layout(const K_Vectors&, const UnitCell&, const Input_para&); +template void Core>::setup_file_layout(const K_Vectors&, const UnitCell&, const Input_para&); template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index b4b25dc01f..b20f029555 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -148,6 +148,8 @@ struct Core /// Set up the AO/band distributions and the band window on the ground-state solver's layout. void setup_ks_layout(const Parallel_Orbitals& pv, const K_Vectors& kv, const UnitCell& ucell, const Input_para& inp); + /// Set up the same distributions for the standalone path, where the ground state comes from files. + void setup_file_layout(const K_Vectors& kv, const UnitCell& ucell, const Input_para& inp); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state; -1 does all `nstates`. From c02f8e63ea2ca21d10fd5e924e3dc5e897702a18 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:16:34 +0800 Subject: [PATCH 21/26] refactor(lr): move the excitation solve into LR::Core --- source/source_esolver/esolver_lr.cpp | 139 +-------------------- source/source_lcao/module_lr/lr_core.cpp | 148 +++++++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 5 +- 3 files changed, 154 insertions(+), 138 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index c03f424b68..6d4f776f43 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -1,10 +1,7 @@ #include "esolver_lr.h" #include "source_hamilt/module_xc/xc_functional.h" -#include "source_lcao/module_lr/hamilt_ulr.h" -#include "source_lcao/module_lr/hsolver_lrtd.h" #include "source_lcao/module_lr/lr_density.h" #include "source_lcao/module_lr/lr_spectrum.h" -#include "source_lcao/module_lr/operator_casida/operator_lr_diag.h" #include "source_lcao/module_lr/ri_benchmark/ri_benchmark.h" #include "source_lcao/module_lr/utils/lr_io.h" #include "source_lcao/module_lr/utils/lr_util.h" @@ -21,7 +18,6 @@ #include "source_base/tool_quit.h" #include "source_base/tool_title.h" #include "source_lcao/module_lr/lr_gs.h" -#include #include #include #include "source_estate/module_dm/dm_from_psi.h" @@ -104,140 +100,9 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste this->setup_eigenvectors_X(); this->pelec->ekb.create(this->lr_.dim.nspin, this->lr_.dim.nstates); - // set once here rather than inside the solver branches: the open-shell `spectrum` branch used - // to leave it empty, and both `after_all_runners` and the gradient index it - this->lr_.amp.spin_types = - this->lr_.dim.openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); - - // 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->lr_.relax.target.active() ? "_step" + std::to_string(istep) : ""; - auto efile_out = [this, &step_suffix](const std::string &label) -> std::string - { return this->out_dir + "Excitation_Energy_" + label + step_suffix + ".dat"; }; - auto vfile_out = [this, &step_suffix](const std::string &label) -> std::string - { - return this->out_dir + "Excitation_Amplitude_" + label + step_suffix + "_" + - std::to_string(this->my_rank_ + 1) + ".dat"; - }; - if (this->inp_->lr_solver == "elpa") - { - ModuleBase::WARNING_QUIT("ESolver_LR", "ESolver_LR doesn't support elpa now."); - } - else if (this->inp_->lr_solver != "spectrum") - { - auto write_states = [this, &efile_out, &vfile_out]( - const std::string &label, const Real *e, const T *v, const int &dim, const int &nst, - const int &prec = 8) -> void - { - if (this->my_rank_ == 0) - { - assert(nst == LR_Util::write_value(efile_out(label), prec, e, nst)); - } - assert(nst * dim == LR_Util::write_value(vfile_out(label), prec, v, nst, dim)); - }; - std::vector precondition(this->inp_->lr_solver == "lapack" ? 0 : this->lr_.amp.nloc, 1.0); - // allocate and initialize A matrix and density matrix - if (this->lr_.dim.openshell) - { - for (int is : {0, 1}) - { - if (this->inp_->lr_solver != "lapack") - { - const int offset_is = is * this->lr_.amp.para_x[0].size(); - OperatorLRDiag pre_op( - this->lr_.gs.eig.c + is * this->lr_.dim.nk * (this->lr_.dim.nocc[0] + this->lr_.dim.nvirt[0]), this->lr_.amp.para_x[is], this->lr_.dim.nk, this->lr_.dim.nocc[is], - this->lr_.dim.nvirt[is], false); - pre_op.act(1, offset_is, 1, precondition.data() + offset_is, precondition.data() + offset_is); - } - } - std::cout << "Solving spin-conserving excitation for open-shell system." << std::endl; - HamiltULR hulr( - xc_kernel, this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->ucell_, orb_cutoff_, this->gd(), - *this->lr_.gs.psi, this->lr_.gs.eig, -#ifdef __EXX - this->exx_lri, this->exx_info.info_global.hybrid_alpha, -#endif - this->lr_.pot.pot, this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat); - LR::HSolver::solve( - hulr, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates, this->lr_.dim.nk, this->lr_.dim.nocc, this->lr_.dim.nvirt, - this->lr_.amp.para_x, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); - if (this->inp_->out_wfc_lr) - { - write_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates); - } - } - else - { - if (this->inp_->lr_solver != "lapack") - { - OperatorLRDiag pre_op( - this->lr_.gs.eig.c, this->lr_.amp.para_x[0], this->lr_.dim.nk, this->lr_.dim.nocc[0], this->lr_.dim.nvirt[0], false); - pre_op.act(1, this->lr_.amp.nloc, 1, precondition.data(), precondition.data()); - } - const std::vector &spin_types = this->lr_.amp.spin_types; - for (int is = 0; is < this->lr_.dim.nspin; ++is) - { - std::cout << " Calculating " << spin_types[is] << " excitations" << std::endl; - HamiltLR hlr( - xc_kernel, this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->ucell_, orb_cutoff_, this->gd(), - *this->lr_.gs.psi, this->lr_.gs.eig, -#ifdef __EXX - this->exx_lri, this->exx_info.info_global.hybrid_alpha, -#endif - this->lr_.pot.pot[is], this->kv, this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat, spin_types[is], this->in_dir, - this->out_dir, this->inp_->ri_hartree_benchmark, - (this->inp_->ri_hartree_benchmark == "aims" ? this->inp_->aims_nbasis : std::vector({}))); - LR::HSolver::solve( - hlr, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates, this->lr_.dim.nk, this->lr_.dim.nocc, this->lr_.dim.nvirt, - this->lr_.amp.para_x, this->pelec->ekb.c + is * this->lr_.dim.nstates, this->inp_->lr_solver, this->inp_->lr_thr, - precondition, true); - if (this->inp_->out_wfc_lr) - { - write_states( - spin_types[is], this->pelec->ekb.c + is * this->lr_.dim.nstates, this->lr_.amp.x[is].template data(), - this->lr_.amp.nloc, this->lr_.dim.nstates); - } - } - } - } - else // lr_solver == "spectrum", read the eigenvalues - { - auto efile_in = [&](const std::string &label) -> std::string - { return this->in_dir + "Excitation_Energy_" + label + ".dat"; }; - auto vfile_in = [this](const std::string &label) -> std::string - { return this->in_dir + "Excitation_Amplitude_" + label + "_" + std::to_string(this->my_rank_ + 1) + ".dat"; }; + // solve the TDA eigenproblem (or read its states back under `lr_solver = spectrum`) + this->lr_.solve(this->pelec->ekb.c, istep); - auto read_states = [&](const std::string &label, Real *e, T *v, const int &dim, const int &nst) -> void - { - if (this->my_rank_ == 0) - { - assert(nst == LR_Util::read_value(efile_in(label), e, nst)); - std::cout << "Rank " << this->my_rank_ << ": finish reading " << efile_in(label) << std::endl; - } -#ifdef __MPI - // in velocity gauge, the eigenvalues may be used to calculate the transition dipole, so we'd better - // broadcast them - MPI_Bcast(e, nst, MPI_DOUBLE, 0, MPI_COMM_WORLD); -#endif - assert(nst * dim == LR_Util::read_value(vfile_in(label), v, nst, dim)); - std::cout << "Rank " << this->my_rank_ << ": finish reading " << vfile_in(label) << std::endl; - }; - std::cout << "reading the excitation states from file: \n"; - if (this->lr_.dim.openshell) - { - read_states("openshell", this->pelec->ekb.c, this->lr_.amp.x[0].template data(), this->lr_.amp.nloc, this->lr_.dim.nstates); - } - else - { - const std::vector &spin_types = this->lr_.amp.spin_types; - for (int is = 0; is < this->lr_.dim.nspin; ++is) - { - read_states( - spin_types[is], this->pelec->ekb.c + is * this->lr_.dim.nstates, this->lr_.amp.x[is].template data(), this->lr_.amp.nloc, - this->lr_.dim.nstates); - } - } - } if (this->lr_.relax.target.active()) { // Re-select which root to follow BEFORE taking the gradient, so the force belongs to diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 5fc6be5659..96de6d834f 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -14,18 +14,23 @@ #include "source_io/module_parameter/input_parameter.h" #include "source_lcao/module_lr/gradient_inputs.h" #include "source_lcao/module_lr/gradient_output.h" +#include "source_lcao/module_lr/hamilt_casida.h" +#include "source_lcao/module_lr/hamilt_ulr.h" +#include "source_lcao/module_lr/hsolver_lrtd.h" #include "source_lcao/module_lr/lr_amp.h" #include "source_lcao/module_lr/lr_dm.h" #include "source_lcao/module_lr/lr_force.h" #include "source_lcao/module_lr/lr_gs.h" #include "source_lcao/module_lr/lr_sforce.h" #include "source_lcao/module_lr/lr_zeq.h" +#include "source_lcao/module_lr/operator_casida/operator_lr_diag.h" #include "source_lcao/module_lr/utils/lr_util.h" #include "source_lcao/module_lr/utils/lr_util_hcontainer.h" #include #include #include +#include namespace LR { @@ -197,6 +202,147 @@ void Core::setup_file_layout(const K_Vectors& kv, const UnitCell& ucell, cons ); } +template +void Core::solve(double* ekb, const int istep) +{ + const Input_para& inp = *this->refs.inp; + // set once here rather than inside the solver branches: the open-shell `spectrum` branch used + // to leave it empty, and both the output path and the gradient index it + this->amp.spin_types = + this->dim.openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); + + // 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->relax.target.active() ? "_step" + std::to_string(istep) : ""; + auto efile_out = [this, &step_suffix](const std::string& label) -> std::string + { return *this->refs.out_dir + "Excitation_Energy_" + label + step_suffix + ".dat"; }; + auto vfile_out = [this, &step_suffix](const std::string& label) -> std::string + { + return *this->refs.out_dir + "Excitation_Amplitude_" + label + step_suffix + "_" + + std::to_string(this->refs.my_rank + 1) + ".dat"; + }; + + if (inp.lr_solver == "elpa") + { + ModuleBase::WARNING_QUIT("LR::Core::solve", "ESolver_LR doesn't support elpa now."); + } + else if (inp.lr_solver != "spectrum") + { + auto write_states = [this, &efile_out, &vfile_out]( + const std::string& label, const Real* e, const T* v, const int& dim, const int& nst, + const int& prec = 8) -> void + { + if (this->refs.my_rank == 0) + { + assert(nst == LR_Util::write_value(efile_out(label), prec, e, nst)); + } + assert(nst * dim == LR_Util::write_value(vfile_out(label), prec, v, nst, dim)); + }; + std::vector precondition(inp.lr_solver == "lapack" ? 0 : this->amp.nloc, 1.0); + // allocate and initialize A matrix and density matrix + if (this->dim.openshell) + { + for (int is : {0, 1}) + { + if (inp.lr_solver != "lapack") + { + const int offset_is = is * this->amp.para_x[0].size(); + OperatorLRDiag pre_op( + this->gs.eig.c + is * this->dim.nk * (this->dim.nocc[0] + this->dim.nvirt[0]), this->amp.para_x[is], + this->dim.nk, this->dim.nocc[is], this->dim.nvirt[is], false); + pre_op.act(1, offset_is, 1, precondition.data() + offset_is, precondition.data() + offset_is); + } + } + std::cout << "Solving spin-conserving excitation for open-shell system." << std::endl; + HamiltULR hulr( + *this->refs.xc_kernel, this->dim.nspin, this->dim.nbasis, this->dim.nocc, this->dim.nvirt, + *this->refs.ucell, *this->refs.orb_cutoff, *this->refs.gd, *this->gs.psi, this->gs.eig, +#ifdef __EXX + *this->refs.exx_lri, this->refs.hybrid_alpha, +#endif + this->pot.pot, *this->refs.kv, this->amp.para_x, this->amp.para_c, this->gs.para_mat); + LR::HSolver::solve(hulr, this->amp.x[0].template data(), this->amp.nloc, this->dim.nstates, + this->dim.nk, this->dim.nocc, this->dim.nvirt, this->amp.para_x, ekb, inp.lr_solver, + inp.lr_thr, precondition, true); + if (inp.out_wfc_lr) + { + write_states("openshell", ekb, this->amp.x[0].template data(), this->amp.nloc, this->dim.nstates); + } + } + else + { + if (inp.lr_solver != "lapack") + { + OperatorLRDiag pre_op(this->gs.eig.c, this->amp.para_x[0], this->dim.nk, this->dim.nocc[0], + this->dim.nvirt[0], false); + pre_op.act(1, this->amp.nloc, 1, precondition.data(), precondition.data()); + } + const std::vector& spin_types = this->amp.spin_types; + for (int is = 0; is < this->dim.nspin; ++is) + { + std::cout << " Calculating " << spin_types[is] << " excitations" << std::endl; + HamiltLR hlr( + *this->refs.xc_kernel, this->dim.nspin, this->dim.nbasis, this->dim.nocc, this->dim.nvirt, + *this->refs.ucell, *this->refs.orb_cutoff, *this->refs.gd, *this->gs.psi, this->gs.eig, +#ifdef __EXX + *this->refs.exx_lri, this->refs.hybrid_alpha, +#endif + this->pot.pot[is], *this->refs.kv, this->amp.para_x, this->amp.para_c, this->gs.para_mat, + spin_types[is], *this->refs.in_dir, *this->refs.out_dir, inp.ri_hartree_benchmark, + (inp.ri_hartree_benchmark == "aims" ? inp.aims_nbasis : std::vector({}))); + LR::HSolver::solve(hlr, this->amp.x[is].template data(), this->amp.nloc, this->dim.nstates, + this->dim.nk, this->dim.nocc, this->dim.nvirt, this->amp.para_x, + ekb + is * this->dim.nstates, inp.lr_solver, inp.lr_thr, precondition, true); + if (inp.out_wfc_lr) + { + write_states(spin_types[is], ekb + is * this->dim.nstates, this->amp.x[is].template data(), + this->amp.nloc, this->dim.nstates); + } + } + } + } + else // lr_solver == "spectrum", read the eigenvalues + { + auto efile_in = [&](const std::string& label) -> std::string + { return *this->refs.in_dir + "Excitation_Energy_" + label + ".dat"; }; + auto vfile_in = [this](const std::string& label) -> std::string + { + return *this->refs.in_dir + "Excitation_Amplitude_" + label + "_" + + std::to_string(this->refs.my_rank + 1) + ".dat"; + }; + + auto read_states = [&](const std::string& label, Real* e, T* v, const int& dim, const int& nst) -> void + { + if (this->refs.my_rank == 0) + { + assert(nst == LR_Util::read_value(efile_in(label), e, nst)); + std::cout << "Rank " << this->refs.my_rank << ": finish reading " << efile_in(label) << std::endl; + } +#ifdef __MPI + // in velocity gauge, the eigenvalues may be used to calculate the transition dipole, so we'd better + // broadcast them + MPI_Bcast(e, nst, MPI_DOUBLE, 0, MPI_COMM_WORLD); +#endif + assert(nst * dim == LR_Util::read_value(vfile_in(label), v, nst, dim)); + std::cout << "Rank " << this->refs.my_rank << ": finish reading " << vfile_in(label) << std::endl; + }; + std::cout << "reading the excitation states from file: \n"; + if (this->dim.openshell) + { + read_states("openshell", ekb, this->amp.x[0].template data(), this->amp.nloc, this->dim.nstates); + } + else + { + const std::vector& spin_types = this->amp.spin_types; + for (int is = 0; is < this->dim.nspin; ++is) + { + read_states(spin_types[is], ekb + is * this->dim.nstates, this->amp.x[is].template data(), + this->amp.nloc, this->dim.nstates); + } + } + } +} + template GradientInputs Core::gradient_inputs() const { @@ -453,6 +599,8 @@ template void Core>::setup_ks_layout(const Parallel_Orbital const Input_para&); template void Core::setup_file_layout(const K_Vectors&, const UnitCell&, const Input_para&); template void Core>::setup_file_layout(const K_Vectors&, const UnitCell&, const Input_para&); +template void Core::solve(double*, int); +template void Core>::solve(double*, int); template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index b20f029555..d1de3407da 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -100,7 +100,7 @@ struct Refs { const UnitCell* ucell = nullptr; const K_Vectors* kv = nullptr; - const Grid_Driver* gd = nullptr; + Grid_Driver* gd = nullptr; const std::vector* orb_cutoff = nullptr; const ModulePW::PW_Basis* rho = nullptr; const ModulePW::PW_Basis* rhod = nullptr; @@ -150,6 +150,9 @@ struct Core const Input_para& inp); /// Set up the same distributions for the standalone path, where the ground state comes from files. void setup_file_layout(const K_Vectors& kv, const UnitCell& ucell, const Input_para& inp); + /// Solve the TDA eigenproblem, or read its states from file under `lr_solver = spectrum`. + /// The `nspin x nstates` eigenvalues are written to `ekb`. + void solve(double* ekb, int istep); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state; -1 does all `nstates`. From 047179c6feaf47c80876d676758c91c6faff68b1 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:21:48 +0800 Subject: [PATCH 22/26] refactor(lr): move the excited-state output into LR::Core --- source/source_esolver/esolver_lr.cpp | 108 +---------------------- source/source_lcao/module_lr/lr_core.cpp | 108 +++++++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 2 + 3 files changed, 111 insertions(+), 107 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index 6d4f776f43..752be35732 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -1,12 +1,8 @@ #include "esolver_lr.h" #include "source_hamilt/module_xc/xc_functional.h" -#include "source_lcao/module_lr/lr_density.h" -#include "source_lcao/module_lr/lr_spectrum.h" #include "source_lcao/module_lr/ri_benchmark/ri_benchmark.h" #include "source_lcao/module_lr/utils/lr_io.h" #include "source_lcao/module_lr/utils/lr_util.h" -#include "source_lcao/module_lr/utils/lr_util_print.h" -#include "source_lcao/module_lr/utils/spectrum_weights.h" #include "source_lcao/module_lr/zeq_solver.h" #include #include @@ -146,110 +142,8 @@ template void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) { basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); - UnitCell &ucell = static_cast(basecell); - ModuleBase::TITLE("ESolver_LR", "after_all_runners"); - if (this->inp_->ri_hartree_benchmark != "none") - { - return; - } // no need to calculate the spectrum in the benchmark routine - - // cal electron-hole density - if (this->inp_->out_chg[0]) - { - LR_Density lr_density( - *this->ucell_, kv, gd(), *this->lr_.gs.psi, orb_cutoff_, pgrid(), this->lr_.dim.nspin, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.nbasis, this->lr_.amp.para_x, this->lr_.amp.para_c, - this->lr_.gs.para_mat, this->lr_.dim.openshell, this->inp_->out_chg[1], this->out_dir); - - if (this->lr_.dim.openshell) - { - for (int is = 0; is < this->lr_.dim.nspin; ++is) - { - const T *const amplitudes = this->lr_.amp.x[0].template data(); - lr_density.output_eh_density_all_states(amplitudes, is, this->lr_.dim.nstates, this->ofs_running_); - } - } - else - { - for (int is = 0; is < this->lr_.amp.x.size(); ++is) - { - const T *const amplitudes = this->lr_.amp.x[is].template data(); - lr_density.output_eh_density_all_states(amplitudes, is, this->lr_.dim.nstates, this->ofs_running_); - } - } - } - - const std::string gauge = LR_Util::tolower(this->inp_->abs_gauge); - const bool calculate_spectrum = gauge != "none"; - const std::vector spatial_weights = LR_Util::spatial_k_weights(this->kv.wk, this->lr_.dim.nspin); - // cal spectrum - if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") - { - const int nspin_tmp = this->inp_->nspin == 2 ? 2 : 1; - this->velocity_mo = LR_Util::cal_velocity_mo( - *this->ucell_, this->gd(), this->tcb(), this->lr_.gs.para_mat, this->lr_.amp.para_c, this->kv, *this->lr_.gs.psi, this->lr_.dim.nk, - nspin_tmp, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt); - } - std::vector freq; - if (calculate_spectrum) - { - freq.resize(100); - std::vector abs_wavelen_range({20, 200}); // default range - if (this->inp_->abs_wavelen_range.size() >= 2 && - std::abs(this->inp_->abs_wavelen_range[1] - this->inp_->abs_wavelen_range[0]) > 0.02) - { - abs_wavelen_range = this->inp_->abs_wavelen_range; - } - double lambda_diff = std::abs(abs_wavelen_range[1] - abs_wavelen_range[0]); - double lambda_min = std::min(abs_wavelen_range[1], abs_wavelen_range[0]); - for (int i = 0; i < freq.size(); ++i) - { - freq[i] = 91.126664 / (lambda_min + 0.01 * static_cast(i + 1) * lambda_diff); - } - } - // auto spin_types = (nspin == 2 && !openshell) ? std::vector({ "singlet", "triplet" }) : - // std::vector({ "updown" }); for (int is = 0;is < this->lr_.amp.x.size() - 1;++is) - for (int is = 0; is < this->lr_.amp.x.size(); ++is) - { - if (!calculate_spectrum) - { - const double *const energies = &this->pelec->ekb.c[is * this->lr_.dim.nstates]; - LR_Util::print_excitation_energies(this->ofs_running_, energies, this->lr_.dim.nstates, this->lr_.amp.spin_types[is]); - } - else - { - LR_Spectrum spectrum( - this->lr_.dim.nspin, this->lr_.dim.nbasis, this->lr_.dim.nocc, this->lr_.dim.nvirt, *this->pw_rho, *this->lr_.gs.psi, *this->ucell_, this->kv, - spatial_weights, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, this->lr_.gs.para_mat, - &this->pelec->ekb.c[is * this->lr_.dim.nstates], this->lr_.gs.eig.c, this->lr_.amp.x[is].template data(), this->lr_.dim.nstates, this->lr_.dim.openshell, - LR_Util::tolower(this->inp_->abs_gauge), this->my_rank_, this->out_dir); - if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") - { - spectrum.set_vmo(this->velocity_mo.data()); - } - spectrum.cal_spectrum(); - spectrum.transition_analysis(this->lr_.amp.spin_types[is] + "_tda"); - if (this->lr_.amp.spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum - { - spectrum.optical_absorption_method1(freq, this->inp_->abs_broadening); - spectrum.write_transition_dipole(this->out_dir + "trans_dipole_" + this->lr_.amp.spin_types[is] + "_tda.dat"); - // =============================================== for test - // ==================================================== spectrum.optical_absorption_method2(freq, - // this->inp_->abs_broadening); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { // TEST - // the formula v/omega rather than v/(e_a-e_i) - // spectrum.test_transition_dipoles_velocity_omega(); - // spectrum.write_transition_dipole(this->out_dir + - // "trans_dipole_" + spin_types[is] + "_vomega_tda.dat"); - // } - // =============================================== for test - // ==================================================== - } - } - if (this->inp_->cal_force && !this->lr_.relax.target.active()) - { - this->lr_.cal_force_grad(is, this->pelec->ekb, this->ofs_running_); - } - } + this->lr_.output(this->pelec->ekb); } // Resolve LR dimensions and initialize kernel potentials. diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 96de6d834f..4391fc72bf 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -1,11 +1,14 @@ #include "source_lcao/module_lr/lr_core.h" #include "source_base/module_external/scalapack_connector.h" +#include "source_base/parallel_grid.h" #include "source_base/timer.h" #include "source_base/tool_quit.h" #include "source_base/tool_title.h" +#include "source_basis/module_ao/parallel_orbitals.h" #include "source_basis/module_nao/two_center_bundle.h" #include "source_basis/module_nao/two_center_integrator.h" +#include "source_basis/module_pw/pw_basis.h" #include "source_cell/klist.h" #include "source_cell/module_neighbor/sltk_grid_driver.h" #include "source_cell/unitcell.h" @@ -18,14 +21,18 @@ #include "source_lcao/module_lr/hamilt_ulr.h" #include "source_lcao/module_lr/hsolver_lrtd.h" #include "source_lcao/module_lr/lr_amp.h" +#include "source_lcao/module_lr/lr_density.h" #include "source_lcao/module_lr/lr_dm.h" #include "source_lcao/module_lr/lr_force.h" #include "source_lcao/module_lr/lr_gs.h" #include "source_lcao/module_lr/lr_sforce.h" +#include "source_lcao/module_lr/lr_spectrum.h" #include "source_lcao/module_lr/lr_zeq.h" #include "source_lcao/module_lr/operator_casida/operator_lr_diag.h" #include "source_lcao/module_lr/utils/lr_util.h" #include "source_lcao/module_lr/utils/lr_util_hcontainer.h" +#include "source_lcao/module_lr/utils/lr_util_print.h" +#include "source_lcao/module_lr/utils/spectrum_weights.h" #include #include @@ -343,6 +350,105 @@ void Core::solve(double* ekb, const int istep) } } +template +void Core::output(const ModuleBase::matrix& ekb) +{ + const Input_para& inp = *this->refs.inp; + std::ofstream& ofs = *this->refs.log; + if (inp.ri_hartree_benchmark != "none") + { + return; // no need to calculate the spectrum in the benchmark routine + } + + // cal electron-hole density + if (inp.out_chg[0]) + { + LR_Density lr_density(*this->refs.ucell, *this->refs.kv, *this->refs.gd, *this->gs.psi, *this->refs.orb_cutoff, + *this->refs.pgrid, this->dim.nspin, this->dim.nocc, this->dim.nvirt, this->dim.nbasis, + this->amp.para_x, this->amp.para_c, this->gs.para_mat, this->dim.openshell, + inp.out_chg[1], *this->refs.out_dir); + + if (this->dim.openshell) + { + for (int is = 0; is < this->dim.nspin; ++is) + { + const T* const amplitudes = this->amp.x[0].template data(); + lr_density.output_eh_density_all_states(amplitudes, is, this->dim.nstates, ofs); + } + } + else + { + for (int is = 0; is < this->amp.x.size(); ++is) + { + const T* const amplitudes = this->amp.x[is].template data(); + lr_density.output_eh_density_all_states(amplitudes, is, this->dim.nstates, ofs); + } + } + } + + const std::string gauge = LR_Util::tolower(inp.abs_gauge); + const bool calculate_spectrum = gauge != "none"; + const std::vector spatial_weights = LR_Util::spatial_k_weights(this->refs.kv->wk, this->dim.nspin); + // cal spectrum + std::vector> velocity_mo; + if (gauge == "velocity") + { + const int nspin_tmp = inp.nspin == 2 ? 2 : 1; + velocity_mo = LR_Util::cal_velocity_mo(*this->refs.ucell, *this->refs.gd, *this->refs.tcb, this->gs.para_mat, + this->amp.para_c, *this->refs.kv, *this->gs.psi, this->dim.nk, nspin_tmp, + this->dim.nbasis, this->dim.nocc, this->dim.nvirt); + } + std::vector freq; + if (calculate_spectrum) + { + freq.resize(100); + std::vector abs_wavelen_range({20, 200}); // default range + if (inp.abs_wavelen_range.size() >= 2 && + std::abs(inp.abs_wavelen_range[1] - inp.abs_wavelen_range[0]) > 0.02) + { + abs_wavelen_range = inp.abs_wavelen_range; + } + double lambda_diff = std::abs(abs_wavelen_range[1] - abs_wavelen_range[0]); + double lambda_min = std::min(abs_wavelen_range[1], abs_wavelen_range[0]); + for (int i = 0; i < freq.size(); ++i) + { + freq[i] = 91.126664 / (lambda_min + 0.01 * static_cast(i + 1) * lambda_diff); + } + } + for (int is = 0; is < this->amp.x.size(); ++is) + { + if (!calculate_spectrum) + { + const double* const energies = &ekb.c[is * this->dim.nstates]; + LR_Util::print_excitation_energies(ofs, energies, this->dim.nstates, this->amp.spin_types[is]); + } + else + { + LR_Spectrum spectrum( + this->dim.nspin, this->dim.nbasis, this->dim.nocc, this->dim.nvirt, *this->refs.rho, *this->gs.psi, + *this->refs.ucell, *this->refs.kv, spatial_weights, *this->refs.gd, *this->refs.orb_cutoff, + *this->refs.tcb, this->amp.para_x, this->amp.para_c, this->gs.para_mat, &ekb.c[is * this->dim.nstates], + this->gs.eig.c, this->amp.x[is].template data(), this->dim.nstates, this->dim.openshell, gauge, + this->refs.my_rank, *this->refs.out_dir); + if (gauge == "velocity") + { + spectrum.set_vmo(velocity_mo.data()); + } + spectrum.cal_spectrum(); + spectrum.transition_analysis(this->amp.spin_types[is] + "_tda"); + if (this->amp.spin_types[is] != "triplet") // triplets has no transition dipole and no contribution to the spectrum + { + spectrum.optical_absorption_method1(freq, inp.abs_broadening); + spectrum.write_transition_dipole(*this->refs.out_dir + "trans_dipole_" + this->amp.spin_types[is] + "_tda.dat"); + } + } + if (inp.cal_force && !this->relax.target.active()) + { + this->cal_force_grad(is, ekb, ofs); + } + } +} + template GradientInputs Core::gradient_inputs() const { @@ -601,6 +707,8 @@ template void Core::setup_file_layout(const K_Vectors&, const UnitCell&, template void Core>::setup_file_layout(const K_Vectors&, const UnitCell&, const Input_para&); template void Core::solve(double*, int); template void Core>::solve(double*, int); +template void Core::output(const ModuleBase::matrix&); +template void Core>::output(const ModuleBase::matrix&); template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index d1de3407da..19f0ecfa92 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -153,6 +153,8 @@ struct Core /// Solve the TDA eigenproblem, or read its states from file under `lr_solver = spectrum`. /// The `nspin x nstates` eigenvalues are written to `ekb`. void solve(double* ekb, int istep); + /// Electron-hole densities, the absorption spectrum and the per-state gradients after the run. + void output(const ModuleBase::matrix& ekb); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state; -1 does all `nstates`. From 72c05beed5440a0b587236fae6abe004e084bdd7 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 18:25:34 +0800 Subject: [PATCH 23/26] refactor(lr): move the kernel potentials and X setup into LR::Core --- source/source_esolver/esolver_lr.cpp | 51 +++++------------------- source/source_esolver/esolver_lr.h | 9 ++--- source/source_lcao/module_lr/lr_core.cpp | 41 +++++++++++++++++++ source/source_lcao/module_lr/lr_core.h | 14 ++++++- 4 files changed, 66 insertions(+), 49 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index 752be35732..e25a3142a3 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -6,7 +6,6 @@ #include "source_lcao/module_lr/zeq_solver.h" #include #include -#include "source_lcao/module_lr/kernel_pots.h" #include "source_io/module_parameter/parameter.h" #include "source_lcao/module_lr/lr_dim.h" #include @@ -93,7 +92,7 @@ void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int iste } // allocate 2-particle state and setup 2d division - this->setup_eigenvectors_X(); + this->lr_.setup_x(); this->pelec->ekb.create(this->lr_.dim.nspin, this->lr_.dim.nstates); // solve the TDA eigenproblem (or read its states back under `lr_solver = spectrum`) @@ -177,38 +176,12 @@ void ModuleESolver::ESolver_LR::reset_dim_spin() template void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) { - this->lr_.pot.pot.assign(this->lr_.dim.nspin, nullptr); - if (this->inp_->ri_hartree_benchmark != "none") - { - return; - } - const auto &grid = pgrid(); - auto prepared = - LR::prepare_lr_potentials(*this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, this->lr_.dim.nspin, this->lr_.dim.openshell); - this->lr_.pot.pot = std::move(prepared.pot); - if (this->inp_->cal_force) - { - this->init_pot_groundstate(chg_gs); - this->lr_.pot.pot_hxc_gs = LR::prepare_gs_potential( - *this->inp_, xc_kernel, *this->pw_rho, *this->ucell_, chg_gs, grid, this->lr_.dim.nspin, this->lr_.dim.openshell, prepared); - } + this->lr_.init_pot(chg_gs); } // LR orbital distributions, excitation amplitudes, and ground-state file input. -template -void ModuleESolver::ESolver_LR::setup_eigenvectors_X() -{ - ModuleBase::TITLE("ESolver_LR", "setup_eigenvectors_X"); - LR::XAmp amp = LR::setup_x(this->lr_.amp.para_c, this->lr_.dim.nocc, this->lr_.dim.nvirt, this->lr_.dim.npairs, this->lr_.gs.eig, this->lr_.dim.nstates, - this->lr_.dim.nk, this->lr_.dim.nspin, this->lr_.dim.openshell, this->inp_->lr_solver == "spectrum", - this->ofs_running_); - this->lr_.amp.x = std::move(amp.x); - this->lr_.amp.para_x = std::move(amp.para_x); - this->lr_.amp.nloc = amp.nloc; -} - template void ModuleESolver::ESolver_LR::read_ks_wfc() { @@ -231,15 +204,6 @@ void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) ///========================= excited-state geometry relaxation ========================= -template -void ModuleESolver::ESolver_LR::init_pot_groundstate(const Charge &chg_gs) -{ - ModuleBase::TITLE("ESolver_LR", "init_pot_gs"); - this->lr_.pot.gs_pot.refresh(*this->inp_, this->xc_kernel, *this->ucell_, this->pw_rhod, this->pw_rho, pgrid(), chg_gs, - this->sfac(), this->vloc(), this->solvent, !this->ks_, PARAM.globalv.has_float_data); -} - - template double ModuleESolver::ESolver_LR::cal_energy() { @@ -387,7 +351,7 @@ void ModuleESolver::ESolver_LR::bind_ground_state_aliases_() } template -LR::Refs ModuleESolver::ESolver_LR::make_refs() const +LR::Refs ModuleESolver::ESolver_LR::make_refs() { LR::Refs refs; refs.ucell = this->ucell_; @@ -405,6 +369,9 @@ LR::Refs ModuleESolver::ESolver_LR::make_refs() const refs.in_dir = &this->in_dir; refs.out_dir = &this->out_dir; refs.xc_kernel = &this->xc_kernel; + refs.refresh_sfac = !this->ks_; + refs.has_float_data = PARAM.globalv.has_float_data; + refs.solvent = &this->solvent; refs.my_rank = this->my_rank_; refs.pv_all = this->ks_ ? &this->ks_->pv : &this->lr_.gs.para_mat_all; #ifdef __EXX @@ -473,8 +440,9 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons } #endif - refresh_from_ks_(ucell); + // bind before the refresh: `refresh_from_ks_` builds the potentials, which read `Refs` this->lr_.bind(this->make_refs()); + refresh_from_ks_(ucell); this->ks_initialized_ = true; } @@ -569,6 +537,8 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell this->set_dim(); this->lr_.setup_file_layout(this->kv, *this->ucell_, *this->inp_); + // bind before the potentials are built: `init_pot` reads `Refs` + this->lr_.bind(this->make_refs()); // read the ground state info // now ModuleIO::read_wfc_nao needs `Parallel_Orbitals` and can only read all the bands @@ -638,7 +608,6 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell // else #endif // ModuleBase::Ylm::set_coefficients() is deprecated - this->lr_.bind(this->make_refs()); } template class ModuleESolver::ESolver_LR; diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 112f983939..2c12d0b11e 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -141,14 +141,12 @@ class ESolver_LR : public ModuleESolver::ESolver_FP LCAO_Orbitals orb_; ///< numerical atomic orbital data for single-point evaluation std::vector> velocity_mo; ///< store the velocity matrix elements in MO basis - /// @brief allocate and set the inital value of X - void setup_eigenvectors_X(); - /// @brief read in the ground state wave function, band energy and occupation virtual void read_ks_wfc(); /// @brief read in the ground state charge density void read_ks_chg(Charge &chg); + /// Build the LR kernel potentials (overridden by BSE). virtual void init_pot(const Charge &chg_gs); /// @brief check the legality of the input parameters @@ -158,9 +156,8 @@ class ESolver_LR : public ModuleESolver::ESolver_FP void reset_dim_spin(); ///========================== for gradient calculation ========================= - void init_pot_groundstate(const Charge &chg_gs); - /// Borrow the geometry-dependent objects `LR::Core` needs for the force path. - LR::Refs make_refs() const; + /// Borrow the geometry-dependent objects `LR::Core` needs. + LR::Refs make_refs(); #ifdef __EXX /// Tdata of Exx_LRI is same as T, for the reason, see operator_lr_exx.h diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 4391fc72bf..8758befa1f 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -20,6 +20,7 @@ #include "source_lcao/module_lr/hamilt_casida.h" #include "source_lcao/module_lr/hamilt_ulr.h" #include "source_lcao/module_lr/hsolver_lrtd.h" +#include "source_lcao/module_lr/kernel_pots.h" #include "source_lcao/module_lr/lr_amp.h" #include "source_lcao/module_lr/lr_density.h" #include "source_lcao/module_lr/lr_dm.h" @@ -350,6 +351,42 @@ void Core::solve(double* ekb, const int istep) } } +template +void Core::setup_x() +{ + ModuleBase::TITLE("LR::Core", "setup_x"); + XAmp amp = LR::setup_x(this->amp.para_c, this->dim.nocc, this->dim.nvirt, this->dim.npairs, this->gs.eig, + this->dim.nstates, this->dim.nk, this->dim.nspin, this->dim.openshell, + this->refs.inp->lr_solver == "spectrum", *this->refs.log); + this->amp.x = std::move(amp.x); + this->amp.para_x = std::move(amp.para_x); + this->amp.nloc = amp.nloc; +} + +template +void Core::init_pot(const Charge& chg_gs) +{ + this->pot.pot.assign(this->dim.nspin, nullptr); + if (this->refs.inp->ri_hartree_benchmark != "none") + { + return; + } + const Parallel_Grid& grid = *this->refs.pgrid; + auto prepared = LR::prepare_lr_potentials(*this->refs.inp, *this->refs.xc_kernel, *this->refs.rho, + *this->refs.ucell, chg_gs, grid, this->dim.nspin, this->dim.openshell); + this->pot.pot = std::move(prepared.pot); + if (this->refs.inp->cal_force) + { + ModuleBase::TITLE("LR::Core", "init_pot_gs"); + this->pot.gs_pot.refresh(*this->refs.inp, *this->refs.xc_kernel, *this->refs.ucell, this->refs.rhod, + this->refs.rho, grid, chg_gs, *this->refs.sfac, *this->refs.vloc, + *this->refs.solvent, this->refs.refresh_sfac, this->refs.has_float_data); + this->pot.pot_hxc_gs = LR::prepare_gs_potential(*this->refs.inp, *this->refs.xc_kernel, *this->refs.rho, + *this->refs.ucell, chg_gs, grid, this->dim.nspin, + this->dim.openshell, prepared); + } +} + template void Core::output(const ModuleBase::matrix& ekb) { @@ -709,6 +746,10 @@ template void Core::solve(double*, int); template void Core>::solve(double*, int); template void Core::output(const ModuleBase::matrix&); template void Core>::output(const ModuleBase::matrix&); +template void Core::setup_x(); +template void Core>::setup_x(); +template void Core::init_pot(const Charge&); +template void Core>::init_pot(const Charge&); template std::vector Core::cal_force(int, const ModuleBase::matrix&, int); template std::vector Core>::cal_force(int, const ModuleBase::matrix&, int); diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index 19f0ecfa92..80fb4da6a5 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -20,6 +20,8 @@ class Grid_Driver; class Structure_Factor; class TwoCenterBundle; class pseudopot_cell_vl; +class Charge; +class surchem; #ifdef __EXX template class Exx_LRI; @@ -102,10 +104,11 @@ struct Refs const K_Vectors* kv = nullptr; Grid_Driver* gd = nullptr; const std::vector* orb_cutoff = nullptr; - const ModulePW::PW_Basis* rho = nullptr; - const ModulePW::PW_Basis* rhod = nullptr; + ModulePW::PW_Basis* rho = nullptr; + ModulePW::PW_Basis* rhod = nullptr; pseudopot_cell_vl* vloc = nullptr; Structure_Factor* sfac = nullptr; + surchem* solvent = nullptr; const TwoCenterBundle* tcb = nullptr; const Input_para* inp = nullptr; std::ofstream* log = nullptr; @@ -113,6 +116,9 @@ struct Refs const std::string* in_dir = nullptr; const std::string* out_dir = nullptr; const std::string* xc_kernel = nullptr; + /// The file (`lr`) path owns `sf`/`vloc`; on `ks-lr` the ground-state solver refreshed them. + bool refresh_sfac = true; + bool has_float_data = false; int my_rank = 0; /// The layout `gs.psi_all` is distributed by: the KS solver's `pv`, or `gs.para_mat_all`. const Parallel_Orbitals* pv_all = nullptr; @@ -155,6 +161,10 @@ struct Core void solve(double* ekb, int istep); /// Electron-hole densities, the absorption spectrum and the per-state gradients after the run. void output(const ModuleBase::matrix& ekb); + /// Allocate the excitation amplitudes and fill their initial guess. + void setup_x(); + /// Build the LR kernel potentials (and the ground-state one used by the force path) on `chg_gs`. + void init_pot(const Charge& chg_gs); /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` /// restricts it to that one state; -1 does all `nstates`. From 384af46144d11c65ec987ad4f165c137e8bc8dd0 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 19:02:12 +0800 Subject: [PATCH 24/26] refactor(lr): move ground-state file reads and Z window into LR::Core --- source/source_esolver/esolver_lr.cpp | 16 ++++------ source/source_esolver/esolver_lr.h | 3 -- source/source_esolver/esolver_lr_lcao_bse.cpp | 2 ++ source/source_lcao/module_lr/lr_core.cpp | 30 +++++++++++++++---- source/source_lcao/module_lr/lr_core.h | 6 +++- 5 files changed, 36 insertions(+), 21 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index e25a3142a3..c857dd3d4c 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -185,20 +185,13 @@ void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) template void ModuleESolver::ESolver_LR::read_ks_wfc() { - this->lr_.read_wfc(this->in_dir, *this->inp_, this->kv, this->ofs_running_); -} - -template -void ModuleESolver::ESolver_LR::fill_z_window_(const int *desc_src) -{ - this->lr_.fill_z(desc_src, this->kv, this->inp_->cal_force, !this->ks_initialized_, this->ofs_running_); + this->lr_.read_wfc(); } template void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) { - LR::read_gs_chg(this->in_dir, *this->inp_, this->lr_.dim.nspin, *this->ucell_, pgrid(), this->pw_rho, chg_gs, - this->my_rank_, this->ofs_running_); + this->lr_.read_chg(chg_gs); } @@ -551,10 +544,11 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell reset_dim_spin(); } // the Z-vector window: after `reset_dim_spin`, so nocc/nvirt/openshell are final + // (the file path is always the first build of the window) #ifdef __MPI - this->fill_z_window_(this->lr_.gs.para_mat_all.desc_wfc); + this->lr_.fill_z_win(this->lr_.gs.para_mat_all.desc_wfc, true); #else - this->fill_z_window_(nullptr); + this->lr_.fill_z_win(nullptr, true); #endif // clear ks info, new elecstate for excition diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h index 2c12d0b11e..e3563b295f 100644 --- a/source/source_esolver/esolver_lr.h +++ b/source/source_esolver/esolver_lr.h @@ -132,9 +132,6 @@ class ESolver_LR : public ModuleESolver::ESolver_FP // but span every virtual band the ground state produced (the input `nbands`), so the // window is widened by raising *nbands*, not `nvirt`. X keeps its own window, so Omega // -- and with it any finite-difference reference -- is untouched. - /// (re)build the Z window from `psi_ks_all_` / `eig_ks_all`. `desc_src` describes the - /// source wavefunction's 2D layout; unused (and may be null) in a serial build. - void fill_z_window_(const int *desc_src); /// Widen `nst` X blocks starting at `istate_begin` from the X window into the Z window, /// zero-filling the virtual rows X does not have. /// @brief variables for parallel distribution of matrix in AO representation diff --git a/source/source_esolver/esolver_lr_lcao_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index 70046b4b52..dda293f054 100644 --- a/source/source_esolver/esolver_lr_lcao_bse.cpp +++ b/source/source_esolver/esolver_lr_lcao_bse.cpp @@ -113,6 +113,8 @@ void ESolver_BSE::before_all_runners(BaseCell &basecell, const Input_para if (!this->inp_->bse_ri_hartree && this->inp_->ri_hartree_benchmark == "none") { + // the potentials below read `Refs` + this->lr_.bind(this->make_refs()); Charge chg_gs; this->read_ks_chg(chg_gs); this->init_pot(chg_gs); diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index 8758befa1f..938befd659 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -44,18 +44,33 @@ namespace LR { template -void Core::read_wfc(const std::string& in_dir, const Input_para& inp, const K_Vectors& kv, std::ostream& log) +void Core::read_wfc() { assert(this->gs.psi != nullptr); + const Input_para& inp = *this->refs.inp; GsWfc wfc = read_gs_wfc(*this->gs.psi, this->gs.eig, this->gs.wg, this->gs.para_mat, this->gs.para_mat_all, - in_dir, inp, this->dim.nocc_in, this->dim.nvirt_in, this->dim.nocc_max, - this->dim.nbands, this->dim.nbasis, kv, inp.cal_force, log); + *this->refs.in_dir, inp, this->dim.nocc_in, this->dim.nvirt_in, this->dim.nocc_max, + this->dim.nbands, this->dim.nbasis, *this->refs.kv, inp.cal_force, *this->refs.log); this->gs.psi_all_own = std::move(wfc.all_own); this->gs.psi_all = wfc.all; this->gs.eig_all = std::move(wfc.eig_all); this->gs.wg_all = std::move(wfc.wg_all); } +template +void Core::read_chg(Charge& chg) +{ + const Input_para& inp = *this->refs.inp; + LR::read_gs_chg(*this->refs.in_dir, inp, this->dim.nspin, *this->refs.ucell, *this->refs.pgrid, this->refs.rho, chg, + this->refs.my_rank, *this->refs.log); +} + +template +void Core::fill_z_win(const int* desc_src, const bool first) +{ + this->fill_z(desc_src, *this->refs.kv, this->refs.inp->cal_force, first, *this->refs.log); +} + template void Core::fill_z(const int* desc_src, const K_Vectors& kv, const bool cal_force, const bool first, std::ostream& log) @@ -727,11 +742,14 @@ ModuleBase::matrix Core::cal_jt_force(const std::vector& return jt.force; } -template void Core::read_wfc(const std::string&, const Input_para&, const K_Vectors&, std::ostream&); -template void Core>::read_wfc(const std::string&, const Input_para&, const K_Vectors&, - std::ostream&); +template void Core::read_wfc(); +template void Core>::read_wfc(); +template void Core::read_chg(Charge&); +template void Core>::read_chg(Charge&); template void Core::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); template void Core>::fill_z(const int*, const K_Vectors&, bool, bool, std::ostream&); +template void Core::fill_z_win(const int*, bool); +template void Core>::fill_z_win(const int*, bool); template void Core::refresh_gs(const KsBands&, const K_Vectors&, const Input_para&, bool, std::ostream&); template void Core>::refresh_gs(const KsBands>&, const K_Vectors&, diff --git a/source/source_lcao/module_lr/lr_core.h b/source/source_lcao/module_lr/lr_core.h index 80fb4da6a5..9b9894b64a 100644 --- a/source/source_lcao/module_lr/lr_core.h +++ b/source/source_lcao/module_lr/lr_core.h @@ -144,9 +144,13 @@ struct Core void bind(const Refs& r) { this->refs = r; } /// Read the ground-state bands this solver needs, from file. - void read_wfc(const std::string& in_dir, const Input_para& inp, const K_Vectors& kv, std::ostream& log); + void read_wfc(); + /// Read the ground-state charge density from file. + void read_chg(Charge& chg); /// Widen the ground-state window into the Z window used by the force path. void fill_z(const int* desc_src, const K_Vectors& kv, bool cal_force, bool first, std::ostream& log); + /// The bound-input counterpart of `fill_z`. + void fill_z_win(const int* desc_src, bool first); /// Re-read the band window that follows the current geometry, then rebuild the Z window. /// `first` selects the one-time spin-channel setup; later calls only validate it. void refresh_gs(const KsBands& bands, const K_Vectors& kv, const Input_para& inp, bool first, From 68ba1fe08de423216a5345f36d1ffae187dba364 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 19:37:52 +0800 Subject: [PATCH 25/26] refactor(lr): drop unused includes from ESolver_LR --- source/source_esolver/esolver_lr.cpp | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/source/source_esolver/esolver_lr.cpp b/source/source_esolver/esolver_lr.cpp index c857dd3d4c..eea060b30b 100644 --- a/source/source_esolver/esolver_lr.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -1,9 +1,6 @@ #include "esolver_lr.h" #include "source_hamilt/module_xc/xc_functional.h" -#include "source_lcao/module_lr/ri_benchmark/ri_benchmark.h" -#include "source_lcao/module_lr/utils/lr_io.h" #include "source_lcao/module_lr/utils/lr_util.h" -#include "source_lcao/module_lr/zeq_solver.h" #include #include #include "source_io/module_parameter/parameter.h" @@ -12,20 +9,11 @@ #include #include "source_base/tool_quit.h" #include "source_base/tool_title.h" -#include "source_lcao/module_lr/lr_gs.h" #include #include -#include "source_estate/module_dm/dm_from_psi.h" #include "source_io/module_output/output_log.h" -#include "source_lcao/module_lr/grad_degen.h" -#include "source_lcao/module_lr/gradient_inputs.h" -#include "source_lcao/module_lr/gradient_output.h" -#include "source_lcao/module_lr/lr_amp.h" -#include "source_lcao/module_lr/lr_dm.h" -#include "source_lcao/module_lr/lr_force.h" #include "source_base/timer.h" #include "source_lcao/module_lr/init_helpers.h" -#include "source_base/module_external/scalapack_connector.h" #include "source_basis/module_pw/pw_basis_big.h" #include "source_cell/module_neighbor/sltk_atom_arrange.h" #include "source_hamilt/module_gint/gint.h" From 2d2a5f8c39a7a2df0f903fe54fb96ffd6fca71e9 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sat, 28 Nov 2026 20:36:46 +0800 Subject: [PATCH 26/26] fix(lr): build window response with the X-window virtual count The Z window widens the virtual space for the CPSCF (Z-vector) solve, but the virtual-window response must be built for the virtuals the caller actually solved for, i.e. the X window. Passing the widened count made the response too large and shifted the triplet forces by ~0.1%: lr_tddft_lda_triplet_window_gamma before: 88.7758685201 after: 88.7747473201 (reference) force_xz / force_xz_os now take the active virtual count explicitly; Core passes dim.nvirt and state_forces passes StateCtx::nvirt. --- source/source_lcao/module_lr/lr_core.cpp | 6 +++-- source/source_lcao/module_lr/lr_sforce.cpp | 7 +++--- source/source_lcao/module_lr/lr_zeq.cpp | 27 +++++++++++----------- source/source_lcao/module_lr/lr_zeq.h | 8 ++++--- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/source/source_lcao/module_lr/lr_core.cpp b/source/source_lcao/module_lr/lr_core.cpp index f525605aaf..8e7547c77f 100644 --- a/source/source_lcao/module_lr/lr_core.cpp +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -560,7 +560,8 @@ std::vector Core::cal_force_xz(const int ispin, const ct: const std::vector& omega, const int label_begin) { ModuleBase::timer::start("LR::Core", "cal_force_xz"); - const auto forces = LR::force_xz(this->gradient_inputs(), this->gs_force_ctx(), ispin, xz, omega, label_begin); + const auto forces = LR::force_xz(this->gradient_inputs(), this->gs_force_ctx(), this->dim.nvirt[0], ispin, xz, + omega, label_begin); ModuleBase::timer::end("LR::Core", "cal_force_xz"); return forces; } @@ -570,7 +571,8 @@ std::vector Core::cal_force_os(const ct::Tensor& xz, cons const int label_begin) { ModuleBase::timer::start("LR::Core", "cal_force_os"); - const auto forces = LR::force_xz_os(this->gradient_inputs(), this->gs_force_ctx(), xz, omega, label_begin); + const auto forces = + LR::force_xz_os(this->gradient_inputs(), this->gs_force_ctx(), this->dim.nvirt, xz, omega, label_begin); ModuleBase::timer::end("LR::Core", "cal_force_os"); return forces; } diff --git a/source/source_lcao/module_lr/lr_sforce.cpp b/source/source_lcao/module_lr/lr_sforce.cpp index 93c4556bd8..6c38e1d234 100644 --- a/source/source_lcao/module_lr/lr_sforce.cpp +++ b/source/source_lcao/module_lr/lr_sforce.cpp @@ -25,7 +25,7 @@ std::vector state_forces(const GradientInputs& in, const { omega[i] = st.ekb[ispin * st.nstates + ist_begin + i]; } - return force_xz(in, gs, ispin, xz, omega, ist_begin); + return force_xz(in, gs, st.nvirt[0], ispin, xz, omega, ist_begin); } template @@ -49,7 +49,7 @@ std::vector state_forces_os(const GradientInputs& in, con { omega[i] = st.ekb[ist_begin + i]; } - return force_xz_os(in, gs, xz, omega, ist_begin); + return force_xz_os(in, gs, st.nvirt, xz, omega, ist_begin); } template @@ -67,7 +67,8 @@ MplLvc build_mpl_state(const GradientInputs& in, const GsForceCtx& gs, con } // The solver is reached only through this callback; everything else is module code. const MplEval eval = [&in, &gs, &st, ispin](const ct::Tensor& x, const std::vector& w, const int label) { - return st.openshell ? force_xz_os(in, gs, x, w, label) : force_xz(in, gs, ispin, x, w, label); + return st.openshell ? force_xz_os(in, gs, st.nvirt, x, w, label) + : force_xz(in, gs, st.nvirt[0], ispin, x, w, label); }; return build_mpl(xz, omega, diag, st.nloc_z, ispin, group, in.ucell, eval, ofs); } diff --git a/source/source_lcao/module_lr/lr_zeq.cpp b/source/source_lcao/module_lr/lr_zeq.cpp index a895bf5d1e..ee0e4e9070 100644 --- a/source/source_lcao/module_lr/lr_zeq.cpp +++ b/source/source_lcao/module_lr/lr_zeq.cpp @@ -33,12 +33,12 @@ module_dm::DensityMatrix gs_dm_for(const GradientInputs& in, const } // namespace template -std::vector force_xz(const GradientInputs& in, const GsForceCtx& gs, const int ispin, - const ct::Tensor& xz, const std::vector& omega, const int label_begin) +std::vector force_xz(const GradientInputs& in, const GsForceCtx& gs, const int nactive, + const int ispin, const ct::Tensor& xz, const std::vector& omega, + const int label_begin) { const int nst = static_cast(omega.size()); - const LR::WindowResponse window - = LR::build_window_response(in, xz, nst, in.nvirt[0], ispin, gs.in_dir); + const LR::WindowResponse window = LR::build_window_response(in, xz, nst, nactive, ispin, gs.in_dir); const ct::Tensor z = solve_zeq(in, xz, ispin, nst, gs.openshell, gs.grad_solver, gs.in_dir, window.density); const auto dm_gs = gs_dm_for(in, gs); LR_Force force_terms(in.ucell, in.kv.kvec_d, in.pmat, gs.rhod, gs.rho, gs.vloc, gs.sfac, in.gd, gs.tcb, @@ -53,11 +53,11 @@ std::vector force_xz(const GradientInputs& in, const GsFo template std::vector force_xz_os(const GradientInputs& in, const GsForceCtx& gs, - const ct::Tensor& xz, const std::vector& omega, - const int label_begin) + const std::vector& nactive, const ct::Tensor& xz, + const std::vector& omega, const int label_begin) { const int nst = static_cast(omega.size()); - const LR::WindowResponse window = LR::build_open_shell_window_response(in, xz, nst, in.nvirt); + const LR::WindowResponse window = LR::build_open_shell_window_response(in, xz, nst, nactive); const ct::Tensor z = solve_zeq(in, xz, 0, nst, gs.openshell, gs.grad_solver, gs.in_dir, window.density); const auto dm_gs = gs_dm_for(in, gs); LR_Force force_terms(in.ucell, in.kv.kvec_d, in.pmat, gs.rhod, gs.rho, gs.vloc, gs.sfac, in.gd, gs.tcb, @@ -77,15 +77,16 @@ template ct::Tensor solve_zeq>(const GradientInputs>&); template std::vector force_xz(const GradientInputs&, const GsForceCtx&, - int, const ct::Tensor&, const std::vector&, int); + int, int, const ct::Tensor&, const std::vector&, int); template std::vector force_xz>(const GradientInputs>&, const GsForceCtx>&, int, - const ct::Tensor&, const std::vector&, - int); + int, const ct::Tensor&, + const std::vector&, int); template std::vector force_xz_os(const GradientInputs&, const GsForceCtx&, - const ct::Tensor&, const std::vector&, int); + const std::vector&, const ct::Tensor&, + const std::vector&, int); template std::vector force_xz_os>( - const GradientInputs>&, const GsForceCtx>&, const ct::Tensor&, - const std::vector&, int); + const GradientInputs>&, const GsForceCtx>&, const std::vector&, + const ct::Tensor&, const std::vector&, int); } // namespace LR diff --git a/source/source_lcao/module_lr/lr_zeq.h b/source/source_lcao/module_lr/lr_zeq.h index 4b2cd7a6df..7fc5a3156f 100644 --- a/source/source_lcao/module_lr/lr_zeq.h +++ b/source/source_lcao/module_lr/lr_zeq.h @@ -33,14 +33,16 @@ ct::Tensor solve_zeq(const GradientInputs& in, const ct::Tensor& xz, int ispi const std::string& grad_solver, const std::string& in_dir, const std::vector>& window_density); -/// Forces of `nst` closed-shell states widened into the Z window. +/// Forces of `nst` closed-shell states widened into the Z window. `nactive` is the X-window +/// virtual count, i.e. the number of virtuals the caller actually solved for. template -std::vector force_xz(const GradientInputs& in, const GsForceCtx& gs, int ispin, +std::vector force_xz(const GradientInputs& in, const GsForceCtx& gs, int nactive, int ispin, const ct::Tensor& xz, const std::vector& omega, int label_begin); /// Open-shell counterpart: both spin channels live in one vector, so the channel is always 0. template -std::vector force_xz_os(const GradientInputs& in, const GsForceCtx& gs, const ct::Tensor& xz, +std::vector force_xz_os(const GradientInputs& in, const GsForceCtx& gs, + const std::vector& nactive, const ct::Tensor& xz, const std::vector& omega, int label_begin); } // namespace LR