diff --git a/source/Makefile.Objects b/source/Makefile.Objects index b98614b0d7..f708c4f212 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -1196,10 +1196,16 @@ OBJS_TENSOR=tensor.o\ lr_spectrum.o\ lr_spectrum_velocity.o\ hamilt_casida.o\ - esolver_lr_orb.o\ - esolver_lr_init.o\ - esolver_lr_cfg.o\ - esolver_lr_lcao_tddft.o\ + lr_dim.o\ + lr_gs.o\ + lr_dm.o\ + lr_relax.o\ + lr_mpl.o\ + lr_zeq.o\ + lr_sforce.o\ + lr_core.o\ + lr_gs_pot.o\ + esolver_lr.o\ OBJS_LR_GRAD=lr_force.o\ xc_kxc.o\ @@ -1220,8 +1226,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..d2e2a59439 100644 --- a/source/source_esolver/CMakeLists.txt +++ b/source/source_esolver/CMakeLists.txt @@ -21,12 +21,7 @@ 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_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_init.cpp b/source/source_esolver/esolver_lr.cpp similarity index 58% rename from source/source_esolver/esolver_lr_init.cpp rename to source/source_esolver/esolver_lr.cpp index 71a8579c0f..da8b9f4e36 100644 --- a/source/source_esolver/esolver_lr_init.cpp +++ b/source/source_esolver/esolver_lr.cpp @@ -1,15 +1,23 @@ +#include "esolver_lr.h" +#include "source_hamilt/module_xc/xc_functional.h" +#include "source_lcao/module_lr/utils/lr_util.h" +#include +#include +#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 +#include +#include "source_io/module_output/output_log.h" +#include "source_base/timer.h" #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 @@ -17,7 +25,226 @@ #include "source_hamilt/module_xc/exx_info.h" #include "source_lcao/module_ri/exx_lri_interface.h" #endif -#include + +using namespace LR; + +// LR execution flow and final spectrum/density output. + + +template +ModuleESolver::ESolver_LR::ESolver_LR( + const Input_para &inp, + const std::string &in_dir, + const std::string &out_dir, + const LRRuntime &runtime) + : in_dir(in_dir), out_dir(out_dir), ofs_running_(runtime.running_log), ofs_warning_(runtime.warning_log), + my_rank_(runtime.rank) +{ +#ifdef __EXX + init_exx_info(this->exx_info, inp); +#endif +} + +template +void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int istep) +{ + basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); + UnitCell &ucell = static_cast(basecell); + + ModuleBase::TITLE("ESolver_LR", "runner"); + ModuleBase::timer::start("ESolver_LR", "runner"); + + if (this->ks_) + { + // `init_pot_groundstate` leaves the global XC type on the LR kernel, so put it back before + // the ground-state SCF. `ESolver_KS::runner` is re-entrant: its `before_scf` rebuilds the + // neighbour lists, the grid tables and the Hamiltonian for the geometry of this step. + XC_Functional::set_xc_type(ucell.atoms[0].ncpp.xc_func); + this->ks_->runner(ucell, istep); + this->conv_esolver = this->ks_->conv_esolver; + if (this->inp_->calculation == "relax" && !this->conv_esolver) + { + ModuleBase::WARNING_QUIT( + "ESolver_LR", "Excited-state relaxation requires a converged ground-state SCF; ionic step rejected"); + } + this->lr_.relax.etot_gs = this->ks_->cal_energy(); + if (!this->ks_initialized_) + { + this->initialize_from_ks_(ucell, *this->inp_); + this->lr_.setup_relax(); // needs the final dimensions, i.e. `openshell` + } + else + { + this->refresh_from_ks_(ucell); + } + } + + // allocate 2-particle state and setup 2d division + 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`) + this->lr_.solve(this->pelec->ekb.c, istep); + + if (this->ks_ && this->inp_->cal_force && !this->lr_.relax.target.active()) + { + // Cache the KS force shared by all single-point excited states. + this->ks_->cal_force(ucell, this->lr_.relax.force_gs); + } + + 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. + 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->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 -- + // 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->lr_.dim.nstates); + auto max_abs = [](const ModuleBase::matrix &m) -> double + { + double v = 0.0; + for (int i = 0; i < m.nr * m.nc; ++i) + { + v = std::max(v, std::abs(m.c[i])); + } + return v; + }; + this->ofs_running_ << std::setprecision(8) << std::fixed << " EXCITED-STATE RELAX step " << istep + << ": E_gs = " << this->lr_.relax.etot_gs * ModuleBase::Ry_to_eV + << " eV, Omega = " << omega * ModuleBase::Ry_to_eV + << " eV, E_exc = " << (this->lr_.relax.etot_gs + omega) * ModuleBase::Ry_to_eV << " eV" + << std::setprecision(6) << " | |F_gs|max = " + << max_abs(this->lr_.relax.force_gs) * ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A + << ", |F_Omega|max = " + << max_abs(this->lr_.relax.lr_force) * ModuleBase::Ry_to_eV / ModuleBase::BOHR_TO_A << " eV/Angstrom" + << std::defaultfloat << std::endl; + } + + ModuleBase::timer::end("ESolver_LR", "runner"); + return; +} + +template +void ModuleESolver::ESolver_LR::after_all_runners(BaseCell &basecell) +{ + basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); + ModuleBase::TITLE("ESolver_LR", "after_all_runners"); + this->lr_.output(this->pelec->ekb); +} + +// 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_; + + this->lr_.dim = LR::resolve_dim(src); +} + +template +void ModuleESolver::ESolver_LR::reset_dim_spin() +{ + LR::apply_spin_pol(this->lr_.dim, *this->inp_); +} + +template +void ModuleESolver::ESolver_LR::init_pot(const Charge &chg_gs) +{ + this->lr_.init_pot(chg_gs); +} + +// LR orbital distributions, excitation amplitudes, and ground-state file input. + + +template +void ModuleESolver::ESolver_LR::read_ks_wfc() +{ + this->lr_.read_wfc(); +} + +template +void ModuleESolver::ESolver_LR::read_ks_chg(Charge &chg_gs) +{ + this->lr_.read_chg(chg_gs); +} + + +///========================= excited-state geometry relaxation ========================= + +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->lr_.relax.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->lr_.relax.etot_gs + this->lr_.relax.target.omega(this->pelec->ekb.c, this->lr_.dim.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->ks_ && this->lr_.relax.force_gs.nr == ucell.nat) + { + ModuleIO::print_force( + this->ofs_running_, ucell, "GROUND-STATE FORCE (eV/Angstrom)", this->lr_.relax.force_gs, false); + } + if (!this->lr_.relax.target.active()) + { // single-point runs print the gradients of every state from `after_all_runners` instead + return; + } + 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."); + } + // Both halves already follow the ABACUS force convention F = -dE/dR (Ry/Bohr), so they add. + // The per-state LR table reports the excitation-energy contribution -d(Omega)/dR; + // adding the ground-state force gives the total force on the excited-state surface. + force.create(ucell.nat, 3); + force = this->lr_.relax.force_gs + this->lr_.relax.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)."); +} + +// Initialize LR from an embedded KS solver or standalone ground-state files. #ifdef __EXX namespace @@ -55,35 +282,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 = exx_ks->make_lr_workspace(*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); -} -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"); -} -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"); -} -#endif - -using namespace LR; - template void ModuleESolver::ESolver_LR::before_all_runners(BaseCell &basecell, const Input_para &inp) { @@ -143,6 +341,37 @@ void ModuleESolver::ESolver_LR::bind_ground_state_aliases_() } } +template +LR::Refs ModuleESolver::ESolver_LR::make_refs() +{ + 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.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 + 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) { @@ -160,52 +389,11 @@ 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); - - this->set_dimension(); + LR::check_lr_parameters(*this->inp_, this->xc_kernel, this->lr_.dim.nspin); - // 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 - ); + this->set_dim(); - // 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->lr_.setup_ks_layout(ks_sol.pv, this->kv, *this->ucell_, *this->inp_); this->pelec = new elecstate::ElecStateLCAO(); orb_cutoff_ = ks_sol.orb_.cutoffs(); @@ -243,6 +431,8 @@ void ModuleESolver::ESolver_LR::initialize_from_ks_(UnitCell &ucell, cons } #endif + // 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; } @@ -252,60 +442,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->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 T* start = &(*this->psi_ks_all_)(ik, start_band + ib, 0); - T* 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_spin2(); // 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."); - } - } + 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); @@ -319,24 +463,17 @@ 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 // 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_spin2`, 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 @@ -371,7 +508,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); @@ -389,42 +526,28 @@ void ModuleESolver::ESolver_LR::initialize_from_unitcell_(UnitCell &ucell LR::setup_2center_table(this->two_center_bundle_own_, ucell, *this->inp_); } - this->set_dimension(); - // 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); - } + 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 // 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) + if (this->lr_.dim.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 + // (the file path is always the first build of the window) #ifdef __MPI - this->fill_z_window_(paraMat_all_.desc_wfc); + this->lr_.fill_z_win(this->lr_.gs.para_mat_all.desc_wfc, true); #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() + this->lr_.fill_z_win(nullptr, true); #endif - ); // clear ks info, new elecstate for excition delete this->pelec; // the ElecStateLCAO allocated above, only needed while reading the KS data diff --git a/source/source_esolver/esolver_lr.h b/source/source_esolver/esolver_lr.h new file mode 100644 index 0000000000..e3563b295f --- /dev/null +++ b/source/source_esolver/esolver_lr.h @@ -0,0 +1,167 @@ +#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" +#include "source_estate/elecstate.h" +#include "source_estate/elecstate_lcao.h" +#include "source_hamilt/hamilt.h" +#include "source_io/module_parameter/input_parameter.h" + +#include +#include +#include //future tensor + +#include "source_esolver/esolver_ks_lcao.h" //for the move constructor +#include "source_estate/module_dm/density_matrix.h" +#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/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 +// #include +#include "source_hamilt/module_xc/exx_info.h" // for Exx_Info value member +#include "source_lcao/module_ri/exx_lri.h" +#endif +namespace LR +{ +template +struct GradientInputs; +} +namespace ModuleESolver +{ +struct LRRuntime +{ + std::ofstream &running_log; + std::ofstream &warning_log; + int rank; +}; + +/// Excited State Solver: Linear Response TDDFT (Tamm Dancoff Approximation) +template +class ESolver_LR : public ModuleESolver::ESolver_FP +{ + public: + ESolver_LR( + const Input_para &inp, + const std::string &in_dir, + const std::string &out_dir, + const LRRuntime &runtime); + ~ESolver_LR() {} + + /// input: input, call, basis(LCAO), psi(ground state), elecstate + // initialize sth. independent of the ground state + virtual void before_all_runners(BaseCell &basecell, const Input_para &inp) override; + virtual void runner(BaseCell &basecell, int istep) override; + virtual void after_all_runners(BaseCell &basecell) override; + + /// Total energy of the excited state being relaxed: E_gs + Omega. Zero outside a + /// relaxation, where nothing consumes it and the old behaviour is kept. + virtual double cal_energy() override; + /// Force on the atoms in the relaxed excited state, F = -d(E_gs + Omega)/dR (Ry/Bohr). + virtual void cal_force(BaseCell &basecell, ModuleBase::matrix &force) override; + /// Not implemented: there is no excited-state stress. `cell-relax` is rejected at input. + virtual void cal_stress(BaseCell &basecell, ModuleBase::matrix &stress) override; + + protected: + const std::string in_dir; + const std::string out_dir; + const UnitCell *ucell_ = nullptr; + std::vector orb_cutoff_; + + /// cached aliases, read once here instead of at every log/print call site below + std::ofstream &ofs_running_; + std::ofstream &ofs_warning_; + const int my_rank_; + + /// @brief the ground-state solver, kept alive across ionic steps (esolver_type = "ks-lr"). + /// Null on the `lr` path, where the ground state comes from files instead. + std::unique_ptr> ks_; + + // Geometry-dependent objects that the ground-state solver already builds for the current + // structure. They are aliased rather than rebuilt: `ESolver_KS_LCAO::before_scf` refreshes + // its own copies every ionic step, so recomputing them here would be both wasted work and + // a chance for the two to disagree. On the `lr` path the pointers are bound to this + // object's own members below, which `initialize_from_unitcell_` fills from file. + Grid_Driver gd_own_; ///< only used when `ks_` is null + TwoCenterBundle two_center_bundle_own_; ///< only used when `ks_` is null + Grid_Driver *gd_ptr_ = nullptr; + const TwoCenterBundle *tcb_ptr_ = nullptr; + Parallel_Grid *pgrid_ptr_ = nullptr; + Structure_Factor *sf_ptr_ = nullptr; + pseudopot_cell_vl *locpp_ptr_ = nullptr; + + Grid_Driver &gd() const { return *this->gd_ptr_; } + const TwoCenterBundle &tcb() const { return *this->tcb_ptr_; } + Parallel_Grid &pgrid() const { return *this->pgrid_ptr_; } + Structure_Factor &sfac() const { return *this->sf_ptr_; } + pseudopot_cell_vl &vloc() const { return *this->locpp_ptr_; } + /// bind the aliases above; `ks_` must already be set (or null for the `lr` path) + void bind_ground_state_aliases_(); + + // @brief only needed for force calculation + + std::string xc_kernel; + + void initialize_from_unitcell_(UnitCell &ucell, const Input_para &inp); + /// one-time setup from the ground-state solver; ends by calling `refresh_from_ks_` + void initialize_from_ks_(UnitCell &ucell, const Input_para &inp); + /// re-read everything that depends on the atomic positions, once per ionic step + void refresh_from_ks_(UnitCell &ucell); + 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) + + std::unique_ptr gint_info_ = nullptr; + + /// 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 + // rotation, so it must not be confined to the `nvirt` window X lives in. + // It should be the whole AO virtual space. + // + // These mirror `psi_ks` / `eig_ks` / `paraC_` / `paraX_` / `nvirt` / `nloc_per_state` + // 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. + /// 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 + LCAO_Orbitals orb_; ///< numerical atomic orbital data for single-point evaluation + std::vector> velocity_mo; ///< store the velocity matrix elements in MO basis + + /// @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 + /// @brief set nocc, nvirt, nbasis, npairs and nstates + void set_dim(); + /// reset nocc, nvirt, npairs after read ground-state wavefunction when nspin=2 + void reset_dim_spin(); + + ///========================== for gradient calculation ========================= + /// 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 + std::shared_ptr> exx_lri = nullptr; + Exx_Info exx_info; +#endif +}; +} // namespace ModuleESolver + +#endif // ABACUS_SOURCE_ESOLVER_ESOLVER_LR_H diff --git a/source/source_esolver/esolver_lr_cfg.cpp b/source/source_esolver/esolver_lr_cfg.cpp deleted file mode 100644 index 8fb02beb0f..0000000000 --- a/source/source_esolver/esolver_lr_cfg.cpp +++ /dev/null @@ -1,172 +0,0 @@ -#include "source_lcao/module_lr/kernel_pots.h" -// Resolve LR dimensions, validate solver options, 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; - -template -void ModuleESolver::ESolver_LR::set_dimension() -{ - 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 - - 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; -} - -template -void ModuleESolver::ESolver_LR::reset_dim_spin2() -{ - 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")); - } - } - - 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; - } -} - -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 Parallel_Grid& grid = pgrid(); - LR::KernelPotentials 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 95c93bb3ae..0000000000 --- a/source/source_esolver/esolver_lr_grad.cpp +++ /dev/null @@ -1,446 +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_force.h" -#include "source_lcao/module_lr/window_response.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"); - 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 - } -} - -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, - const std::vector> &window_density) -{ - 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, window_density); - 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->excited_relax_, 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 LR::GradientInputs inputs = this->gradient_inputs_(); - const LR::WindowResponse window - = LR::build_window_response(inputs, Xz, nst, this->nvirt[0], ispin, this->in_dir); - const ct::Tensor Z = this->solve_zvector_eqation(channel, nst, Xz, window.density); - const module_dm::DensityMatrix dm_gs = this->cal_dm_gs(); - const LR::ForceSettings force_settings{ - this->nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; - LR_Force force_terms( - *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 std::vector forces - = LR::evaluate_closed_shell_force(inputs, force_terms, dm_gs, Xz, Z, omega, label_begin, ispin, window); - ModuleBase::timer::end("ESolver_LR", "cal_force_Xz"); - return forces; -} - -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 LR::GradientInputs inputs = this->gradient_inputs_(); - const LR::WindowResponse window = LR::build_open_shell_window_response(inputs, Xz, nst, this->nvirt); - const ct::Tensor Z = this->solve_zvector_eqation(channel, nst, Xz, window.density); - const module_dm::DensityMatrix dm_gs = this->cal_dm_gs(); - const LR::ForceSettings force_settings{ - this->nspin, this->inp_->test_force, this->inp_->vl_in_h, this->inp_->vh_in_h, this->inp_->dft_functional}; - LR_Force force_terms( - *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 std::vector forces - = LR::evaluate_open_shell_force(inputs, force_terms, dm_gs, Xz, Z, omega, label_begin, window); - ModuleBase::timer::end("ESolver_LR", "cal_force_openshell_Xz"); - return forces; -} - -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. - 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; -} - -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->pot_gs_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_bse.cpp b/source/source_esolver/esolver_lr_lcao_bse.cpp index 5ee74ebe5c..90f3e05641 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); @@ -53,35 +53,35 @@ 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); + 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, 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->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_spin2(); + this->reset_dim_spin(); } LR_Util::setup_2d_division( - this->paraC_, 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,16 +103,18 @@ 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->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); 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); @@ -153,9 +155,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->pot[0], this->kv, this->paraX_, - this->paraC_, 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 +188,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->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->X[is].template data(), this->nloc_per_state, 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 +216,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->nloc_per_state, this->nstates); + this->lr_.amp.nloc, this->lr_.dim.nstates); } malloc_trim(0); } @@ -278,8 +280,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->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,17 +289,17 @@ 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->full_X[is].template data(), this->full_Y[is].template data(), this->nloc_per_state, - 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->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->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 +336,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->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"); @@ -408,20 +410,20 @@ 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 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 +434,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->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->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->paraMat_, &this->tda_ene[is * this->nstates], this->eig_ks.c, - this->X[is].template data(), this->nstates, false /*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, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, + 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 +474,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->kv, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->paraX_, this->paraC_, - this->paraMat_, &this->full_ene[is * this->nstates], this->eig_ks.c, - this->full_X[is].template data(), this->nstates, false /*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, this->kv.wk, this->gd(), this->orb_cutoff_, this->tcb(), this->lr_.amp.para_x, this->lr_.amp.para_c, + 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 +508,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,24 +526,24 @@ 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->paraX_[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 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) { 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"); @@ -587,10 +589,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 +601,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 +642,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,31 +681,31 @@ 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 Parallel_Grid& grid = this->pgrid(); const std::shared_ptr 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->pot[0] = - std::make_shared(kernel, *this->pw_rho, *this->ucell_, chg_gs.nrxx, this->nspin, ST::S1_gs); + this->lr_.pot.pot[0] = + std::make_shared(kernel, *this->pw_rho, *this->ucell_, chg_gs.nrxx, this->lr_.dim.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: @@ -716,30 +718,30 @@ 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->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->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->nloc_per_state), + "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->X.resize(n_spin_types, LR_Util::newTensor({this->nstates, this->nloc_per_state})); - for (ct::Tensor& x : this->X) + 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 (ct::Tensor &x : this->lr_.amp.x) { x.zero(); } @@ -748,11 +750,11 @@ 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)); - 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})); - for (ct::Tensor& x : this->full_X) + 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 (ct::Tensor &x : this->full_X) { x.zero(); } 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_esolver/esolver_lr_lcao_tddft.cpp b/source/source_esolver/esolver_lr_lcao_tddft.cpp deleted file mode 100644 index c4d3762b9b..0000000000 --- a/source/source_esolver/esolver_lr_lcao_tddft.cpp +++ /dev/null @@ -1,367 +0,0 @@ -// 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" -#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" -#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 - -using namespace LR; - -template -ModuleESolver::ESolver_LR::ESolver_LR( - const Input_para &inp, - const std::string &in_dir, - const std::string &out_dir, - const LRRuntime &runtime) - : in_dir(in_dir), out_dir(out_dir), ofs_running_(runtime.running_log), ofs_warning_(runtime.warning_log), - my_rank_(runtime.rank) -{ -#ifdef __EXX - init_exx_info(this->exx_info, inp); -#endif -} - -template -void ModuleESolver::ESolver_LR::runner(BaseCell &basecell, const int istep) -{ - basecell.require_kind(BaseCell::Kind::unitcell, __FUNCTION__); - UnitCell &ucell = static_cast(basecell); - - ModuleBase::TITLE("ESolver_LR", "runner"); - ModuleBase::timer::start("ESolver_LR", "runner"); - - if (this->ks_) - { - // `init_pot_groundstate` leaves the global XC type on the LR kernel, so put it back before - // the ground-state SCF. `ESolver_KS::runner` is re-entrant: its `before_scf` rebuilds the - // neighbour lists, the grid tables and the Hamiltonian for the geometry of this step. - XC_Functional::set_xc_type(ucell.atoms[0].ncpp.xc_func); - this->ks_->runner(ucell, istep); - this->conv_esolver = this->ks_->conv_esolver; - if (this->inp_->calculation == "relax" && !this->conv_esolver) - { - ModuleBase::WARNING_QUIT( - "ESolver_LR", "Excited-state relaxation requires a converged ground-state SCF; ionic step rejected"); - } - this->etot_gs_ = this->ks_->cal_energy(); - if (!this->ks_initialized_) - { - this->initialize_from_ks_(ucell, *this->inp_); - this->setup_relax_target_(); // needs the final dimensions, i.e. `openshell` - } - else - { - this->refresh_from_ks_(ucell); - } - } - - // allocate 2-particle state and setup 2d division - this->setup_eigenvectors_X(); - this->pelec->ekb.create(nspin, this->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->spin_types = - this->openshell ? std::vector({"updown"}) : std::vector({"singlet", "triplet"}); - - if (this->nspin == 1) - { - this->spin_types = {this->inp_->lr_target_spin}; - } - - // a relaxation writes these once per ionic step; without the suffix every step would overwrite - // the last, and the trajectory would be impossible to inspect afterwards - const std::string step_suffix = this->excited_relax_ ? "_step" + std::to_string(istep) : ""; - 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 : nloc_per_state, 1.0); - // allocate and initialize A matrix and density matrix - if (openshell) - { - for (int is : {0, 1}) - { - if (this->inp_->lr_solver != "lapack") - { - const int offset_is = is * this->paraX_[0].size(); - OperatorLRDiag pre_op( - this->eig_ks.c + is * nk * (nocc[0] + nvirt[0]), this->paraX_[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); - } - } - 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, -#ifdef __EXX - this->exx_lri, this->exx_info.info_global.hybrid_alpha, -#endif - this->pot, this->kv, this->paraX_, this->paraC_, this->paraMat_); - LR::HSolver::solve( - hulr, this->X[0].template data(), nloc_per_state, nstates, this->nk, this->nocc, this->nvirt, - this->paraX_, this->pelec->ekb.c, this->inp_->lr_solver, this->inp_->lr_thr, precondition, true); - if (this->inp_->out_wfc_lr) - { - write_states("openshell", this->pelec->ekb.c, this->X[0].template data(), nloc_per_state, nstates); - } - } - else - { - 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()); - } - const std::vector &spin_types = this->spin_types; - for (int is = 0; is < 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, -#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->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, - 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); - } - } - } - } - 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"; }; - - 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 (openshell) - { - read_states("openshell", this->pelec->ekb.c, this->X[0].template data(), nloc_per_state, nstates); - } - else - { - const std::vector &spin_types = this->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, - nstates); - } - } - } - if (this->ks_ && this->inp_->cal_force && !this->excited_relax_) - { - // Cache the KS force shared by all single-point excited states. - this->ks_->cal_force(ucell, this->force_gs_); - } - if (this->excited_relax_) - { - // Re-select which root to follow BEFORE taking the gradient, so the force belongs to - // the same diabatic state as the previous step's. - this->follow_target_state_(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->force_gs_); - this->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_(); - auto max_abs = [](const ModuleBase::matrix &m) -> double - { - double v = 0.0; - for (int i = 0; i < m.nr * m.nc; ++i) - { - v = std::max(v, std::abs(m.c[i])); - } - return v; - }; - this->ofs_running_ << std::setprecision(8) << std::fixed << " EXCITED-STATE RELAX step " << istep - << ": E_gs = " << this->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" - << std::setprecision(6) << " | |F_gs|max = " - << max_abs(this->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" - << std::defaultfloat << std::endl; - } - - ModuleBase::timer::end("ESolver_LR", "runner"); - return; -} - -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(), *psi_ks, orb_cutoff_, pgrid(), nspin, nocc, nvirt, nbasis, paraX_, paraC_, - 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 std::string density_label = is == 0 ? "up" : "down"; - lr_density.output_eh_density_all_states(amplitudes, is, nstates, density_label, this->ofs_running_); - } - } - else - { - for (int is = 0; is < this->X.size(); ++is) - { - const T *const amplitudes = this->X[is].template data(); - lr_density.output_eh_density_all_states( - amplitudes, is, nstates, this->spin_types[is], 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); - // 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->paraC_, this->kv, *this->psi_ks, this->nk, - nspin_tmp, this->nbasis, this->nocc, this->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->X.size() - 1;++is) - for (int is = 0; is < this->X.size(); ++is) - { - if (!calculate_spectrum) - { - const double *const energies = &this->pelec->ekb.c[is * nstates]; - LR_Util::print_excitation_energies(this->ofs_running_, energies, nstates, spin_types[is]); - } - 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, - 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.optical_absorption_method1(freq, this->inp_->abs_broadening); - spectrum.write_transition_dipole(this->out_dir + "trans_dipole_" + spin_types[is] + "_tda.dat"); - // =============================================== for test - // ==================================================== spectrum.optical_absorption_method2(freq, - // this->inp_->abs_broadening); if (LR_Util::tolower(this->inp_->abs_gauge) == "velocity") { // TEST - // the formula v/omega rather than v/(e_a-e_i) - // spectrum.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->excited_relax_) - { - this->cal_force_and_grad_matrix_(is, this->ofs_running_); - } - } -} -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_lcao_tddft.h deleted file mode 100644 index c7e4ecdfd6..0000000000 --- a/source/source_esolver/esolver_lr_lcao_tddft.h +++ /dev/null @@ -1,382 +0,0 @@ -#ifndef ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_TDDFT_H -#define ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_TDDFT_H - -#include "source_cell/unitcell.h" -#include "source_esolver/esolver_fp.h" -#include "source_estate/elecstate.h" -#include "source_estate/elecstate_lcao.h" -#include "source_hamilt/hamilt.h" -#include "source_io/module_parameter/input_parameter.h" - -#include -#include -#include //future tensor - -#include "source_esolver/esolver_ks_lcao.h" //for the move constructor -#include "source_estate/module_dm/density_matrix.h" -#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/pot_hxc_lrtd.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 -#include "source_lcao/module_ri/exx_lri.h" -#endif -namespace LR -{ -template -struct GradientInputs; -} -namespace ModuleESolver -{ -struct LRRuntime -{ - std::ofstream &running_log; - std::ofstream &warning_log; - int rank; -}; - -/// Excited State Solver: Linear Response TDDFT (Tamm Dancoff Approximation) -template -class ESolver_LR : public ModuleESolver::ESolver_FP -{ - public: - ESolver_LR( - const Input_para &inp, - const std::string &in_dir, - const std::string &out_dir, - const LRRuntime &runtime); - ~ESolver_LR() {} - - /// input: input, call, basis(LCAO), psi(ground state), elecstate - // initialize sth. independent of the ground state - virtual void before_all_runners(BaseCell &basecell, const Input_para &inp) override; - virtual void runner(BaseCell &basecell, int istep) override; - virtual void after_all_runners(BaseCell &basecell) override; - - /// Total energy of the excited state being relaxed: E_gs + Omega. Zero outside a - /// relaxation, where nothing consumes it and the old behaviour is kept. - virtual double cal_energy() override; - /// Force on the atoms in the relaxed excited state, F = -d(E_gs + Omega)/dR (Ry/Bohr). - virtual void cal_force(BaseCell &basecell, ModuleBase::matrix &force) override; - /// Not implemented: there is no excited-state stress. `cell-relax` is rejected at input. - virtual void cal_stress(BaseCell &basecell, ModuleBase::matrix &stress) override; - - protected: - const std::string in_dir; - const std::string out_dir; - const UnitCell *ucell_ = nullptr; - std::vector orb_cutoff_; - - /// cached aliases, read once here instead of at every log/print call site below - std::ofstream &ofs_running_; - std::ofstream &ofs_warning_; - const int my_rank_; - - /// @brief the ground-state solver, kept alive across ionic steps (esolver_type = "ks-lr"). - /// Null on the `lr` path, where the ground state comes from files instead. - std::unique_ptr> ks_; - - // Geometry-dependent objects that the ground-state solver already builds for the current - // structure. They are aliased rather than rebuilt: `ESolver_KS_LCAO::before_scf` refreshes - // its own copies every ionic step, so recomputing them here would be both wasted work and - // a chance for the two to disagree. On the `lr` path the pointers are bound to this - // object's own members below, which `initialize_from_unitcell_` fills from file. - Grid_Driver gd_own_; ///< only used when `ks_` is null - TwoCenterBundle two_center_bundle_own_; ///< only used when `ks_` is null - Grid_Driver *gd_ptr_ = nullptr; - const TwoCenterBundle *tcb_ptr_ = nullptr; - Parallel_Grid *pgrid_ptr_ = nullptr; - Structure_Factor *sf_ptr_ = nullptr; - pseudopot_cell_vl *locpp_ptr_ = nullptr; - - Grid_Driver &gd() const { return *this->gd_ptr_; } - const TwoCenterBundle &tcb() const { return *this->tcb_ptr_; } - Parallel_Grid &pgrid() const { return *this->pgrid_ptr_; } - Structure_Factor &sfac() const { return *this->sf_ptr_; } - pseudopot_cell_vl &vloc() const { return *this->locpp_ptr_; } - /// 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 - 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::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.; - - 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) - 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); - /// one-time setup from the ground-state solver; ends by calling `refresh_from_ks_` - void initialize_from_ks_(UnitCell &ucell, const Input_para &inp); - /// re-read everything that depends on the atomic positions, once per ionic step - void refresh_from_ks_(UnitCell &ucell); - 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_(); - 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` - 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; - void set_gint(); - - /// @brief variables for parallel distribution of KS orbitals - Parallel_Blkcyclic paraC_; - /// @brief variables for parallel distribution of excited states - std::vector paraX_; - - // ---------------- the Z-vector (CPSCF) window ---------------- - // The Z-vector equation enforces the Brillouin condition in EVERY occupied-virtual - // rotation, so it must not be confined to the `nvirt` window X lives in. - // It should be the whole AO virtual space. - // - // These mirror `psi_ks` / `eig_ks` / `paraC_` / `paraX_` / `nvirt` / `nloc_per_state` - // 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); - /// 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 - - 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(); - void set_X_initial_guess(); - - /// @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); - - virtual void init_pot(const Charge &chg_gs); - - /// @brief check the legality of the input parameters - /// @brief set nocc, nvirt, nbasis, npairs and nstates - void set_dimension(); - /// reset nocc, nvirt, npairs after read ground-state wavefunction when nspin=2 - void reset_dim_spin2(); - - /// 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`. - ct::Tensor solve_zvector_eqation( - const int ispin, - const int nst, - const ct::Tensor &Xz, - const std::vector> &window_density); - /// Excited-state gradients d(Omega)/dR, one matrix per state solved. `istate_only >= 0` - /// restricts it to that one state: geometry relaxation follows a single state, and the - /// Z-vector solve dominates the cost. -1 does all `nstates`. - 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`. - /// - /// 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 - /// `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); - /// @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; - }; - /// 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); - /// @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); - /// @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. - /// - /// @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 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, - const std::vector &group, - const std::vector &diag, - std::ofstream &ofs); - void test_force(); // test: reproduce the force of ground state - module_dm::DensityMatrix cal_dm_gs(); ///< ground-state density matrix - -#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 -}; -} // namespace ModuleESolver - -#endif // ABACUS_SOURCE_ESOLVER_ESOLVER_LR_LCAO_TDDFT_H diff --git a/source/source_esolver/esolver_lr_orb.cpp b/source/source_esolver/esolver_lr_orb.cpp deleted file mode 100644 index 27b9cf9bf3..0000000000 --- a/source/source_esolver/esolver_lr_orb.cpp +++ /dev/null @@ -1,341 +0,0 @@ -// 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_lcao/module_lr/utils/lr_util.h" -#include -#include - -using namespace LR; - -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 -} - -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()); - - this->X.resize(openshell ? 1 : nspin, LR_Util::newTensor({nstates, nloc_per_state})); - for (container::Tensor& x : X) - { - x.zero(); - } - - // 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)); - } - } - } -} - -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 - { -#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 - } - 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)) - { - 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 (!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)) - { - 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_"); - 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 T* 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_) - { - // Real-Gamma forces include the virtual-window response for both spin formulations. - // Retain diagnostics for missing occupied orbitals and uncomputed bands. - const bool virtual_response = std::is_same::value && this->nk == 1 && start_band == 0; - const auto &diagnosed_virtuals = virtual_response ? this->nvirt_z_ : this->nvirt; - const std::string warning = LR_Util::force_window_warning( - this->nbasis, this->eig_ks_all.nc, start_band, diagnosed_virtuals, this->nvirt_z_); - if (!warning.empty()) - { - this->ofs_running_ << warning << std::endl; - } - } -} - -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; - } - } -} -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 b941c00290..0000000000 --- a/source/source_esolver/esolver_lr_rlx.cpp +++ /dev/null @@ -1,392 +0,0 @@ -#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" -#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->excited_relax_ = (this->inp_->calculation == "relax"); - if (!this->excited_relax_) - { - 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" && this->nspin == 2) ? 1 : 0; - } - this->force_gs_.create(this->ucell_->nat, 3); - this->lr_force_.create(this->ucell_->nat, 3); - this->target_state_ = this->inp_->lr_target_state; // seed; overlap takes over from step 2 - this->ofs_running_ << " Excited-state relaxation follows state " << this->inp_->lr_target_state << " of the " - << (this->openshell ? "updown" : this->inp_->lr_target_spin) - << " 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. -template -void ModuleESolver::ESolver_LR::follow_target_state_(std::ofstream &ofs) -{ - ModuleBase::timer::start("ESolver_LR", "follow_target_state_"); - if (!this->excited_relax_) - { - ModuleBase::timer::end("ESolver_LR", "follow_target_state_"); - return; - } - const int channel = this->openshell ? 0 : this->target_is_; - 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); - 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->excited_relax_) - { - 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 - // surfaces. - return this->etot_gs_ + this->target_omega_(); -} - -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->ks_ && this->force_gs_.nr == ucell.nat) - { - ModuleIO::print_force(this->ofs_running_, ucell, "GROUND-STATE FORCE (eV/Angstrom)", this->force_gs_, false); - } - if (!this->excited_relax_) - { // single-point runs print the gradients of every state from `after_all_runners` instead - return; - } - 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 per-state LR table reports the excitation-energy contribution -d(Omega)/dR; - // adding the ground-state force gives the total force on the excited-state surface. - force.create(ucell.nat, 3); - force = this->force_gs_ + this->lr_force_; - ModuleIO::print_force(this->ofs_running_, ucell, "EXCITED-STATE TOTAL-FORCE (eV/Angstrom)", force, false); -} - -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 -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()) - { - return this->cal_force(this->target_is_, 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_); - std::vector omega(d); - for (int k = 0; k < d; ++k) - { - omega[k] = this->pelec->ekb.c[ekb_off + this->target_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_) - { - if (ist != this->target_state_) - { - ofs << " " << ist; - } - } - ofs << " (Omega_bar = " << this->target_omega_() << " 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 int d = static_cast(this->target_group_.size()); - const std::vector> g = - this->cal_grad_matrix_degenerate(this->target_is_, this->target_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_is_; - 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_); - 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_target_multiplet_` 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_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 6d85aeb3da..00219ad7a5 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -2847,7 +2847,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 std::vector>::iterator 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 3cbde769fa..bc02fdc6ec 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/CMakeLists.txt b/source/source_lcao/module_lr/CMakeLists.txt index fb99c99e87..68daca8690 100644 --- a/source/source_lcao/module_lr/CMakeLists.txt +++ b/source/source_lcao/module_lr/CMakeLists.txt @@ -23,8 +23,17 @@ 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 + lr_relax.cpp + 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/cal_w_from_z.h b/source/source_lcao/module_lr/cal_w_from_z.h index 0e49c8f0b3..a4986a9c95 100644 --- a/source/source_lcao/module_lr/cal_w_from_z.h +++ b/source/source_lcao/module_lr/cal_w_from_z.h @@ -232,7 +232,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/grad_degen.h b/source/source_lcao/module_lr/grad_degen.h index e41a009f5e..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_grad.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_grad.cpp`. +/// stays in `esolver_lr.cpp`. namespace LR { 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_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_core.cpp b/source/source_lcao/module_lr/lr_core.cpp new file mode 100644 index 0000000000..8e7547c77f --- /dev/null +++ b/source/source_lcao/module_lr/lr_core.cpp @@ -0,0 +1,808 @@ +#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" +#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/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" +#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 +#include +#include + +namespace LR +{ + +template +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, + *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) +{ + 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::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 +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 +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 +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"}); + if (this->dim.nspin == 1) + { + this->amp.spin_types = {inp.lr_target_spin}; + } + + // a relaxation writes these once per ionic step; without the suffix every step would overwrite + // the last, and the trajectory would be impossible to inspect afterwards + const std::string step_suffix = this->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 +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; + LR::KernelPotentials 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) +{ + 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(); + const std::string density_label = is == 0 ? "up" : "down"; + lr_density.output_eh_density_all_states(amplitudes, is, this->dim.nstates, density_label, 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, this->amp.spin_types[is], 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 +{ + 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(), this->dim.nvirt[0], 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(), this->dim.nvirt, 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(); +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&, + 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 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 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); +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 new file mode 100644 index 0000000000..9b9894b64a --- /dev/null +++ b/source/source_lcao/module_lr/lr_core.h @@ -0,0 +1,209 @@ +#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_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" +#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; +class Charge; +class surchem; +#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 +{ + 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; +}; + +/// 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 +{ + 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; +}; + +/// 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; + Grid_Driver* gd = nullptr; + const std::vector* orb_cutoff = 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; + Parallel_Grid* pgrid = nullptr; + 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; +#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 +{ + Dim dim; + Amp amp; + GsState gs; + 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(); + /// 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, + 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); + /// 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); + /// 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`. + 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 + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_CORE_H 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..5db5e61398 --- /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; ///< 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 + 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 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/lr_grad_cs.cpp b/source/source_lcao/module_lr/lr_grad_cs.cpp index ad445eb15f..4778831d6a 100644 --- a/source/source_lcao/module_lr/lr_grad_cs.cpp +++ b/source/source_lcao/module_lr/lr_grad_cs.cpp @@ -23,7 +23,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_gs.cpp b/source/source_lcao/module_lr/lr_gs.cpp new file mode 100644 index 0000000000..df98d41adf --- /dev/null +++ b/source/source_lcao/module_lr/lr_gs.cpp @@ -0,0 +1,421 @@ +// 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 +#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 T* 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) + { + // Real-Gamma forces include the virtual-window response for both spin formulations. + // Retain diagnostics for missing occupied orbitals and uncomputed bands. + const bool virtual_response = std::is_same::value && kv.get_nks() == 1 && start_band == 0; + const std::vector& diagnosed_virtuals = virtual_response ? z.nvirt : nvirt; + const std::string warning = + LR_Util::force_window_warning(nbasis, eig_all.nc, start_band, diagnosed_virtuals, z.nvirt); + if (!warning.empty()) + { + log << warning << std::endl; + } + } + 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) +{ + 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&); + +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 new file mode 100644 index 0000000000..6bb3bd6c1c --- /dev/null +++ b/source/source_lcao/module_lr/lr_gs.h @@ -0,0 +1,119 @@ +#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); + +/// 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, + 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 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..833f760c5f --- /dev/null +++ b/source/source_lcao/module_lr/lr_mpl.h @@ -0,0 +1,54 @@ +#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; +}; + +/// 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 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..b165824406 --- /dev/null +++ b/source/source_lcao/module_lr/lr_relax.cpp @@ -0,0 +1,202 @@ +#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" && nspin == 2) ? 1 : 0; + } + 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" : inp.lr_target_spin) + << " 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 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..6c38e1d234 --- /dev/null +++ b/source/source_lcao/module_lr/lr_sforce.cpp @@ -0,0 +1,132 @@ +#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, st.nvirt[0], 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, st.nvirt, 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, 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); +} + +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 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..ee0e4e9070 --- /dev/null +++ b/source/source_lcao/module_lr/lr_zeq.cpp @@ -0,0 +1,92 @@ +#include "source_lcao/module_lr/lr_zeq.h" + +#include "source_lcao/module_lr/lr_dm.h" +#include "source_lcao/module_lr/window_response.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, + const std::vector>& window_density) +{ + 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, window_density); + 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 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, 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, + 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, window); +} + +template +std::vector force_xz_os(const GradientInputs& in, const GsForceCtx& gs, + 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, 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, + 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, window); +} + +template ct::Tensor solve_zeq(const GradientInputs&, const ct::Tensor&, int, int, bool, + const std::string&, const std::string&, + const std::vector>&); +template ct::Tensor solve_zeq>(const GradientInputs>&, const ct::Tensor&, + int, int, bool, const std::string&, const std::string&, + const std::vector>&); +template std::vector force_xz(const GradientInputs&, const GsForceCtx&, + int, int, const ct::Tensor&, const std::vector&, int); +template std::vector force_xz>(const GradientInputs>&, + const GsForceCtx>&, int, + int, const ct::Tensor&, + const std::vector&, int); +template std::vector force_xz_os(const GradientInputs&, const GsForceCtx&, + const std::vector&, const ct::Tensor&, + const std::vector&, int); +template std::vector force_xz_os>( + 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 new file mode 100644 index 0000000000..7fc5a3156f --- /dev/null +++ b/source/source_lcao/module_lr/lr_zeq.h @@ -0,0 +1,50 @@ +#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, + const std::vector>& window_density); + +/// 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 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 std::vector& nactive, const ct::Tensor& xz, + const std::vector& omega, int label_begin); + +} // namespace LR + +#endif // ABACUS_SOURCE_LCAO_MODULE_LR_LR_ZEQ_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..834308d564 --- /dev/null +++ b/source/source_lcao/module_lr/potentials/lr_gs_pot.cpp @@ -0,0 +1,68 @@ +#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_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..171feede25 --- /dev/null +++ b/source/source_lcao/module_lr/potentials/lr_gs_pot.h @@ -0,0 +1,53 @@ +#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_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