votca 2026-dev
Loading...
Searching...
No Matches
dftengine.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2026 The VOTCA Development Team
3 * (http://www.votca.org)
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License")
6 *
7 * You may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19
20// Third party includes
21#include <algorithm>
22#include <boost/format.hpp>
23#include <iomanip>
24#include <iostream>
25#include <map>
26#include <optional>
27#include <sstream>
28#include <string>
29
30// VOTCA includes
33
34// Local VOTCA includes
39#include "votca/xtp/aomatrix.h"
41#include "votca/xtp/citations.h"
43#include "votca/xtp/dftengine.h"
48#include "votca/xtp/logger.h"
49#include "votca/xtp/mmregion.h"
50#include "votca/xtp/orbitals.h"
53
54namespace votca {
55namespace xtp {
56
57namespace {
58
59void CanonicalizeOrbitalPhases(Eigen::MatrixXd& coeffs) {
60 constexpr double tol = 1e-14;
61
62 for (Index col = 0; col < coeffs.cols(); ++col) {
63 Eigen::Index pivot = 0;
64 const double maxabs = coeffs.col(col).cwiseAbs().maxCoeff(&pivot);
65
66 if (maxabs <= tol) {
67 continue;
68 }
69
70 if (coeffs(pivot, col) < 0.0) {
71 coeffs.col(col) *= -1.0;
72 }
73 }
74}
75
76void CanonicalizeOrbitalPhases(tools::EigenSystem& mos) {
77 CanonicalizeOrbitalPhases(mos.eigenvectors());
78}
79
80} // namespace
81
82// Defined in libint2_derivative_calls.cc; used by Initialize() to reject
83// compute_forces on builds without derivative integrals.
85
98
100
101 const std::string key_xtpdft = "xtpdft";
102 dftbasis_name_ = options.get(".basisset").as<std::string>();
103
104 if (options.exists(".auxbasisset")) {
105 auxbasis_name_ = options.get(".auxbasisset").as<std::string>();
106 }
107
108 if (!auxbasis_name_.empty()) {
109 screening_eps_ = options.get(key_xtpdft + ".screening_eps").as<double>();
111 options.get(key_xtpdft + ".fock_matrix_reset").as<Index>();
112 }
113 if (options.exists(".ecp")) {
114 ecp_name_ = options.get(".ecp").as<std::string>();
115 }
116
117 if (options.exists(key_xtpdft + ".force_uks_path")) {
118 force_uks_path_ = options.get(key_xtpdft + ".force_uks_path").as<bool>();
119 }
120
121 if (options.exists(key_xtpdft + ".polarizability")) {
123 options.get(key_xtpdft + ".polarizability").as<bool>();
124 }
125
126 if (options.exists(key_xtpdft + ".compute_forces")) {
127 compute_forces_ = options.get(key_xtpdft + ".compute_forces").as<bool>();
128 }
130 // Fail before the SCF rather than after it.
131 throw std::runtime_error(
132 "compute_forces=true was requested, but libint2 was built without "
133 "derivative integrals for one or more of the required operator "
134 "categories (one-body, two-center Coulomb metric, three-center RI). "
135 "Many packaged libint2 builds (Homebrew, Ubuntu apt, etc.) lack "
136 "them; rebuild libint2 with --enable-1body/--enable-eri2/"
137 "--enable-eri3 to use this feature.");
138 }
139 if (compute_forces_ && !ecp_name_.empty()) {
140 // H0 contains V_ECP, but the force routines have no d(V_ECP)/dR term;
141 // refuse rather than return incomplete forces.
142 throw std::runtime_error(
143 "compute_forces=true was requested together with an ECP ('" +
144 ecp_name_ +
145 "'), but the analytic nuclear forces do not include the ECP "
146 "term d(V_ECP)/dR. Either drop the ECP or do not request "
147 "compute_forces.");
148 }
149
150 if (options.exists(key_xtpdft + ".cdft.enabled")) {
151 cdft_enabled_ = options.get(key_xtpdft + ".cdft.enabled").as<bool>();
152 }
153 if (cdft_enabled_) {
154 // Only the spec is stored here; the Constraint needs the molecule and
155 // is built in Evaluate() by BuildCDFTConstraint.
156 std::string indices_str =
157 options.get(key_xtpdft + ".cdft.indices").as<std::string>();
158 if (indices_str.empty()) {
159 throw std::runtime_error(
160 "cdft.enabled=true was requested, but cdft.indices is empty; "
161 "specify the atoms of the constrained fragment (0-based, e.g. "
162 "'1 3 13:17', same syntax as the fragment indices in "
163 "diabatization.xml).");
164 }
165 cdft_constraint_spec_.atom_indices =
166 IndexParser().CreateIndexVector(indices_str);
167 cdft_constraint_spec_.target_charge =
168 options.get(key_xtpdft + ".cdft.charge").as<double>();
169 cdft_constraint_spec_.initial_lambda =
170 options.get(key_xtpdft + ".cdft.initial_lambda").as<double>();
172 options.get(key_xtpdft + ".cdft.max_iterations").as<Index>();
174 options.get(key_xtpdft + ".cdft.population_tolerance").as<double>();
175 cdft_constraint_spec_.guess_strategy =
176 options.get(key_xtpdft + ".cdft.guess_strategy").as<std::string>();
177 // CDFT itself needs no derivative integrals, so no
178 // HasLibint2DerivativeSupport() check here.
179 }
180
181 initial_guess_ = options.get(".initial_guess").as<std::string>();
182
183 if (initial_guess_ == "dimer_guess") {
184 dimer_guess_orbA_name_ = options.get(".dimer_guess_orbA").as<std::string>();
185 dimer_guess_orbB_name_ = options.get(".dimer_guess_orbB").as<std::string>();
186 if (dimer_guess_orbA_name_.empty() || dimer_guess_orbB_name_.empty()) {
187 throw std::runtime_error(
188 "initial_guess=dimer_guess requires both dimer_guess_orbA and "
189 "dimer_guess_orbB to be set to real monomer .orb file paths.");
190 }
191 }
192
193 grid_name_ = options.get(key_xtpdft + ".integration_grid").as<std::string>();
194 xc_functional_name_ = options.get(".functional").as<std::string>();
195
196 if (options.exists(key_xtpdft + ".externaldensity")) {
199 options.get(key_xtpdft + ".externaldensity.orbfile").as<std::string>();
200 gridquality_ = options.get(key_xtpdft + ".externaldensity.gridquality")
201 .as<std::string>();
202 state_ =
203 options.get(key_xtpdft + ".externaldensity.state").as<std::string>();
204 }
205
206 if (options.exists(".externalfield")) {
208 extfield_ = options.get(".externalfield").as<Eigen::Vector3d>();
209 }
210
211 conv_opt_.Econverged =
212 options.get(key_xtpdft + ".convergence.energy").as<double>();
213 conv_opt_.error_converged =
214 options.get(key_xtpdft + ".convergence.error").as<double>();
215 max_iter_ =
216 options.get(key_xtpdft + ".convergence.max_iterations").as<Index>();
217
218 std::string method =
219 options.get(key_xtpdft + ".convergence.method").as<std::string>();
220 if (method == "DIIS") {
221 conv_opt_.usediis = true;
222 } else if (method == "mixing") {
223 conv_opt_.usediis = false;
224 }
225 if (!conv_opt_.usediis) {
226 conv_opt_.histlength = 1;
227 conv_opt_.maxout = false;
228 }
229 conv_opt_.mixingparameter =
230 options.get(key_xtpdft + ".convergence.mixing").as<double>();
231 // Ceiling for adaptive damping, see convergenceacc.h.
232 conv_opt_.mixingmax =
233 options.get(key_xtpdft + ".convergence.mixing_max").as<double>();
234 conv_opt_.levelshift =
235 options.get(key_xtpdft + ".convergence.levelshift").as<double>();
236 conv_opt_.levelshiftend =
237 options.get(key_xtpdft + ".convergence.levelshift_end").as<double>();
238 // Independent from adiis_start, see convergenceacc.h and
239 // UKSConvergenceAcc::Iterate.
240 conv_opt_.mixingend =
241 options.get(key_xtpdft + ".convergence.mixing_end").as<double>();
242 conv_opt_.maxout =
243 options.get(key_xtpdft + ".convergence.DIIS_maxout").as<bool>();
244 conv_opt_.histlength =
245 options.get(key_xtpdft + ".convergence.DIIS_length").as<Index>();
246 conv_opt_.diis_start =
247 options.get(key_xtpdft + ".convergence.DIIS_start").as<double>();
248 conv_opt_.adiis_start =
249 options.get(key_xtpdft + ".convergence.ADIIS_start").as<double>();
250 conv_opt_.davidson_max_iter =
251 options.get(key_xtpdft + ".convergence.davidson_max_iter").as<Index>();
252 conv_opt_.energy_reset = options.ifExistsReturnElseReturnDefault<double>(
253 key_xtpdft + ".convergence.energy_reset", 1.0);
254 conv_opt_.second_order = options.ifExistsReturnElseReturnDefault<std::string>(
255 key_xtpdft + ".convergence.second_order", "auto");
256 if (conv_opt_.second_order != "auto" && conv_opt_.second_order != "always" &&
257 conv_opt_.second_order != "off") {
258 throw std::runtime_error(
259 "xtpdft.convergence.second_order must be auto, always or off, not " +
260 conv_opt_.second_order);
261 }
263 key_xtpdft + ".overlap_tolerance", 1e-8);
265 key_xtpdft + ".ri_pair_threshold", 1e-10);
266
267 if (options.exists(key_xtpdft + ".dft_in_dft.activeatoms")) {
269 options.get(key_xtpdft + ".dft_in_dft.activeatoms").as<std::string>();
271 options.get(key_xtpdft + ".dft_in_dft.threshold").as<double>();
273 options.get(key_xtpdft + ".dft_in_dft.levelshift").as<double>();
274 truncate_ =
275 options.get(key_xtpdft + ".dft_in_dft.truncate_basis").as<bool>();
277 key_xtpdft + ".dft_in_dft.grow", false);
278 active_growth_.window = options.ifExistsReturnElseReturnDefault<double>(
279 key_xtpdft + ".dft_in_dft.grow_window", 0.1) *
281 active_growth_.threshold = options.ifExistsReturnElseReturnDefault<double>(
282 key_xtpdft + ".dft_in_dft.grow_threshold", 0.0025);
283 // without a truncated basis the embedded virtual space is the full one
284 active_growth_.include_virtuals = truncate_;
285 if (truncate_) {
287 options.get(key_xtpdft + ".dft_in_dft.truncation_threshold")
288 .as<double>();
289 }
290 }
291}
292
293void DFTEngine::PrintMOs(const Eigen::VectorXd& MOEnergies, Log::Level level) {
294 XTP_LOG(level, *pLog_) << " Orbital energies: " << std::flush;
295 XTP_LOG(level, *pLog_) << " index occupation energy(Hartree) " << std::flush;
296
297 for (Index i = 0; i < MOEnergies.size(); ++i) {
298 Index occupancy = 0;
299 if (i < num_docc_) {
300 occupancy = 2;
301 } else if (i < num_docc_ + num_socc_alpha_) {
302 occupancy = 1;
303 }
304
305 XTP_LOG(level, *pLog_) << (boost::format(" %1$5d %2$1d %3$+1.10f") %
306 i % occupancy % MOEnergies(i))
307 .str()
308 << std::flush;
309 }
310 return;
311}
312
313void DFTEngine::PrintMOsUKS(const Eigen::VectorXd& alpha_energies,
314 const Eigen::VectorXd& beta_energies,
315 Log::Level level) const {
316 XTP_LOG(level, *pLog_) << " UKS orbital energies:" << std::flush;
317 XTP_LOG(level, *pLog_) << " index occ eps_a(Ha) eps_b(Ha)"
318 << std::flush;
319
320 const Index nrows =
321 std::max<Index>(alpha_energies.size(), beta_energies.size());
322
323 for (Index i = 0; i < nrows; ++i) {
324 const bool occ_a = (i < num_alpha_electrons_);
325 const bool occ_b = (i < num_beta_electrons_);
326
327 std::string occ = "0";
328 if (occ_a && occ_b) {
329 occ = "2";
330 } else if (occ_a) {
331 occ = "a";
332 } else if (occ_b) {
333 occ = "b";
334 }
335
336 std::string eps_a = " -";
337 std::string eps_b = " -";
338
339 if (i < alpha_energies.size()) {
340 eps_a = (boost::format("%+1.10f") % alpha_energies(i)).str();
341 }
342 if (i < beta_energies.size()) {
343 eps_b = (boost::format("%+1.10f") % beta_energies(i)).str();
344 }
345
346 XTP_LOG(level, *pLog_) << (boost::format(
347 " %1$5d %2$1s %3$15s %4$15s") %
348 i % occ % eps_a % eps_b)
349 .str()
350 << std::flush;
351 }
352
353 if (num_alpha_electrons_ > 0 &&
354 num_alpha_electrons_ < alpha_energies.size()) {
355 XTP_LOG(level, *pLog_) << (boost::format(
356 " alpha HOMO-LUMO gap: %+1.10f Ha") %
357 (alpha_energies(num_alpha_electrons_) -
358 alpha_energies(num_alpha_electrons_ - 1)))
359 .str()
360 << std::flush;
361 }
362
363 if (num_beta_electrons_ > 0 && num_beta_electrons_ < beta_energies.size()) {
364 XTP_LOG(level, *pLog_) << (boost::format(
365 " beta HOMO-LUMO gap: %+1.10f Ha") %
366 (beta_energies(num_beta_electrons_) -
367 beta_energies(num_beta_electrons_ - 1)))
368 .str()
369 << std::flush;
370 }
371}
372
373void DFTEngine::CalcElDipole(const Orbitals& orb) const {
374 QMState state = QMState("n");
375 Eigen::Vector3d result = orb.CalcElDipole(state);
377 << TimeStamp() << " Electric Dipole is[e*bohr]:\n\t\t dx=" << result[0]
378 << "\n\t\t dy=" << result[1] << "\n\t\t dz=" << result[2] << std::flush;
379 return;
380}
381
382// Defined in libint2_derivative_calls.cc. Unlike DFTGradient::RIJGradient
383// etc., these return AO-matrix derivatives d(M_munu)/dR, which are
384// contracted with the density below.
385using AOMatrixDerivative = std::array<Eigen::MatrixXd, 3>;
386std::vector<AOMatrixDerivative> ComputeOverlapDerivatives(
387 const AOBasis& aobasis);
388std::vector<AOMatrixDerivative> ComputeKineticDerivatives(
389 const AOBasis& aobasis);
390std::vector<AOMatrixDerivative> ComputeNuclearAttractionDerivatives(
391 const AOBasis& aobasis, const QMMolecule& mol);
392
393// Total ground-state gradient (nuclear repulsion, one-electron, overlap
394// Pulay, RI-J, XC and, for hybrids, RI-K) from the converged density matrix,
395// stored as the force -dE/dR via Orbitals::setForces(). The individual terms
396// are tested in test_dftgradient.cc and test_xcgradient.cc.
398 Orbitals& orb, const Eigen::MatrixXd& Dmat,
399 const Vxc_Potential<Vxc_Grid>& vxcpotential) const {
400 if (auxbasis_name_.empty()) {
402 << TimeStamp()
403 << " Skipping force calculation: RI-J gradient (DFTGradient::"
404 "RIJGradient) only implements the RI path, but this SCF ran "
405 "without an auxiliary basis (conventional 4-center ERIs)."
406 << std::flush;
407 return;
408 }
409
412 << TimeStamp()
413 << " Skipping force calculation: the libint2 this was built "
414 "against lacks derivative integrals for one or more required "
415 "operator categories; rebuild libint2 with "
416 "--enable-1body/--enable-eri2/--enable-eri3 to use analytic "
417 "forces."
418 << std::flush;
419 return;
420 }
421
422 if (!ecp_name_.empty()) {
423 // Normally rejected in Initialize(); repeated here in case the members
424 // were set otherwise. Skip instead of throwing after a converged SCF.
426 << TimeStamp() << " Skipping force calculation: an ECP ('" << ecp_name_
427 << "') was used for this SCF, but analytic nuclear forces do "
428 "not include the ECP term d(V_ECP)/dR."
429 << std::flush;
430 return;
431 }
432
433 const QMMolecule& mol = orb.QMAtoms();
434 Index natoms = mol.size();
435
436 XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Starting force calculation ("
437 << natoms << " atoms)" << std::flush;
438
439 // One-electron (kinetic + nuclear attraction) contribution,
440 // dE_one/dR_A = Tr[D d(T+V_ne)/dR_A]. See
441 // ComputeNuclearAttractionDerivatives for the sign convention.
443 << " Computing one-electron (kinetic + nuclear "
444 "attraction) derivatives"
445 << std::flush;
446 std::vector<AOMatrixDerivative> dT = ComputeKineticDerivatives(dftbasis_);
447 std::vector<AOMatrixDerivative> dVne =
449 Eigen::MatrixXd eone_grad = Eigen::MatrixXd::Zero(natoms, 3);
450 for (Index a = 0; a < natoms; ++a) {
451 for (Index xyz = 0; xyz < 3; ++xyz) {
452 eone_grad(a, xyz) = Dmat.cwiseProduct(dT[a][xyz] + dVne[a][xyz]).sum();
453 }
454 }
456 << TimeStamp() << " One-electron derivatives done" << std::flush;
457
458 // Overlap (SCF Pulay) term from the orthonormality constraint
459 // C^T S(R) C = I. For canonical MOs at convergence the Lagrange
460 // multipliers are the orbital energies, giving
461 // dE/dR_A|_overlap = -Tr[W dS/dR_A], W = 2 C_occ diag(eps_occ) C_occ^T
462 // (energy-weighted density, factor 2 for closed shells; cf. the libint2
463 // SCF gradient example). Not to be confused with PulayGradient, the
464 // basis-function term of the XC integral.
466 Eigen::MatrixXd C_occ = orb.MOs().eigenvectors().leftCols(n_occ);
467 Eigen::VectorXd eps_occ = orb.MOs().eigenvalues().head(n_occ);
468 Eigen::MatrixXd W = 2.0 * C_occ * eps_occ.asDiagonal() * C_occ.transpose();
469
471 << TimeStamp() << " Computing overlap (Pulay) derivatives"
472 << std::flush;
473 std::vector<AOMatrixDerivative> dS = ComputeOverlapDerivatives(dftbasis_);
474 Eigen::MatrixXd overlap_pulay_grad = Eigen::MatrixXd::Zero(natoms, 3);
475 for (Index a = 0; a < natoms; ++a) {
476 for (Index xyz = 0; xyz < 3; ++xyz) {
477 overlap_pulay_grad(a, xyz) = -W.cwiseProduct(dS[a][xyz]).sum();
478 }
479 }
481 << TimeStamp() << " Overlap derivatives done" << std::flush;
482
484 << TimeStamp() << " Computing RI-J (Coulomb) gradient" << std::flush;
485 Eigen::MatrixXd rij_term =
488 << TimeStamp() << " RI-J gradient done" << std::flush;
489
491 << TimeStamp() << " Computing XC grid (Pulay + weight) gradient terms"
492 << std::flush;
493 Eigen::MatrixXd pulay_term = vxcpotential.PulayGradient(Dmat, dftbasis_);
494 Eigen::MatrixXd weight_term = vxcpotential.GridWeightGradient(Dmat, mol);
495 Eigen::MatrixXd nucrep_term = DFTGradient::NuclearRepulsionDerivative(mol);
497 << TimeStamp() << " XC grid gradient terms done" << std::flush;
498
499 Eigen::MatrixXd grad = nucrep_term + eone_grad + overlap_pulay_grad +
500 rij_term + pulay_term + weight_term;
501
502 // Exact-exchange (RI-K) gradient, hybrids only (O(Naux * Nao^2 * nocc)
503 // work, O(Naux * nocc^2 + Naux^2) memory). Its energy,
504 // E_K = -sum_ij c_ij.d_ij, equals 0.25*Dmat.cwiseProduct(K).sum() at
505 // ScaHFX_ = 1 (tested in test_dftgradient.cc), so the contribution is
506 // ScaHFX_ * RIKGradient, as exx = 0.25*ScaHFX_*Dmat.cwiseProduct(K).sum().
507 if (ScaHFX_ > 0.0) {
509 << TimeStamp() << " Computing RI-K (exact exchange) gradient"
510 << std::flush;
513 << TimeStamp() << " RI-K gradient done" << std::flush;
514 }
515
516 // Translational invariance: the total gradient must sum to zero over
517 // atoms. Only logged, not thrown.
518 Eigen::Vector3d sum = grad.colwise().sum();
519 if (sum.cwiseAbs().maxCoeff() > 1e-4) {
521 << TimeStamp()
522 << " WARNING: computed forces do not sum to zero across atoms "
523 "(translational invariance check failed, max component="
524 << sum.cwiseAbs().maxCoeff()
525 << ") -- treat these forces with "
526 "caution."
527 << std::flush;
528 }
529
530 // All terms above are dE/dR; store the force -dE/dR (the convention of
531 // e.g. ASE's Calculator.get_forces()).
532 Eigen::MatrixXd force = -grad;
533 orb.setForces(force);
534
536 << TimeStamp() << " Computed and stored ground-state nuclear forces."
537 << std::flush;
538 // Printed in atomic units (Hartree/Bohr), as stored.
539 XTP_LOG(Log::error, *pLog_) << " Forces [Ha/Bohr]" << std::flush;
540 for (Index a = 0; a < natoms; ++a) {
541 std::string output =
542 (boost::format(" %1$s"
543 " %2$+1.6f %3$+1.6f %4$+1.6f") %
544 mol[a].getElement() % force(a, 0) % force(a, 1) % force(a, 2))
545 .str();
546 XTP_LOG(Log::error, *pLog_) << output << std::flush;
547 }
548}
549
551 const QMMolecule& mol, const tools::EigenSystem& MOs_alpha,
552 const tools::EigenSystem& MOs_beta) const {
553 // W = W_alpha + W_beta without the closed-shell factor 2.
554 //
555 // This term accounts for the implicit R-dependence of C through
556 // C^T S(R) C = I and is only valid at an SCF stationary point, so it has
557 // no fixed-C finite-difference counterpart. test_dftengine_private.cc
558 // checks it against the RKS formula for alpha == beta
559 // (overlap_pulay_gradient_uks_reduces_to_rks) and the other non-XC terms
560 // by fixed-C finite differences
561 // (compute_non_xc_gradient_uks_finite_difference).
562 Index n_occ_alpha = num_alpha_electrons_;
563 Index n_occ_beta = num_beta_electrons_;
564 Eigen::MatrixXd C_alpha_occ = MOs_alpha.eigenvectors().leftCols(n_occ_alpha);
565 Eigen::MatrixXd C_beta_occ = MOs_beta.eigenvectors().leftCols(n_occ_beta);
566 Eigen::VectorXd eps_alpha_occ = MOs_alpha.eigenvalues().head(n_occ_alpha);
567 Eigen::VectorXd eps_beta_occ = MOs_beta.eigenvalues().head(n_occ_beta);
568 Eigen::MatrixXd W =
569 C_alpha_occ * eps_alpha_occ.asDiagonal() * C_alpha_occ.transpose() +
570 C_beta_occ * eps_beta_occ.asDiagonal() * C_beta_occ.transpose();
571
572 Index natoms = mol.size();
573 std::vector<AOMatrixDerivative> dS = ComputeOverlapDerivatives(dftbasis_);
574 Eigen::MatrixXd overlap_pulay_grad = Eigen::MatrixXd::Zero(natoms, 3);
575 for (Index a = 0; a < natoms; ++a) {
576 for (Index xyz = 0; xyz < 3; ++xyz) {
577 overlap_pulay_grad(a, xyz) = -W.cwiseProduct(dS[a][xyz]).sum();
578 }
579 }
580 return overlap_pulay_grad;
581}
582
584 const QMMolecule& mol, const UKSConvergenceAcc::SpinDensity& Dspin,
585 const tools::EigenSystem& MOs_alpha,
586 const tools::EigenSystem& MOs_beta) const {
587 Index natoms = mol.size();
588 const Eigen::MatrixXd D_total = Dspin.total();
589
590 // One-electron and RI-J terms as for RKS, with D_total = D_alpha + D_beta
591 // in place of the closed-shell Dmat.
592 std::vector<AOMatrixDerivative> dT = ComputeKineticDerivatives(dftbasis_);
593 std::vector<AOMatrixDerivative> dVne =
595 Eigen::MatrixXd eone_grad = Eigen::MatrixXd::Zero(natoms, 3);
596 for (Index a = 0; a < natoms; ++a) {
597 for (Index xyz = 0; xyz < 3; ++xyz) {
598 eone_grad(a, xyz) = D_total.cwiseProduct(dT[a][xyz] + dVne[a][xyz]).sum();
599 }
600 }
601
602 Eigen::MatrixXd overlap_pulay_grad =
603 ComputeOverlapPulayGradientUKS(mol, MOs_alpha, MOs_beta);
604
605 Eigen::MatrixXd grad =
607 overlap_pulay_grad +
609
610 // Exact exchange (RI-K), hybrids only. UKS exchange uses
611 // ERIs::CalculateEXX_dmat(P) = 0.5*ERIs::CalculateEXX_mos(C) for
612 // P = C C^T, while RIKGradient corresponds to CalculateEXX_mos, hence
613 // dE_exx/dR = 0.5*ScaHFX_*[RIKGradient(C_alpha_occ)+RIKGradient(C_beta_occ)].
614 if (ScaHFX_ > 0.0) {
615 Eigen::MatrixXd C_alpha_occ =
616 MOs_alpha.eigenvectors().leftCols(num_alpha_electrons_);
617 Eigen::MatrixXd C_beta_occ =
618 MOs_beta.eigenvectors().leftCols(num_beta_electrons_);
619 grad += 0.5 * ScaHFX_ *
622 }
623 return grad;
624}
625
627 Orbitals& orb, const UKSConvergenceAcc::SpinDensity& Dspin,
628 const tools::EigenSystem& MOs_alpha, const tools::EigenSystem& MOs_beta,
629 const Vxc_Potential<Vxc_Grid>& vxcpotential) const {
630 if (auxbasis_name_.empty()) {
632 << TimeStamp()
633 << " Skipping UKS force calculation: RI-J gradient only "
634 "implements the RI path, but this SCF ran without an "
635 "auxiliary basis."
636 << std::flush;
637 return;
638 }
639
642 << TimeStamp()
643 << " Skipping UKS force calculation: the libint2 this was "
644 "built against lacks derivative integrals for one or more "
645 "required operator categories; rebuild libint2 with "
646 "--enable-1body/--enable-eri2/--enable-eri3 to use "
647 "analytic forces."
648 << std::flush;
649 return;
650 }
651
652 if (!ecp_name_.empty()) {
653 // See ComputeAndStoreForces.
655 << TimeStamp() << " Skipping UKS force calculation: an ECP ('"
656 << ecp_name_
657 << "') was used for this SCF, but analytic nuclear forces do "
658 "not include the ECP term d(V_ECP)/dR."
659 << std::flush;
660 return;
661 }
662
663 Eigen::MatrixXd grad =
664 ComputeNonXCGradientUKS(orb.QMAtoms(), Dspin, MOs_alpha, MOs_beta);
665
666 // XC gradient (LDA and GGA), see PulayGradientUKS/GridWeightGradientUKS.
667 grad += vxcpotential.PulayGradientUKS(Dspin.alpha, Dspin.beta, dftbasis_);
668 grad += vxcpotential.GridWeightGradientUKS(Dspin.alpha, Dspin.beta,
669 orb.QMAtoms());
670
671 // Translational invariance check, logged only (as for RKS).
672 Eigen::Vector3d sum = grad.colwise().sum();
673 if (sum.cwiseAbs().maxCoeff() > 1e-4) {
675 << TimeStamp()
676 << " WARNING: computed UKS forces do not sum to zero across "
677 "atoms (translational invariance check failed, max "
678 "component="
679 << sum.cwiseAbs().maxCoeff()
680 << ") -- treat these forces with "
681 "caution."
682 << std::flush;
683 }
684
685 // Store the force -dE/dR, as for RKS.
686 Eigen::MatrixXd force = -grad;
687 orb.setForces(force);
688
690 << TimeStamp() << " Computed and stored ground-state UKS nuclear forces."
691 << std::flush;
692 // Printed in atomic units (Hartree/Bohr), as stored.
693 const QMMolecule& mol_for_print = orb.QMAtoms();
694 XTP_LOG(Log::error, *pLog_) << " Forces [Ha/Bohr]" << std::flush;
695 for (Index a = 0; a < force.rows(); ++a) {
696 std::string output = (boost::format(" %1$s"
697 " %2$+1.6f %3$+1.6f %4$+1.6f") %
698 mol_for_print[a].getElement() % force(a, 0) %
699 force(a, 1) % force(a, 2))
700 .str();
701 XTP_LOG(Log::error, *pLog_) << output << std::flush;
702 }
703}
704
705// Build the Coulomb and exact-exchange contributions generated by the current
706// density matrix. The returned pair is conventionally interpreted as
707//
708// (J[P], -K[P]),
709//
710// so that the hybrid Fock update becomes F = H0 + J[P] + a_x (-K[P]) + V_xc.
711// For RI/3c builds the occupied MO block is supplied when available to avoid an
712// unnecessary reconstruction of exchange intermediates.
713std::array<Eigen::MatrixXd, 2> DFTEngine::CalcERIs_EXX(
714 const Eigen::MatrixXd& MOCoeff, const Eigen::MatrixXd& Dmat,
715 double error) const {
716 if (!auxbasis_name_.empty()) {
717 std::array<Eigen::MatrixXd, 2> result;
718 {
719 auto t = timings_.Measure("J (RI)");
720 result[0] = ERIs_.CalculateERIs_3c(Dmat);
721 }
722 if (conv_accelerator_.getUseMixing() || MOCoeff.rows() == 0) {
723 auto t = timings_.Measure("K (RI, from density matrix)");
724 result[1] = ERIs_.CalculateEXX_3c(Eigen::MatrixXd::Zero(0, 0), Dmat);
725 } else {
726 auto t = timings_.Measure("K (RI, from occupied MOs)");
727 Eigen::MatrixXd occblock = MOCoeff.leftCols(num_docc_ + num_socc_alpha_);
728 result[1] = ERIs_.CalculateEXX_3c(occblock, Dmat);
729 }
730 return result;
731 } else {
732 auto t = timings_.Measure("J+K (4c)");
733 return ERIs_.CalculateERIs_EXX_4c(Dmat, error);
734 }
735}
736
737// Pure Coulomb contribution J[P] from the current AO density matrix. The code
738// dispatches to either RI/3c or conventional 4-center integral evaluation.
739Eigen::MatrixXd DFTEngine::CalcERIs(const Eigen::MatrixXd& Dmat,
740 double error) const {
741 if (!auxbasis_name_.empty()) {
742 auto t = timings_.Measure("J (RI)");
743 return ERIs_.CalculateERIs_3c(Dmat);
744 } else {
745 auto t = timings_.Measure("J (4c)");
746 return ERIs_.CalculateERIs_4c(Dmat, error);
747 }
748}
749
751 const double gb = 1024.0 * 1024.0 * 1024.0;
752 const double n = double(dftbasis_.AOBasisSize());
753 const double threads = double(OPENMP::getMaxThreads());
755 << TimeStamp() << " DFT dimensions: " << dftbasis_.AOBasisSize()
756 << " basis functions, " << OPENMP::getMaxThreads() << " threads"
757 << std::flush;
758 if (!auxbasis_name_.empty()) {
759 const double naux = double(ERIs_.AuxSize());
760 // the stored basis-function pairs for every aux function
761 const double tensor =
762 naux * double(ERIs_.StoredPairs()) * sizeof(double) / gb;
763 const double kept = double(ERIs_.StoredPairs()) /
764 double(std::max<Index>(1, ERIs_.AllPairs()));
765 // per thread: the OpenMP reduction copy of J or K, and for K the
766 // unpacked 3c slice plus the product temporaries
767 const double scratch = threads * 4 * n * n * sizeof(double) / gb;
769 << TimeStamp() << " RI: " << ERIs_.AuxSize() << " aux functions ("
770 << ERIs_.Removedfunctions()
771 << " removed from the metric); stored 3c tensor "
772 << std::setprecision(3) << tensor << " GB (" << 100.0 * kept
773 << "% of the pairs at ri_pair_threshold " << ri_pair_threshold_
774 << "); J/K scratch up to about " << scratch << " GB" << std::flush;
775 }
776 double rss = DFTTimings::ResidentMemoryGB(false);
777 if (rss >= 0) {
779 << TimeStamp()
780 << " Resident memory after setup: " << std::setprecision(3) << rss
781 << " GB" << std::flush;
782 }
783}
784
786 const Mat_p_Energy& H0) const {
787 return conv_accelerator_.SolveFockmatrix(H0.matrix());
788}
789
790// Construct a self-consistent model-potential guess by starting from an
791// atomic density P^(0), evaluating
792//
793// F[P^(0)] = H0 + J[P^(0)] + a_x (-K[P^(0)]) + V_xc[P^(0)],
794//
795// and diagonalizing the resulting Fock matrix once.
797 const Mat_p_Energy& H0, const QMMolecule& mol,
798 const Vxc_Potential<Vxc_Grid>& vxcpotential) const {
799 Eigen::MatrixXd Dmat = [&]() {
800 auto t = timings_.Measure("guess: atomic densities");
801 return AtomicGuess(mol);
802 }();
803 Mat_p_Energy e_vxc = [&]() {
804 auto t = timings_.Measure("Vxc");
805 return vxcpotential.IntegrateVXC(Dmat);
806 }();
808 << TimeStamp() << " Filled DFT Vxc matrix " << std::flush;
809
810 Eigen::MatrixXd H = H0.matrix() + e_vxc.matrix();
811
812 if (ScaHFX_ > 0) {
813 std::array<Eigen::MatrixXd, 2> both =
814 CalcERIs_EXX(Eigen::MatrixXd::Zero(0, 0), Dmat, 1e-12);
815 H += both[0];
816 H += ScaHFX_ * both[1];
817 } else {
818 H += CalcERIs(Dmat, 1e-12);
819 }
820 return conv_accelerator_.SolveFockmatrix(H);
821}
822
824 timings_.Reset();
825 if (cdft_enabled_) {
826 citations::Cite("Wu:2005");
827 }
828 // a tensor carried over from a guess would describe another state
830 bool success = EvaluateAndTime(orb);
831 timings_.Report(*pLog_, Log::error);
832 if (success && compute_polarizability_) {
834 }
835 double peak = DFTTimings::ResidentMemoryGB(true);
836 if (peak >= 0) {
838 << TimeStamp() << " Peak resident memory of this process so far: "
839 << std::setprecision(3) << peak << " GB" << std::flush;
840 }
841 return success;
842}
843
846 throw std::runtime_error(
847 "xtpdft polarizability: closed-shell ground states only");
848 }
850 << TimeStamp()
851 << " Static polarizability (coupled-perturbed KS, 3 uniform fields)"
852 << std::flush;
853 AODipole dipole;
854 dipole.setCenter(orb.QMAtoms().getPos());
855 dipole.Fill(dftbasis_);
856 const std::vector<Eigen::MatrixXd> h(dipole.Matrix().begin(),
857 dipole.Matrix().end());
858 const std::vector<Eigen::MatrixXd> dP = StaticResponse(orb, h);
859 Eigen::Matrix3d alpha;
860 for (Index a = 0; a < 3; ++a) {
861 for (Index c = 0; c < 3; ++c) {
862 alpha(a, c) = -dipole.Matrix()[std::size_t(a)]
863 .cwiseProduct(dP[std::size_t(c)])
864 .sum();
865 }
866 }
867 alpha = 0.5 * (alpha + alpha.transpose()).eval();
868 orb.setPolarizability(alpha);
869 const double A3 = std::pow(tools::conv::bohr2ang, 3);
871 << TimeStamp() << " Polarizability [a.u.]:\n"
872 << alpha << "\n isotropic " << alpha.trace() / 3
873 << " a.u. = " << alpha.trace() / 3 * A3 << " A^3" << std::flush;
874}
875
877 if (cdft_enabled_) {
878 // Dispatched before the setup below, which RunCDFT does itself.
881
882 // No forces during the lambda trials of RunCDFT; only the converged
883 // lambda's force is needed. Restored whether or not RunCDFT converges.
884 bool original_compute_forces = compute_forces_;
885 compute_forces_ = false;
886 bool converged = RunCDFT(orb, constraint);
887 compute_forces_ = original_compute_forces;
888
889 if (converged && original_compute_forces) {
890 // One more UKS evaluation at the converged lambda to compute the DFT
891 // force. orb holds the converged MOs, so the SCF converges almost
892 // immediately; only the setup is repeated, to keep RunCDFT's
893 // interface unchanged.
895 << TimeStamp()
896 << " CDFT converged -- computing the ordinary DFT force once, "
897 "for the final, converged density only"
898 << std::flush;
899 Prepare(orb);
900 Mat_p_Energy H0 = SetupH0(orb.QMAtoms());
901 Vxc_Potential<Vxc_Grid> vxcpotential = SetupVxc(orb.QMAtoms());
902 ConfigOrbfile(orb);
903 EvaluateUKS(orb, H0, vxcpotential);
904 }
905
906 if (converged && orb.hasForces()) {
907 // Add the CDFT constraint term to the DFT force, once, at the
908 // converged lambda. The constraint only carries the summed weight
909 // matrix, so the per-atom contributions are rebuilt from
910 // cdft_constraint_spec_.atom_indices; this repeats the (cheap, no SCF)
911 // reference-density, basis and grid setup of BuildCDFTConstraint.
912 std::map<std::string, Eigen::MatrixXd> reference_densities =
914 AOBasis full_dftbasis;
915 {
916 BasisSet basisset;
917 basisset.Load(dftbasis_name_);
918 full_dftbasis.Fill(basisset, orb.QMAtoms());
919 }
920 Vxc_Grid grid;
921 grid.GridSetup(grid_name_, orb.QMAtoms(), full_dftbasis);
922 std::vector<HirshfeldPartition::AtomicReference> atoms =
924 orb.QMAtoms(), dftbasis_name_, reference_densities);
925
926 std::array<Eigen::MatrixXd, 2> Dspin =
928 // Total density, as the charge constraint has
929 // spin_alpha_coefficient = spin_beta_coefficient = +1.
930 Eigen::MatrixXd density_total = Dspin[0] + Dspin[1];
931
932 Eigen::MatrixXd cdft_gradient_correction =
933 Eigen::MatrixXd::Zero(static_cast<Index>(orb.QMAtoms().size()), 3);
934 for (Index atom_index : cdft_constraint_spec_.atom_indices) {
935 cdft_gradient_correction +=
937 atoms, atom_index, density_total, orb.QMAtoms(), full_dftbasis,
938 grid);
939 }
940 // ComputeCDFTForceContribution returns d(Tr[D W_c])/dR; the gradient
941 // correction is +lambda times that, so the force gets -lambda times it.
942 orb.setForces(orb.getForces() -
943 constraint.lambda * cdft_gradient_correction);
944 }
945 return converged;
946 }
947
948 // Prepare replaces orb's basis, so record which basis its MOs belong to.
949 const std::string previous_basis =
950 orb.hasDFTbasisName() ? orb.getDFTbasisName() : "";
951 Prepare(orb);
953
954 const std::string configured_guess = initial_guess_;
955 warm_started_ = false;
956 if (warm_start_ && initial_guess_ != "orbfile") {
957 std::string reason;
958 if (UsableAsWarmStart(orb, previous_basis, reason)) {
959 initial_guess_ = "orbfile";
960 warm_started_ = true;
962 << TimeStamp()
963 << " Starting from the orbitals of the previous QM/MM iteration"
964 << std::flush;
965 } else {
967 << TimeStamp() << " Previous orbitals not usable as guess (" << reason
968 << "); using " << initial_guess_ << std::flush;
969 }
970 }
971
972 Mat_p_Energy H0 = SetupH0(orb.QMAtoms());
973 Vxc_Potential<Vxc_Grid> vxcpotential = [&]() {
974 auto t = timings_.Measure("setup: XC grid");
975 return SetupVxc(orb.QMAtoms());
976 }();
977 ConfigOrbfile(orb);
978
979 bool success = false;
983 << TimeStamp()
984 << " Forcing closed-shell singlet through UKS development path."
985 << std::flush;
986 }
987 success = EvaluateUKS(orb, H0, vxcpotential);
988 } else {
989 success = EvaluateClosedShell(orb, H0, vxcpotential);
990 }
991 initial_guess_ = configured_guess;
992 warm_started_ = false;
993 return success;
994}
995
997 const std::string& previous_basis,
998 std::string& reason) const {
999 if (!orb.hasMOs()) {
1000 reason = "no MOs";
1001 return false;
1002 }
1003 const Index n = dftbasis_.AOBasisSize();
1004 if (orb.MOs().eigenvectors().rows() != n ||
1005 orb.MOs().eigenvectors().cols() != n) {
1006 reason = "basis size differs";
1007 return false;
1008 }
1009 if (!previous_basis.empty() && previous_basis != orb.getDFTbasisName()) {
1010 reason = "basis set differs";
1011 return false;
1012 }
1015 reason = "electron count differs";
1016 return false;
1017 }
1018 return true;
1019}
1020
1022 HirshfeldPartition::Constraint& constraint) {
1023 Prepare(orb);
1024 Mat_p_Energy H0 = SetupH0(orb.QMAtoms());
1025 Vxc_Potential<Vxc_Grid> vxcpotential = SetupVxc(orb.QMAtoms());
1026 ConfigOrbfile(orb);
1027
1028 // initial_guess_ is switched to "orbfile" for warm starts; restored on
1029 // every exit path.
1030 std::string saved_initial_guess = initial_guess_;
1031
1032 constraints_ = {constraint};
1033
1034 // Bisection in lambda: needs only monotonicity of the population in
1035 // lambda, no dN/dlambda. The bracket is centred on constraint.lambda and
1036 // doubled in width until the mismatch changes sign or
1037 // kMaxBracketAttempts is reached.
1038 double lambda_lo = constraint.lambda - 0.1;
1039 double lambda_hi = constraint.lambda + 0.1;
1040
1041 auto EvaluateMismatch = [&](double lambda) -> double {
1042 constraints_[0].lambda = lambda;
1044 << TimeStamp() << " CDFT: starting inner SCF at lambda=" << lambda
1045 << std::flush;
1046 bool scf_converged = EvaluateUKS(orb, H0, vxcpotential);
1047 if (!scf_converged) {
1048 throw std::runtime_error(
1049 "RunCDFT: inner SCF did not converge at lambda=" +
1050 std::to_string(lambda));
1051 }
1052 if (cdft_constraint_spec_.guess_strategy == "warmstart") {
1053 initial_guess_ = "orbfile"; // warm start every subsequent call
1054 }
1055 // "fresh": keep the configured guess for every trial, for cases where
1056 // consecutive lambdas give very different densities (dftpackage.xml).
1057 std::array<Eigen::MatrixXd, 2> Dspin =
1059 double population =
1060 constraint.spin_alpha_coefficient *
1061 Dspin[0].cwiseProduct(constraint.weight_matrix).sum() +
1062 constraint.spin_beta_coefficient *
1063 Dspin[1].cwiseProduct(constraint.weight_matrix).sum();
1064 return population - constraint.target_population;
1065 };
1066
1067 try {
1068 double mismatch_lo = EvaluateMismatch(lambda_lo);
1069 double mismatch_hi = EvaluateMismatch(lambda_hi);
1070
1071 Index bracket_attempts = 0;
1072 constexpr Index kMaxBracketAttempts = 10;
1073 while (mismatch_lo * mismatch_hi > 0.0 &&
1074 bracket_attempts < kMaxBracketAttempts) {
1075 double width = lambda_hi - lambda_lo;
1076 lambda_lo -= 0.5 * width;
1077 lambda_hi += 0.5 * width;
1078 mismatch_lo = EvaluateMismatch(lambda_lo);
1079 mismatch_hi = EvaluateMismatch(lambda_hi);
1080 ++bracket_attempts;
1081 }
1082 if (mismatch_lo * mismatch_hi > 0.0) {
1084 << TimeStamp()
1085 << " RunCDFT: could not bracket a root for the population "
1086 "mismatch after "
1087 << kMaxBracketAttempts
1088 << " bracket-expansion attempts -- the target population may "
1089 "be unreachable for this system, or the initial "
1090 "lambda guess may be far from the actual root."
1091 << std::flush;
1092 initial_guess_ = saved_initial_guess;
1093 constraints_.clear();
1094 return false;
1095 }
1096
1097 for (Index outer_iter = 0; outer_iter < max_cdft_iterations_;
1098 ++outer_iter) {
1099 double lambda_mid = 0.5 * (lambda_lo + lambda_hi);
1100 double mismatch_mid = EvaluateMismatch(lambda_mid);
1101
1103 << TimeStamp() << " CDFT outer iteration " << outer_iter + 1 << " of "
1104 << max_cdft_iterations_ << ": lambda=" << lambda_mid
1105 << " population mismatch=" << mismatch_mid << std::flush;
1106
1107 if (std::abs(mismatch_mid) < cdft_population_tolerance_) {
1108 constraint.lambda = lambda_mid;
1109 initial_guess_ = saved_initial_guess;
1111 << TimeStamp() << " CDFT converged after " << outer_iter + 1
1112 << " outer iterations, lambda=" << lambda_mid << std::flush;
1113 return true;
1114 }
1115
1116 if (mismatch_mid * mismatch_lo < 0.0) {
1117 lambda_hi = lambda_mid;
1118 mismatch_hi = mismatch_mid;
1119 } else {
1120 lambda_lo = lambda_mid;
1121 mismatch_lo = mismatch_mid;
1122 }
1123 }
1124 } catch (const std::runtime_error&) {
1125 initial_guess_ = saved_initial_guess;
1126 constraints_.clear();
1127 throw;
1128 }
1129
1131 << TimeStamp()
1132 << " RunCDFT: outer bisection loop did not converge "
1133 "within "
1134 << max_cdft_iterations_ << " iterations." << std::flush;
1135 constraint.lambda = 0.5 * (lambda_lo + lambda_hi);
1136 initial_guess_ = saved_initial_guess;
1137 return false;
1138}
1139
1140// Restricted SCF loop. The total energy is assembled as
1141//
1142// E = Tr[P H0] + E_nuc + E_coul + E_xc + E_exx,
1143//
1144// with P = 2 C_occ C_occ^T. DIIS or mixing updates the density until both
1145// the energy change and the commutator error are converged.
1147 Orbitals& orb, const Mat_p_Energy& H0,
1148 const Vxc_Potential<Vxc_Grid>& vxcpotential) {
1149
1151 MOs.eigenvalues() = Eigen::VectorXd::Zero(H0.cols());
1152 MOs.eigenvectors() = Eigen::MatrixXd::Zero(H0.rows(), H0.cols());
1153
1154 if (initial_guess_ == "orbfile") {
1156 << TimeStamp() << " Reading guess from orbitals object/file"
1157 << std::flush;
1158 MOs = orb.MOs();
1160 } else {
1162 << TimeStamp() << " Setup Initial Guess using: " << initial_guess_
1163 << std::flush;
1164 if (initial_guess_ == "independent") {
1165 MOs = IndependentElectronGuess(H0);
1166 } else if (initial_guess_ == "atom") {
1167 MOs = ModelPotentialGuess(H0, orb.QMAtoms(), vxcpotential);
1168 } else if (initial_guess_ == "huckel") {
1169 MOs = ExtendedHuckelGuess(orb.QMAtoms());
1170 } else if (initial_guess_ == "huckel_dft") {
1171 MOs = ExtendedHuckelDFTGuess(H0, orb.QMAtoms(), vxcpotential);
1172 } else if (initial_guess_ == "dimer_guess") {
1173 // Closed-shell dimer: the block-diagonal guess is restricted as long
1174 // as both monomers carry identical alpha and beta MOs (restricted,
1175 // closed-shell monomers). Open-shell monomers need the UKS path.
1176 Orbitals dimer_guess_orb = BuildDimerGuessFromMonomerFiles(orb.QMAtoms());
1177 if (dimer_guess_orb.getNumberOfAlphaElectrons() !=
1178 dimer_guess_orb.getNumberOfBetaElectrons() ||
1179 !(dimer_guess_orb.MOs().eigenvectors() ==
1180 dimer_guess_orb.MOs_beta().eigenvectors())) {
1181 throw std::runtime_error(
1182 "initial_guess=dimer_guess: this is a restricted (closed-shell) "
1183 "calculation, but at least one monomer .orb file is open-shell "
1184 "or unrestricted. Use force_uks_path to run the dimer "
1185 "unrestricted with this guess.");
1186 }
1187 if (dimer_guess_orb.getNumberOfAlphaElectrons() != num_alpha_electrons_) {
1188 throw std::runtime_error(
1189 "initial_guess=dimer_guess: the monomers have " +
1190 std::to_string(2 * dimer_guess_orb.getNumberOfAlphaElectrons()) +
1191 " electrons in total, but this calculation has " +
1192 std::to_string(2 * num_alpha_electrons_) +
1193 ". Check the monomer charges against the dimer charge.");
1194 }
1195 MOs = dimer_guess_orb.MOs();
1197 } else {
1198 throw std::runtime_error("Initial guess method not known/implemented");
1199 }
1200 }
1201
1202 ConvergenceAcc::SpinDensity spin_dmat =
1203 conv_accelerator_.DensityMatrixSpinResolved(MOs);
1204 Eigen::MatrixXd Dmat = spin_dmat.total();
1205
1207 << TimeStamp() << " Guess Matrix gives N=" << std::setprecision(9)
1208 << Dmat.cwiseProduct(dftAOoverlap_.Matrix()).sum() << " electrons."
1209 << std::flush;
1210
1211 // Closed-shell energy Hessian for second-order (TRAH) SCF steps:
1212 // d^2E/dx dx = 4 [F_vv X - X F_oo + C_v^T G[dP] C_o], with X(a, i) = x_ia,
1213 // dP = 2 (C_v X C_o^T + C_o X^T C_v^T) and G the response of J, K and
1214 // V_xc, as in StaticResponse (there in canonical orbitals).
1216 conv_accelerator_.setOrbitalHessian(
1217 [this, &vxcpotential](const tools::EigenSystem& mos,
1218 const Eigen::MatrixXd& F,
1219 const Eigen::MatrixXd& X) {
1220 return RKSOrbitalHessian(vxcpotential, mos, F, X);
1221 });
1222 }
1223
1225 << TimeStamp() << " STARTING SCF cycle" << std::flush;
1227 << " ----------------------------------------------"
1228 "----------------------------"
1229 << std::flush;
1230
1231 Eigen::MatrixXd J = Eigen::MatrixXd::Zero(Dmat.rows(), Dmat.cols());
1232 Eigen::MatrixXd K;
1233 if (ScaHFX_ > 0) {
1234 K = Eigen::MatrixXd::Zero(Dmat.rows(), Dmat.cols());
1235 }
1236
1237 double start_incremental_F_threshold = 1e-4;
1238 if (!auxbasis_name_.empty()) {
1239 start_incremental_F_threshold = 0.0; // Disable if RI is used
1240 }
1241 IncrementalFockBuilder incremental_fock(*pLog_, start_incremental_F_threshold,
1243 incremental_fock.Configure(Dmat);
1244 conv_accelerator_.StartNewSCF();
1245
1246 for (Index this_iter = 0; this_iter < max_iter_; this_iter++) {
1247 XTP_LOG(Log::error, *pLog_) << std::flush;
1248 XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Iteration " << this_iter + 1
1249 << " of " << max_iter_ << std::flush;
1250
1251 Mat_p_Energy e_vxc = [&]() {
1252 auto t = timings_.Measure("Vxc");
1253 return vxcpotential.IntegrateVXC(Dmat);
1254 }();
1256 << TimeStamp() << " Filled DFT Vxc matrix " << std::flush;
1257
1258 Eigen::MatrixXd H = H0.matrix() + e_vxc.matrix();
1259 double Eone = Dmat.cwiseProduct(H0.matrix()).sum();
1260 double Etwo = e_vxc.energy();
1261 double exx = 0.0;
1262
1263 incremental_fock.Start(this_iter, conv_accelerator_.getDIIsError());
1264 incremental_fock.resetMatrices(J, K, Dmat);
1265 incremental_fock.UpdateCriteria(conv_accelerator_.getDIIsError(),
1266 this_iter);
1267
1268 double integral_error =
1269 std::min(conv_accelerator_.getDIIsError() * 1e-5, 1e-5);
1270
1271 if (ScaHFX_ > 0) {
1272 std::array<Eigen::MatrixXd, 2> both = CalcERIs_EXX(
1273 MOs.eigenvectors(), incremental_fock.getDmat_diff(), integral_error);
1274 J += both[0];
1275 H += J;
1276 Etwo += 0.5 * Dmat.cwiseProduct(J).sum();
1277 K += both[1];
1278 H += 0.5 * ScaHFX_ * K;
1279 exx = 0.25 * ScaHFX_ * Dmat.cwiseProduct(K).sum();
1281 << TimeStamp() << " Filled F+K matrix " << std::flush;
1282 } else {
1283 J += CalcERIs(incremental_fock.getDmat_diff(), integral_error);
1285 << TimeStamp() << " Filled F matrix " << std::flush;
1286 H += J;
1287 Etwo += 0.5 * Dmat.cwiseProduct(J).sum();
1288 }
1289
1290 Etwo += exx;
1291 double totenergy = Eone + H0.energy() + Etwo;
1292
1293 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " Single particle energy "
1294 << std::setprecision(12) << Eone << std::flush;
1295 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " Two particle energy "
1296 << std::setprecision(12) << Etwo << std::flush;
1298 << TimeStamp() << std::setprecision(12) << " Local Exc contribution "
1299 << e_vxc.energy() << std::flush;
1300 if (ScaHFX_ > 0) {
1302 << TimeStamp() << std::setprecision(12)
1303 << " Non local Ex contribution " << exx << std::flush;
1304 }
1306 << TimeStamp() << " Total Energy " << std::setprecision(12) << totenergy
1307 << std::flush;
1308
1309 {
1310 auto t = timings_.Measure("DIIS/ADIIS + diagonalisation");
1311 Dmat = conv_accelerator_.Iterate(Dmat, H, MOs, totenergy);
1312 }
1313 incremental_fock.UpdateDmats(Dmat, conv_accelerator_.getDIIsError(),
1314 this_iter);
1315
1317
1318 if (num_docc_ + num_socc_alpha_ > 0 &&
1319 num_docc_ + num_socc_alpha_ < MOs.eigenvalues().size()) {
1321 << "\t\tGAP "
1324 << std::flush;
1325 }
1326
1327 if (conv_accelerator_.isConverged()) {
1329 << TimeStamp() << " Total Energy has converged to "
1330 << std::setprecision(9) << conv_accelerator_.getDeltaE()
1331 << "[Ha] after " << this_iter + 1
1332 << " iterations. DIIS error is converged up to "
1333 << conv_accelerator_.getDIIsError() << std::flush;
1335 << TimeStamp() << " Final Single Point Energy "
1336 << std::setprecision(12) << totenergy << " Ha" << std::flush;
1337 XTP_LOG(Log::error, *pLog_) << TimeStamp() << std::setprecision(12)
1338 << " Final Local Exc contribution "
1339 << e_vxc.energy() << " Ha" << std::flush;
1340 if (ScaHFX_ > 0) {
1341 XTP_LOG(Log::error, *pLog_) << TimeStamp() << std::setprecision(12)
1342 << " Final Non Local Ex contribution "
1343 << exx << " Ha" << std::flush;
1344 }
1345
1347
1348 Index nuclear_charge = 0;
1349 for (const QMAtom& atom : orb.QMAtoms()) {
1350 nuclear_charge += atom.getNuccharge();
1351 }
1352
1353 orb.setQMEnergy(totenergy);
1354 orb.MOs() = MOs;
1358 orb.setChargeAndSpin(
1359 nuclear_charge - numofelectrons_,
1361
1362 if (compute_forces_) {
1363 auto t = timings_.Measure("forces");
1364 ComputeAndStoreForces(orb, Dmat, vxcpotential);
1365 }
1366
1367 CalcElDipole(orb);
1368 return true;
1369 } else if (this_iter == max_iter_ - 1) {
1371 << TimeStamp() << " DFT calculation has not converged after "
1372 << max_iter_
1373 << " iterations. Use more iterations or another convergence "
1374 "acceleration scheme."
1375 << std::flush;
1376 return false;
1377 }
1378 }
1379
1380 return true;
1381}
1382
1383// Unrestricted SCF loop. The alpha and beta channels are iterated through
1384// separate Fock matrices
1385//
1386// F^alpha = H0 + J[P^alpha + P^beta] + V_xc^alpha + K^alpha
1387// F^beta = H0 + J[P^alpha + P^beta] + V_xc^beta + K^beta,
1388//
1389// while the total energy uses the spin-summed one-electron and Coulomb terms
1390// together with spin-resolved XC and exact-exchange contributions.
1392 const Vxc_Potential<Vxc_Grid>& vxcpotential) {
1393 tools::EigenSystem MOs_alpha;
1394 tools::EigenSystem MOs_beta;
1395
1396 MOs_alpha.eigenvalues() = Eigen::VectorXd::Zero(H0.cols());
1397 MOs_alpha.eigenvectors() = Eigen::MatrixXd::Zero(H0.rows(), H0.cols());
1398 MOs_beta.eigenvalues() = Eigen::VectorXd::Zero(H0.cols());
1399 MOs_beta.eigenvectors() = Eigen::MatrixXd::Zero(H0.rows(), H0.cols());
1400
1401 UKSConvergenceAcc conv_uks;
1402
1406
1410
1411 conv_uks.Configure(opt_alpha, opt_beta);
1412 conv_uks.setLogger(pLog_);
1414
1415 if (initial_guess_ == "orbfile") {
1417 << TimeStamp() << " Reading UKS guess from orbitals object/file"
1418 << std::flush;
1419
1420 MOs_alpha = orb.MOs();
1421 MOs_alpha.eigenvectors() = OrthogonalizeGuess(MOs_alpha.eigenvectors());
1422
1423 if (orb.hasBetaMOs()) {
1424 MOs_beta = orb.MOs_beta();
1425 MOs_beta.eigenvectors() = OrthogonalizeGuess(MOs_beta.eigenvectors());
1426 } else {
1428 << TimeStamp()
1429 << " Orbital file has no beta MOs, using alpha guess for beta."
1430 << std::flush;
1431 MOs_beta = MOs_alpha;
1432 }
1433 } else if (initial_guess_ == "dimer_guess") {
1435 << TimeStamp()
1436 << " Building UKS guess from two monomer .orb files (dimer_guess)"
1437 << std::flush;
1438 Orbitals dimer_guess_orb = BuildDimerGuessFromMonomerFiles(orb.QMAtoms());
1439 MOs_alpha = dimer_guess_orb.MOs();
1440 MOs_alpha.eigenvectors() = OrthogonalizeGuess(MOs_alpha.eigenvectors());
1441 MOs_beta = dimer_guess_orb.MOs_beta();
1442 MOs_beta.eigenvectors() = OrthogonalizeGuess(MOs_beta.eigenvectors());
1443 } else {
1445 << TimeStamp() << " Setup UKS Initial Guess using: " << initial_guess_
1446 << std::flush;
1447
1448 tools::EigenSystem guess;
1449 if (initial_guess_ == "independent") {
1450 guess = IndependentElectronGuess(H0);
1451 } else if (initial_guess_ == "atom") {
1452 guess = ModelPotentialGuess(H0, orb.QMAtoms(), vxcpotential);
1453 } else if (initial_guess_ == "huckel") {
1454 guess = ExtendedHuckelGuess(orb.QMAtoms());
1455 } else if (initial_guess_ == "huckel_dft") {
1456 guess = ExtendedHuckelDFTGuess(H0, orb.QMAtoms(), vxcpotential);
1457 } else {
1458 throw std::runtime_error("Initial guess method not known/implemented");
1459 }
1460
1461 MOs_alpha = guess;
1462 MOs_beta = guess;
1463 }
1464
1465 // Build the initial spin densities P^alpha and P^beta from the chosen
1466 // starting orbitals before entering the coupled UKS iterations.
1468 conv_uks.DensityMatrix(MOs_alpha, MOs_beta);
1469
1471 << TimeStamp() << " UKS guess gives Nalpha="
1472 << Dspin.alpha.cwiseProduct(dftAOoverlap_.Matrix()).sum()
1473 << " Nbeta=" << Dspin.beta.cwiseProduct(dftAOoverlap_.Matrix()).sum()
1474 << " Ntot=" << Dspin.total().cwiseProduct(dftAOoverlap_.Matrix()).sum()
1475 << std::flush;
1476
1478 << TimeStamp() << " STARTING UKS SCF cycle" << std::flush;
1480 << " ------------------------------------------------------------"
1481 << std::flush;
1482
1483 for (Index this_iter = 0; this_iter < max_iter_; ++this_iter) {
1484 XTP_LOG(Log::error, *pLog_) << std::flush;
1485 XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Iteration " << this_iter + 1
1486 << " of " << max_iter_ << std::flush;
1487
1488 Eigen::MatrixXd H_alpha = H0.matrix();
1489 Eigen::MatrixXd H_beta = H0.matrix();
1490
1491 // The Coulomb contribution depends only on the total density
1492 // P = P^alpha + P^beta, while exchange and XC remain spin resolved.
1493 const Eigen::MatrixXd D_total = Dspin.total();
1494
1495 double E_one = Dspin.alpha.cwiseProduct(H0.matrix()).sum() +
1496 Dspin.beta.cwiseProduct(H0.matrix()).sum();
1497
1498 double E_coul = 0.0;
1499 double E_xc = 0.0;
1500 double E_exx = 0.0;
1501
1502 double integral_error = std::min(conv_uks.getDIIsError() * 1e-5, 1e-5);
1503
1504 if (ScaHFX_ > 0) {
1505 std::array<Eigen::MatrixXd, 2> both_alpha = CalcERIs_EXX(
1506 Eigen::MatrixXd::Zero(0, 0), Dspin.alpha, integral_error);
1507 std::array<Eigen::MatrixXd, 2> both_beta =
1508 CalcERIs_EXX(Eigen::MatrixXd::Zero(0, 0), Dspin.beta, integral_error);
1509
1510 Eigen::MatrixXd J = both_alpha[0] + both_beta[0];
1511 Eigen::MatrixXd K_alpha = both_alpha[1];
1512 Eigen::MatrixXd K_beta = both_beta[1];
1513
1514 H_alpha += J + ScaHFX_ * K_alpha;
1515 H_beta += J + ScaHFX_ * K_beta;
1516
1517 E_coul = 0.5 * D_total.cwiseProduct(J).sum();
1518 E_exx = 0.5 * ScaHFX_ *
1519 (Dspin.alpha.cwiseProduct(K_alpha).sum() +
1520 Dspin.beta.cwiseProduct(K_beta).sum());
1521 } else {
1522 Eigen::MatrixXd J = CalcERIs(D_total, integral_error);
1523 H_alpha += J;
1524 H_beta += J;
1525 E_coul = 0.5 * D_total.cwiseProduct(J).sum();
1526 }
1527
1528 auto vxc = [&]() {
1529 auto t = timings_.Measure("Vxc");
1530 return vxcpotential.IntegrateVXCSpin(Dspin.alpha, Dspin.beta);
1531 }();
1532 H_alpha += vxc.vxc_alpha;
1533 H_beta += vxc.vxc_beta;
1534 E_xc = vxc.energy;
1535
1536 double totenergy = H0.energy() + E_one + E_coul + E_xc + E_exx;
1537
1538 // CDFT constraint potential (no-op if constraints_ is empty): adds
1539 // lambda_c * spin_alpha/beta_coefficient * W_c to the alpha/beta Fock
1540 // matrices (charge constraint: +1/+1; a spin constraint would use
1541 // +1/-1) and uses the Wu-Van Voorhis Lagrangian
1542 // E_CDFT = E_KS + sum_c lambda_c (N_c - N_c^target).
1543 if (!constraints_.empty()) {
1545 H_alpha += (c.lambda * c.spin_alpha_coefficient) * c.weight_matrix;
1546 H_beta += (c.lambda * c.spin_beta_coefficient) * c.weight_matrix;
1547 double population =
1548 c.spin_alpha_coefficient *
1549 Dspin.alpha.cwiseProduct(c.weight_matrix).sum() +
1550 c.spin_beta_coefficient *
1551 Dspin.beta.cwiseProduct(c.weight_matrix).sum();
1552 totenergy += c.lambda * (population - c.target_population);
1553 }
1554 }
1555
1556 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " One particle energy "
1557 << std::setprecision(12) << E_one << std::flush;
1558 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " Coulomb contribution "
1559 << std::setprecision(12) << E_coul << std::flush;
1560 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " XC contribution "
1561 << std::setprecision(12) << E_xc << std::flush;
1562 if (ScaHFX_ > 0) {
1564 << TimeStamp() << " EXX contribution " << std::setprecision(12)
1565 << E_exx << std::flush;
1566 }
1568 << TimeStamp() << " Total Energy " << std::setprecision(12) << totenergy
1569 << std::flush;
1570
1571 UKSConvergenceAcc::SpinFock Hspin{H_alpha, H_beta};
1572
1573 // Coupled Fock builder: both spin densities enter the Coulomb/exchange
1574 // and XC terms together, so CoupledAugmentedHessianStep/
1575 // BuildCoupledSigmaVector see the alpha-beta coupling (shared Coulomb
1576 // potential, cross-spin XC kernel). Same H0 + J/K + V_xc sequence as
1577 // H_alpha/H_beta above, so the current density reproduces them.
1578 conv_uks.setCoupledFockBuilder(
1579 [this, &H0, &vxcpotential](const Eigen::MatrixXd& alpha_new,
1580 const Eigen::MatrixXd& beta_new) {
1581 return BuildUKSFock(H0.matrix(), vxcpotential, alpha_new, beta_new);
1582 });
1583 // Analytic Hessian products (spin-polarized f_xc); without second
1584 // derivatives in libxc UKSConvergenceAcc falls back to finite
1585 // differences of the coupled Fock builder.
1586 conv_uks.setOrbitalHessian(
1587 [this, &vxcpotential](
1588 const tools::EigenSystem& mos_alpha,
1589 const tools::EigenSystem& mos_beta, const Eigen::MatrixXd& F_alpha,
1590 const Eigen::MatrixXd& F_beta, const Eigen::MatrixXd& X) {
1591 return UKSOrbitalHessian(vxcpotential, mos_alpha, mos_beta, F_alpha,
1592 F_beta, X);
1593 });
1594
1595 {
1596 auto t = timings_.Measure("DIIS/ADIIS + diagonalisation");
1597 Dspin = conv_uks.Iterate(Dspin, Hspin, MOs_alpha, MOs_beta, totenergy);
1598 }
1600 MOs_beta = MOs_alpha;
1601 Dspin.beta = Dspin.alpha;
1602 }
1603
1605 << TimeStamp()
1606 << " Nalpha=" << Dspin.alpha.cwiseProduct(dftAOoverlap_.Matrix()).sum()
1607 << " Nbeta=" << Dspin.beta.cwiseProduct(dftAOoverlap_.Matrix()).sum()
1608 << std::flush;
1609
1611 << TimeStamp() << " <Sz> = "
1612 << 0.5 * double(num_alpha_electrons_ - num_beta_electrons_)
1613 << std::flush;
1614
1615 PrintMOsUKS(MOs_alpha.eigenvalues(), MOs_beta.eigenvalues(), Log::info);
1616
1617 if (conv_uks.isConverged()) {
1618 Index nuclear_charge = 0;
1619 for (const QMAtom& atom : orb.QMAtoms()) {
1620 nuclear_charge += atom.getNuccharge();
1621 }
1622
1623 CanonicalizeOrbitalPhases(MOs_alpha);
1624 CanonicalizeOrbitalPhases(MOs_beta);
1625
1626 orb.setQMEnergy(totenergy);
1627 orb.MOs() = MOs_alpha;
1628 orb.MOs_beta() = MOs_beta;
1633 orb.setChargeAndSpin(
1634 nuclear_charge - numofelectrons_,
1636
1638 << TimeStamp() << " UKS converged after " << this_iter + 1
1639 << " iterations. Delta E=" << conv_uks.getDeltaE()
1640 << " DIIS error=" << conv_uks.getDIIsError() << std::flush;
1641
1643 << TimeStamp() << " Final Single Point Energy "
1644 << std::setprecision(12) << totenergy << " Ha" << std::flush;
1646 << TimeStamp() << std::setprecision(12) << " Final XC contribution "
1647 << E_xc << " Ha" << std::flush;
1648 if (ScaHFX_ > 0) {
1650 << TimeStamp() << std::setprecision(12)
1651 << " Final EXX contribution " << E_exx << " Ha" << std::flush;
1652 }
1653
1655 << TimeStamp() << " <Sz> = "
1656 << 0.5 * double(num_alpha_electrons_ - num_beta_electrons_)
1657 << std::flush;
1658
1659 PrintMOsUKS(MOs_alpha.eigenvalues(), MOs_beta.eigenvalues(), Log::error);
1660
1661 if (compute_forces_) {
1662 auto t = timings_.Measure("forces");
1663 ComputeAndStoreForcesUKS(orb, Dspin, MOs_alpha, MOs_beta, vxcpotential);
1664 }
1665
1666 CalcElDipole(orb);
1667 return true;
1668 }
1669
1670 if (this_iter == max_iter_ - 1) {
1672 << TimeStamp() << " UKS calculation has not converged after "
1673 << max_iter_ << " iterations." << std::flush;
1674 return false;
1675 }
1676 }
1677
1678 return false;
1679}
1680
1681// One-electron core Hamiltonian and its constant energy offset.
1682//
1683// The matrix part is
1684//
1685// H0 = T + V_nuc + V_ECP + V_ext,
1686//
1687// while the scalar energy collects all nucleus-nucleus and nucleus-external
1688// interaction terms that do not depend on the electronic density.
1690 auto h0_timer =
1691 std::make_unique<DFTTimings::Scope>(timings_, "setup: one-electron H0");
1692
1693 AOKinetic dftAOkinetic;
1694
1695 dftAOkinetic.Fill(dftbasis_);
1697 << TimeStamp() << " Filled DFT Kinetic energy matrix ." << std::flush;
1698
1699 AOMultipole dftAOESP;
1700 dftAOESP.FillPotential(dftbasis_, mol);
1702 << TimeStamp() << " Filled DFT nuclear potential matrix." << std::flush;
1703
1704 Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.Matrix();
1706 << TimeStamp() << " Constructed independent particle hamiltonian "
1707 << std::flush;
1708 double E0 = NuclearRepulsion(mol);
1709 XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Nuclear Repulsion Energy is "
1710 << std::setprecision(9) << E0 << std::flush;
1711
1712 if (!ecp_name_.empty()) {
1713 AOECP dftAOECP;
1714 dftAOECP.FillPotential(dftbasis_, ecp_);
1715 H0 += dftAOECP.Matrix();
1717 << TimeStamp() << " Filled DFT ECP matrix" << std::flush;
1718 }
1719 h0_timer.reset();
1720
1721 if (externalsites_ != nullptr) {
1722 XTP_LOG(Log::error, *pLog_) << TimeStamp() << " " << externalsites_->size()
1723 << " External sites" << std::flush;
1724 bool has_quadrupoles = std::any_of(
1725 externalsites_->begin(), externalsites_->end(),
1726 [](const std::unique_ptr<StaticSite>& s) { return s->getRank() == 2; });
1727 std::string header =
1728 " Name Coordinates[a0] charge[e] dipole[e*a0] ";
1729 if (has_quadrupoles) {
1730 header += " quadrupole[e*a0^2]";
1731 }
1732 XTP_LOG(Log::error, *pLog_) << header << std::flush;
1733 Index limit = 50;
1734 Index counter = 0;
1735 for (const std::unique_ptr<StaticSite>& site : *externalsites_) {
1736 if (counter == limit) {
1737 break;
1738 }
1739 std::string output =
1740 (boost::format(" %1$s"
1741 " %2$+1.4f %3$+1.4f %4$+1.4f"
1742 " %5$+1.4f") %
1743 site->getElement() % site->getPos()[0] % site->getPos()[1] %
1744 site->getPos()[2] % site->getCharge())
1745 .str();
1746 const Eigen::Vector3d& dipole = site->getDipole();
1747 output += (boost::format(" %1$+1.4f %2$+1.4f %3$+1.4f") % dipole[0] %
1748 dipole[1] % dipole[2])
1749 .str();
1750 if (site->getRank() > 1) {
1751 Eigen::VectorXd quadrupole = site->Q().tail<5>();
1752 output +=
1753 (boost::format(" %1$+1.4f %2$+1.4f %3$+1.4f %4$+1.4f %5$+1.4f") %
1754 quadrupole[0] % quadrupole[1] % quadrupole[2] % quadrupole[3] %
1755 quadrupole[4])
1756 .str();
1757 }
1758 XTP_LOG(Log::error, *pLog_) << output << std::flush;
1759 counter++;
1760 }
1761 if (counter == limit) {
1763 << " ... (" << externalsites_->size() - limit
1764 << " sites not displayed)\n"
1765 << std::flush;
1766 }
1767
1768 auto t = timings_.Measure("setup: external multipoles");
1769 Mat_p_Energy ext_multipoles =
1772 << TimeStamp() << " Nuclei-external site interaction energy "
1773 << std::setprecision(9) << ext_multipoles.energy() << std::flush;
1774 E0 += ext_multipoles.energy();
1775 H0 += ext_multipoles.matrix();
1776 }
1777
1779 Orbitals extdensity;
1780 extdensity.ReadFromCpt(orbfilename_);
1781 Mat_p_Energy extdensity_result = IntegrateExternalDensity(mol, extdensity);
1782 E0 += extdensity_result.energy();
1784 << TimeStamp() << " Nuclei-external density interaction energy "
1785 << std::setprecision(9) << extdensity_result.energy() << std::flush;
1786 H0 += extdensity_result.matrix();
1787 }
1788
1789 if (ext_potential_matrix_.size() > 0) {
1790 if (ext_potential_matrix_.rows() != H0.rows() ||
1791 ext_potential_matrix_.cols() != H0.cols()) {
1792 throw std::runtime_error(
1793 "DFTEngine: the external potential matrix does not match the DFT "
1794 "basis");
1795 }
1797 }
1798
1800
1802 << TimeStamp() << " Integrating external electric field with F[Hrt]="
1803 << extfield_.transpose() << std::flush;
1804 H0 += IntegrateExternalField(mol);
1805 }
1806
1807 if (has_ewaldgrid_) {
1809 << TimeStamp() << " Integrating external Ewald Potential" << std::flush;
1810 auto t = timings_.Measure("setup: Ewald potential on grid");
1811 Vxc_Grid ewaldgrid;
1812 ewaldgrid.GridSetup(grid_name_, mol, dftbasis_);
1813
1814 // The rebuild is required: external_ewaldgrid_ was built in QMRegion
1815 // against a local AOBasis, and a Vxc_Grid holds raw `const AOShell*`
1816 // into that basis, which now dangle. Only its coordinates and potential
1817 // values may be read (see QMRegion::ewaldgrid_).
1818 //
1819 // The grids agree only if both used the same grid name, molecule and
1820 // basis; checked, since a mismatch would silently give a wrong H0.
1821 if (ewaldgrid.getBoxesSize() != external_ewaldgrid_.getBoxesSize()) {
1822 throw std::runtime_error(
1823 "DFTEngine: the external Ewald potential grid has " +
1824 std::to_string(external_ewaldgrid_.getBoxesSize()) +
1825 " boxes but this molecule's own grid has " +
1826 std::to_string(ewaldgrid.getBoxesSize()) +
1827 ". The potential was evaluated on a different grid than the one "
1828 "being integrated over.");
1829 }
1830 // make sure the Potential values are copied from the external ewald grid to
1831 // this one
1832 for (Index i = 0; i < ewaldgrid.getBoxesSize(); ++i) {
1833 GridBox& box = ewaldgrid[i];
1834 const std::vector<double>& source =
1835 external_ewaldgrid_[i].getPotentialValues();
1836 if (Index(source.size()) != box.size()) {
1837 throw std::runtime_error("DFTEngine: box " + std::to_string(i) +
1838 " of the external Ewald "
1839 "potential grid holds " +
1840 std::to_string(source.size()) +
1841 " values for " + std::to_string(box.size()) +
1842 " grid points.");
1843 }
1844 std::vector<double>& values = box.getPotentialValues();
1845 values = source;
1846 }
1847 // The AO matrix depends on the basis, the grid and the potential values;
1848 // reuse it from the previous run if all three are the same.
1849 std::string ewald_key;
1850 if (setup_cache_ != nullptr) {
1851 double sum = 0.0;
1852 double sum2 = 0.0;
1853 Index points = 0;
1854 for (Index i = 0; i < ewaldgrid.getBoxesSize(); ++i) {
1855 for (double v : ewaldgrid[i].getPotentialValues()) {
1856 sum += v;
1857 sum2 += v * v;
1858 ++points;
1859 }
1860 }
1861 std::ostringstream key;
1862 key << std::setprecision(17) << RISetupKey() << "|" << grid_name_ << "|"
1863 << points << "|" << sum << "|" << sum2;
1864 ewald_key = key.str();
1865 }
1866 if (setup_cache_ != nullptr && setup_cache_->ewald_key == ewald_key &&
1867 setup_cache_->ewald_matrix.rows() == dftbasis_.AOBasisSize()) {
1868 H0 += setup_cache_->ewald_matrix;
1870 << TimeStamp()
1871 << " Reusing the Ewald potential matrix of the previous run"
1872 << std::flush;
1873 } else {
1874 Ewald_Potential<Vxc_Grid> EwaldIntegration(ewaldgrid);
1875 const Eigen::MatrixXd ewald_matrix =
1876 EwaldIntegration.IntegrateEwald(dftbasis_.AOBasisSize()).matrix();
1877 H0 += ewald_matrix;
1878 if (setup_cache_ != nullptr) {
1879 setup_cache_->ewald_key = ewald_key;
1880 setup_cache_->ewald_matrix = ewald_matrix;
1881 }
1882 }
1883
1884 // The grid reaches the electron density only. The nuclei sit in the
1885 // same potential, and their share arrives as a scalar -- the same
1886 // pairing IntegrateExternalMultipoles has with ExternalRepulsion.
1888 << TimeStamp() << " Nuclei-external Ewald potential energy "
1889 << std::setprecision(9) << ewald_nuclear_energy_ << std::flush;
1891 }
1892
1893 return Mat_p_Energy(E0, H0);
1894}
1895
1896std::string DFTEngine::RISetupKey() const {
1897 std::ostringstream key;
1898 key << std::setprecision(17) << dftbasis_name_ << "|" << auxbasis_name_ << "|"
1900 for (const AOBasis* basis : {&dftbasis_, &auxbasis_}) {
1901 key << "|";
1902 for (const AOShell& shell : *basis) {
1903 key << static_cast<int>(shell.getL()) << "," << shell.getSize() << ","
1904 << shell.getPos().x() << "," << shell.getPos().y() << ","
1905 << shell.getPos().z() << ";";
1906 }
1907 }
1908 return key.str();
1909}
1910
1911void DFTEngine::setSCFToleranceFloor(double energy, double error) {
1912 if (energy <= conv_opt_.Econverged && error <= conv_opt_.error_converged) {
1913 return;
1914 }
1915 conv_opt_.Econverged = std::max(conv_opt_.Econverged, energy);
1916 conv_opt_.error_converged = std::max(conv_opt_.error_converged, error);
1918 << TimeStamp() << " SCF thresholds for this run: Delta E "
1919 << conv_opt_.Econverged << " Ha, DIIS error " << conv_opt_.error_converged
1920 << " (set by the caller)" << std::flush;
1921}
1922
1924 if (setup_cache_ == nullptr || auxbasis_name_.empty() ||
1925 ERIs_.AuxSize() == 0) {
1926 return;
1927 }
1928 setup_cache_->eris = std::move(ERIs_);
1929 setup_cache_->eris_key = eris_key_;
1930 setup_cache_->has_eris = true;
1931}
1932
1933// Precompute SCF-invariant matrices: overlap for the generalized eigenvalue
1934// problem and the RI/4c electron-repulsion backend that later yields J[P] and
1935// K[P].
1937 auto overlap_timer =
1938 std::make_unique<DFTTimings::Scope>(timings_, "setup: overlap, S^-1/2");
1941 << TimeStamp() << " Filled DFT Overlap matrix." << std::flush;
1942
1943 conv_opt_.numberofelectrons = numofelectrons_;
1944 conv_opt_.number_alpha_electrons = num_alpha_electrons_;
1945 conv_opt_.number_beta_electrons = num_beta_electrons_;
1949 conv_accelerator_.Configure(conv_opt_);
1950 conv_accelerator_.setLogger(pLog_);
1952 conv_accelerator_.PrintConfigOptions();
1953 overlap_timer.reset();
1954
1955 if (!auxbasis_name_.empty() && setup_cache_ != nullptr &&
1956 setup_cache_->has_eris && setup_cache_->eris_key == RISetupKey()) {
1957 // same basis sets and geometry as the previous run (QM/MM iteration)
1958 ERIs_ = std::move(setup_cache_->eris);
1959 setup_cache_->has_eris = false;
1960 eris_key_ = setup_cache_->eris_key;
1962 << TimeStamp()
1963 << " Reusing the RI integrals of the previous run (same basis sets "
1964 "and geometry)"
1965 << std::flush;
1966 } else if (!auxbasis_name_.empty()) {
1967 // prepare invariant part of electron repulsion integrals
1968 auto ri_start = DFTTimings::Clock::now();
1969 if (setup_cache_ != nullptr) {
1970 setup_cache_->has_eris = false;
1971 setup_cache_->eris = ERIs(); // free a stale tensor before building
1973 }
1975 double ri_seconds =
1976 std::chrono::duration<double>(DFTTimings::Clock::now() - ri_start)
1977 .count();
1978 timings_.Add("setup: RI metric V^-1/2", ERIs_.MetricSeconds());
1979 timings_.Add("setup: RI 3c integrals", ri_seconds - ERIs_.MetricSeconds());
1981 << TimeStamp() << " Inverted AUX Coulomb matrix, removed "
1982 << ERIs_.Removedfunctions() << " functions from aux basis"
1983 << std::flush;
1985 << TimeStamp()
1986 << " Setup invariant parts of Electron Repulsion integrals "
1987 << std::flush;
1988 } else {
1990 << TimeStamp() << " Calculating 4c diagonals. " << std::flush;
1991 auto t = timings_.Measure("setup: 4c Schwarz screening");
1992 ERIs_.Initialize_4c(dftbasis_);
1994 << TimeStamp() << " Calculated 4c diagonals. " << std::flush;
1995 }
1996
1997 return;
1998}
1999
2000namespace {
2001// Spherically averaged atom SCF used for the atomic guess and the
2002// Hirshfeld reference densities.
2003//
2004// Averaged over rotations, an operator on one atom keeps, between two
2005// shells of equal l, (trace / (2l+1)) times the identity and nothing
2006// between different l. The averaged problem therefore separates into one
2007// small "radial" problem per l over the shells of that l, whose levels are
2008// (2l+1)-fold degenerate. Electrons are filled into these levels by aufbau;
2009// a partly filled level holds them spread evenly over its 2l+1 components.
2010// The density is spherical by construction, so there is no orientation of
2011// a partly filled shell to choose and no symmetry breaking to converge
2012// through (with integer occupation of the individual orbitals, an open p
2013// or d shell made the SCF stall or oscillate).
2014class SphericalAtomSCF {
2015 public:
2016 explicit SphericalAtomSCF(const AOBasis& basis) : n_(basis.AOBasisSize()) {
2017 for (const AOShell& shell : basis) {
2018 const Index l = static_cast<Index>(shell.getL());
2019 Index g = 0;
2020 while (g < Index(l_.size()) && l_[g] != l) {
2021 ++g;
2022 }
2023 if (g == Index(l_.size())) {
2024 l_.push_back(l);
2025 starts_.emplace_back();
2026 }
2027 starts_[g].push_back(shell.getStartIndex());
2028 }
2029 }
2030
2031 Index Groups() const { return Index(l_.size()); }
2032
2034 Eigen::MatrixXd Reduce(const Eigen::MatrixXd& full, Index g) const {
2035 const std::vector<Index>& st = starts_[g];
2036 const Index size = 2 * l_[g] + 1;
2037 Eigen::MatrixXd red(st.size(), st.size());
2038 for (Index i = 0; i < Index(st.size()); ++i) {
2039 for (Index j = 0; j < Index(st.size()); ++j) {
2040 red(i, j) = full.block(st[i], st[j], size, size).trace() / double(size);
2041 }
2042 }
2043 return red;
2044 }
2045
2048 Eigen::MatrixXd Expand(const std::vector<Eigen::MatrixXd>& red) const {
2049 Eigen::MatrixXd full = Eigen::MatrixXd::Zero(n_, n_);
2050 for (Index g = 0; g < Groups(); ++g) {
2051 const std::vector<Index>& st = starts_[g];
2052 const Index size = 2 * l_[g] + 1;
2053 for (Index i = 0; i < Index(st.size()); ++i) {
2054 for (Index j = 0; j < Index(st.size()); ++j) {
2055 full.block(st[i], st[j], size, size)
2056 .diagonal()
2057 .setConstant(red[g](i, j));
2058 }
2059 }
2060 }
2061 return full;
2062 }
2063
2066 std::vector<Eigen::MatrixXd> Density(
2067 const std::vector<Eigen::MatrixXd>& fock,
2068 const std::vector<Eigen::MatrixXd>& overlap,
2069 const std::vector<Eigen::VectorXd>& occupation) const {
2070 std::vector<Eigen::MatrixXd> dens(Groups());
2071 for (Index g = 0; g < Groups(); ++g) {
2072 Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(fock[g],
2073 overlap[g]);
2074 const Index nocc = occupation[g].size();
2075 const Eigen::MatrixXd c = es.eigenvectors().leftCols(nocc);
2076 dens[g] = c * (occupation[g] / double(2 * l_[g] + 1)).asDiagonal() *
2077 c.transpose();
2078 }
2079 return dens;
2080 }
2081
2084 std::vector<Eigen::VectorXd> AufbauOccupation(
2085 const std::vector<Eigen::MatrixXd>& fock,
2086 const std::vector<Eigen::MatrixXd>& overlap, double nelectrons) const {
2087 struct Level {
2088 double energy;
2089 Index group;
2090 Index index;
2091 };
2092 std::vector<Level> levels;
2093 std::vector<Eigen::VectorXd> occ(Groups());
2094 for (Index g = 0; g < Groups(); ++g) {
2095 Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(
2096 fock[g], overlap[g], Eigen::EigenvaluesOnly);
2097 occ[g] = Eigen::VectorXd::Zero(es.eigenvalues().size());
2098 for (Index k = 0; k < es.eigenvalues().size(); ++k) {
2099 levels.push_back({es.eigenvalues()(k), g, k});
2100 }
2101 }
2102 std::stable_sort(
2103 levels.begin(), levels.end(),
2104 [](const Level& a, const Level& b) { return a.energy < b.energy; });
2105 double left = nelectrons;
2106 for (const Level& lev : levels) {
2107 const double take = std::clamp(left, 0.0, double(2 * l_[lev.group] + 1));
2108 occ[lev.group](lev.index) = take;
2109 left -= take;
2110 }
2111 return occ;
2112 }
2113
2117 bool OccupationFromSubshells(
2118 const std::vector<std::array<double, 3>>& subshells,
2119 const std::vector<Eigen::MatrixXd>& overlap,
2120 std::vector<Eigen::VectorXd>& occ) const {
2121 occ.assign(Groups(), Eigen::VectorXd());
2122 for (Index g = 0; g < Groups(); ++g) {
2123 occ[g] = Eigen::VectorXd::Zero(overlap[g].rows());
2124 }
2125 for (const auto& sub : subshells) {
2126 const Index l = Index(sub[0]);
2127 const Index k = Index(sub[1]);
2128 Index g = 0;
2129 while (g < Groups() && l_[g] != l) {
2130 ++g;
2131 }
2132 if (g == Groups() || k >= occ[g].size()) {
2133 return false;
2134 }
2135 occ[g](k) += sub[2];
2136 }
2137 return true;
2138 }
2139
2140 private:
2141 Index n_;
2142 std::vector<Index> l_;
2143 std::vector<std::vector<Index>> starts_;
2144};
2145
2146// Pulay DIIS on a flattened Fock vector with a flattened error vector.
2147class SimpleDIIS {
2148 public:
2149 explicit SimpleDIIS(Index maxhist) : maxhist_(maxhist) {}
2150
2151 Eigen::VectorXd Extrapolate(const Eigen::VectorXd& fock,
2152 const Eigen::VectorXd& error) {
2153 focks_.push_back(fock);
2154 errors_.push_back(error);
2155 if (Index(focks_.size()) > maxhist_) {
2156 focks_.erase(focks_.begin());
2157 errors_.erase(errors_.begin());
2158 }
2159 const Index m = Index(focks_.size());
2160 if (m < 2) {
2161 return fock;
2162 }
2163 Eigen::MatrixXd b = Eigen::MatrixXd::Zero(m + 1, m + 1);
2164 for (Index i = 0; i < m; ++i) {
2165 for (Index j = 0; j <= i; ++j) {
2166 b(i, j) = b(j, i) = errors_[i].dot(errors_[j]);
2167 }
2168 b(i, m) = b(m, i) = -1.0;
2169 }
2170 // Scale the error overlaps to order one: near convergence they are
2171 // ~1e-12 next to the -1 constraint entries, and a rank-revealing solver
2172 // would treat the whole block as zero (the extrapolation then stalls).
2173 // The scale only changes the Lagrange multiplier, not the coefficients.
2174 const double scale = b.topLeftCorner(m, m).diagonal().maxCoeff();
2175 if (scale > 0.0) {
2176 b.topLeftCorner(m, m) /= scale;
2177 }
2178 Eigen::VectorXd rhs = Eigen::VectorXd::Zero(m + 1);
2179 rhs(m) = -1.0;
2180 const Eigen::VectorXd x = b.colPivHouseholderQr().solve(rhs);
2181 if (!x.allFinite()) {
2182 return fock;
2183 }
2184 Eigen::VectorXd result = Eigen::VectorXd::Zero(fock.size());
2185 for (Index i = 0; i < m; ++i) {
2186 result += x(i) * focks_[i];
2187 }
2188 return result;
2189 }
2190
2191 private:
2192 Index maxhist_;
2193 std::vector<Eigen::VectorXd> focks_;
2194 std::vector<Eigen::VectorXd> errors_;
2195};
2196
2197// Valence subshells of a neutral atom for the spherical atom SCF, as
2198// {l, k, alpha electrons, beta electrons}, k counting the subshells of that
2199// l from the lowest valence one. Subshells are filled by the Madelung (n+l,
2200// then n) rule; the ncore electrons an ECP replaces are taken from the
2201// lowest subshells in (n, l) order (def2: 28 = 1s-3d, 46, 60 = up to 4f,
2202// ...). Every subshell holds alpha and beta electrons equally except that
2203// alpha - beta = nalpha - nbeta is put into the open subshells, highest
2204// first. Empty if the ECP core does not end at a subshell boundary or the
2205// spin difference does not fit.
2206std::vector<std::array<double, 4>> ValenceConfiguration(Index z, Index ncore,
2207 Index nalpha,
2208 Index nbeta) {
2209 struct Sub {
2210 Index n;
2211 Index l;
2212 double electrons;
2213 };
2214 std::vector<Sub> subs;
2215 Index left = z;
2216 for (Index sum = 1; left > 0; ++sum) {
2217 for (Index l = (sum - 1) / 2; l >= 0 && left > 0; --l) {
2218 const Index take = std::min(left, 2 * (2 * l + 1));
2219 subs.push_back({sum - l, l, double(take)});
2220 left -= take;
2221 }
2222 }
2223 std::stable_sort(subs.begin(), subs.end(), [](const Sub& a, const Sub& b) {
2224 return a.n < b.n || (a.n == b.n && a.l < b.l);
2225 });
2226 Index removed = 0;
2227 std::size_t first = 0;
2228 while (first < subs.size() && removed < ncore) {
2229 removed += Index(subs[first].electrons);
2230 ++first;
2231 }
2232 if (removed != ncore) {
2233 return {};
2234 }
2235 std::vector<std::array<double, 4>> result;
2236 for (std::size_t i = first; i < subs.size(); ++i) {
2237 Index k = 0;
2238 for (std::size_t j = first; j < i; ++j) {
2239 k += (subs[j].l == subs[i].l) ? 1 : 0;
2240 }
2241 result.push_back({double(subs[i].l), double(k), 0.5 * subs[i].electrons,
2242 0.5 * subs[i].electrons});
2243 }
2244 // spin polarisation into the open subshells, last filled first
2245 double excess = 0.5 * double(nalpha - nbeta);
2246 for (auto it = result.rbegin(); it != result.rend() && excess > 0.0; ++it) {
2247 const double capacity = double(2 * Index((*it)[0]) + 1);
2248 const double move = std::min(excess, capacity - (*it)[2]);
2249 if (move > 0.0 && (*it)[3] >= move) {
2250 (*it)[2] += move;
2251 (*it)[3] -= move;
2252 excess -= move;
2253 }
2254 }
2255 if (excess > 1e-12) {
2256 return {};
2257 }
2258 return result;
2259}
2260
2261// Hund's-rule ground-state (alpha, beta) electron counts for the s/p-block
2262// elements H-Ca, Ga-Kr and In-Xe. d- and f-block elements are not covered:
2263// the d^n s^2 vs d^(n+1) s^1 competition is functional-dependent (CP2K's
2264// ATOM code likewise requires explicit occupations). Returns std::nullopt
2265// for those, and callers fall back to the parity split.
2266//
2267// Aufbau order 1s,2s,2p,3s,3p,4s,3d,4p,5s,4d,5p with Hund's rule in the
2268// open p shell: p^n gives n alpha for n <= 3, and 3 alpha + (n-3) beta for
2269// n > 3.
2270std::optional<std::pair<Index, Index>> HundsRuleAlphaBetaElectrons(
2271 Index nuclear_charge) {
2272 switch (nuclear_charge) {
2273 case 1:
2274 return std::make_pair(1, 0); // H: 1s1
2275 case 2:
2276 return std::make_pair(1, 1); // He: 1s2
2277 case 3:
2278 return std::make_pair(2, 1); // Li: [He] 2s1
2279 case 4:
2280 return std::make_pair(2, 2); // Be: 2s2
2281 case 5:
2282 return std::make_pair(3, 2); // B: 2p1
2283 case 6:
2284 return std::make_pair(4, 2); // C: 2p2 (2a)
2285 case 7:
2286 return std::make_pair(5, 2); // N: 2p3 (3a)
2287 case 8:
2288 return std::make_pair(5, 3); // O: 2p4 (3a+1b)
2289 case 9:
2290 return std::make_pair(5, 4); // F: 2p5 (3a+2b)
2291 case 10:
2292 return std::make_pair(5, 5); // Ne: 2p6
2293 case 11:
2294 return std::make_pair(6, 5); // Na: [Ne] 3s1
2295 case 12:
2296 return std::make_pair(6, 6); // Mg: 3s2
2297 case 13:
2298 return std::make_pair(7, 6); // Al: 3p1
2299 case 14:
2300 return std::make_pair(8, 6); // Si: 3p2 (2a)
2301 case 15:
2302 return std::make_pair(9, 6); // P: 3p3 (3a)
2303 case 16:
2304 return std::make_pair(9, 7); // S: 3p4 (3a+1b)
2305 case 17:
2306 return std::make_pair(9, 8); // Cl: 3p5 (3a+2b)
2307 case 18:
2308 return std::make_pair(9, 9); // Ar: 3p6
2309 case 19:
2310 return std::make_pair(10, 9); // K: [Ar] 4s1
2311 case 20:
2312 return std::make_pair(10, 10); // Ca: 4s2
2313 // 21-30 (Sc-Zn): 3d block, not covered.
2314 case 31:
2315 return std::make_pair(16, 15); // Ga: [Zn] 4p1
2316 case 32:
2317 return std::make_pair(17, 15); // Ge: 4p2 (2a)
2318 case 33:
2319 return std::make_pair(18, 15); // As: 4p3 (3a)
2320 case 34:
2321 return std::make_pair(18, 16); // Se: 4p4 (3a+1b)
2322 case 35:
2323 return std::make_pair(18, 17); // Br: 4p5 (3a+2b)
2324 case 36:
2325 return std::make_pair(18, 18); // Kr: 4p6
2326 // 39-48 (Y-Cd): 4d block, not covered.
2327 case 49:
2328 return std::make_pair(25, 24); // In: [Cd] 5p1
2329 case 50:
2330 return std::make_pair(26, 24); // Sn: 5p2 (2a)
2331 case 51:
2332 return std::make_pair(27, 24); // Sb: 5p3 (3a)
2333 case 52:
2334 return std::make_pair(27, 25); // Te: 5p4 (3a+1b)
2335 case 53:
2336 return std::make_pair(27, 26); // I: 5p5 (3a+2b)
2337 case 54:
2338 return std::make_pair(27, 27); // Xe: 5p6
2339 default:
2340 return std::nullopt;
2341 }
2342}
2343} // namespace
2344
2346 const QMAtom& uniqueAtom, bool use_hunds_rule_occupation) const {
2347 bool with_ecp = !ecp_name_.empty();
2348 if (uniqueAtom.getElement() == "H" || uniqueAtom.getElement() == "He") {
2349 with_ecp = false;
2350 }
2351
2352 QMMolecule atom = QMMolecule("individual_atom", 0);
2353 atom.push_back(uniqueAtom);
2354
2355 BasisSet basisset;
2356 basisset.Load(dftbasis_name_);
2357 AOBasis dftbasis;
2358 dftbasis.Fill(basisset, atom);
2359 Vxc_Grid grid;
2360 grid.GridSetup(grid_name_, atom, dftbasis);
2361 Vxc_Potential<Vxc_Grid> gridIntegration(grid);
2362 gridIntegration.setXCfunctional(xc_functional_name_);
2363
2364 ECPAOBasis ecp;
2365 if (with_ecp) {
2366 ECPBasisSet ecps;
2367 ecps.Load(ecp_name_);
2368 ecp.Fill(ecps, atom);
2369 }
2370
2371 // Electrons of the neutral atom that the basis describes: without the
2372 // core an ECP replaces (ecp.Fill sets it on the atom in `atom`, not on
2373 // uniqueAtom, which therefore must not be used here).
2374 const Index z = uniqueAtom.getElementNumber();
2375 const Index ncore = z - atom[0].getNuccharge();
2376 const Index numofelectrons = atom[0].getNuccharge();
2377 Index alpha_e = 0;
2378 Index beta_e = 0;
2379
2380 // Total alpha/beta split. The SAD guess (AtomicGuess) uses the
2381 // parity-based split; the Hirshfeld reference densities of CDFT ask for
2382 // the Hund's-rule ground state (use_hunds_rule_occupation). Either way
2383 // the atom is spherical and its open subshells fractionally occupied.
2384 if (use_hunds_rule_occupation) {
2385 auto hunds_rule = HundsRuleAlphaBetaElectrons(z);
2386 if (hunds_rule.has_value()) {
2387 // the ECP core is closed-shell
2388 alpha_e = hunds_rule->first - ncore / 2;
2389 beta_e = hunds_rule->second - ncore / 2;
2390 } else {
2392 << TimeStamp()
2393 << " No Hund's-rule ground-state occupation table "
2394 "entry for nuclear charge "
2395 << z
2396 << " (d/f-block elements are not covered); "
2397 "falling back to the parity-based alpha/beta split."
2398 << std::flush;
2399 use_hunds_rule_occupation = false;
2400 }
2401 }
2402 if (!use_hunds_rule_occupation) {
2403 if ((numofelectrons % 2) != 0) {
2404 alpha_e = numofelectrons / 2 + numofelectrons % 2;
2405 beta_e = numofelectrons / 2;
2406 } else {
2407 alpha_e = numofelectrons / 2;
2408 beta_e = alpha_e;
2409 }
2410 }
2411
2412 AOOverlap dftAOoverlap;
2413 AOKinetic dftAOkinetic;
2414 AOMultipole dftAOESP;
2415 AOECP dftAOECP;
2416 ERIs ERIs_atom;
2417
2418 dftAOoverlap.Fill(dftbasis);
2419 dftAOkinetic.Fill(dftbasis);
2420
2421 dftAOESP.FillPotential(dftbasis, atom);
2422 ERIs_atom.Initialize_4c(dftbasis);
2423
2424 Eigen::MatrixXd H0 = dftAOkinetic.Matrix() + dftAOESP.Matrix();
2425 if (with_ecp) {
2426 dftAOECP.FillPotential(dftbasis, ecp);
2427 H0 += dftAOECP.Matrix();
2428 }
2429
2430 if (uniqueAtom.getElement() == "H") {
2431 // One electron: the lowest orbital of H0, as before.
2432 Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(
2433 H0, dftAOoverlap.Matrix());
2434 const Eigen::VectorXd c = es.eigenvectors().col(0);
2435 return c * c.transpose();
2436 }
2437
2438 // Spherically averaged SCF with fractional occupation of open shells
2439 // (see SphericalAtomSCF).
2440 const SphericalAtomSCF sph(dftbasis);
2441 const Index ngroups = sph.Groups();
2442 using Radial = std::vector<Eigen::MatrixXd>;
2443 Radial S_red(ngroups);
2444 Radial H0_red(ngroups);
2445 // S^-1/2 of each group, to measure the error in an orthonormal basis
2446 Radial X_red(ngroups);
2447 for (Index g = 0; g < ngroups; ++g) {
2448 S_red[g] = sph.Reduce(dftAOoverlap.Matrix(), g);
2449 H0_red[g] = sph.Reduce(H0, g);
2450 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(S_red[g]);
2451 X_red[g] = es.eigenvectors() *
2452 es.eigenvalues().cwiseInverse().cwiseSqrt().asDiagonal() *
2453 es.eigenvectors().transpose();
2454 }
2455
2456 // Energy and averaged Fock matrices of the spin densities (radial)
2457 struct State {
2458 Radial Da, Db, Fa, Fb;
2459 double energy = 0.0;
2460 };
2461 // from the functional, not ScaHFX_: that member is only set in SetupVxc,
2462 // and this function is also called without it (Hirshfeld references, tests)
2463 const double scahfx =
2465 auto Build = [&](const Radial& Da, const Radial& Db) {
2466 const Eigen::MatrixXd D_alpha = sph.Expand(Da);
2467 const Eigen::MatrixXd D_beta = sph.Expand(Db);
2468 const Eigen::MatrixXd D_total = D_alpha + D_beta;
2469 Eigen::MatrixXd H_alpha = H0;
2470 Eigen::MatrixXd H_beta = H0;
2471 double e_two = 0.0;
2472 if (scahfx > 0) {
2473 std::array<Eigen::MatrixXd, 2> both_alpha =
2474 ERIs_atom.CalculateERIs_EXX_4c(D_alpha, 1e-12);
2475 std::array<Eigen::MatrixXd, 2> both_beta =
2476 ERIs_atom.CalculateERIs_EXX_4c(D_beta, 1e-12);
2477 const Eigen::MatrixXd hartree = both_alpha[0] + both_beta[0];
2478 H_alpha += hartree + scahfx * both_alpha[1];
2479 H_beta += hartree + scahfx * both_beta[1];
2480 e_two = 0.5 * D_total.cwiseProduct(hartree).sum() +
2481 0.5 * scahfx *
2482 (both_alpha[1].cwiseProduct(D_alpha).sum() +
2483 both_beta[1].cwiseProduct(D_beta).sum());
2484 } else {
2485 const Eigen::MatrixXd hartree =
2486 ERIs_atom.CalculateERIs_4c(D_total, 1e-12);
2487 H_alpha += hartree;
2488 H_beta += hartree;
2489 e_two = 0.5 * D_total.cwiseProduct(hartree).sum();
2490 }
2491 const auto vxc = gridIntegration.IntegrateVXCSpin(D_alpha, D_beta);
2492 H_alpha += vxc.vxc_alpha;
2493 H_beta += vxc.vxc_beta;
2494 State st;
2495 st.Da = Da;
2496 st.Db = Db;
2497 st.energy = D_total.cwiseProduct(H0).sum() + e_two + vxc.energy;
2498 st.Fa.resize(ngroups);
2499 st.Fb.resize(ngroups);
2500 for (Index g = 0; g < ngroups; ++g) {
2501 st.Fa[g] = sph.Reduce(H_alpha, g);
2502 st.Fb[g] = sph.Reduce(H_beta, g);
2503 }
2504 return st;
2505 };
2506 // Fixed occupation of the valence subshells (Madelung configuration); an
2507 // aufbau occupation that may change between iterations only if there is
2508 // none for this atom and basis.
2509 std::vector<Eigen::VectorXd> occ_alpha;
2510 std::vector<Eigen::VectorXd> occ_beta;
2511 bool fixed_occupation = false;
2512 {
2513 const std::vector<std::array<double, 4>> config =
2514 ValenceConfiguration(z, ncore, alpha_e, beta_e);
2515 std::vector<std::array<double, 3>> alpha_subshells;
2516 std::vector<std::array<double, 3>> beta_subshells;
2517 for (const auto& sub : config) {
2518 alpha_subshells.push_back({sub[0], sub[1], sub[2]});
2519 beta_subshells.push_back({sub[0], sub[1], sub[3]});
2520 }
2521 fixed_occupation =
2522 !config.empty() &&
2523 sph.OccupationFromSubshells(alpha_subshells, S_red, occ_alpha) &&
2524 sph.OccupationFromSubshells(beta_subshells, S_red, occ_beta);
2525 if (!fixed_occupation) {
2527 << TimeStamp() << " No subshell configuration for "
2528 << uniqueAtom.getElement()
2529 << " in this basis/ECP; atomic SCF uses aufbau occupation"
2530 << std::flush;
2531 }
2532 }
2533 auto Occupy = [&](const Radial& F, bool alpha) {
2534 if (fixed_occupation) {
2535 return sph.Density(F, S_red, alpha ? occ_alpha : occ_beta);
2536 }
2537 return sph.Density(
2538 F, S_red,
2539 sph.AufbauOccupation(F, S_red, double(alpha ? alpha_e : beta_e)));
2540 };
2541 // flattened Fock matrices and commutator errors F D S - S D F
2542 auto Flatten = [&](const State& st, Eigen::VectorXd& fock,
2543 Eigen::VectorXd& error) {
2544 Index total = 0;
2545 for (Index g = 0; g < ngroups; ++g) {
2546 total += 2 * st.Fa[g].size();
2547 }
2548 fock.resize(total);
2549 error.resize(total);
2550 Index pos = 0;
2551 for (Index spin = 0; spin < 2; ++spin) {
2552 const Radial& F = (spin == 0) ? st.Fa : st.Fb;
2553 const Radial& D = (spin == 0) ? st.Da : st.Db;
2554 for (Index g = 0; g < ngroups; ++g) {
2555 const Eigen::MatrixXd fds = F[g] * D[g] * S_red[g];
2556 const Eigen::MatrixXd err =
2557 X_red[g] * (fds - fds.transpose()) * X_red[g];
2558 const Index size = F[g].size();
2559 fock.segment(pos, size) =
2560 Eigen::Map<const Eigen::VectorXd>(F[g].data(), size);
2561 error.segment(pos, size) =
2562 Eigen::Map<const Eigen::VectorXd>(err.data(), size);
2563 pos += size;
2564 }
2565 }
2566 };
2567 auto Unflatten = [&](const Eigen::VectorXd& fock, Radial& Fa, Radial& Fb) {
2568 Index pos = 0;
2569 for (Index spin = 0; spin < 2; ++spin) {
2570 Radial& F = (spin == 0) ? Fa : Fb;
2571 for (Index g = 0; g < ngroups; ++g) {
2572 const Index rows = S_red[g].rows();
2573 F[g] = Eigen::Map<const Eigen::MatrixXd>(fock.data() + pos, rows, rows);
2574 pos += rows * rows;
2575 }
2576 }
2577 };
2578
2579 // Pulay DIIS on the averaged Fock matrices. With the occupation of each
2580 // subshell fixed, the density is a smooth function of the Fock matrix and
2581 // DIIS converges in about 5-15 iterations for H-Kr (including the 3d
2582 // metals, where aufbau occupation flips between 4s and 3d).
2583 State cur = Build(Occupy(H0_red, true), Occupy(H0_red, false));
2584 SimpleDIIS diis(8);
2585 const Index maxiter = 100;
2586 // The molecule's tolerances, but not tighter than the atom needs as a
2587 // starting density: 1e-7 is at the noise floor of the atomic integrals and
2588 // grid for the 3d metals, where DIIS then stalls.
2589 const double error_tolerance = std::max(conv_opt_.error_converged, 1e-6);
2590 const double energy_tolerance = std::max(conv_opt_.Econverged, 1e-8);
2591 double energy_old = cur.energy;
2592 bool converged = false;
2593 Index this_iter = 0;
2594 for (; this_iter < maxiter; this_iter++) {
2595 Eigen::VectorXd fock;
2596 Eigen::VectorXd error;
2597 Flatten(cur, fock, error);
2598 const double max_error = error.cwiseAbs().maxCoeff();
2600 << TimeStamp() << " Iter " << this_iter << " of " << maxiter << " Etot "
2601 << std::setprecision(12) << cur.energy << " error " << max_error
2602 << std::flush;
2603 if (this_iter > 0 && max_error < error_tolerance &&
2604 std::abs(cur.energy - energy_old) < energy_tolerance) {
2605 converged = true;
2606 break;
2607 }
2608 energy_old = cur.energy;
2609 Radial Fa(ngroups);
2610 Radial Fb(ngroups);
2611 Unflatten(diis.Extrapolate(fock, error), Fa, Fb);
2612 cur = Build(Occupy(Fa, true), Occupy(Fb, false));
2613 }
2614 if (converged) {
2616 << TimeStamp() << " Converged after " << this_iter + 1
2617 << " iterations, Etot=" << std::setprecision(12) << cur.energy
2618 << std::flush;
2619 } else {
2621 << TimeStamp() << " Not converged after " << maxiter
2622 << " iterations. Unconverged density." << std::flush;
2623 }
2624 const Radial& Da = cur.Da;
2625 const Radial& Db = cur.Db;
2626
2627 const Eigen::MatrixXd density = sph.Expand(Da) + sph.Expand(Db);
2629 << TimeStamp() << " Atomic density Matrix for " << uniqueAtom.getElement()
2630 << " gives N=" << std::setprecision(9)
2631 << density.cwiseProduct(dftAOoverlap.Matrix()).sum() << " electrons."
2632 << std::flush;
2633 return density;
2634}
2635
2636Eigen::MatrixXd DFTEngine::AtomicGuess(const QMMolecule& mol) const {
2637
2638 std::vector<std::string> elements = mol.FindUniqueElements();
2640 << TimeStamp() << " Scanning molecule of size " << mol.size()
2641 << " for unique elements" << std::flush;
2642 QMMolecule uniqueelements = QMMolecule("uniqueelements", 0);
2643 for (auto element : elements) {
2644 uniqueelements.push_back(QMAtom(0, element, Eigen::Vector3d::Zero()));
2645 }
2646
2647 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " " << uniqueelements.size()
2648 << " unique elements found" << std::flush;
2649 std::vector<Eigen::MatrixXd> uniqueatom_guesses;
2650 for (QMAtom& unique_atom : uniqueelements) {
2652 << TimeStamp() << " Calculating atom density for "
2653 << unique_atom.getElement() << std::flush;
2654 Eigen::MatrixXd dmat_unrestricted = RunAtomicDFT_unrestricted(unique_atom);
2655 uniqueatom_guesses.push_back(dmat_unrestricted);
2656 }
2657
2658 Eigen::MatrixXd guess =
2659 Eigen::MatrixXd::Zero(dftbasis_.AOBasisSize(), dftbasis_.AOBasisSize());
2660 Index start = 0;
2661 for (const QMAtom& atom : mol) {
2662 Index index = 0;
2663 for (; index < uniqueelements.size(); index++) {
2664 if (atom.getElement() == uniqueelements[index].getElement()) {
2665 break;
2666 }
2667 }
2668 Eigen::MatrixXd& dmat_unrestricted = uniqueatom_guesses[index];
2669 guess.block(start, start, dmat_unrestricted.rows(),
2670 dmat_unrestricted.cols()) = dmat_unrestricted;
2671 start += dmat_unrestricted.rows();
2672 }
2673
2674 return guess;
2675}
2676
2677std::map<std::string, Eigen::MatrixXd>
2679 std::vector<std::string> elements = mol.FindUniqueElements();
2681 << TimeStamp() << " Scanning molecule of size " << mol.size()
2682 << " for unique elements (Hirshfeld reference densities)" << std::flush;
2683
2684 std::map<std::string, Eigen::MatrixXd> reference_densities;
2685 for (const std::string& element : elements) {
2686 QMAtom unique_atom(0, element, Eigen::Vector3d::Zero());
2688 << TimeStamp() << " Calculating Hirshfeld reference density for "
2689 << element << std::flush;
2690 // Hund's-rule ground state, unlike the SAD guess in AtomicGuess.
2691 reference_densities[element] = RunAtomicDFT_unrestricted(
2692 unique_atom, /*use_hunds_rule_occupation=*/true);
2693 }
2694 return reference_densities;
2695}
2696
2697// Coupled UKS Fock matrices of the spin densities (alpha_new, beta_new):
2698// H0 + J + a_x K + V_xc, plus the CDFT constraint potential, exactly as in
2699// the EvaluateUKS loop. Used for the finite-difference Hessian products.
2701 const Eigen::MatrixXd& H0, const Vxc_Potential<Vxc_Grid>& vxcpotential,
2702 const Eigen::MatrixXd& alpha_new, const Eigen::MatrixXd& beta_new) {
2704 H_new.alpha = H0;
2705 H_new.beta = H0;
2706 constexpr double kIntegralError = 1e-8;
2707 if (ScaHFX_ > 0) {
2708 std::array<Eigen::MatrixXd, 2> both_alpha_new =
2709 CalcERIs_EXX(Eigen::MatrixXd::Zero(0, 0), alpha_new, kIntegralError);
2710 std::array<Eigen::MatrixXd, 2> both_beta_new =
2711 CalcERIs_EXX(Eigen::MatrixXd::Zero(0, 0), beta_new, kIntegralError);
2712 Eigen::MatrixXd J_new = both_alpha_new[0] + both_beta_new[0];
2713 H_new.alpha += J_new + ScaHFX_ * both_alpha_new[1];
2714 H_new.beta += J_new + ScaHFX_ * both_beta_new[1];
2715 } else {
2716 Eigen::MatrixXd J_new = CalcERIs(alpha_new + beta_new, kIntegralError);
2717 H_new.alpha += J_new;
2718 H_new.beta += J_new;
2719 }
2720 auto vxc_new = [&]() {
2721 auto t = timings_.Measure("Vxc");
2722 return vxcpotential.IntegrateVXCSpin(alpha_new, beta_new);
2723 }();
2724 H_new.alpha += vxc_new.vxc_alpha;
2725 H_new.beta += vxc_new.vxc_beta;
2727 H_new.alpha += (c.lambda * c.spin_alpha_coefficient) * c.weight_matrix;
2728 H_new.beta += (c.lambda * c.spin_beta_coefficient) * c.weight_matrix;
2729 }
2730 return H_new;
2731}
2732
2733// Closed-shell energy Hessian d^2E/dx dx (layout of trah.h) at the orbitals
2734// mos with Fock matrix F, applied to the columns of X. With X(a, i) = x_ia:
2735// (H x) = 4 [F_vv X - X F_oo + C_v^T G[dP] C_o],
2736// dP = 2 (C_v X C_o^T + C_o X^T C_v^T),
2737// G the response of J, 0.5 a_x K and V_xc (CoupledResponse).
2739 const tools::EigenSystem& mos,
2740 const Eigen::MatrixXd& F,
2741 const Eigen::MatrixXd& X) {
2742 const Index nocc = num_docc_;
2743 const Eigen::MatrixXd& C = mos.eigenvectors();
2744 const Index nvirt = C.cols() - nocc;
2745 const Eigen::MatrixXd C_occ = C.leftCols(nocc);
2746 const Eigen::MatrixXd C_virt = C.rightCols(nvirt);
2747 const Eigen::MatrixXd F_oo = C_occ.transpose() * F * C_occ;
2748 const Eigen::MatrixXd F_vv = C_virt.transpose() * F * C_virt;
2749 const Eigen::MatrixXd P0 = 2.0 * C_occ * C_occ.transpose();
2750 using RowMajor =
2751 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
2752 std::vector<Eigen::MatrixXd> U;
2753 for (Index k = 0; k < X.cols(); ++k) {
2754 const Eigen::VectorXd x = X.col(k);
2755 U.push_back(Eigen::Map<const RowMajor>(x.data(), nocc, nvirt).transpose());
2756 }
2757 const std::vector<Eigen::MatrixXd> G =
2758 CoupledResponse(vxc, P0, C_occ, C_virt, U);
2759 Eigen::MatrixXd HX(X.rows(), X.cols());
2760 for (Index k = 0; k < X.cols(); ++k) {
2761 const RowMajor R = 4.0 * (F_vv * U[std::size_t(k)] -
2762 U[std::size_t(k)] * F_oo + G[std::size_t(k)])
2763 .transpose();
2764 HX.col(k) = Eigen::Map<const Eigen::VectorXd>(R.data(), R.size());
2765 }
2766 return HX;
2767}
2768
2769// UKS energy Hessian d^2E/dx dx (layout of trah.h, alpha block first) at
2770// the orbitals mos_alpha/mos_beta with Fock matrices F_alpha/F_beta,
2771// applied to the columns of X. Per spin s, with X_s(a, i) = x_ia:
2772// (H x)_s = 2 [F_vv X_s - X_s F_oo + C_v^T G_s C_o],
2773// dP_s = C_v X_s C_o^T + C_o X_s^T C_v^T,
2774// G_s = J[dP_a + dP_b] + a_x K[dP_s] + dV_xc,s[dP_a, dP_b].
2775// The constraint potential of CDFT is in F; it has no response.
2777 const Vxc_Potential<Vxc_Grid>& vxc, const tools::EigenSystem& mos_alpha,
2778 const tools::EigenSystem& mos_beta, const Eigen::MatrixXd& F_alpha,
2779 const Eigen::MatrixXd& F_beta, const Eigen::MatrixXd& X) {
2780 using RowMajor =
2781 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
2782 struct Channel {
2783 Index nocc;
2784 Index nvirt;
2785 Eigen::MatrixXd C_occ;
2786 Eigen::MatrixXd C_virt;
2787 Eigen::MatrixXd F_oo;
2788 Eigen::MatrixXd F_vv;
2789 Eigen::MatrixXd P;
2790 };
2791 auto setup = [](const tools::EigenSystem& mos, const Eigen::MatrixXd& F,
2792 Index nocc) {
2793 Channel c;
2794 const Eigen::MatrixXd& C = mos.eigenvectors();
2795 c.nocc = nocc;
2796 c.nvirt = C.cols() - nocc;
2797 c.C_occ = C.leftCols(nocc);
2798 c.C_virt = C.rightCols(c.nvirt);
2799 c.F_oo = c.C_occ.transpose() * F * c.C_occ;
2800 c.F_vv = c.C_virt.transpose() * F * c.C_virt;
2801 c.P = c.C_occ * c.C_occ.transpose();
2802 return c;
2803 };
2804 const std::array<Channel, 2> ch = {
2805 setup(mos_alpha, F_alpha, num_alpha_electrons_),
2806 setup(mos_beta, F_beta, num_beta_electrons_)};
2807 const std::array<Index, 2> offset = {0, ch[0].nocc * ch[0].nvirt};
2808
2809 const Index ncols = X.cols();
2810 std::vector<std::array<Eigen::MatrixXd, 2>> U(
2811 static_cast<std::size_t>(ncols));
2812 std::vector<std::array<Eigen::MatrixXd, 2>> dP(
2813 static_cast<std::size_t>(ncols));
2814 for (Index k = 0; k < ncols; ++k) {
2815 for (std::size_t s = 0; s < 2; ++s) {
2816 const Channel& c = ch[s];
2817 const Eigen::VectorXd x = X.col(k).segment(offset[s], c.nocc * c.nvirt);
2818 U[std::size_t(k)][s] =
2819 Eigen::Map<const RowMajor>(x.data(), c.nocc, c.nvirt).transpose();
2820 const Eigen::MatrixXd half =
2821 c.C_virt * U[std::size_t(k)][s] * c.C_occ.transpose();
2822 dP[std::size_t(k)][s] = half + half.transpose();
2823 }
2824 }
2825 std::vector<std::array<Eigen::MatrixXd, 2>> G;
2826 {
2827 auto t = timings_.Measure("second order: f_xc (spin)");
2828 G = vxc.IntegrateFXCSpin(ch[0].P, ch[1].P, dP);
2829 }
2830 Eigen::MatrixXd HX(X.rows(), ncols);
2831 for (Index k = 0; k < ncols; ++k) {
2832 std::array<Eigen::MatrixXd, 2>& g = G[std::size_t(k)];
2833 const std::array<Eigen::MatrixXd, 2>& d = dP[std::size_t(k)];
2834 if (!auxbasis_name_.empty()) {
2835 {
2836 auto t = timings_.Measure("second order: J (RI)");
2837 const Eigen::MatrixXd J = ERIs_.CalculateERIs_3c(d[0] + d[1]);
2838 g[0] += J;
2839 g[1] += J;
2840 }
2841 if (ScaHFX_ > 0) {
2842 auto t = timings_.Measure("second order: K (RI)");
2843 for (std::size_t s = 0; s < 2; ++s) {
2844 // dP_s = 1/2 [(A + C_o)(A + C_o)^T - (A - C_o)(A - C_o)^T]
2845 const Eigen::MatrixXd A = ch[s].C_virt * U[std::size_t(k)][s];
2846 g[s] += 0.5 * ScaHFX_ *
2847 ERIs_.CalculateEXX_factors(A + ch[s].C_occ, A - ch[s].C_occ);
2848 }
2849 }
2850 } else {
2851 auto t = timings_.Measure("second order: J+K (4c)");
2852 const std::array<Eigen::MatrixXd, 2> jk_a =
2853 ERIs_.CalculateERIs_EXX_4c(d[0], 1e-12);
2854 const std::array<Eigen::MatrixXd, 2> jk_b =
2855 ERIs_.CalculateERIs_EXX_4c(d[1], 1e-12);
2856 g[0] += jk_a[0] + jk_b[0];
2857 g[1] += jk_a[0] + jk_b[0];
2858 if (ScaHFX_ > 0) {
2859 g[0] += ScaHFX_ * jk_a[1];
2860 g[1] += ScaHFX_ * jk_b[1];
2861 }
2862 }
2863 for (std::size_t s = 0; s < 2; ++s) {
2864 const Channel& c = ch[s];
2865 const Eigen::MatrixXd& u = U[std::size_t(k)][s];
2866 const RowMajor R = 2.0 * (c.F_vv * u - u * c.F_oo +
2867 c.C_virt.transpose() * g[s] * c.C_occ)
2868 .transpose();
2869 HX.col(k).segment(offset[s], c.nocc * c.nvirt) =
2870 Eigen::Map<const Eigen::VectorXd>(R.data(), R.size());
2871 }
2872 }
2873 return HX;
2874}
2875
2876std::vector<Eigen::MatrixXd> DFTEngine::CoupledResponse(
2877 const Vxc_Potential<Vxc_Grid>& vxc, const Eigen::MatrixXd& P0,
2878 const Eigen::MatrixXd& C_occ, const Eigen::MatrixXd& C_virt,
2879 const std::vector<Eigen::MatrixXd>& U,
2880 const Vxc_Potential<Vxc_Grid>::FXCKernel* fxc_kernel) {
2881 auto density = [&](const Eigen::MatrixXd& u) {
2882 const Eigen::MatrixXd half = (C_virt * u) * C_occ.transpose();
2883 return Eigen::MatrixXd(2.0 * (half + half.transpose()));
2884 };
2885 std::vector<Eigen::MatrixXd> dP;
2886 for (const Eigen::MatrixXd& u : U) {
2887 dP.push_back(density(u));
2888 }
2889 std::vector<Eigen::MatrixXd> G;
2890 {
2891 auto t = timings_.Measure("response: f_xc");
2892 G = (fxc_kernel != nullptr) ? vxc.ApplyFXC(*fxc_kernel, dP)
2893 : vxc.IntegrateFXC(P0, dP);
2894 }
2895 std::vector<Eigen::MatrixXd> result;
2896 for (std::size_t k = 0; k < U.size(); ++k) {
2897 if (!auxbasis_name_.empty()) {
2898 {
2899 auto t = timings_.Measure("response: J (RI)");
2900 G[k] += ERIs_.CalculateERIs_3c(dP[k]);
2901 }
2902 if (ScaHFX_ > 0) {
2903 auto t = timings_.Measure("response: K (RI)");
2904 const Eigen::MatrixXd A = C_virt * U[k];
2905 G[k] +=
2906 0.5 * ScaHFX_ * ERIs_.CalculateEXX_factors(A + C_occ, A - C_occ);
2907 }
2908 } else {
2909 auto t = timings_.Measure("response: J+K (4c)");
2910 const std::array<Eigen::MatrixXd, 2> jk =
2911 ERIs_.CalculateERIs_EXX_4c(dP[k], 1e-12);
2912 G[k] += jk[0];
2913 if (ScaHFX_ > 0) {
2914 G[k] += 0.5 * ScaHFX_ * jk[1];
2915 }
2916 }
2917 result.push_back(C_virt.transpose() * G[k] * C_occ);
2918 }
2919 return result;
2920}
2921
2922std::vector<Eigen::MatrixXd> DFTEngine::StaticResponse(
2923 const Orbitals& orb, const std::vector<Eigen::MatrixXd>& perturbations,
2924 double tolerance, Index max_iterations) {
2925 timings_.Reset();
2926 Orbitals work = orb;
2927 Prepare(work);
2929 throw std::runtime_error(
2930 "DFTEngine::StaticResponse: closed-shell ground states only");
2931 }
2932 const Index n_ao = dftbasis_.AOBasisSize();
2933 if (!orb.hasMOs() || orb.MOs().eigenvectors().rows() != n_ao) {
2934 throw std::runtime_error(
2935 "DFTEngine::StaticResponse: the orbitals do not belong to this basis");
2936 }
2937 const Vxc_Potential<Vxc_Grid> vxc = SetupVxc(work.QMAtoms());
2938
2939 const Index n_occ = num_docc_;
2940 const Index n_mo = orb.MOs().eigenvectors().cols();
2941 const Index n_virt = n_mo - n_occ;
2942 const Eigen::MatrixXd C_occ = orb.MOs().eigenvectors().leftCols(n_occ);
2943 const Eigen::MatrixXd C_virt = orb.MOs().eigenvectors().rightCols(n_virt);
2944 const Eigen::VectorXd& e = orb.MOs().eigenvalues();
2945 // e_a - e_i
2946 Eigen::MatrixXd diag(n_virt, n_occ);
2947 for (Index i = 0; i < n_occ; ++i) {
2948 diag.col(i) = e.tail(n_virt).array() - e(i);
2949 }
2950 if (diag.minCoeff() <= 0.0) {
2951 throw std::runtime_error(
2952 "DFTEngine::StaticResponse: no gap between occupied and virtual "
2953 "orbitals");
2954 }
2955 const Eigen::MatrixXd P0 = 2.0 * C_occ * C_occ.transpose();
2956
2957 const Index n_rhs = Index(perturbations.size());
2958 std::vector<Eigen::MatrixXd> b(static_cast<std::size_t>(n_rhs));
2959 for (Index k = 0; k < n_rhs; ++k) {
2960 const Eigen::MatrixXd& h = perturbations[std::size_t(k)];
2961 if (h.rows() != n_ao || h.cols() != n_ao) {
2962 throw std::runtime_error(
2963 "DFTEngine::StaticResponse: perturbation does not match the basis");
2964 }
2965 b[std::size_t(k)] = -(C_virt.transpose() * h * C_occ);
2966 }
2967
2968 auto density = [&](const Eigen::MatrixXd& U) {
2969 const Eigen::MatrixXd half = (C_virt * U) * C_occ.transpose();
2970 return Eigen::MatrixXd(2.0 * (half + half.transpose()));
2971 };
2972 // the orbital Hessian (A + B) applied to the U of several right-hand sides
2973 // the XC kernel at P0, once for all iterations
2975 {
2976 auto t = timings_.Measure("response: f_xc kernel");
2977 fxc_kernel = vxc.PrepareFXC(P0);
2978 }
2979 auto apply = [&](const std::vector<Eigen::MatrixXd>& U) {
2980 std::vector<Eigen::MatrixXd> result =
2981 CoupledResponse(vxc, P0, C_occ, C_virt, U, &fxc_kernel);
2982 for (std::size_t k = 0; k < U.size(); ++k) {
2983 result[k] += diag.cwiseProduct(U[k]);
2984 }
2985 return result;
2986 };
2987
2988 // Galerkin projection on one subspace shared by all right-hand sides,
2989 // grown by the preconditioned residuals (block preconditioned CG for a
2990 // symmetric positive definite Hessian); the right-hand sides profit from
2991 // each other's directions.
2992 const double kDropNorm = 1e-10;
2993 std::vector<Eigen::MatrixXd> V; // orthonormal (Frobenius)
2994 std::vector<Eigen::MatrixXd> AV; // Hessian applied to V
2995 std::vector<Eigen::MatrixXd> x(static_cast<std::size_t>(n_rhs));
2996 std::vector<Eigen::MatrixXd> r(static_cast<std::size_t>(n_rhs));
2997 std::vector<double> bnorm(static_cast<std::size_t>(n_rhs), 0.0);
2998 std::vector<Index> active;
2999 for (Index k = 0; k < n_rhs; ++k) {
3000 const std::size_t kk = std::size_t(k);
3001 bnorm[kk] = b[kk].norm();
3002 x[kk] = Eigen::MatrixXd::Zero(n_virt, n_occ);
3003 r[kk] = b[kk];
3004 if (bnorm[kk] > 0.0) {
3005 active.push_back(k);
3006 }
3007 }
3008 Index iteration = 0;
3009 while (!active.empty()) {
3010 if (iteration == max_iterations) {
3011 throw std::runtime_error(
3012 "DFTEngine::StaticResponse: CPKS did not converge in " +
3013 std::to_string(max_iterations) + " iterations");
3014 }
3015 ++iteration;
3016 // new directions: preconditioned residuals, orthonormalized against the
3017 // subspace and each other (twice, for stability)
3018 std::vector<Eigen::MatrixXd> fresh;
3019 for (Index k : active) {
3020 Eigen::MatrixXd v = r[std::size_t(k)].cwiseQuotient(diag);
3021 const double norm0 = v.norm();
3022 for (Index pass = 0; pass < 2; ++pass) {
3023 for (const Eigen::MatrixXd& u : V) {
3024 v -= u.cwiseProduct(v).sum() * u;
3025 }
3026 for (const Eigen::MatrixXd& u : fresh) {
3027 v -= u.cwiseProduct(v).sum() * u;
3028 }
3029 }
3030 const double norm = v.norm();
3031 if (norm > kDropNorm * norm0) {
3032 fresh.push_back(v / norm);
3033 }
3034 }
3035 if (fresh.empty()) {
3036 throw std::runtime_error(
3037 "DFTEngine::StaticResponse: CPKS subspace stopped growing");
3038 }
3039 const std::vector<Eigen::MatrixXd> Afresh = apply(fresh);
3040 V.insert(V.end(), fresh.begin(), fresh.end());
3041 AV.insert(AV.end(), Afresh.begin(), Afresh.end());
3042 const Index m = Index(V.size());
3043 Eigen::MatrixXd M(m, m);
3044 for (Index i = 0; i < m; ++i) {
3045 for (Index j = 0; j <= i; ++j) {
3046 M(i, j) =
3047 0.5 * (V[std::size_t(i)].cwiseProduct(AV[std::size_t(j)]).sum() +
3048 V[std::size_t(j)].cwiseProduct(AV[std::size_t(i)]).sum());
3049 M(j, i) = M(i, j);
3050 }
3051 }
3052 const Eigen::LDLT<Eigen::MatrixXd> solver(M);
3053 std::vector<Index> still;
3054 double worst = 0.0;
3055 for (Index k : active) {
3056 const std::size_t kk = std::size_t(k);
3057 Eigen::VectorXd proj(m);
3058 for (Index i = 0; i < m; ++i) {
3059 proj(i) = V[std::size_t(i)].cwiseProduct(b[kk]).sum();
3060 }
3061 const Eigen::VectorXd y = solver.solve(proj);
3062 x[kk].setZero();
3063 r[kk] = b[kk];
3064 for (Index i = 0; i < m; ++i) {
3065 x[kk] += y(i) * V[std::size_t(i)];
3066 r[kk] -= y(i) * AV[std::size_t(i)];
3067 }
3068 const double rel = r[kk].norm() / bnorm[kk];
3069 worst = std::max(worst, rel);
3070 if (rel >= tolerance) {
3071 still.push_back(k);
3072 }
3073 }
3075 << TimeStamp() << " CPKS iteration " << iteration << ": "
3076 << fresh.size() << " new directions, subspace " << m
3077 << ", largest relative residual " << worst << std::flush;
3078 active = still;
3079 }
3080
3081 std::vector<Eigen::MatrixXd> dP;
3082 for (const Eigen::MatrixXd& u : x) {
3083 dP.push_back(density(u));
3084 }
3085 timings_.Report(*pLog_, Log::error);
3086 return dP;
3087}
3088
3089std::vector<HirshfeldPartition::AtomicReference> DFTEngine::HirshfeldReferences(
3090 const QMMolecule& mol) const {
3093}
3094
3096 const QMMolecule& mol, const CDFTConstraintSpec& spec) const {
3097 std::map<std::string, Eigen::MatrixXd> reference_densities =
3099
3100 AOBasis full_dftbasis;
3101 {
3102 BasisSet basisset;
3103 basisset.Load(dftbasis_name_);
3104 full_dftbasis.Fill(basisset, mol);
3105 }
3106
3107 Vxc_Grid grid;
3108 grid.GridSetup(grid_name_, mol, full_dftbasis);
3109
3110 std::vector<HirshfeldPartition::AtomicReference> atoms =
3112 reference_densities);
3113
3115 constraint.weight_matrix = Eigen::MatrixXd::Zero(full_dftbasis.AOBasisSize(),
3116 full_dftbasis.AOBasisSize());
3117 double neutral_reference_population = 0.0;
3118 for (Index atom_index : spec.atom_indices) {
3119 if (atom_index < 0 || atom_index >= static_cast<Index>(mol.size())) {
3120 throw std::runtime_error(
3121 "BuildCDFTConstraint: cdft.indices contains atom index " +
3122 std::to_string(atom_index) + ", but this molecule only has " +
3123 std::to_string(mol.size()) +
3124 " atoms (0-based indexing -- valid range is 0.." +
3125 std::to_string(mol.size() - 1) + ").");
3126 }
3127 // Hirshfeld weights are additive, w_fragment(r) = sum_{i in fragment}
3128 // w_i(r); the neutral reference population is the sum of the nuclear
3129 // charges.
3131 atoms, atom_index, full_dftbasis, grid);
3132 neutral_reference_population +=
3133 static_cast<double>(mol[atom_index].getNuccharge());
3134 }
3135
3136 constraint.target_population =
3137 neutral_reference_population - spec.target_charge;
3138 constraint.lambda = spec.initial_lambda;
3139 constraint.spin_alpha_coefficient = 1.0;
3140 constraint.spin_beta_coefficient = 1.0;
3141
3143 << TimeStamp() << " CDFT constraint: " << spec.atom_indices.size()
3144 << " atom(s), neutral reference population="
3145 << neutral_reference_population
3146 << ", requested relative charge=" << spec.target_charge
3147 << ", absolute target population=" << constraint.target_population
3148 << std::flush;
3149
3150 return constraint;
3151}
3152
3154 // A warm start was checked in UsableAsWarmStart, against the basis the MOs
3155 // were computed in.
3156 if (initial_guess_ == "orbfile" && !warm_started_) {
3157
3158 if (orb.hasDFTbasisName()) {
3159 if (orb.getDFTbasisName() != dftbasis_name_) {
3160 throw std::runtime_error(
3161 (boost::format("Basisset Name in guess orb file "
3162 "and in dftengine option file differ %1% vs %2%") %
3164 .str());
3165 }
3166 } else {
3168 << TimeStamp()
3169 << " WARNING: "
3170 "Orbital file has no basisset information,"
3171 "using it as a guess might work or not for calculation with "
3172 << dftbasis_name_ << std::flush;
3173 }
3174 }
3175
3176 const Index target_charge = orb.getCharge();
3177 const Index multiplicity = orb.getSpin();
3178
3179 orb.setChargeAndSpin(target_charge, multiplicity);
3182
3184 orb.setXCGrid(grid_name_);
3185 orb.setScaHFX(ScaHFX_);
3186 if (!ecp_name_.empty()) {
3187 orb.setECPName(ecp_name_);
3188 }
3189 if (!auxbasis_name_.empty()) {
3191 }
3192
3193 if (initial_guess_ == "orbfile") {
3194 if (orb.hasECPName() || !ecp_name_.empty()) {
3195 if (orb.getECPName() != ecp_name_) {
3196 throw std::runtime_error(
3197 (boost::format("ECPs in orb file: %1% and options %2% differ") %
3198 orb.getECPName() % ecp_name_)
3199 .str());
3200 }
3201 }
3204 throw std::runtime_error(
3205 (boost::format("Number of electrons in guess orb file "
3206 "and in dftengine differ: "
3207 "alpha %1% vs %2%, beta %3% vs %4%.") %
3210 .str());
3211 }
3212 if (orb.getBasisSetSize() != dftbasis_.AOBasisSize()) {
3213 throw std::runtime_error(
3214 (boost::format("Number of levels in guess orb file: "
3215 "%1% and in dftengine: %2% differ.") %
3216 orb.getBasisSetSize() % dftbasis_.AOBasisSize())
3217 .str());
3218 }
3219 } else {
3222 }
3223 return;
3224}
3225
3226void DFTEngine::Prepare(Orbitals& orb, Index numofelectrons) {
3227 QMMolecule& mol = orb.QMAtoms();
3228
3230 << TimeStamp() << " Using " << OPENMP::getMaxThreads() << " threads"
3231 << std::flush;
3232
3234 << TimeStamp() << " Using " << EigenBackendDescription() << std::flush;
3235
3236 XTP_LOG(Log::error, *pLog_) << " Molecule Coordinates [A] " << std::flush;
3237 for (const QMAtom& atom : mol) {
3238 const Eigen::Vector3d pos = atom.getPos() * tools::conv::bohr2ang;
3239 std::string output = (boost::format(" %1$s"
3240 " %2$+1.4f %3$+1.4f %4$+1.4f") %
3241 atom.getElement() % pos[0] % pos[1] % pos[2])
3242 .str();
3243
3244 XTP_LOG(Log::error, *pLog_) << output << std::flush;
3245 }
3246
3248 dftbasis_ = orb.getDftBasis();
3249
3251 << TimeStamp() << " Loaded DFT Basis Set " << dftbasis_name_ << " with "
3252 << dftbasis_.AOBasisSize() << " functions" << std::flush;
3253
3254 if (!auxbasis_name_.empty()) {
3255 BasisSet auxbasisset;
3256 auxbasisset.Load(auxbasis_name_);
3257 auxbasis_.Fill(auxbasisset, mol);
3259 << TimeStamp() << " Loaded AUX Basis Set " << auxbasis_name_ << " with "
3260 << auxbasis_.AOBasisSize() << " functions" << std::flush;
3261 }
3262 if (!ecp_name_.empty()) {
3263 ECPBasisSet ecpbasisset;
3264 ecpbasisset.Load(ecp_name_);
3266 << TimeStamp() << " Loaded ECP library " << ecp_name_ << std::flush;
3267
3268 std::vector<std::string> results = ecp_.Fill(ecpbasisset, mol);
3270 << TimeStamp() << " Filled ECP Basis" << std::flush;
3271 if (results.size() > 0) {
3272 std::string message = "";
3273 for (const std::string& element : results) {
3274 message += " " + element;
3275 }
3277 << TimeStamp() << " Found no ECPs for elements" << message
3278 << std::flush;
3279 }
3280 }
3281
3282 numofelectrons_ = 0;
3285 num_docc_ = 0;
3286 num_socc_alpha_ = 0;
3287
3288 Index nuclear_charge = 0;
3289 for (const QMAtom& atom : mol) {
3290 nuclear_charge += atom.getNuccharge();
3291 }
3292
3293 Index target_charge = orb.getCharge();
3294 Index multiplicity = orb.getSpin();
3295
3296 if (multiplicity < 1) {
3297 throw std::runtime_error("Spin multiplicity must be >= 1.");
3298 }
3299
3300 if (numofelectrons >= 0) {
3301 numofelectrons_ = numofelectrons;
3302 } else {
3303 numofelectrons_ = nuclear_charge - target_charge;
3304 }
3305
3306 Index spin_excess = multiplicity - 1;
3307
3308 if (numofelectrons_ < 0) {
3309 throw std::runtime_error("Computed a negative number of electrons.");
3310 }
3311
3312 if (spin_excess > numofelectrons_) {
3313 throw std::runtime_error(
3314 "Spin multiplicity incompatible with total number of electrons.");
3315 }
3316
3317 if (((numofelectrons_ + spin_excess) % 2) != 0) {
3318 throw std::runtime_error(
3319 "Charge and spin multiplicity imply non-integer alpha/beta "
3320 "occupations.");
3321 }
3322
3323 num_alpha_electrons_ = (numofelectrons_ + spin_excess) / 2;
3324 num_beta_electrons_ = (numofelectrons_ - spin_excess) / 2;
3325
3328
3330 << TimeStamp() << " Total number of electrons: " << numofelectrons_
3331 << " (charge=" << target_charge << ", multiplicity=" << multiplicity
3332 << ", alpha=" << num_alpha_electrons_ << ", beta=" << num_beta_electrons_
3333 << ", docc=" << num_docc_ << ", socc=" << num_socc_alpha_ << ")"
3334 << std::flush;
3335
3337 return;
3338}
3339
3342 if (ScaHFX_ > 0) {
3344 << TimeStamp() << " Using hybrid functional with alpha=" << ScaHFX_
3345 << std::flush;
3346 }
3347 Vxc_Grid grid;
3348 grid.GridSetup(grid_name_, mol, dftbasis_);
3349 Vxc_Potential<Vxc_Grid> vxc(grid);
3352 << TimeStamp() << " Setup numerical integration grid " << grid_name_
3353 << " for vxc functional " << xc_functional_name_ << std::flush;
3355 << "\t\t " << " with " << grid.getGridSize() << " points"
3356 << " divided into " << grid.getBoxesSize() << " boxes" << std::flush;
3357 return vxc;
3358}
3359
3360double DFTEngine::NuclearRepulsion(const QMMolecule& mol) const {
3361 double E_nucnuc = 0.0;
3362
3363 for (Index i = 0; i < mol.size(); i++) {
3364 const Eigen::Vector3d& r1 = mol[i].getPos();
3365 double charge1 = double(mol[i].getNuccharge());
3366 for (Index j = 0; j < i; j++) {
3367 const Eigen::Vector3d& r2 = mol[j].getPos();
3368 double charge2 = double(mol[j].getNuccharge());
3369 E_nucnuc += charge1 * charge2 / (r1 - r2).norm();
3370 }
3371 }
3372 return E_nucnuc;
3373}
3374
3375// spherically average the density matrix belonging to two shells
3376// Average of an atom's density matrix over all rotations about the nucleus.
3377// In real spherical harmonics a rotation acts on each shell by an orthogonal
3378// matrix that depends only on l, so the average of the block between two
3379// shells is (trace / (2l+1)) times the identity if both have the same l, and
3380// zero otherwise. The result is independent of the orientation of the input
3381// (an open-shell atom's SCF converges to a symmetry-broken solution whose
3382// orientation is decided by round-off) and keeps the number of electrons:
3383// the overlap between shells of one atom is diagonal within equal l and zero
3384// between different l.
3386 const Eigen::MatrixXd& dmat, const AOBasis& dftbasis) const {
3387 Eigen::MatrixXd avdmat = Eigen::MatrixXd::Zero(dmat.rows(), dmat.cols());
3388 for (const AOShell& shellrow : dftbasis) {
3389 for (const AOShell& shellcol : dftbasis) {
3390 if (shellrow.getL() != shellcol.getL()) {
3391 continue;
3392 }
3393 const Index size = shellrow.getNumFunc();
3394 const double diagavg = dmat.block(shellrow.getStartIndex(),
3395 shellcol.getStartIndex(), size, size)
3396 .trace() /
3397 double(size);
3398 avdmat
3399 .block(shellrow.getStartIndex(), shellcol.getStartIndex(), size, size)
3400 .diagonal()
3401 .setConstant(diagavg);
3402 }
3403 }
3404 return avdmat;
3405}
3406
3407namespace {
3408// The charge-response sites among the external sites (PolarSite with
3409// isChargeResponse): their induced charge and dipole are Gaussians.
3410const PolarSite* AsChargeResponseSite(const StaticSite& site) {
3411 const PolarSite* p = dynamic_cast<const PolarSite*>(&site);
3412 return (p != nullptr && p->isChargeResponse()) ? p : nullptr;
3413}
3414} // namespace
3415
3417 const QMMolecule& mol,
3418 const std::vector<std::unique_ptr<StaticSite>>& multipoles) const {
3419
3420 if (multipoles.size() == 0) {
3421 return 0;
3422 }
3423
3424 double E_ext = 0;
3425 eeInteractor interactor;
3426 for (const QMAtom& atom : mol) {
3427 StaticSite nucleus = StaticSite(atom, double(atom.getNuccharge()));
3428 for (const std::unique_ptr<StaticSite>& site : multipoles) {
3429 if ((site->getPos() - nucleus.getPos()).norm() < 1e-7) {
3431 << " External site sits on nucleus, "
3432 "interaction between them is ignored."
3433 << std::flush;
3434 continue;
3435 }
3436 // The nuclei must see the permanent multipoles plus the induced
3437 // dipole, as the electrons do (AOMultipole::FillBlock uses the virtual
3438 // getDipole(), which includes the induced dipole of a PolarSite).
3439 // eeInteractor::CalcStaticEnergy_site reads the non-virtual Q(), i.e.
3440 // permanent moments only, so the induced dipole is added here. Since
3441 // the electronic and nuclear terms nearly cancel for a neutral QM
3442 // region, omitting it gives large errors. VSiteA itself is correct:
3443 // the induction solver treats permanent and induced moments
3444 // separately, and changing it would double-count induced dipoles.
3445 Vector9d Q = site->Q();
3446 if (const PolarSite* p = AsChargeResponseSite(*site)) {
3447 // induced charge and dipole of a charge-response site: Gaussians,
3448 // as the electrons see them (IntegrateExternalMultipoles)
3449 const Eigen::Vector3d r = nucleus.getPos() - p->getPos();
3450 const GaussianKernel k(r.norm(), p->CRWidth());
3451 E_ext += nucleus.getCharge() * (p->Induced_Charge() * k.B0 +
3452 k.B1 * p->getInducedDipole().dot(r));
3453 } else {
3454 Q.segment<3>(1) += site->getInducedDipole(); // zero for a StaticSite
3455 }
3456 Index rank = site->getRank();
3457 if (rank < 1 && Q.segment<3>(1).norm() > 1e-12) {
3458 rank = 1; // same promotion, same threshold, as AOMultipole
3459 }
3460 StaticSite effective(site->getId(), site->getElement(), site->getPos());
3461 effective.setMultipole(Q, rank);
3462
3463 E_ext += interactor.CalcStaticEnergy_site(effective, nucleus);
3464 }
3465 }
3466 return E_ext;
3467}
3468
3469Eigen::MatrixXd DFTEngine::IntegrateExternalField(const QMMolecule& mol) const {
3470
3471 AODipole dipole;
3472 dipole.setCenter(mol.getPos());
3473 dipole.Fill(dftbasis_);
3474 Eigen::MatrixXd result =
3475 Eigen::MatrixXd::Zero(dipole.Dimension(), dipole.Dimension());
3476 for (Index i = 0; i < 3; i++) {
3477 result -= dipole.Matrix()[i] * extfield_[i];
3478 }
3479 return result;
3480}
3481
3483 const QMMolecule& mol,
3484 const std::vector<std::unique_ptr<StaticSite>>& multipoles) const {
3485
3486 Mat_p_Energy result(dftbasis_.AOBasisSize(), dftbasis_.AOBasisSize());
3487 result.energy() = ExternalRepulsion(mol, multipoles);
3488
3489 // Charge-response sites: permanent multipoles as points (below, with all
3490 // sites), induced charge and dipole as Gaussians (AOGaussianSites).
3491 std::vector<AOGaussianSites::Source> gaussian;
3492 for (const std::unique_ptr<StaticSite>& site : multipoles) {
3493 if (const PolarSite* p = AsChargeResponseSite(*site)) {
3494 gaussian.push_back({p->getPos(), p->CRWidth(), p->Induced_Charge(),
3495 p->getInducedDipole()});
3496 }
3497 }
3498 if (!gaussian.empty()) {
3499 // the point sites' induced dipoles, without the charge-response sites
3500 std::vector<std::unique_ptr<StaticSite>> point_sites;
3501 for (const std::unique_ptr<StaticSite>& site : multipoles) {
3502 if (AsChargeResponseSite(*site) != nullptr) {
3503 continue;
3504 }
3505 const PolarSite* p = dynamic_cast<const PolarSite*>(site.get());
3506 if (p != nullptr) {
3507 point_sites.push_back(std::make_unique<PolarSite>(*p));
3508 } else {
3509 point_sites.push_back(std::make_unique<StaticSite>(*site));
3510 }
3511 }
3512 AOMultipole permanent;
3513 permanent.FillPotential(dftbasis_, multipoles,
3515 AOMultipole induced;
3516 induced.FillPotential(dftbasis_, point_sites,
3518 result.matrix() = permanent.Matrix() + induced.Matrix() -
3521 << TimeStamp() << " Filled DFT external multipole potential matrix ("
3522 << gaussian.size() << " charge-response sites as Gaussians)"
3523 << std::flush;
3524 return result;
3525 }
3526
3527 if (setup_cache_ == nullptr) {
3528 AOMultipole dftAOESP;
3529 dftAOESP.FillPotential(dftbasis_, multipoles);
3531 << TimeStamp() << " Filled DFT external multipole potential matrix"
3532 << std::flush;
3533 result.matrix() = dftAOESP.Matrix();
3534 return result;
3535 }
3536
3537 // In QM/MM only the induced dipoles change between iterations. The
3538 // potential is linear in the moments, so the permanent part is kept in the
3539 // cache and reused as long as basis, positions and permanent moments are
3540 // exactly the same; the induced dipoles are integrated every run.
3541 Eigen::MatrixXd sites(Index(multipoles.size()), 13);
3542 for (Index i = 0; i < Index(multipoles.size()); ++i) {
3543 const StaticSite& site = *multipoles[i];
3544 sites.block<1, 3>(i, 0) = site.getPos().transpose();
3545 sites(i, 3) = double(site.getRank());
3546 sites.block<1, 9>(i, 4) = site.Q().transpose();
3547 }
3548 const std::string key = RISetupKey();
3549 if (setup_cache_->multipole_key == key &&
3550 setup_cache_->multipole_matrix.rows() == dftbasis_.AOBasisSize() &&
3551 setup_cache_->multipole_sites.rows() == sites.rows() &&
3552 setup_cache_->multipole_sites == sites) {
3553 result.matrix() = setup_cache_->multipole_matrix;
3555 << TimeStamp()
3556 << " Reusing the permanent multipole potential matrix of the previous "
3557 "run"
3558 << std::flush;
3559 } else {
3560 AOMultipole permanent;
3561 permanent.FillPotential(dftbasis_, multipoles,
3563 result.matrix() = permanent.Matrix();
3564 setup_cache_->multipole_key = key;
3565 setup_cache_->multipole_sites = sites;
3566 setup_cache_->multipole_matrix = permanent.Matrix();
3568 << TimeStamp() << " Filled DFT permanent multipole potential matrix"
3569 << std::flush;
3570 }
3571
3572 const bool has_induced =
3573 std::any_of(multipoles.begin(), multipoles.end(),
3574 [](const std::unique_ptr<StaticSite>& site) {
3575 return site->getInducedDipole().norm() > 1e-12;
3576 });
3577 if (has_induced) {
3578 AOMultipole induced;
3580 result.matrix() += induced.Matrix();
3582 << TimeStamp() << " Filled DFT induced dipole potential matrix"
3583 << std::flush;
3584 }
3585
3586 return result;
3587}
3588
3590 const QMMolecule& mol, const Orbitals& extdensity) const {
3591 BasisSet basis;
3592 basis.Load(extdensity.getDFTbasisName());
3593 AOBasis aobasis;
3594 aobasis.Fill(basis, extdensity.QMAtoms());
3595 Vxc_Grid grid;
3596 grid.GridSetup(gridquality_, extdensity.QMAtoms(), aobasis);
3597 DensityIntegration<Vxc_Grid> numint(grid);
3598 Eigen::MatrixXd dmat = extdensity.DensityMatrixFull(state_);
3599
3600 numint.IntegrateDensity(dmat);
3602 << TimeStamp() << " Calculated external density" << std::flush;
3603 Eigen::MatrixXd e_contrib = numint.IntegratePotential(dftbasis_);
3605 << TimeStamp() << " Calculated potential from electron density"
3606 << std::flush;
3607 AOMultipole esp;
3608 esp.FillPotential(dftbasis_, extdensity.QMAtoms());
3609
3610 double nuc_energy = 0.0;
3611 for (const QMAtom& atom : mol) {
3612 nuc_energy +=
3613 numint.IntegratePotential(atom.getPos()) * double(atom.getNuccharge());
3614 for (const QMAtom& extatom : extdensity.QMAtoms()) {
3615 const double dist = (atom.getPos() - extatom.getPos()).norm();
3616 nuc_energy +=
3617 double(atom.getNuccharge()) * double(extatom.getNuccharge()) / dist;
3618 }
3619 }
3621 << TimeStamp() << " Calculated potential from nuclei" << std::flush;
3623 << TimeStamp() << " Electrostatic: " << nuc_energy << std::flush;
3624 return Mat_p_Energy(nuc_energy, e_contrib + esp.Matrix());
3625}
3626
3628 const Eigen::MatrixXd& GuessMOs) const {
3629 Eigen::MatrixXd nonortho =
3630 GuessMOs.transpose() * dftAOoverlap_.Matrix() * GuessMOs;
3631 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(nonortho);
3632 Eigen::MatrixXd result = GuessMOs * es.operatorInverseSqrt();
3633 return result;
3634}
3635
3636/*************************************************************
3637 * Extended Hueckel Theory
3638 ************************************************************/
3640 const QMMolecule& mol) const {
3641
3643
3644 const Index nao = dftbasis_.AOBasisSize();
3645 Eigen::VectorXd eps = Eigen::VectorXd::Zero(nao);
3646
3647 for (const AOShell& shell : dftbasis_) {
3648
3649 int l = static_cast<int>(shell.getL());
3650 Index start = shell.getStartIndex();
3651 Index nfunc = shell.getNumFunc();
3652
3653 const QMAtom& atom = mol[shell.getAtomIndex()];
3654 const std::string& element = atom.getElement();
3655
3656 int used_l = l;
3657 double e = params.GetWithFallback(element, l, &used_l);
3658
3659 for (Index i = 0; i < nfunc; ++i) {
3660 eps(start + i) = e;
3661 }
3662 }
3663
3664 return eps;
3665}
3666
3667Eigen::MatrixXd DFTEngine::BuildEHTHamiltonian(const QMMolecule& mol) const {
3668
3669 const Eigen::MatrixXd& S = dftAOoverlap_.Matrix();
3670 const Index nao = S.rows();
3671 Eigen::VectorXd eps = BuildEHTOrbitalEnergies(mol);
3672 Eigen::MatrixXd H = Eigen::MatrixXd::Zero(nao, nao);
3673 constexpr double K = 1.75;
3674
3675 for (Index mu = 0; mu < nao; ++mu) {
3676 H(mu, mu) = eps(mu);
3677 for (Index nu = 0; nu < mu; ++nu) {
3678 double hij = K * S(mu, nu) * 0.5 * (eps(mu) + eps(nu));
3679 H(mu, nu) = hij;
3680 H(nu, mu) = hij;
3681 }
3682 }
3683
3684 return H;
3685}
3686
3688
3690 << TimeStamp() << " Building Extended Huckel guess" << std::flush;
3691
3692 Eigen::MatrixXd H = BuildEHTHamiltonian(mol);
3693
3695 << TimeStamp() << " Solving EHT generalized eigenproblem" << std::flush;
3696
3697 return conv_accelerator_.SolveFockmatrix(H);
3698}
3699
3701 const Mat_p_Energy& H0, const QMMolecule& mol,
3702 const Vxc_Potential<Vxc_Grid>& vxcpotential) const {
3703
3705
3706 Eigen::MatrixXd Dmat = conv_accelerator_.DensityMatrix(eht);
3707
3708 Mat_p_Energy e_vxc = vxcpotential.IntegrateVXC(Dmat);
3709
3710 Eigen::MatrixXd H = H0.matrix() + e_vxc.matrix();
3711
3712 if (ScaHFX_ > 0) {
3713 std::array<Eigen::MatrixXd, 2> both =
3714 CalcERIs_EXX(Eigen::MatrixXd::Zero(0, 0), Dmat, 1e-12);
3715 H += both[0];
3716 H += ScaHFX_ * both[1];
3717 } else {
3718 H += CalcERIs(Dmat, 1e-12);
3719 }
3720
3721 return conv_accelerator_.SolveFockmatrix(H);
3722}
3723
3725 const QMMolecule& dimer_mol) const {
3726 Orbitals monomerA;
3728 Orbitals monomerB;
3730
3731 const QMMolecule& atomsA = monomerA.QMAtoms();
3732 const QMMolecule& atomsB = monomerB.QMAtoms();
3733 Index nA = atomsA.size();
3734 Index nB = atomsB.size();
3735
3736 // Check 1: atom count and element sequence (before the geometry check,
3737 // since an ordering error gives a clearer message here).
3738 if (nA + nB != dimer_mol.size()) {
3739 throw std::runtime_error(
3740 "BuildDimerGuessFromMonomerFiles: monomer A (" + std::to_string(nA) +
3741 " atoms) + monomer B (" + std::to_string(nB) +
3742 " atoms) does not equal this calculation's molecule (" +
3743 std::to_string(dimer_mol.size()) +
3744 " atoms): wrong monomer file(s), or the molecule is not the "
3745 "concatenation of the two monomers.");
3746 }
3747 for (Index i = 0; i < nA; ++i) {
3748 if (atomsA[i].getElement() != dimer_mol[i].getElement()) {
3749 throw std::runtime_error(
3750 "BuildDimerGuessFromMonomerFiles: monomer A atom " +
3751 std::to_string(i) + " (" + atomsA[i].getElement() +
3752 ") does not match this calculation's atom " + std::to_string(i) +
3753 " (" + dimer_mol[i].getElement() +
3754 "); dimer_guess requires monomer A to be the first N_A atoms of "
3755 "the molecule, in the same order.");
3756 }
3757 }
3758 for (Index i = 0; i < nB; ++i) {
3759 if (atomsB[i].getElement() != dimer_mol[nA + i].getElement()) {
3760 throw std::runtime_error(
3761 "BuildDimerGuessFromMonomerFiles: monomer B atom " +
3762 std::to_string(i) + " (" + atomsB[i].getElement() +
3763 ") does not match this calculation's atom " + std::to_string(nA + i) +
3764 " (" + dimer_mol[nA + i].getElement() +
3765 "); dimer_guess requires monomer B to be the remaining atoms of "
3766 "the molecule (after monomer A), in the same order.");
3767 }
3768 }
3769
3770 // Check 2: intra-monomer interatomic distances, which are invariant under
3771 // the rigid translation/rotation placing a monomer into the dimer.
3772 constexpr double kGeometryToleranceBohr = 1e-3;
3773 auto CheckInternalGeometry = [&](const QMMolecule& monomer_atoms,
3774 Index offset_in_dimer,
3775 const std::string& label) {
3776 Index n = monomer_atoms.size();
3777 for (Index i = 0; i < n; ++i) {
3778 for (Index j = i + 1; j < n; ++j) {
3779 double monomer_distance =
3780 (monomer_atoms[i].getPos() - monomer_atoms[j].getPos()).norm();
3781 double dimer_distance = (dimer_mol[offset_in_dimer + i].getPos() -
3782 dimer_mol[offset_in_dimer + j].getPos())
3783 .norm();
3784 double diff = std::abs(monomer_distance - dimer_distance);
3785 if (diff > kGeometryToleranceBohr) {
3786 throw std::runtime_error(
3787 "BuildDimerGuessFromMonomerFiles: " + label +
3788 "'s internal geometry does not match this calculation's "
3789 "molecule: distance between its atoms " +
3790 std::to_string(i) + " and " + std::to_string(j) + " is " +
3791 std::to_string(monomer_distance) +
3792 " Bohr in the monomer file, but " +
3793 std::to_string(dimer_distance) +
3794 " Bohr in this calculation's molecule (difference " +
3795 std::to_string(diff) + " Bohr, tolerance " +
3796 std::to_string(kGeometryToleranceBohr) + " Bohr).");
3797 }
3798 }
3799 }
3800 };
3801 CheckInternalGeometry(atomsA, 0, "Monomer A");
3802 CheckInternalGeometry(atomsB, nA, "Monomer B");
3803
3804 // The MO coefficients are copied without rotating them, so the guess is
3805 // only exact if each monomer is translated, not rotated, into the dimer.
3806 auto MaxDeviationFromTranslation = [&](const QMMolecule& monomer_atoms,
3807 Index offset_in_dimer) {
3808 Eigen::Vector3d shift =
3809 dimer_mol[offset_in_dimer].getPos() - monomer_atoms[0].getPos();
3810 double max_dev = 0.0;
3811 for (Index i = 0; i < monomer_atoms.size(); ++i) {
3812 double dev = (dimer_mol[offset_in_dimer + i].getPos() -
3813 monomer_atoms[i].getPos() - shift)
3814 .norm();
3815 max_dev = std::max(max_dev, dev);
3816 }
3817 return max_dev;
3818 };
3819 auto WarnIfRotated = [&](const QMMolecule& monomer_atoms,
3820 Index offset_in_dimer, const std::string& label) {
3821 double dev = MaxDeviationFromTranslation(monomer_atoms, offset_in_dimer);
3822 if (dev > kGeometryToleranceBohr) {
3824 << TimeStamp() << " WARNING: " << label
3825 << " is rotated with respect to its .orb file (max deviation " << dev
3826 << " bohr after translation). Its MO coefficients are not "
3827 "rotated, so the dimer guess will be poor."
3828 << std::flush;
3829 }
3830 };
3831 WarnIfRotated(atomsA, 0, "Monomer A");
3832 WarnIfRotated(atomsB, nA, "Monomer B");
3833
3834 Orbitals dimer_guess;
3835 // PrepareDimerGuessMixedSpin calls SetupDftBasis, which needs QMAtoms()
3836 // to be set (as in iqm.cc for PrepareDimerGuess).
3837 dimer_guess.QMAtoms() = dimer_mol;
3838 dimer_guess.PrepareDimerGuessMixedSpin(monomerA, monomerB);
3839 return dimer_guess;
3840}
3841
3842} // namespace xtp
3843} // namespace votca
const Eigen::VectorXd & eigenvalues() const
Definition eigensystem.h:30
const Eigen::MatrixXd & eigenvectors() const
Definition eigensystem.h:33
class to manage program options with xml serialization functionality
Definition property.h:55
Property & get(const std::string &key)
get existing property
Definition property.cc:79
bool exists(const std::string &key) const
check whether property exists
Definition property.cc:122
T as() const
return value as type
Definition property.h:283
T ifExistsReturnElseReturnDefault(const std::string &key, T defaultvalue) const
Definition property.h:332
Container to hold Basisfunctions for all atoms.
Definition aobasis.h:42
Index AOBasisSize() const
Definition aobasis.h:46
void Fill(const BasisSet &bs, const QMMolecule &atoms)
Definition aobasis.cc:85
Index Dimension() final
Definition aomatrix.h:95
void setCenter(const Eigen::Vector3d &r)
Definition aomatrix.h:98
const std::array< Eigen::MatrixXd, 3 > & Matrix() const
Definition aomatrix.h:96
void Fill(const AOBasis &aobasis) final
void FillPotential(const AOBasis &aobasis, const ECPAOBasis &ecp)
Definition aoecp.cc:59
static Eigen::MatrixXd Potential(const AOBasis &basis, const std::vector< Source > &sources)
void Fill(const AOBasis &aobasis) final
const Eigen::MatrixXd & Matrix() const
Definition aomatrix.h:41
void FillPotential(const AOBasis &aobasis, const QMMolecule &atoms)
@ Permanent
permanent moments only (charge, dipole, quadrupole)
Definition aopotential.h:72
@ Induced
induced dipoles only; sites without one are skipped
Definition aopotential.h:73
void Fill(const AOBasis &aobasis) final
const Eigen::MatrixXd & Matrix() const
Definition aomatrix.h:52
const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > & Matrix() const
Definition aopotential.h:39
void push_back(const T &atom)
std::vector< std::string > FindUniqueElements() const
const Eigen::Vector3d & getPos() const
void Load(const std::string &name)
Definition basisset.cc:149
Eigen::MatrixXd CalcERIs(const Eigen::MatrixXd &Dmat, double error) const
Build the Coulomb matrix contribution from the current density matrix.
Definition dftengine.cc:739
Eigen::MatrixXd ComputeOverlapPulayGradientUKS(const QMMolecule &mol, const tools::EigenSystem &MOs_alpha, const tools::EigenSystem &MOs_beta) const
Definition dftengine.cc:550
ActiveRegion::Options active_growth_
Definition dftengine.h:666
std::string auxbasis_name_
Definition dftengine.h:591
std::string gridquality_
Definition dftengine.h:653
tools::EigenSystem ModelPotentialGuess(const Mat_p_Energy &H0, const QMMolecule &mol, const Vxc_Potential< Vxc_Grid > &vxcpotential) const
Definition dftengine.cc:796
Mat_p_Energy IntegrateExternalMultipoles(const QMMolecule &mol, const std::vector< std::unique_ptr< StaticSite > > &multipoles) const
tools::EigenSystem IndependentElectronGuess(const Mat_p_Energy &H0) const
Generate an initial guess by diagonalizing the core Hamiltonian only.
Definition dftengine.cc:785
void setSCFToleranceFloor(double energy, double error)
std::string eris_key_
Definition dftengine.h:634
Orbitals BuildDimerGuessFromMonomerFiles(const QMMolecule &dimer_mol) const
void ComputePolarizability(Orbitals &orb)
Definition dftengine.cc:844
double cdft_population_tolerance_
Definition dftengine.h:708
Eigen::MatrixXd ext_potential_matrix_
Definition dftengine.h:663
void ComputeAndStoreForces(Orbitals &orb, const Eigen::MatrixXd &Dmat, const Vxc_Potential< Vxc_Grid > &vxcpotential) const
Definition dftengine.cc:397
bool EvaluateClosedShell(Orbitals &orb, const Mat_p_Energy &H0, const Vxc_Potential< Vxc_Grid > &vxcpotential)
Run the restricted closed-shell SCF loop and store the converged result.
void PrintMOsUKS(const Eigen::VectorXd &alpha_energies, const Eigen::VectorXd &beta_energies, Log::Level level) const
Print separate alpha and beta orbital energies for a UKS calculation.
Definition dftengine.cc:313
void ReportDimensionsAndMemory() const
Basis dimensions and the memory of the large intermediates.
Definition dftengine.cc:750
std::string dftbasis_name_
Definition dftengine.h:592
DFTSetupCache * setup_cache_
Definition dftengine.h:633
bool EvaluateUKS(Orbitals &orb, const Mat_p_Energy &H0, const Vxc_Potential< Vxc_Grid > &vxcpotential)
Eigen::MatrixXd RunAtomicDFT_unrestricted(const QMAtom &uniqueAtom, bool use_hunds_rule_occupation=false) const
Mat_p_Energy IntegrateExternalDensity(const QMMolecule &mol, const Orbitals &extdensity) const
std::vector< Eigen::MatrixXd > CoupledResponse(const Vxc_Potential< Vxc_Grid > &vxc, const Eigen::MatrixXd &P0, const Eigen::MatrixXd &C_occ, const Eigen::MatrixXd &C_virt, const std::vector< Eigen::MatrixXd > &U, const Vxc_Potential< Vxc_Grid >::FXCKernel *fxc_kernel=nullptr)
std::string ecp_name_
Definition dftengine.h:593
std::string grid_name_
Definition dftengine.h:609
void Prepare(Orbitals &orb, Index numofelectrons=-1)
Vxc_Grid external_ewaldgrid_
Definition dftengine.h:683
std::string initial_guess_
Definition dftengine.h:614
std::string orbfilename_
Definition dftengine.h:652
UKSConvergenceAcc::SpinFock BuildUKSFock(const Eigen::MatrixXd &H0, const Vxc_Potential< Vxc_Grid > &vxcpotential, const Eigen::MatrixXd &alpha_new, const Eigen::MatrixXd &beta_new)
Eigen::MatrixXd AtomicGuess(const QMMolecule &mol) const
Build an atomic-density based initial guess in the AO basis.
bool EvaluateAndTime(Orbitals &orb)
Evaluate() without the timing report.
Definition dftengine.cc:876
std::vector< HirshfeldPartition::AtomicReference > HirshfeldReferences(const QMMolecule &mol) const
Eigen::MatrixXd BuildEHTHamiltonian(const QMMolecule &mol) const
Build the extended-Hückel Hamiltonian for the current molecule.
Eigen::MatrixXd IntegrateExternalField(const QMMolecule &mol) const
Integrate a homogeneous external electric field into the AO basis.
Eigen::Vector3d extfield_
Definition dftengine.h:659
std::array< Eigen::MatrixXd, 2 > CalcERIs_EXX(const Eigen::MatrixXd &MOCoeff, const Eigen::MatrixXd &Dmat, double error) const
Definition dftengine.cc:713
Eigen::MatrixXd UKSOrbitalHessian(const Vxc_Potential< Vxc_Grid > &vxc, const tools::EigenSystem &mos_alpha, const tools::EigenSystem &mos_beta, const Eigen::MatrixXd &F_alpha, const Eigen::MatrixXd &F_beta, const Eigen::MatrixXd &X)
HirshfeldPartition::Constraint BuildCDFTConstraint(const QMMolecule &mol, const CDFTConstraintSpec &spec) const
void Initialize(tools::Property &options)
Read DFT, grid, and SCF settings from the user options tree.
Definition dftengine.cc:99
std::string xc_functional_name_
Definition dftengine.h:648
void CalcElDipole(const Orbitals &orb) const
Evaluate and print the electronic dipole moment from the final density.
Definition dftengine.cc:373
double ExternalRepulsion(const QMMolecule &mol, const std::vector< std::unique_ptr< StaticSite > > &multipoles) const
ConvergenceAcc::options conv_opt_
Definition dftengine.h:624
void SetupInvariantMatrices()
Precompute AO matrices that remain unchanged throughout the SCF procedure.
tools::EigenSystem ExtendedHuckelDFTGuess(const Mat_p_Energy &H0, const QMMolecule &mol, const Vxc_Potential< Vxc_Grid > &vxcpotential) const
std::map< std::string, Eigen::MatrixXd > ComputeHirshfeldReferenceDensities(const QMMolecule &mol) const
std::string active_atoms_as_string_
Definition dftengine.h:665
void ComputeAndStoreForcesUKS(Orbitals &orb, const UKSConvergenceAcc::SpinDensity &Dspin, const tools::EigenSystem &MOs_alpha, const tools::EigenSystem &MOs_beta, const Vxc_Potential< Vxc_Grid > &vxcpotential) const
Definition dftengine.cc:626
void ConfigOrbfile(Orbitals &orb)
Propagate basis-set, XC, and metadata settings into the orbital container.
Eigen::VectorXd BuildEHTOrbitalEnergies(const QMMolecule &mol) const
Build orbital energies used in the extended-Hückel starting guess.
std::vector< Eigen::MatrixXd > StaticResponse(const Orbitals &orb, const std::vector< Eigen::MatrixXd > &perturbations, double tolerance=1e-7, Index max_iterations=100)
std::vector< HirshfeldPartition::Constraint > constraints_
Definition dftengine.h:702
bool UsableAsWarmStart(const Orbitals &orb, const std::string &previous_basis, std::string &reason) const
Definition dftengine.cc:996
void PrintMOs(const Eigen::VectorXd &MOEnergies, Log::Level level)
Print a one-spin list of orbital energies and occupations to the logger.
Definition dftengine.cc:293
Eigen::MatrixXd RKSOrbitalHessian(const Vxc_Potential< Vxc_Grid > &vxc, const tools::EigenSystem &mos, const Eigen::MatrixXd &F, const Eigen::MatrixXd &X)
AOOverlap dftAOoverlap_
Definition dftengine.h:612
Mat_p_Energy SetupH0(const QMMolecule &mol) const
Assemble the one-electron core Hamiltonian for the current molecule.
tools::EigenSystem ExtendedHuckelGuess(const QMMolecule &mol) const
Eigen::MatrixXd OrthogonalizeGuess(const Eigen::MatrixXd &GuessMOs) const
Orthonormalize an initial MO guess with respect to the AO overlap matrix.
Eigen::MatrixXd SphericalAverageShells(const Eigen::MatrixXd &dmat, const AOBasis &dftbasis) const
bool Evaluate(Orbitals &orb)
Definition dftengine.cc:823
CDFTConstraintSpec cdft_constraint_spec_
Definition dftengine.h:711
Eigen::MatrixXd ComputeNonXCGradientUKS(const QMMolecule &mol, const UKSConvergenceAcc::SpinDensity &Dspin, const tools::EigenSystem &MOs_alpha, const tools::EigenSystem &MOs_beta) const
Definition dftengine.cc:583
bool RunCDFT(Orbitals &orb, HirshfeldPartition::Constraint &constraint)
std::string dimer_guess_orbB_name_
Definition dftengine.h:619
std::vector< std::unique_ptr< StaticSite > > * externalsites_
Definition dftengine.h:644
Vxc_Potential< Vxc_Grid > SetupVxc(const QMMolecule &mol)
std::string RISetupKey() const
double NuclearRepulsion(const QMMolecule &mol) const
Compute the classical nucleus-nucleus repulsion energy.
ConvergenceAcc conv_accelerator_
Definition dftengine.h:626
std::string dimer_guess_orbA_name_
Definition dftengine.h:618
static Eigen::MatrixXd RIKGradient(const Eigen::MatrixXd &occ_mo_coeffs, const AOBasis &auxbasis, const AOBasis &dftbasis)
static Eigen::MatrixXd NuclearRepulsionDerivative(const QMMolecule &mol)
static Eigen::MatrixXd RIJGradient(const Eigen::MatrixXd &density, const AOBasis &auxbasis, const AOBasis &dftbasis)
static double ResidentMemoryGB(bool peak)
Definition dfttimings.cc:69
double IntegratePotential(const Eigen::Vector3d &rvector) const
double IntegrateDensity(const Eigen::MatrixXd &density_matrix)
Container to hold ECPs for all atoms.
Definition ecpaobasis.h:43
std::vector< std::string > Fill(const ECPBasisSet &bs, QMMolecule &atoms)
Definition ecpaobasis.cc:69
void Load(const std::string &name)
Takes a density matrix and and an auxiliary basis set and calculates the electron repulsion integrals...
Definition ERIs.h:35
std::array< Eigen::MatrixXd, 2 > CalculateERIs_EXX_4c(const Eigen::MatrixXd &DMAT, double error) const
Definition ERIs.h:90
void Initialize_4c(const AOBasis &dftbasis)
Definition ERIs.cc:39
Eigen::MatrixXd CalculateERIs_4c(const Eigen::MatrixXd &DMAT, double error) const
Definition ERIs.h:85
Mat_p_Energy IntegrateEwald(Index basissize) const
double GetWithFallback(const std::string &element, int l, int *used_l=nullptr) const
Index size() const
Definition gridbox.h:71
std::vector< double > & getPotentialValues()
Definition gridbox.h:58
static std::vector< AtomicReference > BuildAtomicReferences(const QMMolecule &mol, const std::string &basisset_name, const std::map< std::string, Eigen::MatrixXd > &reference_densities)
static Eigen::MatrixXd BuildWeightMatrix(const std::vector< AtomicReference > &atoms, Index target_atom_index, const AOBasis &full_dftbasis, const Vxc_Grid &grid)
static Eigen::MatrixXd ComputeCDFTForceContribution(const std::vector< AtomicReference > &atoms, Index target_atom_index, const Eigen::MatrixXd &density_matrix, const QMMolecule &mol, const AOBasis &full_dftbasis, const Vxc_Grid &grid)
void UpdateDmats(const Eigen::MatrixXd &dmat, double DiisError, Index Iteration)
void Configure(const Eigen::MatrixXd &dmat)
void resetMatrices(Eigen::MatrixXd &J, Eigen::MatrixXd &K, const Eigen::MatrixXd &dmat)
void Start(Index iteration, double DiisError)
void UpdateCriteria(double DiisError, Index Iteration)
const Eigen::MatrixXd & getDmat_diff() const
std::vector< Index > CreateIndexVector(const std::string &Ids) const
Eigen::MatrixXd & matrix()
Definition eigen.h:97
double & energy()
Definition eigen.h:98
Index cols() const
Definition eigen.h:96
Index rows() const
Definition eigen.h:95
Container for molecular orbitals and derived one-particle data.
Definition orbitals.h:47
void setScaHFX(double ScaHFX)
Store the fraction of exact exchange associated with the functional.
Definition orbitals.h:480
Index getCharge() const
Return the stored total charge.
Definition orbitals.h:254
void clearPolarizability()
Definition orbitals.h:315
Index getSpin() const
Return the stored spin multiplicity.
Definition orbitals.h:252
bool hasForces() const
Report whether nuclear forces have been stored.
Definition orbitals.h:301
const tools::EigenSystem & MOs_beta() const
Return read-only access to beta-spin molecular orbitals.
Definition orbitals.h:202
bool hasMOs() const
Report whether alpha/restricted molecular orbitals are available.
Definition orbitals.h:185
std::array< Eigen::MatrixXd, 2 > DensityMatrixGroundStateSpinResolved() const
Definition orbitals.cc:1429
Index getNumberOfAlphaElectrons() const
Return the stored number of alpha electrons.
Definition orbitals.h:159
void setNumberOfAlphaElectrons(Index electrons)
Store the total number of alpha electrons.
Definition orbitals.h:139
Eigen::MatrixXd DensityMatrixFull(const QMState &state) const
Definition orbitals.cc:150
void PrepareDimerGuessMixedSpin(const Orbitals &orbitalsA, const Orbitals &orbitalsB)
Dimer guess from two converged monomers of arbitrary charge and spin.
Definition orbitals.cc:1046
void SetupAuxBasis(std::string aux_basis_name)
Definition orbitals.cc:108
void setNumberOfBetaElectrons(Index electrons)
Store the total number of beta electrons.
Definition orbitals.h:144
void setForces(const Eigen::MatrixXd &forces)
Definition orbitals.h:323
void setECPName(const std::string &ECP)
Store the effective core potential label.
Definition orbitals.h:170
void setXCGrid(std::string grid)
Store the numerical XC grid quality label.
Definition orbitals.h:283
void setNumberOfOccupiedLevels(Index occupied_levels)
Definition orbitals.h:122
Index getBasisSetSize() const
Return the number of AO basis functions in the DFT basis.
Definition orbitals.h:72
void setQMEnergy(double qmenergy)
Store the total DFT energy.
Definition orbitals.h:295
bool hasECPName() const
Report whether an effective core potential label has been stored.
Definition orbitals.h:164
const tools::EigenSystem & MOs() const
Return read-only access to alpha/restricted molecular orbitals.
Definition orbitals.h:192
const QMMolecule & QMAtoms() const
Return read-only access to the molecular geometry.
Definition orbitals.h:262
void ReadFromCpt(const std::string &filename)
Read the orbital container from a checkpoint file on disk.
Definition orbitals.cc:1238
void setNumberOfOccupiedLevelsBeta(Index occupied_levels_beta)
Store the number of occupied beta-spin orbitals.
Definition orbitals.h:134
void setChargeAndSpin(Index charge, Index spin)
Definition orbitals.h:246
bool hasDFTbasisName() const
Report whether a DFT basis-set name has been stored.
Definition orbitals.h:357
const std::string & getECPName() const
Return the effective core potential label.
Definition orbitals.h:167
const std::string & getDFTbasisName() const
Return the DFT basis-set name.
Definition orbitals.h:362
bool hasBetaMOs() const
Report whether beta-spin molecular orbitals are available.
Definition orbitals.h:187
void SetupDftBasis(std::string basis_name)
Build and attach the DFT AO basis from the stored molecular geometry.
Definition orbitals.cc:99
void setPolarizability(const Eigen::Matrix3d &alpha)
Definition orbitals.h:312
const Eigen::MatrixXd & getForces() const
Return the stored nuclear forces (Natoms x 3, Hartree/Bohr).
Definition orbitals.h:318
Eigen::Vector3d CalcElDipole(const QMState &state) const
Compute the electronic dipole moment associated with a state density.
Definition orbitals.cc:307
Index getNumberOfBetaElectrons() const
Return the stored number of beta electrons.
Definition orbitals.h:161
const AOBasis & getDftBasis() const
Return the DFT AO basis, throwing if it has not been initialized.
Definition orbitals.h:372
void setXCFunctionalName(std::string functionalname)
Definition orbitals.h:276
Class to represent Atom/Site in electrostatic+polarization.
Definition polarsite.h:36
bool isChargeResponse() const
Definition polarsite.h:106
container for QM atoms
Definition qmatom.h:37
Index getElementNumber() const
Definition qmatom.h:80
const std::string & getElement() const
Definition qmatom.h:72
Identifier for QMstates. Strings like S1 are converted into enum +zero indexed int.
Definition qmstate.h:135
Class to represent Atom/Site in electrostatic.
Definition staticsite.h:37
void setMultipole(const Vector9d &multipole, Index rank)
Definition staticsite.h:87
const Eigen::Vector3d & getPos() const
Definition staticsite.h:80
double getCharge() const
Definition staticsite.h:110
Index getRank() const
Definition staticsite.h:78
const Vector9d & Q() const
Definition staticsite.h:111
Timestamp returns the current time as a string Example: cout << TimeStamp().
Definition logger.h:224
SpinDensity DensityMatrix(const tools::EigenSystem &MOs_alpha, const tools::EigenSystem &MOs_beta) const
void setOverlap(AOOverlap &S, double etol)
void Configure(const options &opt_alpha, const options &opt_beta)
SpinDensity Iterate(const SpinDensity &dmat, SpinFock &H, tools::EigenSystem &MOs_alpha, tools::EigenSystem &MOs_beta, double totE)
void setOrbitalHessian(const OrbitalHessian &hessian)
void setCoupledFockBuilder(const CoupledFockBuilder &builder)
Index getGridSize() const
Definition vxc_grid.h:41
void GridSetup(const std::string &type, const QMMolecule &atoms, const AOBasis &basis)
Definition vxc_grid.cc:230
Index getBoxesSize() const
Definition vxc_grid.h:42
Eigen::MatrixXd GridWeightGradient(const Eigen::MatrixXd &density_matrix, const QMMolecule &atoms) const
Eigen::MatrixXd PulayGradient(const Eigen::MatrixXd &density_matrix, const AOBasis &dftbasis) const
FXCKernel PrepareFXC(const Eigen::MatrixXd &density_matrix) const
std::vector< Eigen::MatrixXd > ApplyFXC(const FXCKernel &kernel, const std::vector< Eigen::MatrixXd > &response_matrices) const
IntegrateFXC with a prepared kernel (the same results).
Eigen::MatrixXd PulayGradientUKS(const Eigen::MatrixXd &dmat_alpha, const Eigen::MatrixXd &dmat_beta, const AOBasis &dftbasis) const
Mat_p_Energy IntegrateVXC(const Eigen::MatrixXd &density_matrix) const
void setXCfunctional(const std::string &functional)
std::vector< std::array< Eigen::MatrixXd, 2 > > IntegrateFXCSpin(const Eigen::MatrixXd &dmat_alpha, const Eigen::MatrixXd &dmat_beta, const std::vector< std::array< Eigen::MatrixXd, 2 > > &response) const
static double getExactExchange(const std::string &functional)
std::vector< Eigen::MatrixXd > IntegrateFXC(const Eigen::MatrixXd &density_matrix, const std::vector< Eigen::MatrixXd > &response_matrices) const
Eigen::MatrixXd GridWeightGradientUKS(const Eigen::MatrixXd &dmat_alpha, const Eigen::MatrixXd &dmat_beta, const QMMolecule &atoms) const
SpinResult IntegrateVXCSpin(const Eigen::MatrixXd &dmat_alpha, const Eigen::MatrixXd &dmat_beta) const
Mediates interaction between polar and static sites.
double CalcStaticEnergy_site(const StaticSite &site1, const StaticSite &site2) const
#define XTP_LOG(level, log)
Definition logger.h:40
const double ev2hrt
Definition constants.h:54
const double bohr2ang
Definition constants.h:49
Index getMaxThreads()
Definition eigen.h:145
void Cite(const std::string &key)
marks a reference as used (thread safe; unknown keys are printed as such)
Definition citations.cc:289
Charge transport classes.
Definition ERIs.h:28
std::vector< AOMatrixDerivative > ComputeNuclearAttractionDerivatives(const AOBasis &aobasis, const QMMolecule &mol)
std::vector< AOMatrixDerivative > ComputeKineticDerivatives(const AOBasis &aobasis)
std::vector< AOMatrixDerivative > ComputeOverlapDerivatives(const AOBasis &aobasis)
std::string EigenBackendDescription()
Definition eigen.h:63
std::array< Eigen::MatrixXd, 3 > AOMatrixDerivative
Provides a means for comparing floating point numbers.
Definition basebead.h:33
Eigen::Index Index
Definition types.h:26
Level
be loud and noisy
Definition globals.h:28
Spin-resolved density matrices returned for open-shell SCF updates.
Eigen::MatrixXd total() const
Return the total density P = P^alpha + P^beta.
Interaction of two normalized Gaussian charge distributions exp(-r^2/s_i^2) and exp(-r^2/s_j^2): erf(...
Eigen::Matrix< double, 9, 1 > Vector9d
Definition eigen.h:37