58 if (options.
exists(
".excited_state_forces")) {
60 options.
get(
".excited_state_forces").
as<std::string>();
63 const std::string tasks = options.
get(
".tasks").
as<std::string>();
65 const std::vector<std::string> list = tok.ToVector();
67 std::find(list.begin(), list.end(),
"gradients") != list.end();
68 if (has && list.size() > 1) {
69 throw std::runtime_error(
70 "tasks: gradients cannot be combined with other tasks (with dft "
71 "and gwbse the gradients are computed in the same run anyway)");
75 if (options.
exists(
".qp_gradients")) {
78 if (options.
exists(
".relaxed_density")) {
81 if (options.
exists(
".excited_state_forces_follow")) {
83 options.
get(
".excited_state_forces_follow").
as<std::string>();
85 if (options.
exists(
".excited_state_forces_qp_response")) {
87 options.
get(
".excited_state_forces_qp_response").
as<
bool>();
90 if (options.
exists(
".mpsfile")) {
95 if (options.
exists(
".guess")) {
102 if (options.
exists(
".moguess")) {
114 log_.setMultithreading(
true);
115 log_.setCommonPreface(
"\n... ...");
126 throw std::runtime_error(
127 "tasks gradients: set qp_gradients, excited_state_forces and/or "
131 <<
"Gradients from the GW-BSE data in " <<
archive_file_ << std::flush;
151 <<
"Reading guess from " <<
guess_file_ << std::flush;
155 <<
"Reading structure from " <<
xyzfile_ << std::flush;
175 orbitals.
MOs() = moguess_orbitals.
MOs();
192 std::unique_ptr<QMPackage> qmpackage =
195 qmpackage->setLog(&
log_);
197 qmpackage->setRunDir(
".");
204 qmpackage->AddRegion(region);
234 throw std::runtime_error(
"relaxed_density: not for truncated bases");
243 if (summary.
exists(
"output")) {
246 <<
"Writing output to " <<
xml_output_ << std::flush;
247 std::ofstream ofout(
xml_output_, std::ofstream::out);
248 ofout << (summary.
get(
"output"));
261 throw std::runtime_error(
263 " holds no excited-state forces");
266 const Eigen::VectorXd ov =
271 for (
Index i = 0; i < ov.size(); ++i) {
273 second = std::max(second, ov(i));
276 const QMState state(ref_state.
Type(), best,
false);
280 <<
" here (overlap " << ov(best) <<
", next largest " << second <<
")"
282 if (ov(best) < 0.5 || second > 0.8 * ov(best)) {
285 <<
" WARNING: root following is ambiguous (states mix strongly or "
286 "the geometry step is large)"
306 <<
TimeStamp() <<
" Including the response of the QP corrections"
311 <<
" QP corrections kept fixed (excited_state_forces_qp_response "
312 "false, or not G0W0/evGW with sigma_integrator ppm or exact)"
323 throw std::runtime_error(
"relaxed_density: needs the xtp DFT package");
338 Eigen::Vector3d change;
339 for (
Index k = 0; k < 3; ++k) {
340 change(k) = -(dipole.
Matrix()[k].cwiseProduct(diff)).sum();
344 <<
" stored (relaxed_density); dipole change from the ground state "
346 << std::setprecision(8) << change.transpose() << std::flush;
351 auto parse_one = [homo](std::string token) {
352 token.erase(std::remove_if(token.begin(), token.end(), ::isspace),
354 std::transform(token.begin(), token.end(), token.begin(), ::tolower);
356 std::string rest = token;
357 if (token.rfind(
"homo", 0) == 0) {
359 rest = token.substr(4);
360 }
else if (token.rfind(
"lumo", 0) == 0) {
362 rest = token.substr(4);
364 if (rest.empty() && rest.size() != token.size()) {
367 std::size_t used = 0;
370 offset =
Index(std::stol(rest, &used));
371 }
catch (std::exception&) {
372 used = std::string::npos;
374 if (used != rest.size() || rest.empty() ||
375 (rest.size() != token.size() && rest[0] !=
'+' && rest[0] !=
'-')) {
376 throw std::runtime_error(
"qp_gradients: cannot read level '" + token +
377 "' (e.g. homo-2, lumo+3 or an MO index)");
379 return base + offset;
381 std::vector<Index> levels;
382 std::stringstream list(text);
384 while (std::getline(list, item,
',')) {
385 const std::size_t colon = item.find(
':');
386 const Index first = parse_one(item.substr(0, colon));
387 const Index last = (colon == std::string::npos)
389 : parse_one(item.substr(colon + 1));
391 throw std::runtime_error(
"qp_gradients: empty range '" + item +
"'");
393 for (
Index level = first; level <= last; ++level) {
394 if (std::find(levels.begin(), levels.end(), level) == levels.end()) {
395 levels.push_back(level);
399 std::sort(levels.begin(), levels.end());
405 throw std::runtime_error(
"qp_gradients: needs the xtp DFT package");
408 throw std::runtime_error(
409 "qp_gradients: embedding and truncated bases are not supported");
411 const std::vector<Index> requested =
416 const Eigen::MatrixXd stored_gradients = orbitals.
getQPGradients();
417 std::vector<Index> levels;
418 for (
Index level : requested) {
419 if (std::find(stored.begin(), stored.end(), level) == stored.end()) {
420 levels.push_back(level);
423 if (levels.empty()) {
425 <<
TimeStamp() <<
" QP gradients of all requested levels are "
426 <<
"already stored" << std::flush;
429 if (levels.size() < requested.size()) {
432 << requested.size() - levels.size()
433 <<
" requested level(s) are already stored" << std::flush;
436 <<
TimeStamp() <<
" Analytic gradients of the QP energies of "
437 << levels.size() <<
" level(s), " << levels.front() <<
" to "
438 << levels.back() <<
" (HOMO is " << orbitals.
getHomo() <<
")"
450 <<
TimeStamp() <<
" QP energies rebuilt for the gradient: max "
453 throw std::runtime_error(
454 "qp_gradients: the QP energies rebuilt for the gradient differ "
455 "from the GW ones by " +
461 std::vector<std::pair<Index, Eigen::MatrixXd>> merged;
462 for (std::size_t l = 0; l < stored.size(); ++l) {
463 merged.emplace_back(stored[l],
464 stored_gradients.middleRows(
Index(l) * natoms, natoms));
466 for (std::size_t l = 0; l < levels.size(); ++l) {
469 std::sort(merged.begin(), merged.end(),
470 [](
const auto& a,
const auto& b) { return a.first < b.first; });
471 Eigen::MatrixXd all(
Index(merged.size()) * natoms, 3);
472 std::vector<Index> all_levels;
473 for (std::size_t l = 0; l < merged.size(); ++l) {
474 all.middleRows(
Index(l) * natoms, natoms) = merged[l].second;
475 all_levels.push_back(merged[l].first);
484 auto lower = [](std::string text) {
485 std::transform(text.begin(), text.end(), text.begin(), ::tolower);
488 auto check = [&](
const std::string& what,
const std::string& stored,
489 const std::string& option) {
490 if (lower(stored) != lower(option)) {
491 throw std::runtime_error(
"tasks gradients: " + what +
" of " +
493 ", the options say " + option +
494 "; use the options of the run that wrote "
500 throw std::runtime_error(
"tasks gradients: " +
archive_file_ +
520 throw std::runtime_error(
521 "excited_state_forces: only singlet or triplet BSE states (e.g. s1)");
524 throw std::runtime_error(
"excited_state_forces: needs the xtp DFT package");
527 throw std::runtime_error(
528 "excited_state_forces: embedding and truncated bases are not "
532 throw std::runtime_error(
533 "excited_state_forces: needs the ground-state forces, set "
534 "dftpackage.xtpdft.compute_forces to true");
538 << (orbitals.
getTDAApprox() ?
" (TDA)" :
" (full BSE)") << std::flush;
541 orbitals, singlet, state.
StateIdx());
556 const double omega_error = std::abs(result.
omega - omega);
558 <<
TimeStamp() <<
" Excitation energy rebuilt for the gradient: "
559 <<
"deviation from the BSE eigenvalue " << omega_error <<
" Ha"
561 if (omega_error > 1
e-4) {
562 throw std::runtime_error(
563 "excited_state_forces: the excitation energy rebuilt for the "
565 std::to_string(result.
omega) +
566 " Ha) differs from the BSE eigenvalue (" + std::to_string(omega) +
567 " Ha); the GW-BSE setup (e.g. environment screening, dynamical "
568 "screening of the BSE kernel) is not covered by the gradient");
570 if (omega_error > 1
e-6) {
573 <<
" WARNING: the BSE eigenvalue is converged only to about "
575 <<
" Ha; tighten bse.davidson.tolerance (strict or lapack) for "
576 "energies consistent with the forces"
581 <<
TimeStamp() <<
" QP energies rebuilt for the gradient: max "
586 <<
TimeStamp() <<
" RPA energies rebuilt for the gradient: max "
592 throw std::runtime_error(
593 "excited_state_forces: the QP energies rebuilt for the gradient "
594 "differ from the GW ones by " +
600 <<
TimeStamp() <<
" Excited-state forces (Hartree/Bohr) of "
601 << state.
ToString() <<
", Omega = " << omega <<
" Ha:\n"
602 << forces << std::flush;
const std::string & Name() const
void setCenter(const Eigen::Vector3d &r)
const std::array< Eigen::MatrixXd, 3 > & Matrix() const
void Fill(const AOBasis &aobasis) final
const Eigen::Vector3d & getPos() const
void LoadFromFile(std::string filename)
Electronic ground-state via Density-Functional Theory.
void setLogger(Logger *pLog)
Attach the logger used for SCF progress and diagnostics.
Eigen::MatrixXd RelaxedDensityMatrix(const Orbitals &orb, const QMState &state, const tools::Property &gwbse, bool qp_response=true)
static BSEGradientInput QPGradientInputFromOrbitals(const Orbitals &orb, const std::vector< Index > &levels)
void Initialize(tools::Property &options)
Read DFT, grid, and SCF settings from the user options tree.
BSEGradientResult BSEExcitationGradient(const Orbitals &orb, const BSEGradientInput &input)
static BSEGradientInput BSEGradientInputFromOrbitals(const Orbitals &orb, bool singlet, Index index)
static bool ConfigureQPResponse(BSEGradientInput &input, const Orbitals &orb, const tools::Property &gwbse, Logger *log)
void ParseOptions(const tools::Property &user_options)
tools::Property package_options_
std::string archive_file_
std::string excited_state_forces_
void ComputeExcitedStateForces(Orbitals &orbitals)
bool excited_state_forces_qp_response_
std::string moguess_file_
void SetupQPResponse(DFTEngine::BSEGradientInput &input, const Orbitals &orbitals)
QMState FollowState(const Orbitals &orbitals)
std::string excited_state_forces_follow_
std::string relaxed_density_
tools::Property gwbseengine_options_
static std::vector< Index > ParseLevels(const std::string &text, Index homo)
std::string qp_gradients_
void CheckStoredRun(const Orbitals &orbitals) const
void ComputeQPGradients(Orbitals &orbitals)
void ComputeRelaxedDensity(Orbitals &orbitals)
Electronic Excitations via Density-Functional Theory.
void ExcitationEnergies(Orbitals &orbitals)
const tools::Property & ReportSummary() const
void setLog(Logger *pLog)
void setQMPackage(QMPackage *qmpackage)
void Initialize(tools::Property &options, std::string archive_filename)
void push_back(const T &seg)
Container for molecular orbitals and derived one-particle data.
void setRelaxedDensity(const Eigen::MatrixXd &density, const std::string &state)
const Eigen::MatrixXd getTruncMOsFullBasis() const
Return truncated active-region orbitals represented in the full AO basis.
const tools::EigenSystem & BSETriplets() const
Return read-only access to triplet BSE eigenpairs.
const Eigen::MatrixXd & getQPGradients() const
Index getHomo() const
Return the default HOMO index used by spin-agnostic callers.
bool hasAuxbasisName() const
Report whether an auxiliary basis-set name has been stored.
bool hasForces() const
Report whether nuclear forces have been stored.
const tools::EigenSystem & MOs_beta() const
Return read-only access to beta-spin molecular orbitals.
const tools::EigenSystem & BSESinglets() const
Return read-only access to singlet BSE eigenpairs.
bool getTDAApprox() const
Return whether the Tamm-Dancoff approximation is enabled.
const std::vector< Index > & getQPGradientLevels() const
const AOBasis & getAuxBasis() const
Return the auxiliary AO basis, throwing if it has not been initialized.
Index getNumberOfAlphaElectrons() const
Return the stored number of alpha electrons.
std::string getCalculationType() const
Return the stored calculation-type tag.
bool hasQMAtoms() const
Report whether a molecular geometry has been stored.
void setNumberOfAlphaElectrons(Index electrons)
Store the total number of alpha electrons.
void SetupAuxBasis(std::string aux_basis_name)
void setNumberOfBetaElectrons(Index electrons)
Store the total number of beta electrons.
const std::string & getExcitedStateForcesState() const
const Eigen::VectorXd & RPAInputEnergies() const
Return read-only access to the RPA input energies.
const tools::EigenSystem & MOs() const
Return read-only access to alpha/restricted molecular orbitals.
Eigen::MatrixXd DensityMatrixGroundState() const
Build the ground-state AO density matrix from the stored orbitals.
const QMMolecule & QMAtoms() const
Return read-only access to the molecular geometry.
const std::string & getXCFunctionalName() const
Return the exchange-correlation functional label.
void setQPGradients(const Eigen::MatrixXd &gradients, const std::vector< Index > &levels)
void ReadFromCpt(const std::string &filename)
Read the orbital container from a checkpoint file on disk.
void setExcitedStateForces(const Eigen::MatrixXd &forces, const std::string &state)
void WriteToCpt(const std::string &filename) const
Write the orbital container to a checkpoint file on disk.
bool hasBetaMOs() const
Report whether beta-spin molecular orbitals are available.
void SetupDftBasis(std::string basis_name)
Build and attach the DFT AO basis from the stored molecular geometry.
const Eigen::MatrixXd & getForces() const
Return the stored nuclear forces (Natoms x 3, Hartree/Bohr).
Index getNumberOfBetaElectrons() const
Return the stored number of beta electrons.
const AOBasis & getDftBasis() const
Return the DFT AO basis, throwing if it has not been initialized.
void LoadFromFile(std::string filename)
Identifier for QMstates. Strings like S1 are converted into enum +zero indexed int.
std::string ToString() const
const QMStateType & Type() const
Timestamp returns the current time as a string Example: cout << TimeStamp().
#define XTP_LOG(level, log)
Charge transport classes.
ClassicalSegment< StaticSite > StaticSegment
Eigen::VectorXd ExcitonOverlaps(const Orbitals &ref, const QMState &ref_state, const Orbitals &cur, QMStateType type)
Provides a means for comparing floating point numbers.
static Level current_level
double qp_rebuild_error
with qp_response: max |E - rebuilt QP energy| over the QP window
double omega
X^T H X from the rebuilt BSE Hamiltonian (equals the BSE eigenvalue).
double rpa_rebuild_error
with qp_selfconsistent: max |R - rebuilt RPA energy|
std::vector< Eigen::MatrixXd > qp_gradients
for qp_levels: dE_p/dR per level (natoms x 3 each), Hartree/Bohr