52 throw std::runtime_error(
54 " must always be region 0. Currently only one qm region is possible.");
67 if (prop.
exists(
"statetracker")) {
74 throw std::runtime_error(
75 "No statetracker options for excited states found");
81 if (prop.
exists(
"statetracker")) {
88 throw std::runtime_error(
"No statetracker options for KS states found");
93 prop.
get(
"grid_for_potential").
as<std::string>();
103 if (prop.
get(
"dftpackage.xtpdft.dft_in_dft.activeatoms")
110 if (prop.
exists(
"environment_screening")) {
122 throw std::runtime_error(
123 "environment_screening with state " +
initstate_.ToString() +
124 ": the charged DFT state would be polarized in the QM/MM loop and "
125 "screened again in GW. Run the neutral molecule and ask for the "
126 "quasiparticle level instead: state pqpN (or dqpN) with N the "
127 "HOMO or LUMO index.");
130 throw std::runtime_error(
131 "environment_screening is implemented for closed-shell GW-BSE "
132 "only; the unrestricted exciton state " +
133 initstate_.ToString() +
" is not supported.");
136 throw std::runtime_error(
137 "environment_screening needs a GW-BSE state (an exciton or a "
138 "quasiparticle level); " +
139 initstate_.ToString() +
" has no GW-BSE calculation to screen.");
148 throw std::runtime_error(
149 "environment_screening: site_width must be >= 0 (0 for point "
155 std::replace(shells.begin(), shells.end(),
',',
' ');
156 std::istringstream in(shells);
162 <<
" Environment screening on: ground-state QM/MM loop, then one "
163 "screened GW-BSE run. K_reac "
171 throw std::runtime_error(
172 "relaxed_density: needs a GW-BSE state (exciton or QP level)");
175 throw std::runtime_error(
176 "relaxed_density: not available with environment_screening (the "
177 "screened GW-BSE energy has no relaxed density yet)");
180 throw std::runtime_error(
181 "relaxed_density: not available with DFT-in-DFT embedding");
183 if (
dftoptions_.get(
"name").as<std::string>() !=
"xtp") {
184 throw std::runtime_error(
"relaxed_density: needs the xtp DFT package");
213 if (
orb_.isOpenShell()) {
214 throw std::runtime_error(
"GWBSE not implemented for open-shell systems");
219 "inactive_screening",
"none"));
221 throw std::runtime_error(
222 "gwbse.inactive_screening needs a projection-based embedding "
223 "(dftpackage.xtpdft.dft_in_dft).");
227 Index active_electrons =
orb_.getNumOfActiveElectrons();
229 if (active_electrons % 2 != 0) {
230 throw std::runtime_error(
231 "DFT-in-DFT embedded GWBSE currently supports only closed-shell "
232 "active spaces with an even number of electrons");
240 "inactive_screening_complete_g",
false),
242 "inactive_screening_radius", 0.0) *
246 Index active_occ = active_electrons / 2;
250 active_occ, inactive);
255 orb_.setNumberOfOccupiedLevels(active_occ);
256 orb_.setNumberOfOccupiedLevelsBeta(active_occ);
257 orb_.setNumberOfAlphaElectrons(active_occ);
258 orb_.setNumberOfBetaElectrons(active_occ);
259 orb_.setChargeAndSpin(
orb_.getCharge(), 1);
266 return orb_.getExcitedStateEnergy(state);
271 return orb_.getExcitedStateEnergy(state);
273 return -
orb_.getExcitedStateEnergy(state);
277 const std::vector<std::unique_ptr<Region> >& regions)
const {
282 bool have_damp =
false;
284 for (
const std::unique_ptr<Region>& reg : regions) {
285 if (reg->identify() != Polardummy.
identify()) {
295 throw std::runtime_error(
296 "environment_screening: shell region " +
297 std::to_string(polar.
getId()) +
298 " has charge-response segments; a shell responds with "
299 "alpha/epsilon per site, which has no induced charges. Use "
300 "Thole segments there.");
307 throw std::runtime_error(
308 "environment_screening: the explicit polar regions respond as one "
309 "coupled Thole system and must share exp_damp; found " +
310 std::to_string(env.
exp_damp) +
" and " +
311 std::to_string(polar.
ExpDamp()) +
".");
319 const bool is_polar = std::any_of(
320 regions.begin(), regions.end(),
321 [&](
const std::unique_ptr<Region>& reg) {
322 return reg->getId() == id && reg->identify() == Polardummy.identify();
325 throw std::runtime_error(
"environment_screening: shell region " +
327 " is not a polar region of this job.");
333 <<
" WARNING: environment_screening is on but there is no polar "
334 "region; GW-BSE runs unscreened."
344 !
dftoptions_.get(
"auxbasisset").as<std::string>().empty()) {
345 return dftoptions_.get(
"auxbasisset").as<std::string>();
348 !
gwbseoptions_.get(
"auxbasisset").as<std::string>().empty()) {
351 return "aux-" +
dftoptions_.get(
"basisset").as<std::string>();
355 const std::vector<std::unique_ptr<Region> >& regions)
const {
374 <<
TimeStamp() <<
" Checking the screening environment (" << auxname
375 <<
", " << auxbasis.
AOBasisSize() <<
" functions)" << std::flush;
379 throw std::runtime_error(
380 "environment_screening: 1 + R is not positive definite (lowest "
382 std::to_string(check.
lowest) +
383 "): the environment would screen some charge fluctuation of the QM "
384 "region by more than the fluctuation itself. Diagnosis:\n" +
388 <<
TimeStamp() <<
" Screening environment is stable: lowest eigenvalue "
389 <<
"of R " << check.
lowest <<
" (must be > -1)" << std::flush;
394 std::vector<std::unique_ptr<Region> >& regions) {
398 if (
orb_.getCalculationType() ==
"Truncated") {
399 throw std::runtime_error(
400 "environment_screening is not implemented for truncated active "
407 <<
TimeStamp() <<
" Running environment-screened GW-BSE" << std::flush;
408 const double e_dft =
orb_.getDFTTotalEnergy();
422 <<
" eV, region energy " << energy <<
" Hartree" << std::flush;
440 auto qp = [&](
Index level) {
441 const std::string kind =
orb_.hasQPdiag() ?
"dqp" :
"pqp";
442 return orb_.getExcitedStateEnergy(
QMState(kind + std::to_string(level)));
460 std::vector<const Eigen::Vector3d*> src =
ewaldgrid_.getGridpoints();
461 std::vector<Eigen::Vector3d> dst(src.size());
462 std::transform(src.begin(), src.end(), dst.begin(),
463 [](
const Eigen::Vector3d* v) { return *v; });
483 if (
orb_.QMAtoms().size() == 0) {
484 throw std::runtime_error(
485 "QMRegion::PrepareEwaldPotentialGrid: the region holds no atoms. The "
486 "grid is built over the QM molecule, so this must run after the "
487 "region has been filled.");
489 std::string dftbasis_name =
dftoptions_.get(
"basisset").as<std::string>();
490 std::string grid_name =
491 dftoptions_.get(
"xtpdft.integration_grid").as<std::string>();
494 bs.
Load(dftbasis_name);
496 dftbasis.
Fill(bs, mol);
497 ewaldgrid_.GridSetup(grid_name, mol, dftbasis);
499 <<
TimeStamp() <<
" Constructed Grid for Integration of Ewald Potential"
511 const double Echange =
E_hist_.getDiff();
512 const Eigen::MatrixXd diff_ao =
Dmat_hist_.getDiff();
513 const double n = double(diff_ao.cols());
519 const bool orthonormal =
overlap_sqrt_.rows() == diff_ao.rows();
520 const Eigen::MatrixXd diff =
523 const double Dchange = diff.norm() / n;
524 const double Dmax = diff.cwiseAbs().maxCoeff();
525 std::string info =
"not converged";
526 bool converged =
false;
531 std::ostringstream measure;
533 measure <<
" (orthonormal basis; AO basis: RMS " << diff_ao.norm() / n
534 <<
" Max " << diff_ao.cwiseAbs().maxCoeff() <<
")";
536 measure <<
" (AO basis)";
539 <<
" Region:" << this->
identify() <<
" " << this->
getId() <<
" is "
540 << info <<
" deltaE=" << Echange <<
" RMS Dmat=" << Dchange
541 <<
" MaxDmat=" << Dmax << measure.str() << std::flush;
549 std::accumulate(interact_energies.begin(), interact_energies.end(), 0.0);
552 <<
" Calculated interaction potentials with other regions. E[hrt]= "
553 << e_ext << std::flush;
576 throw std::runtime_error(
"QMEwald can only run with XTP as qmpackage.");
584 const bool warm_start =
E_hist_.filled() &&
orb_.hasMOs();
616 if (!Logfile_parse) {
618 errormsg_ =
"Parsing DFT logfile failed.";
622 if (!Orbfile_parse) {
624 errormsg_ =
"Parsing DFT orbfile failed.";
629 if (
orb_.isOpenShell()) {
630 throw std::runtime_error(
631 "MO localization not implemented for open-shell systems");
638 if (
orb_.isOpenShell()) {
639 throw std::runtime_error(
640 "DFT-in-DFT not implemented for open-shell systems");
643 std::unique_ptr<QMPackage> xtpdft =
645 xtpdft->setLog(&
log_);
654 xtpdft->setCharge(
charge);
656 std::vector<double> energies = std::vector<double>(regions.size(), 0.0);
657 for (std::unique_ptr<Region>& reg : regions) {
658 Index id = reg->getId();
659 if (
id == this->
getId()) {
666 <<
TimeStamp() <<
" Evaluating interaction between "
668 << reg->identify() <<
" " << reg->getId() << std::flush;
669 if (reg->identify() == Staticdummy.
identify()) {
671 xtpdft->AddRegion(*staticregion);
672 }
else if (reg->identify() == Polardummy.
identify()) {
674 xtpdft->AddRegion(*polarregion);
676 throw std::runtime_error(
677 "Interaction of regions with types:" + this->
identify() +
" and " +
678 reg->identify() +
" not implemented");
682 e_ext = std::accumulate(interact_energies.begin(), interact_energies.end(),
686 <<
" Calculated interaction potentials with other regions. E[hrt]= "
687 << e_ext << std::flush;
689 xtpdft->WriteInputFile(
orb_);
690 bool active_run = xtpdft->RunActiveRegion();
692 throw std::runtime_error(
"\n DFT in DFT embedding failed. Stopping!");
694 Logfile_parse = xtpdft->ParseLogFile(
orb_);
695 if (!Logfile_parse) {
696 throw std::runtime_error(
"\n Parsing DFT logfile failed. Stopping!");
701 double energy =
orb_.getDFTTotalEnergy();
707 energy +=
orb_.getExcitedStateEnergy(state);
710 energy -=
orb_.getExcitedStateEnergy(state);
729 if (
orb_.getCalculationType() ==
"Truncated") {
730 orb_.MOs().eigenvectors() =
orb_.getTruncMOsFullBasis();
731 orb_.QMAtoms().clearAtoms();
732 orb_.QMAtoms() = originalmol;
733 orb_.SetupDftBasis(
orb_.getDftBasis().Name());
734 orb_.SetupAuxBasis(
orb_.getAuxBasis().Name());
744 const bool relaxable =
747 return orb_.DensityMatrixFull(state);
757 const Eigen::MatrixXd unrelaxed =
orb_.DensityMatrixFull(state);
763 Eigen::Vector3d change;
764 for (
Index k = 0; k < 3; ++k) {
770 <<
": electronic dipole change by the relaxation (e*bohr) "
771 << change.transpose() << std::flush;
782 orb_.getDFTbasisName().empty()) {
788 }
catch (
const std::runtime_error&) {
794 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(overlap.
Matrix());
796 es.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal() *
797 es.eigenvectors().transpose();
801 if (
orb_.QMAtoms().size() == 0) {
802 orb_.QMAtoms() = mol;
804 orb_.QMAtoms().AddContainer(mol);
814 nuccharge += a.getNuccharge();
817 Index electrons =
orb_.getNumberOfAlphaElectrons();
818 if (
orb_.isOpenShell()) {
819 electrons +=
orb_.getNumberOfBetaElectrons();
824 charge = double(nuccharge - electrons);
851 std::string dft_package_name =
dftoptions_.get(
"name").as<std::string>();
866 throw std::runtime_error(
867 "QMRegion-QMRegion interaction is not implemented yet.");
877 throw std::runtime_error(
878 "polar region " + std::to_string(region.
getId()) +
879 " has charge-response segments, which only the xtp DFT package "
880 "supports (dftpackage name " +
881 qmpackage_->getPackageName() +
"). Use xtp or Thole segments.");
898#pragma omp parallel for
899 for (
Index i = 0; i <
Index(segments.size()); ++i) {
900 if (segments[i].hasChargeResponse()) {
908 std::vector<PolarSegment>& segments)
const {
926 double N_comp = dmat.cwiseProduct(overlap.
Matrix()).sum();
927 if (std::abs(Ngrid - N_comp) > 0.001) {
930 <<
"WARNING: Calculated Densities at Numerical Grid, Number of "
932 << Ngrid <<
" is far away from the the real value " << N_comp
933 <<
", you should increase the accuracy of the integration grid."
936#pragma omp parallel for
937 for (
Index i = 0; i <
Index(segments.size()); ++i) {
951 std::vector<PolarSite*> cr_sites;
953 if (seg.hasChargeResponse()) {
955 cr_sites.push_back(&site);
959 if (!cr_sites.empty()) {
960 std::vector<Eigen::Vector3d> points;
961 std::vector<double> widths;
963 points.push_back(site->getPos());
964 widths.push_back(site->CRWidth());
967 const Eigen::MatrixXd electrons =
969 for (
Index k = 0; k <
Index(cr_sites.size()); ++k) {
970 PolarSite& site = *cr_sites[std::size_t(k)];
971 site.
Phi_noE() -= electrons(k, 0);
972 site.
V_noE() -= electrons.block<1, 3>(k, 1).transpose();
974 const Eigen::Vector3d r = site.
getPos() - atom.getPos();
976 const double Z = double(atom.getNuccharge());
978 site.
V_noE() -= Z * kern.
B1 * r;
999 orb_.WriteBasisSetsToCpt(v);
1017 r(state,
"initial_state");
1021 orb_.ReadFromCpt(rr);
1022 orb_.ReadBasisSetsFromCpt(rr);
1067 points.push_back(atom.getPos());
1069 const Eigen::VectorXd phi_all = region.
PotentialAt(points);
1070 const Eigen::VectorXd phi = phi_all.head(n_grid);
1071 const Eigen::VectorXd phi_nuclei = phi_all.tail(phi_all.size() - n_grid);
1082 values.resize(std::size_t(n_box));
1083 for (
Index p = 0; p < n_box; ++p) {
1084 values[std::size_t(p)] = phi[offset + p];
1088 if (offset != phi.size()) {
1089 throw std::runtime_error(
1090 "QMRegion::InteractwithEwaldRegion: the grid holds " +
1091 std::to_string(offset) +
" points across its boxes but " +
1092 std::to_string(phi.size()) +
1093 " potential values were evaluated. getGridpoints() and the box "
1094 "walk above disagree about the point ordering.");
void WriteContainer(T &container)
Container to hold Basisfunctions for all atoms.
Index AOBasisSize() const
void Fill(const BasisSet &bs, const QMMolecule &atoms)
void setCenter(const Eigen::Vector3d &r)
const std::array< Eigen::MatrixXd, 3 > & Matrix() const
void Fill(const AOBasis &aobasis) final
static Eigen::MatrixXd PotentialAndGradientAt(const AOBasis &basis, const Eigen::MatrixXd &D, const std::vector< Eigen::Vector3d > &points, const std::vector< double > &widths)
void Fill(const AOBasis &aobasis) final
const Eigen::MatrixXd & Matrix() const
void push_back(const T &atom)
void Load(const std::string &name)
CheckpointReader openChild(const std::string &childName) const
CheckpointWriter openChild(const std::string &childName) const
bool hasChargeResponse() const
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)
void Initialize(tools::Property &options)
Read DFT, grid, and SCF settings from the user options tree.
Eigen::Vector3d IntegrateField(const Eigen::Vector3d &rvector) const
double IntegrateDensity(const Eigen::MatrixXd &density_matrix)
static Eigen::MatrixXd Metric(const AOBasis &auxbasis)
T for an auxiliary basis on its own: the metric TCMatrix_gwbse::Fill folds into the three-centre inte...
static ScreeningCheck Check(const AOBasis &auxbasis, const QMMolecule &atoms, const ScreeningEnvironment &env, const Eigen::MatrixXd &T, Index n_modes=3)
Builds R for env and reports whether 1 + R is positive definite, and why not.
The periodic Ewald background, as a Region.
Eigen::VectorXd PotentialAt(const std::vector< Eigen::Vector3d > &points) const
Electronic excitations from GW-BSE.
void setScreeningEnvironment(const ScreeningEnvironment &env)
void setInactiveScreening(InactiveScreeningInput input)
void Initialize(tools::Property &options)
void setLogger(Logger *pLog)
const std::vector< Eigen::Vector3d > & getGridPoints() const
std::vector< double > & getPotentialValues()
static tools::EigenSystem CompleteGOrbitals(const tools::EigenSystem &embedded, Index n_active_occupied, const InactiveScreeningInput &input)
The MOs GW-BSE works with for complete G: the inactive occupied orbitals (semicanonical,...
static InactiveScreeningInput Prepare(const Orbitals &full, InactiveScreeningInput::Mode mode, bool complete_g=false, double radius=0.0)
The input for GWBSE, from the full reference orbitals (before they are replaced by the embedded ones)...
std::vector< T >::iterator begin()
std::vector< T >::iterator end()
void computePML(Orbitals &orbitals)
bool hasChargeResponse() const
std::string identify() const override
Class to represent Atom/Site in electrostatic+polarization.
const Eigen::Vector3d & V_noE() const
void AppendResult(tools::Property &prop) const override
StateTracker statetracker_
hist< Eigen::MatrixXd > Dmat_hist_
void PrepareEwaldPotentialGrid()
std::string grid_accuracy_for_ext_interaction_
std::string identify() const override
void AddNucleiFields(std::vector< PolarSegment > &segments, const StaticSegment &seg) const
std::shared_ptr< DFTSetupCache > setup_cache_
void SaveReferenceOrbitals()
std::unique_ptr< QMPackage > qmpackage_
bool screening_include_kreac_
void push_back(const QMMolecule &mol)
ReferenceOrbitals reference_
void WriteToCpt(CheckpointWriter &w) const override
double InteractwithStaticRegion(const StaticRegion ®ion) override
void EvaluateScreenedGWBSE(std::vector< std::unique_ptr< Region > > ®ions)
QMState relaxed_dmat_state_
void AppendScreenedSiteEnergies(tools::Property &prop) const
std::string ScreeningAuxBasisName() const
double ewald_nuclear_energy_
double InteractwithPolarRegion(const PolarRegion ®ion) override
QMRegion(Index id, Logger &log, std::string workdir)
double StateEnergy(const QMState &state) const
void WritePDB(csg::PDBWriter &writer) const override
void RestoreReferenceOrbitals()
double InteractwithEwaldRegion(const EwaldRegion ®ion) override
void ReadFromCpt(CheckpointReader &r) override
ScreeningEnvironment BuildScreeningEnvironment(const std::vector< std::unique_ptr< Region > > ®ions) const
InactiveScreeningInput PrepareOrbitalsForGWBSE()
bool Converged() const override
void Evaluate(std::vector< std::unique_ptr< Region > > ®ions) override
tools::Property localize_options_
std::vector< Eigen::Vector3d > copyEwaldGrid()
double InteractwithQMRegion(const QMRegion ®ion) override
void ApplyQMFieldToPolarSegments(std::vector< PolarSegment > &segments) const
bool ewald_potential_evaluated_
Eigen::MatrixXd StateDensity(const QMState &state) const
Eigen::MatrixXd overlap_sqrt_
double screening_shell_dielectric_
void Initialize(const tools::Property &prop) override
std::vector< Index > screening_shell_regions_
double charge() const override
double screening_site_width_
Eigen::MatrixXd relaxed_dmat_
void CheckScreeningEnvironment(const std::vector< std::unique_ptr< Region > > ®ions) const
tools::Property dftoptions_
tools::Property gwbseoptions_
bool isSingleParticleState() const
Identifier for QMstates. Strings like S1 are converted into enum +zero indexed int.
std::string ToString() const
const QMStateType & Type() const
std::vector< double > ApplyInfluenceOfOtherRegions(std::vector< std::unique_ptr< Region > > ®ions)
std::string identify() const override
Class to represent Atom/Site in electrostatic.
const Eigen::Vector3d & getPos() const
Timestamp returns the current time as a string Example: cout << TimeStamp().
void GridSetup(const std::string &type, const QMMolecule &atoms, const AOBasis &basis)
Mediates interaction between polar and static sites.
#define XTP_LOG(level, log)
void Cite(const std::string &key)
marks a reference as used (thread safe; unknown keys are printed as such)
Charge transport classes.
ClassicalSegment< PolarSite > PolarSegment
ClassicalSegment< StaticSite > StaticSegment
Provides a means for comparing floating point numbers.
Interaction of two normalized Gaussian charge distributions exp(-r^2/s_i^2) and exp(-r^2/s_j^2): erf(...
Outcome of EnvironmentScreening::Check: whether 1 + R is positive definite, and a human-readable acco...
The polarizable environment a GW-BSE calculation is screened by: what a QM/MM job hands to GWBSE (GWB...
std::vector< PolarSegment > explicit_segments
std::vector< PolarSegment > shell_segments