votca 2026-dev
Loading...
Searching...
No Matches
embeddingengine.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2023 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 *References- (1) A Simple, Exact Density-Functional-Theory
21 *Embedding Scheme. Frederick R. Manby, Martina Stella, Jason D. Goodpaster, and
22 *Thomas F. Miller Journal of Chemical Theory and Computation 2012 8 (8),
23 *2564-2568 DOI: 10.1021/ct300544e
24 *(2) Taylor A. Barnes, Jason D. Goodpaster, Frederick R. Manby, and Thomas F.
25 *Miller III , "Accurate basis set truncation for wavefunction embedding", J.
26 *Chem. Phys. 139, 024103 (2013) https://doi.org/10.1063/1.4811112
27 *(3) Simon J. Bennie, Martina Stella, Thomas F. Miller III, and Frederick R.
28 *Manby , "Accelerating wavefunction in density-functional-theory embedding by
29 *truncating the active basis set", J. Chem. Phys. 143, 024105 (2015)
30 *https://doi.org/10.1063/1.4923367
31 *(3) Projection-Based Wavefunction-in-DFT Embedding
32 *Sebastian J. R. Lee, Matthew Welborn, Frederick R. Manby, and Thomas F. Miller
33 *III Accounts of Chemical Research 2019 52 (5), 1359-1368
34 *DOI: 10.1021/acs.accounts.8b00672
35 */
36
37// Third party includes
38#include <algorithm>
39#include <boost/format.hpp>
40#include <sstream>
41
42// VOTCA includes
45
46// Local VOTCA includes
50#include "votca/xtp/aomatrix.h"
52#include "votca/xtp/citations.h"
54#include "votca/xtp/dftengine.h"
57#include "votca/xtp/logger.h"
58#include "votca/xtp/mmregion.h"
59#include "votca/xtp/orbitals.h"
61
62namespace votca {
63namespace xtp {
64
66 citations::Cite("Manby:2012");
67 citations::Cite("Sundaram:2024");
68
69 // reading in the orbitals of the full DFT calculation
70 tools::EigenSystem embeddingMOs = orb.MOs();
71
72 // constructing the full electron density matrix
73 const Eigen::MatrixXd FullDensityMatrix = orb.DensityMatrixGroundState();
74 XTP_LOG(Log::error, *pLog_) << std::flush;
76 << TimeStamp() << " Starting Projection based dft-in-dft embedding"
77 << std::flush;
78
79 // reading the localized orbitals and update the occupied orbitals in MOs
81 << TimeStamp() << " Passing localized orbitals as the initial guess"
82 << std::flush;
83 Eigen::MatrixXd LMOs = orb.getLMOs();
84
85 embeddingMOs.eigenvectors().leftCols(orb.getNumberOfAlphaElectrons()) = LMOs;
86
87 // determine the active and inactive electron densities
88 std::vector<Index> activeatoms =
90
92 << "Indices of active atoms selected are: " << active_atoms_as_string_
93 << std::flush;
94 {
95 // connectivity check, frontier-orbital coverage and optional growth
96 // (dft_in_dft.grow) from the full reference MOs
97 const ActiveRegion::Report region =
98 ActiveRegion::Evaluate(orb, activeatoms, active_growth_);
99 XTP_LOG(Log::error, *pLog_) << region.Format() << std::flush;
100 // the cores of the active atoms are the only ones in the active space
101 // (their localized core orbitals are assigned to the active region)
102 Index active_core_levels = 0;
103 if (!orb.hasECPName()) {
104 ECPBasisSet corelevels;
105 corelevels.Load("corelevels");
106 Index core_electrons = 0;
107 for (Index a : region.atoms) {
108 core_electrons +=
109 corelevels.getElement(orb.QMAtoms()[a].getElement()).getNcore();
110 }
111 active_core_levels = core_electrons / 2;
112 }
113 orb.setActiveCoreLevels(active_core_levels);
114 if (!region.added.empty()) {
115 activeatoms = region.atoms;
116 std::ostringstream list;
117 for (Index a : activeatoms) {
118 list << a << " ";
119 }
121 << "Active atoms after growing: " << list.str() << std::flush;
122 }
123 }
124 ActiveDensityMatrix DMAT_A(orb, activeatoms, active_threshold_);
125 const Eigen::MatrixXd InitialActiveDensityMatrix = DMAT_A.compute_Dmat_A()[0];
126 Eigen::MatrixXd InitialInactiveMOs = DMAT_A.compute_Dmat_A()[2];
127
129 << TimeStamp() << " Active density formation done" << std::flush;
130
131 Eigen::MatrixXd InactiveDensityMatrix =
132 FullDensityMatrix - InitialActiveDensityMatrix;
133
134 orb.setInactiveDensity(InactiveDensityMatrix);
135
136 // AOoverlap to calculate number of active/inactive electrons
137 AOBasis aobasis = orb.getDftBasis();
138 AOOverlap overlap;
139 overlap.Fill(aobasis);
140
141 Index all_electrons = static_cast<Index>(
142 std::round(FullDensityMatrix.cwiseProduct(overlap.Matrix()).sum()));
143 active_electrons_ = static_cast<Index>(std::round(
144 InitialActiveDensityMatrix.cwiseProduct(overlap.Matrix()).sum()));
145 Index inactive_electrons = static_cast<Index>(
146 std::round(InactiveDensityMatrix.cwiseProduct(overlap.Matrix()).sum()));
147
149 << TimeStamp() << " Total electrons: " << all_electrons << std::flush;
151 << TimeStamp() << " Active electrons: " << active_electrons_
152 << std::flush;
154 << TimeStamp() << " Inactive electrons: " << inactive_electrons
155 << std::flush;
156
157 // check for consistency
158 if ((active_electrons_ + inactive_electrons) != all_electrons) {
159 throw std::runtime_error(
160 " Sum of active and inactive electrons does "
161 "not match full number of electrons!");
162 return false;
163 }
164
165 // setup the DFT engine with the active electrons only
167
168 // setup one-electron part of the Hamiltonian
169 Mat_p_Energy H0 = SetupH0(orb.QMAtoms());
170
171 // energy of the one-electron part of the Hamiltonian
172 const double E0_full = FullDensityMatrix.cwiseProduct(H0.matrix()).sum();
173 const double E0_initial_active =
174 InitialActiveDensityMatrix.cwiseProduct(H0.matrix()).sum();
175 E_nuc_ = H0.energy();
176
177 // setup the Vxc integrator
178 Vxc_Potential<Vxc_Grid> vxcpotential = SetupVxc(orb.QMAtoms());
179 // get the constant XC contributions for the embedding
180 const Mat_p_Energy xc_full = vxcpotential.IntegrateVXC(FullDensityMatrix);
181 const Mat_p_Energy xc_initial_active =
182 vxcpotential.IntegrateVXC(InitialActiveDensityMatrix);
183
184 // get the constant Coulomb matrices for the embedding
185 Eigen::MatrixXd J_full =
186 Eigen::MatrixXd::Zero(FullDensityMatrix.rows(), FullDensityMatrix.cols());
187 Eigen::MatrixXd J_initial_active =
188 Eigen::MatrixXd::Zero(FullDensityMatrix.rows(), FullDensityMatrix.cols());
189 Eigen::MatrixXd K_full =
190 Eigen::MatrixXd::Zero(FullDensityMatrix.rows(), FullDensityMatrix.cols());
191 Eigen::MatrixXd K_initial_active =
192 Eigen::MatrixXd::Zero(FullDensityMatrix.rows(), FullDensityMatrix.cols());
193 if (ScaHFX_ > 0) {
194 std::array<Eigen::MatrixXd, 2> JandK_full =
195 CalcERIs_EXX(embeddingMOs.eigenvectors(), FullDensityMatrix, 1e-12);
196 std::array<Eigen::MatrixXd, 2> JandK_initial_active = CalcERIs_EXX(
197 embeddingMOs.eigenvectors(), InitialActiveDensityMatrix, 1e-12);
198 J_full = JandK_full[0];
199 K_full = 0.5 * ScaHFX_ * JandK_full[1];
200 J_initial_active = JandK_initial_active[0];
201 K_initial_active = 0.5 * ScaHFX_ * JandK_initial_active[1];
202 } else {
203 J_full = CalcERIs(FullDensityMatrix, 1e-12);
204 J_initial_active = CalcERIs(InitialActiveDensityMatrix, 1e-12);
205 }
206 // get the Hartree energies
207 const double E_Hartree_full =
208 0.5 * FullDensityMatrix.cwiseProduct(J_full + K_full).sum();
209 const double E_Hartree_initial_active =
210 0.5 * InitialActiveDensityMatrix
211 .cwiseProduct(J_initial_active + K_initial_active)
212 .sum();
213
214 // Energy of the full reference system
215 Total_E_full_ = E0_full + E_Hartree_full + xc_full.energy() + E_nuc_;
216
218 << TimeStamp()
219 << " Reference total energy full electron system: " << Total_E_full_
220 << " Ha" << std::flush;
221
222 // projection parameter, to be made an option
223 Eigen::MatrixXd ProjectionOperator =
224 overlap.Matrix() * InactiveDensityMatrix * overlap.Matrix();
225
226 // XC and Hartree contribution to the external embedding potential/energy
227 const Eigen::MatrixXd v_embedding = J_full + K_full + xc_full.matrix() -
228 J_initial_active - K_initial_active -
229 xc_initial_active.matrix();
230
231 const double constant_embedding_energy = Total_E_full_ - E0_initial_active -
232 E_Hartree_initial_active -
233 xc_initial_active.energy();
234
236 << TimeStamp() << " Constant energy embedding terms: " << std::flush;
238 << TimeStamp() << " 1) E_DFT[full]: " << Total_E_full_ << std::flush;
240 << TimeStamp() << " 2) E_0[initial active]: " << E0_initial_active
241 << std::flush;
243 << TimeStamp() << " 3) E_H[initial active]: " << E_Hartree_initial_active
244 << std::flush;
245 XTP_LOG(Log::info, *pLog_) << TimeStamp() << " 4) E_XC[initial active]: "
246 << xc_initial_active.energy() << std::flush;
248 << TimeStamp() << " Total 1 -2 -3 -4: " << constant_embedding_energy
249 << std::flush;
250
251 if (truncate_) { // Truncation starts here
252 orb.setCalculationType("Truncated");
253 TruncateBasis(orb, activeatoms, H0, InitialActiveDensityMatrix, v_embedding,
254 InitialInactiveMOs);
255 active_and_border_atoms_ = activeatoms;
256 }
257 // SCF loop if you don't truncate active region
258 else {
259 orb.setCalculationType("Embedded_noTrunc");
260 Eigen::MatrixXd ActiveDensityMatrix = InitialActiveDensityMatrix;
261 conv_accelerator_.StartNewSCF();
262 for (Index this_iter = 0; this_iter < max_iter_; this_iter++) {
263 XTP_LOG(Log::error, *pLog_) << std::flush;
265 << TimeStamp() << " Iteration " << this_iter + 1 << " of "
266 << max_iter_ << std::flush;
267
268 // get the XC contribution for the updated active density matrix
269 Mat_p_Energy xc_active = vxcpotential.IntegrateVXC(ActiveDensityMatrix);
270 double E_xc_active = xc_active.energy();
271
272 // get the Hartree contribution for the updated active density matrix
273 Eigen::MatrixXd J_active = Eigen::MatrixXd::Zero(
275 Eigen::MatrixXd K_active = Eigen::MatrixXd::Zero(
277 if (ScaHFX_ > 0) {
278 std::array<Eigen::MatrixXd, 2> JandK_active = CalcERIs_EXX(
279 embeddingMOs.eigenvectors(), ActiveDensityMatrix, 1e-12);
280 J_active = JandK_active[0];
281 K_active = 0.5 * ScaHFX_ * JandK_active[1];
282
283 } else {
284 J_active = CalcERIs(ActiveDensityMatrix, 1e-12);
285 }
286 double E_Hartree_active =
287 0.5 * ActiveDensityMatrix.cwiseProduct(J_active + K_active).sum();
288
289 // update the active Hamiltonian
290 const Eigen::MatrixXd Level_Shift_Operator =
291 levelshift_ * ProjectionOperator;
292 Eigen::MatrixXd H_active = H0.matrix() + v_embedding +
293 Level_Shift_Operator + xc_active.matrix() +
294 J_active + K_active;
295
296 const double E0_active =
297 ActiveDensityMatrix.cwiseProduct(H0.matrix()).sum();
298 const double E_embedding =
299 (ActiveDensityMatrix - InitialActiveDensityMatrix)
300 .cwiseProduct(v_embedding)
301 .sum();
302 const double E_levelshift =
303 ActiveDensityMatrix.cwiseProduct(Level_Shift_Operator).sum();
304
305 double TotalEnergy = E0_active + E_Hartree_active + E_xc_active +
306 constant_embedding_energy + E_levelshift +
307 E_embedding;
308
310 << TimeStamp() << " Total Energy after embedding: " << TotalEnergy
311 << std::flush;
313 << TimeStamp() << " I) E_0[active]: " << E0_active << std::flush;
315 << TimeStamp() << " II) E_H[active]: " << E_Hartree_active
316 << std::flush;
318 << TimeStamp() << " III) E_xc[active]: " << E_xc_active << std::flush;
320 << TimeStamp() << " IV) E_ext_emb :" << constant_embedding_energy
321 << std::flush;
323 << TimeStamp() << " V) E_corr_emb :" << E_embedding << std::flush;
325 << TimeStamp() << " VI) E_levelshift :" << E_levelshift
326 << std::flush;
328 << TimeStamp() << " Total I + II + III + IV + V +VI :" << TotalEnergy
329 << std::flush;
330
331 // get a new density matrix in the active region
333 << std::endl
334 << "Active electrons in = "
335 << ActiveDensityMatrix.cwiseProduct(overlap.Matrix()).sum()
336 << std::flush;
338 ActiveDensityMatrix, H_active, embeddingMOs, TotalEnergy);
340 << std::endl
341 << "Active electrons out= "
342 << ActiveDensityMatrix.cwiseProduct(overlap.Matrix()).sum()
343 << std::flush;
344
345 PrintMOs(embeddingMOs.eigenvalues(), Log::info);
346
347 if (conv_accelerator_.isConverged()) {
349 << TimeStamp() << " Total embedding energy has converged to "
350 << std::setprecision(9) << conv_accelerator_.getDeltaE()
351 << "[Ha] after " << this_iter + 1
352 << " iterations. DIIS error is converged up to "
353 << conv_accelerator_.getDIIsError() << std::flush;
355 << TimeStamp() << " Final Single Point Energy of embedding "
356 << std::setprecision(12) << TotalEnergy << " Ha" << std::flush;
358 << "The difference between the reference energy and the embedding "
359 "energy is "
360 << Total_E_full_ - TotalEnergy << " Ha" << std::flush;
361
362 if (abs(Total_E_full_ - TotalEnergy) > 1e-3) {
364 << "Warning!! The difference is greater than 1e-03 Ha"
365 << std::flush;
366 }
367
368 PrintMOs(embeddingMOs.eigenvalues(), Log::error);
369 orb.setEmbeddedMOs(embeddingMOs);
371 CalcElDipole(orb);
372 break;
373 } else if (this_iter == max_iter_ - 1) {
375 << TimeStamp()
376 << " DFT calculation for active region has not converged after "
377 << max_iter_
378 << " iterations. Use more iterations or another convergence "
379 "acceleration scheme."
380 << std::flush;
381 return false;
382 }
383 }
384 }
385 return true;
386}
387
389 if (truncate_) {
390 activemol_.ReorderAtomIDs();
391 trunc_orb.QMAtoms() = activemol_;
392 Prepare(trunc_orb, active_electrons_);
393 Vxc_Potential<Vxc_Grid> vxcpotential = SetupVxc(trunc_orb.QMAtoms());
394 ConfigOrbfile(trunc_orb);
395 AOBasis aobasis = trunc_orb.getDftBasis();
396 AOOverlap overlap;
397 overlap.Fill(aobasis);
398
399 const double E0_initial_truncated =
400 InitialActiveDmat_trunc_.cwiseProduct(H0_trunc_).sum();
401 const Mat_p_Energy xc_initial_truncated =
403 Eigen::MatrixXd J_initial_truncated = Eigen::MatrixXd::Zero(
405 Eigen::MatrixXd K_initial_truncated = Eigen::MatrixXd::Zero(
407 tools::EigenSystem MOs_trunc;
408 MOs_trunc.eigenvalues() = Eigen::VectorXd::Zero(H0_trunc_.cols());
409 MOs_trunc.eigenvectors() =
410 Eigen::MatrixXd::Zero(H0_trunc_.rows(), H0_trunc_.cols());
411 if (ScaHFX_ > 0) {
412 std::array<Eigen::MatrixXd, 2> JandK_initial_truncated = CalcERIs_EXX(
413 MOs_trunc.eigenvectors(), InitialActiveDmat_trunc_, 1e-12);
414 J_initial_truncated = JandK_initial_truncated[0];
415 K_initial_truncated = 0.5 * ScaHFX_ * JandK_initial_truncated[1];
416 } else {
417 J_initial_truncated = CalcERIs(InitialActiveDmat_trunc_, 1e-12);
418 }
419 // get the Hartree energies
420 const double E_Hartree_initial_truncated =
422 .cwiseProduct(J_initial_truncated + K_initial_truncated)
423 .sum();
424 const double Initial_truncated_energy = E0_initial_truncated +
425 E_Hartree_initial_truncated +
426 xc_initial_truncated.energy();
428 << "Initial truncated energy = " << Initial_truncated_energy
429 << std::flush;
430
431 Eigen::MatrixXd PurifiedActiveDmat_trunc =
433 Eigen::MatrixXd TruncatedDensityMatrix = PurifiedActiveDmat_trunc;
434
435 conv_accelerator_.StartNewSCF();
436 for (Index this_iter = 0; this_iter < max_iter_; this_iter++) {
437 XTP_LOG(Log::error, *pLog_) << std::flush;
439 << TimeStamp() << " Iteration " << this_iter + 1 << " of "
440 << max_iter_ << std::flush;
441
442 // get the XC contribution for the updated truncated density matrix
443 Mat_p_Energy xc_truncated =
444 vxcpotential.IntegrateVXC(TruncatedDensityMatrix);
445 double E_xc_truncated = xc_truncated.energy();
446
447 // get the Hartree contribution for the updated truncated density matrix
448 Eigen::MatrixXd J_truncated = Eigen::MatrixXd::Zero(
449 TruncatedDensityMatrix.rows(), TruncatedDensityMatrix.cols());
450 Eigen::MatrixXd K_truncated = Eigen::MatrixXd::Zero(
451 TruncatedDensityMatrix.rows(), TruncatedDensityMatrix.cols());
452 if (ScaHFX_ > 0) {
453 std::array<Eigen::MatrixXd, 2> JandK_truncated = CalcERIs_EXX(
454 MOs_trunc.eigenvectors(), TruncatedDensityMatrix, 1e-12);
455 J_truncated = JandK_truncated[0];
456 K_truncated = 0.5 * ScaHFX_ * JandK_truncated[1];
457
458 } else {
459 J_truncated = CalcERIs(TruncatedDensityMatrix, 1e-12);
460 }
461 double E_Hartree_truncated =
462 0.5 *
463 TruncatedDensityMatrix.cwiseProduct(J_truncated + K_truncated).sum();
464 // update the truncated Hamiltonian
465 Eigen::MatrixXd H_truncated =
466 H0_trunc_ + xc_truncated.matrix() + J_truncated + K_truncated;
467
468 double TruncatedTotalEnergy =
469 TruncatedDensityMatrix.cwiseProduct(H0_trunc_).sum() +
470 E_Hartree_truncated + E_xc_truncated + Total_E_full_ -
471 Initial_truncated_energy +
472 ((TruncatedDensityMatrix - InitialActiveDmat_trunc_)
473 .cwiseProduct(v_embedding_trunc_)
474 .sum());
475 // get the new truncated density matrix
477 << "Electrons in = "
478 << TruncatedDensityMatrix.cwiseProduct(overlap.Matrix()).sum()
479 << std::flush;
480 TruncatedDensityMatrix = conv_accelerator_.Iterate(
481 TruncatedDensityMatrix, H_truncated, MOs_trunc, TruncatedTotalEnergy);
483 << "Electrons out = "
484 << TruncatedDensityMatrix.cwiseProduct(overlap.Matrix()).sum()
485 << std::flush;
486
488 << TimeStamp() << " E_trunc (Ha) = "
489 << TruncatedDensityMatrix.cwiseProduct(H0_trunc_).sum() +
490 E_Hartree_truncated + E_xc_truncated
491 << "\n \t \t \t" << " E_fullDFT (Ha) = " << Total_E_full_
492 << "\n \t \t \t"
493 << " E_initial_trunc(Ha) = " << Initial_truncated_energy
494 << "\n \t \t \t" << " E_embedding_correction(Ha) = "
495 << ((TruncatedDensityMatrix - InitialActiveDmat_trunc_)
496 .cwiseProduct(v_embedding_trunc_)
497 .sum())
498 << std::flush;
499
501 << " Truncated Energy of the system: E_trunc + E_fullDFT - "
502 << "\n \t \t" << " E_initial_trunc + E_embedding_correction = "
503 << TruncatedTotalEnergy << std::flush;
504
505 PrintMOs(MOs_trunc.eigenvalues(), Log::info);
506
507 if (conv_accelerator_.isConverged()) {
509 << TimeStamp() << " Total embedding energy has converged to "
510 << std::setprecision(9) << conv_accelerator_.getDeltaE()
511 << "[Ha] after " << this_iter + 1
512 << " iterations. DIIS error is converged up to "
513 << conv_accelerator_.getDIIsError() << std::flush;
515 << TimeStamp() << " Final Single Point Energy of embedding "
516 << std::setprecision(12) << TruncatedTotalEnergy << " Ha"
517 << std::flush;
518
519 PrintMOs(MOs_trunc.eigenvalues(), Log::error);
520 trunc_orb.setEmbeddedMOs(MOs_trunc);
522 break;
523 }
524 }
526 }
527 return true;
528}
529
530void DFTEngine::TruncateBasis(Orbitals& orb, std::vector<Index>& activeatoms,
531 Mat_p_Energy& H0,
532 Eigen::MatrixXd InitialActiveDensityMatrix,
533 Eigen::MatrixXd v_embedding,
534 Eigen::MatrixXd InitialInactiveMOs) {
535 AOBasis aobasis;
536 aobasis = orb.getDftBasis();
537 AOOverlap overlap;
538 overlap.Fill(aobasis);
539 // Mulliken population per basis function on every active atom
540 Eigen::VectorXd DiagonalofDmatA = InitialActiveDensityMatrix.diagonal();
541 Eigen::VectorXd DiagonalofOverlap = overlap.Matrix().diagonal();
542 Eigen::VectorXd MnP = DiagonalofDmatA.cwiseProduct(DiagonalofOverlap);
543
544 // Get a vector containing the number of basis functions per atom
545 const std::vector<Index>& numfuncpatom = aobasis.getFuncPerAtom();
546 numfuncpatom_ = numfuncpatom;
547 Index numofactivebasisfunction = 0;
548 // Store start indices. Will be used later
549 std::vector<Index> start_indices, start_indices_activemolecule;
550 Index start_idx = 0, start_idx_activemolecule = 0;
551 std::vector<Index> borderatoms;
552 for (Index atom_num = 0; atom_num < orb.QMAtoms().size(); atom_num++) {
553 start_indices.push_back(start_idx);
554 /* Condition for basis fn on an atom to be counted: either in active
555 region or MnP of any function > threshold (border atoms) */
556 bool partOfActive =
557 (std::find(activeatoms.begin(), activeatoms.end(),
558 orb.QMAtoms()[atom_num].getId()) != activeatoms.end());
559 if (partOfActive == true) {
560 activemol_.push_back(orb.QMAtoms()[atom_num]);
561 /* if active append the atom to the new molecule. Also increment active
562 basis function size and start indices */
563 start_indices_activemolecule.push_back(start_idx_activemolecule);
564 start_idx_activemolecule += numfuncpatom[atom_num];
565 numofactivebasisfunction += numfuncpatom[atom_num];
566 } else {
567 std::vector<const AOShell*> inactiveshell =
568 aobasis.getShellsofAtom(orb.QMAtoms()[atom_num].getId());
569 bool loop_break = false;
570 for (const AOShell* shell : inactiveshell) {
571 for (Index shell_fn_no = shell->getStartIndex();
572 shell_fn_no < shell->getStartIndex() + shell->getNumFunc();
573 shell_fn_no++) {
574 if (MnP[shell_fn_no] > truncation_threshold_) {
575 activeatoms.push_back(atom_num);
576 borderatoms.push_back(atom_num); // push this index to border
577 // atoms
578 activemol_.push_back(orb.QMAtoms()[atom_num]);
579 loop_break = true; // if any function in the whole atom satisfies
580 // we break loop to check next atom
581 start_indices_activemolecule.push_back(start_idx_activemolecule);
582 start_idx_activemolecule += numfuncpatom[atom_num];
583 numofactivebasisfunction += numfuncpatom[atom_num];
584 break;
585 }
586 }
587 if (loop_break) break;
588 }
589 }
590 start_idx += numfuncpatom[atom_num];
591 }
592
593 // Sort atoms before you cut the Hamiltonian
594 sort(activeatoms.begin(), activeatoms.end());
595 sort(borderatoms.begin(), borderatoms.end());
596 Eigen::MatrixXd InactiveDensityMatrix = orb.getInactiveDensity();
597 XTP_LOG(Log::error, *pLog_) << std::flush;
599 << "Active + Border Molecule Size = " << activeatoms.size() << "\n \t \t "
600 << "Border Molecule Size = " << borderatoms.size() << std::flush;
601 Eigen::MatrixXd ProjectionOperator =
602 overlap.Matrix() * InactiveDensityMatrix * overlap.Matrix();
603
604 Eigen::MatrixXd H_embedding =
605 H0.matrix() + v_embedding + levelshift_ * ProjectionOperator;
606
607 if (borderatoms.size() != 0) {
608 Eigen::MatrixXd BorderMOs;
609 for (Index lmo_index = 0; lmo_index < InitialInactiveMOs.cols();
610 lmo_index++) {
611 double mullikenpop_lmo_borderatoms = 0;
612 for (Index borderatom : borderatoms) {
613 Index start = start_indices[borderatom];
614 Index size = numfuncpatom[borderatom];
615 mullikenpop_lmo_borderatoms +=
616 (InitialInactiveMOs.col(lmo_index) *
617 InitialInactiveMOs.col(lmo_index).transpose() * overlap.Matrix())
618 .diagonal()
619 .segment(start, size)
620 .sum();
621 }
622 /*If more than half of a MO contributes on a border atom include that in
623 * the Border MOs list. Not made an user option. If you want to fix
624 * further for density leak you can reduce this number*/
625 if (mullikenpop_lmo_borderatoms > 0.25) {
626 BorderMOs.conservativeResize(InitialInactiveMOs.rows(),
627 BorderMOs.cols() + 1);
628 BorderMOs.col(BorderMOs.cols() - 1) = InitialInactiveMOs.col(lmo_index);
629 }
630 }
631
632 Eigen::MatrixXd BorderDmat = 2 * BorderMOs * BorderMOs.transpose();
633 Eigen::MatrixXd BorderProjectionOperator =
634 overlap.Matrix() * BorderDmat * overlap.Matrix();
635 Eigen::MatrixXd DistantProjectionOperator =
636 ProjectionOperator - BorderProjectionOperator;
637 // 1e+2 is the suitable projection value for border MOs: see citations
638 H_embedding +=
639 1e+2 * BorderProjectionOperator +
640 levelshift_ * (DistantProjectionOperator - ProjectionOperator);
641 }
642
643 // from here it is time to truncate Hamiltonian H0
644 H0_trunc_ =
645 Eigen::MatrixXd::Zero(numofactivebasisfunction, numofactivebasisfunction);
647 Eigen::MatrixXd::Zero(numofactivebasisfunction, numofactivebasisfunction);
649 Eigen::MatrixXd::Zero(numofactivebasisfunction, numofactivebasisfunction);
650 // Defined needed matrices with basisset_size * basisset_size
651
652 for (Index activeatom1_idx = 0; activeatom1_idx < Index(activeatoms.size());
653 activeatom1_idx++) {
654 Index activeatom1 = activeatoms[activeatom1_idx];
655 for (Index activeatom2_idx = 0; activeatom2_idx < Index(activeatoms.size());
656 activeatom2_idx++) {
657 Index activeatom2 = activeatoms[activeatom2_idx];
658 // Fill the H0, Dmat and v_embedding at the right indices
659 H0_trunc_.block(start_indices_activemolecule[activeatom1_idx],
660 start_indices_activemolecule[activeatom2_idx],
661 numfuncpatom[activeatom1], numfuncpatom[activeatom2]) =
662 H_embedding.block(
663 start_indices[activeatom1], start_indices[activeatom2],
664 numfuncpatom[activeatom1], numfuncpatom[activeatom2]);
666 start_indices_activemolecule[activeatom1_idx],
667 start_indices_activemolecule[activeatom2_idx],
668 numfuncpatom[activeatom1], numfuncpatom[activeatom2]) =
669 InitialActiveDensityMatrix.block(
670 start_indices[activeatom1], start_indices[activeatom2],
671 numfuncpatom[activeatom1], numfuncpatom[activeatom2]);
672 v_embedding_trunc_.block(start_indices_activemolecule[activeatom1_idx],
673 start_indices_activemolecule[activeatom2_idx],
674 numfuncpatom[activeatom1],
675 numfuncpatom[activeatom2]) =
676 v_embedding.block(
677 start_indices[activeatom1], start_indices[activeatom2],
678 numfuncpatom[activeatom1], numfuncpatom[activeatom2]);
679 }
680 }
681}
682
683Eigen::MatrixXd DFTEngine::McWeenyPurification(Eigen::MatrixXd& Dmat_in,
684 AOOverlap& overlap) {
685 Eigen::MatrixXd Ssqrt = overlap.Sqrt();
686 Eigen::MatrixXd InvSsqrt = overlap.Pseudo_InvSqrt(1e-8);
687 Eigen::MatrixXd ModifiedDmat = 0.5 * Ssqrt * Dmat_in * Ssqrt;
688 for (Index iter = 0; iter < 100; iter++) {
689 Eigen::MatrixXd Dmat_new = (3 * ModifiedDmat * ModifiedDmat) -
690 (2 * ModifiedDmat * ModifiedDmat * ModifiedDmat);
691 double IdempotencyError =
692 ((Dmat_new * Dmat_new - Dmat_new) * (Dmat_new * Dmat_new - Dmat_new))
693 .trace();
695 << "Idempotency Error: " << IdempotencyError << std::flush;
696
697 ModifiedDmat = Dmat_new;
698 if (IdempotencyError < 1e-20) break;
699 }
700 Eigen::MatrixXd Dmat_out = 2 * InvSsqrt * ModifiedDmat * InvSsqrt;
701 return 0.5 * (Dmat_out + Dmat_out.transpose());
702}
703
704void DFTEngine::TruncMOsFullBasis(Orbitals& orb, std::vector<Index> activeatoms,
705 std::vector<Index> numfuncpatom) {
706 Eigen::MatrixXd expandtruncorb = orb.getEmbeddedMOs().eigenvectors();
707 Index start_index = 0;
708 Index numofactualactoms = numfuncpatom.size();
709 for (Index atomindex = 0; atomindex < numofactualactoms; atomindex++) {
710 bool partOfActive = (std::find(activeatoms.begin(), activeatoms.end(),
711 atomindex) != activeatoms.end());
712 if (partOfActive == false) {
713 expandtruncorb =
714 InsertZeroRows(expandtruncorb, start_index, numfuncpatom[atomindex]);
715 }
716 start_index += numfuncpatom[atomindex];
717 }
718 orb.setTruncMOsFullBasis(expandtruncorb);
719}
720
721Eigen::MatrixXd DFTEngine::InsertZeroRows(Eigen::MatrixXd MOsMatrix,
722 Index startidx, Index numofzerorows) {
723 Eigen::MatrixXd FinalMatrix =
724 Eigen::MatrixXd::Zero(MOsMatrix.rows() + numofzerorows, MOsMatrix.cols());
725 FinalMatrix.topRows(startidx) = MOsMatrix.topRows(startidx);
726 FinalMatrix.bottomRows(MOsMatrix.rows() - startidx) =
727 MOsMatrix.bottomRows(MOsMatrix.rows() - startidx);
728 return FinalMatrix;
729}
730} // namespace xtp
731} // namespace votca
const Eigen::VectorXd & eigenvalues() const
Definition eigensystem.h:30
const Eigen::MatrixXd & eigenvectors() const
Definition eigensystem.h:33
Container to hold Basisfunctions for all atoms.
Definition aobasis.h:42
const std::vector< const AOShell * > getShellsofAtom(Index AtomId) const
Definition aobasis.cc:63
const std::vector< Index > & getFuncPerAtom() const
Definition aobasis.h:72
void Fill(const AOBasis &aobasis) final
Eigen::MatrixXd Pseudo_InvSqrt(double etol)
Definition aomatrix.cc:29
const Eigen::MatrixXd & Matrix() const
Definition aomatrix.h:52
Eigen::MatrixXd Sqrt()
Definition aomatrix.cc:45
std::array< Eigen::MatrixXd, 3 > compute_Dmat_A()
static Report Evaluate(const Orbitals &full, const std::vector< Index > &active, const Options &options)
Checks the input region, and with options.grow adds every atom whose population in a frontier orbital...
Eigen::MatrixXd CalcERIs(const Eigen::MatrixXd &Dmat, double error) const
Build the Coulomb matrix contribution from the current density matrix.
Definition dftengine.cc:739
bool EvaluateTruncatedActiveRegion(Orbitals &trunc_orb)
ActiveRegion::Options active_growth_
Definition dftengine.h:702
Eigen::MatrixXd InitialActiveDmat_trunc_
Definition dftengine.h:708
void TruncMOsFullBasis(Orbitals &orb, std::vector< Index > activeatoms, std::vector< Index > numfuncpatom)
void TruncateBasis(Orbitals &orb, std::vector< Index > &activeatoms, Mat_p_Energy &H0, Eigen::MatrixXd InitialActiveDensityMatrix, Eigen::MatrixXd v_embedding, Eigen::MatrixXd InitialInactiveMOs)
bool EvaluateActiveRegion(Orbitals &orb)
void Prepare(Orbitals &orb, Index numofelectrons=-1)
Eigen::MatrixXd InsertZeroRows(Eigen::MatrixXd MOsMatrix, Index startidx, Index numofzerorows)
Insert zero rows into an MO coefficient matrix at the requested position.
std::array< Eigen::MatrixXd, 2 > CalcERIs_EXX(const Eigen::MatrixXd &MOCoeff, const Eigen::MatrixXd &Dmat, double error) const
Definition dftengine.cc:713
Eigen::MatrixXd H0_trunc_
Definition dftengine.h:707
void CalcElDipole(const Orbitals &orb) const
Evaluate and print the electronic dipole moment from the final density.
Definition dftengine.cc:373
std::string active_atoms_as_string_
Definition dftengine.h:701
void ConfigOrbfile(Orbitals &orb)
Propagate basis-set, XC, and metadata settings into the orbital container.
QMMolecule activemol_
Definition dftengine.h:692
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
std::vector< Index > numfuncpatom_
Definition dftengine.h:716
std::vector< Index > active_and_border_atoms_
Definition dftengine.h:715
Mat_p_Energy SetupH0(const QMMolecule &mol) const
Assemble the one-electron core Hamiltonian for the current molecule.
Eigen::MatrixXd v_embedding_trunc_
Definition dftengine.h:709
Eigen::MatrixXd McWeenyPurification(Eigen::MatrixXd &Dmat_in, AOOverlap &overlap)
Vxc_Potential< Vxc_Grid > SetupVxc(const QMMolecule &mol)
ConvergenceAcc conv_accelerator_
Definition dftengine.h:662
void Load(const std::string &name)
const ECPElement & getElement(std::string element_type) const
Index getNcore() const
Definition ecpbasisset.h:90
std::vector< Index > CreateIndexVector(const std::string &Ids) const
Eigen::MatrixXd & matrix()
Definition eigen.h:97
double & energy()
Definition eigen.h:98
Container for molecular orbitals and derived one-particle data.
Definition orbitals.h:47
void setCalculationType(std::string CalcType)
Store the calculation-type tag used by downstream workflows.
Definition orbitals.h:240
void setInactiveDensity(Eigen::MatrixXd inactivedensity)
Store the inactive-region density matrix used in embedding workflows.
Definition orbitals.h:760
void setNumofActiveElectrons(const Index active_electrons)
Store the number of electrons assigned to the active region.
Definition orbitals.h:747
void setTruncMOsFullBasis(const Eigen::MatrixXd &expandedMOs)
Store truncated active-region orbitals expanded back to the full AO basis.
Definition orbitals.h:64
Index getNumberOfAlphaElectrons() const
Return the stored number of alpha electrons.
Definition orbitals.h:159
const Eigen::MatrixXd & getLMOs() const
Return localized molecular orbitals, if available.
Definition orbitals.h:733
void setActiveCoreLevels(Index n)
Definition orbitals.h:755
const Eigen::MatrixXd & getInactiveDensity() const
Return the inactive-region density matrix used in embedding workflows.
Definition orbitals.h:758
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
Eigen::MatrixXd DensityMatrixGroundState() const
Build the ground-state AO density matrix from the stored orbitals.
Definition orbitals.cc:224
const QMMolecule & QMAtoms() const
Return read-only access to the molecular geometry.
Definition orbitals.h:262
void setEmbeddedMOs(tools::EigenSystem &system)
Store molecular orbitals obtained from an embedding calculation.
Definition orbitals.h:58
const tools::EigenSystem & getEmbeddedMOs() const
Return molecular orbitals obtained from an embedding calculation.
Definition orbitals.h:61
const AOBasis & getDftBasis() const
Return the DFT AO basis, throwing if it has not been initialized.
Definition orbitals.h:386
Timestamp returns the current time as a string Example: cout << TimeStamp().
Definition logger.h:224
Mat_p_Energy IntegrateVXC(const Eigen::MatrixXd &density_matrix) const
#define XTP_LOG(level, log)
Definition logger.h:40
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
Provides a means for comparing floating point numbers.
Definition basebead.h:33
Eigen::Index Index
Definition types.h:26