votca 2026-dev
Loading...
Searching...
No Matches
vxc_potential.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 <cmath>
24#include <exception>
25#include <iomanip>
26#include <iostream>
27#include <stdexcept>
28#include <vector>
29
30// VOTCA includes
32
33// Local VOTCA includes
34#include "votca/xtp/aobasis.h"
38#include "votca/xtp/vxc_grid.h"
40
41namespace votca {
42namespace xtp {
43
44namespace {
45// Range-separated hybrids (HSE, CAM-B3LYP, ...) need erf-attenuated exact
46// exchange, which neither the DFT nor GW parts implement: the code would use
47// cam_alpha as a global exchange fraction and run a different functional
48// without notice. Refuse them.
49void RejectRangeSeparated(const xc_func_type& func, const std::string& name) {
50 if (func.cam_beta != 0.0 || func.cam_omega != 0.0) {
51 throw std::runtime_error(
52 "Functional " + name +
53 " is a range-separated hybrid; range-separated exact exchange is not "
54 "implemented in xtp (DFT and GW). Use a global hybrid or a semilocal "
55 "functional.");
56 }
57}
58} // namespace
59
60template <class Grid>
62 if (setXC_) {
63 xc_func_end(&xfunc);
64 xc_func_end(&xfunc_pol_);
65 if (use_separate_) {
66 xc_func_end(&cfunc);
67 xc_func_end(&cfunc_pol_);
68 }
69 }
70}
71
72template <class Grid>
73double Vxc_Potential<Grid>::getExactExchange(const std::string& functional) {
74 double exactexchange = 0.0;
76
77 std::vector<std::string> functional_names =
78 tools::Tokenizer(functional, " ").ToVector();
79
80 if (functional_names.size() > 2) {
81 throw std::runtime_error("Too many functional names");
82 } else if (functional_names.empty()) {
83 throw std::runtime_error("Specify at least one functional");
84 }
85
86 for (const std::string& functional_name : functional_names) {
87 int func_id = map.getID(functional_name);
88 if (func_id < 0) {
89 exactexchange = 0.0;
90 break;
91 }
92
93 xc_func_type func;
94 if (xc_func_init(&func, func_id, XC_UNPOLARIZED) != 0) {
95 throw std::runtime_error(
96 (boost::format("Functional %s not found\n") % functional_name).str());
97 }
98
99 try {
100 RejectRangeSeparated(func, functional_name);
101 } catch (...) {
102 xc_func_end(&func);
103 throw;
104 }
105
106 if (exactexchange > 0 && func.cam_alpha > 0) {
107 xc_func_end(&func);
108 throw std::runtime_error(
109 "You have specified two functionals with exact exchange");
110 }
111
112 exactexchange += func.cam_alpha;
113 xc_func_end(&func);
114 }
115
116 return exactexchange;
117}
118
119template <class Grid>
120void Vxc_Potential<Grid>::setXCfunctional(const std::string& functional) {
121 Vxc_Functionals map;
122 std::vector<std::string> strs =
123 tools::Tokenizer(functional, " ,\n\t").ToVector();
124
125 xfunc_id = 0;
126 use_separate_ = false;
127 cfunc_id = 0;
128
129 if (strs.size() == 1) {
130 xfunc_id = map.getID(strs[0]);
131 } else if (strs.size() == 2) {
132 xfunc_id = map.getID(strs[0]);
133 cfunc_id = map.getID(strs[1]);
134 use_separate_ = true;
135 } else {
136 throw std::runtime_error(
137 "LIBXC. Please specify one combined or an exchange and a correlation "
138 "functionals");
139 }
140
141 // Keep the stored handles UNPOLARIZED for the closed-shell/restricted code
142 // path. The UKS path creates temporary polarized handles inside
143 // EvaluateXCSpin().
144 if (xc_func_init(&xfunc, xfunc_id, XC_UNPOLARIZED) != 0) {
145 throw std::runtime_error(
146 (boost::format("Functional %s not found\n") % strs[0]).str());
147 }
148
149 try {
150 RejectRangeSeparated(xfunc, strs[0]);
151 } catch (...) {
152 xc_func_end(&xfunc);
153 throw;
154 }
155
156 if (xfunc.info->kind != 2 && !use_separate_) {
157 throw std::runtime_error(
158 "Your functional misses either correlation or exchange, please specify "
159 "another functional, separated by whitespace");
160 }
161
162 if (use_separate_) {
163 if (xc_func_init(&cfunc, cfunc_id, XC_UNPOLARIZED) != 0) {
164 xc_func_end(&xfunc);
165 throw std::runtime_error(
166 (boost::format("Functional %s not found\n") % strs[1]).str());
167 }
168
169 try {
170 RejectRangeSeparated(cfunc, strs[1]);
171 } catch (...) {
172 xc_func_end(&xfunc);
173 xc_func_end(&cfunc);
174 throw;
175 }
176
177 if ((xfunc.info->kind + cfunc.info->kind) != 1) {
178 xc_func_end(&xfunc);
179 xc_func_end(&cfunc);
180 throw std::runtime_error(
181 "Your functionals are not one exchange and one correlation");
182 }
183 }
184
185 // Polarized twins for the UKS path.
186 if (xc_func_init(&xfunc_pol_, xfunc_id, XC_POLARIZED) != 0) {
187 throw std::runtime_error(
188 "Failed to initialize polarized exchange XC "
189 "functional.");
190 }
191 if (use_separate_ && xc_func_init(&cfunc_pol_, cfunc_id, XC_POLARIZED) != 0) {
192 xc_func_end(&xfunc_pol_);
193 throw std::runtime_error(
194 "Failed to initialize polarized correlation XC "
195 "functional.");
196 }
197
198 auto is_gga = [](const xc_func_type& f) {
199 return f.info->family == XC_FAMILY_GGA ||
200 f.info->family == XC_FAMILY_HYB_GGA;
201 };
202 is_gga_ = is_gga(xfunc) || (use_separate_ && is_gga(cfunc));
203
204 setXC_ = true;
205 return;
206}
207
208namespace {
209// One libxc call for n points with any supported family.
210void CallLibxc(const xc_func_type& f, Index n, const double* rho,
211 const double* sigma, double* exc, double* vrho, double* vsigma) {
212 switch (f.info->family) {
213 case XC_FAMILY_LDA:
214 xc_lda_exc_vxc(&f, std::size_t(n), rho, exc, vrho);
215 break;
216 case XC_FAMILY_GGA:
217 case XC_FAMILY_HYB_GGA:
218 xc_gga_exc_vxc(&f, std::size_t(n), rho, sigma, exc, vrho, vsigma);
219 break;
220 default:
221 throw std::runtime_error("Unsupported XC functional family.");
222 }
223}
224} // namespace
225
226template <class Grid>
228 const double* sigma, double* exc,
229 double* vrho, double* vsigma) const {
230 std::fill(vsigma, vsigma + n, 0.0);
231 CallLibxc(xfunc, n, rho, sigma, exc, vrho, vsigma);
232 if (use_separate_) {
233 std::vector<double> e(n), vr(n), vs(n, 0.0);
234 CallLibxc(cfunc, n, rho, sigma, e.data(), vr.data(), vs.data());
235 for (Index i = 0; i < n; ++i) {
236 exc[i] += e[i];
237 vrho[i] += vr[i];
238 vsigma[i] += vs[i];
239 }
240 }
241}
242
243template <class Grid>
245 const double* sigma, double* exc,
246 double* vrho,
247 double* vsigma) const {
248 std::fill(vsigma, vsigma + 3 * n, 0.0);
249 CallLibxc(xfunc_pol_, n, rho, sigma, exc, vrho, vsigma);
250 if (use_separate_) {
251 std::vector<double> e(n), vr(2 * n), vs(3 * n, 0.0);
252 CallLibxc(cfunc_pol_, n, rho, sigma, e.data(), vr.data(), vs.data());
253 for (Index i = 0; i < n; ++i) {
254 exc[i] += e[i];
255 }
256 for (Index i = 0; i < 2 * n; ++i) {
257 vrho[i] += vr[i];
258 }
259 for (Index i = 0; i < 3 * n; ++i) {
260 vsigma[i] += vs[i];
261 }
262 }
263}
264
265template <class Grid>
267 double rho, double sigma) const {
268 typename Vxc_Potential<Grid>::XC_entry result;
269 EvaluateXCBatch(1, &rho, &sigma, &result.f_xc, &result.df_drho,
270 &result.df_dsigma);
271 return result;
272}
273
274template <class Grid>
276 double rho_a, double rho_b, double sigma_aa, double sigma_ab,
277 double sigma_bb) const {
279 const double rho[2] = {rho_a, rho_b};
280 const double sigma[3] = {sigma_aa, sigma_ab, sigma_bb};
281 double vrho[2];
282 double vsigma[3];
283 EvaluateXCSpinBatch(1, rho, sigma, &result.f_xc, vrho, vsigma);
284 result.vrho_a = vrho[0];
285 result.vrho_b = vrho[1];
286 result.vsigma_aa = vsigma[0];
287 result.vsigma_ab = vsigma[1];
288 result.vsigma_bb = vsigma[2];
289 return result;
290}
291
292// Points are processed in blocks inside each box. With Phi the box's AO
293// values (functions x points) and dPhi their gradients, the work that scales
294// with the square of the box's basis size is two matrix products per block:
295// Y = D Phi (density and its gradient at every point)
296// Vxc += A Phi^T, A_p = w_p (vrho_p/2 phi_p + 2 vsigma_p dPhi_p grad rho_p)
297// and libxc is called once per block. Per point, only O(functions) work
298// remains. Same formulas as the former point-by-point loop.
299template <class Grid>
301 const Eigen::MatrixXd& density_matrix) const {
302 assert(density_matrix.isApprox(density_matrix.transpose()) &&
303 "Density matrix has to be symmetric!");
304
305 Mat_p_Energy vxc = Mat_p_Energy(density_matrix.rows(), density_matrix.cols());
306
307#pragma omp parallel for schedule(guided) reduction(+ : vxc)
308 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
309 const GridBox& box = grid_[i];
310 if (!box.Matrixsize()) {
311 continue;
312 }
313
314 // two because we have to use the density matrix and its transpose
315 const Eigen::MatrixXd DMAT_here = 2 * box.ReadFromBigMatrix(density_matrix);
316
317 double cutoff =
318 1.e-40 / double(density_matrix.rows()) / double(density_matrix.rows());
319 if (DMAT_here.cwiseAbs2().maxCoeff() < cutoff) {
320 continue;
321 }
322
323 const Index nf = box.Matrixsize();
324 const Index block = std::min(kPointBlock, box.size());
325 Eigen::MatrixXd Vxc_here = Eigen::MatrixXd::Zero(nf, nf);
326 Eigen::MatrixXd phi(nf, block);
327 Eigen::MatrixXd dphi(nf, 3 * block);
328 Eigen::MatrixXd y(nf, block);
329 Eigen::MatrixXd a(nf, block);
330 std::vector<Index> kept;
331 std::vector<double> rho, sigma, exc, vrho, vsigma;
332 std::vector<Eigen::Vector3d> grad;
333 double EXC_box = 0.0;
334
335 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
336 const std::vector<double>& weights = box.getGridWeights();
337
338 for (Index start = 0; start < box.size(); start += block) {
339 const Index nb = std::min(block, box.size() - start);
340 for (Index p = 0; p < nb; ++p) {
341 box.CalcAOValues(points[start + p], phi, dphi, p);
342 }
343 y.leftCols(nb).noalias() = DMAT_here * phi.leftCols(nb);
344
345 kept.clear();
346 rho.clear();
347 sigma.clear();
348 grad.clear();
349 for (Index p = 0; p < nb; ++p) {
350 const double r = 0.5 * phi.col(p).dot(y.col(p));
351 if (r * weights[start + p] < 1.e-20) {
352 continue;
353 }
354 const Eigen::Vector3d g =
355 dphi.middleCols(3 * p, 3).transpose() * y.col(p);
356 kept.push_back(p);
357 rho.push_back(r);
358 sigma.push_back(g.squaredNorm());
359 grad.push_back(g);
360 }
361 const Index nk = Index(kept.size());
362 if (nk == 0) {
363 continue;
364 }
365 exc.resize(nk);
366 vrho.resize(nk);
367 vsigma.resize(nk);
368 EvaluateXCBatch(nk, rho.data(), sigma.data(), exc.data(), vrho.data(),
369 vsigma.data());
370
371 // Kept points are compacted to the front: column k receives point
372 // kept[k] >= k, which has been read by then.
373 for (Index k = 0; k < nk; ++k) {
374 const Index p = kept[k];
375 const double w = weights[start + p];
376 EXC_box += w * rho[k] * exc[k];
377 a.col(k) = (w * 0.5 * vrho[k]) * phi.col(p);
378 if (is_gga_) {
379 a.col(k).noalias() +=
380 (w * 2.0 * vsigma[k]) * (dphi.middleCols(3 * p, 3) * grad[k]);
381 }
382 if (k != p) {
383 phi.col(k) = phi.col(p);
384 }
385 }
386 Vxc_here.noalias() += a.leftCols(nk) * phi.leftCols(nk).transpose();
387 }
388
389 box.AddtoBigMatrix(vxc.matrix(), Vxc_here);
390 vxc.energy() += EXC_box;
391 }
392
393 return Mat_p_Energy(vxc.energy(), vxc.matrix() + vxc.matrix().transpose());
394}
395
396namespace {
397// first and second derivatives of one functional (unpolarized)
398void CallLibxcFXC(const xc_func_type& f, Index n, const double* rho,
399 const double* sigma, double* vrho, double* vsigma,
400 double* v2rho2, double* v2rhosigma, double* v2sigma2) {
401 if (!(f.info->flags & XC_FLAGS_HAVE_FXC)) {
402 throw std::runtime_error(std::string("Functional ") + f.info->name +
403 " has no second derivatives in libxc");
404 }
405 switch (f.info->family) {
406 case XC_FAMILY_LDA:
407 xc_lda_vxc_fxc(&f, std::size_t(n), rho, vrho, v2rho2);
408 break;
409 case XC_FAMILY_GGA:
410 case XC_FAMILY_HYB_GGA:
411 xc_gga_vxc_fxc(&f, std::size_t(n), rho, sigma, vrho, vsigma, v2rho2,
412 v2rhosigma, v2sigma2);
413 break;
414 default:
415 throw std::runtime_error("Unsupported XC functional family.");
416 }
417}
418} // namespace
419
420template <class Grid>
422 const double* sigma, double* vsigma,
423 double* v2rho2, double* v2rhosigma,
424 double* v2sigma2) const {
425 std::vector<double> vrho(n);
426 EvaluateVXCFXCBatch(n, rho, sigma, vrho.data(), vsigma, v2rho2, v2rhosigma,
427 v2sigma2);
428}
429
430template <class Grid>
432 const double* sigma, double* vrho,
433 double* vsigma, double* v2rho2,
434 double* v2rhosigma,
435 double* v2sigma2) const {
436 std::fill(vsigma, vsigma + n, 0.0);
437 std::fill(v2rhosigma, v2rhosigma + n, 0.0);
438 std::fill(v2sigma2, v2sigma2 + n, 0.0);
439 CallLibxcFXC(xfunc, n, rho, sigma, vrho, vsigma, v2rho2, v2rhosigma,
440 v2sigma2);
441 if (use_separate_) {
442 std::vector<double> vr(n), vs(n, 0.0), rr(n), rs(n, 0.0), ss(n, 0.0);
443 CallLibxcFXC(cfunc, n, rho, sigma, vr.data(), vs.data(), rr.data(),
444 rs.data(), ss.data());
445 for (Index i = 0; i < n; ++i) {
446 vrho[i] += vr[i];
447 vsigma[i] += vs[i];
448 v2rho2[i] += rr[i];
449 v2rhosigma[i] += rs[i];
450 v2sigma2[i] += ss[i];
451 }
452 }
453}
454
455template <class Grid>
457 const double* sigma,
458 double* vsigma, double* v2rho2,
459 double* v2rhosigma,
460 double* v2sigma2) const {
461 std::vector<double> vrho(2 * n);
462 std::fill(vsigma, vsigma + 3 * n, 0.0);
463 std::fill(v2rhosigma, v2rhosigma + 6 * n, 0.0);
464 std::fill(v2sigma2, v2sigma2 + 6 * n, 0.0);
465 CallLibxcFXC(xfunc_pol_, n, rho, sigma, vrho.data(), vsigma, v2rho2,
466 v2rhosigma, v2sigma2);
467 if (use_separate_) {
468 std::vector<double> vr(2 * n), vs(3 * n, 0.0), rr(3 * n), rs(6 * n, 0.0),
469 ss(6 * n, 0.0);
470 CallLibxcFXC(cfunc_pol_, n, rho, sigma, vr.data(), vs.data(), rr.data(),
471 rs.data(), ss.data());
472 for (Index i = 0; i < 3 * n; ++i) {
473 vsigma[i] += vs[i];
474 v2rho2[i] += rr[i];
475 }
476 for (Index i = 0; i < 6 * n; ++i) {
477 v2rhosigma[i] += rs[i];
478 v2sigma2[i] += ss[i];
479 }
480 }
481}
482
483// First-order change of IntegrateVXCSpin. Per point, with g_s = grad rho_s,
484// sigma = (g_a.g_a, g_a.g_b, g_b.g_b) and the first-order changes drho_s,
485// dg_s = grad drho_s:
486// dsigma = (2 g_a.dg_a, g_a.dg_b + dg_a.g_b, 2 g_b.dg_b)
487// dv_rho_s = sum_t v2rho2_st drho_t + sum_c v2rhosigma_sc dsigma_c
488// dv_sigma_c = sum_t v2rhosigma_tc drho_t + sum_d v2sigma2_cd dsigma_d
489// dV_a = int dv_rho_a chi chi + (2 dv_aa g_a + 2 v_aa dg_a + dv_ab g_b
490// + v_ab dg_b).grad(chi chi)
491// and dV_b likewise (a <-> b, aa <-> bb); assembled as in IntegrateVXCSpin.
492template <class Grid>
493std::vector<std::array<Eigen::MatrixXd, 2>>
495 const Eigen::MatrixXd& dmat_alpha, const Eigen::MatrixXd& dmat_beta,
496 const std::vector<std::array<Eigen::MatrixXd, 2>>& response) const {
497 const Index n_ao = dmat_alpha.rows();
498 const Index n_resp = Index(response.size());
499 std::vector<std::array<Eigen::MatrixXd, 2>> result(
500 static_cast<std::size_t>(n_resp),
501 {Eigen::MatrixXd::Zero(n_ao, n_ao), Eigen::MatrixXd::Zero(n_ao, n_ao)});
502 if (n_resp == 0) {
503 return result;
504 }
505 auto wrong_size = [n_ao](const std::array<Eigen::MatrixXd, 2>& r) {
506 return r[0].rows() != n_ao || r[0].cols() != n_ao || r[1].rows() != n_ao ||
507 r[1].cols() != n_ao;
508 };
509 if (std::any_of(response.begin(), response.end(), wrong_size)) {
510 throw std::runtime_error(
511 "IntegrateFXCSpin: response matrix does not match the density "
512 "matrix");
513 }
514 // fail before the grid loop for functionals without fxc
515 {
516 const double rho[2] = {0.1, 0.05};
517 const double sigma[3] = {0.01, 0.005, 0.004};
518 double vs[3], rr[3], rs[6], ss[6];
519 EvaluateFXCSpinBatch(1, rho, sigma, vs, rr, rs, ss);
520 }
521
522 // targets in the order alpha_0, beta_0, alpha_1, beta_1, ...
523 std::vector<Eigen::MatrixXd*> targets;
524 for (std::array<Eigen::MatrixXd, 2>& m : result) {
525 targets.push_back(&m[0]);
526 targets.push_back(&m[1]);
527 }
528 GridBoxAccumulator acc(targets);
529#pragma omp parallel for schedule(guided)
530 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
531 const GridBox& box = grid_[i];
532 if (!box.Matrixsize()) {
533 continue;
534 }
535 const Eigen::MatrixXd DMa = box.ReadFromBigMatrix(dmat_alpha);
536 const Eigen::MatrixXd DMb = box.ReadFromBigMatrix(dmat_beta);
537 std::vector<Eigen::MatrixXd> dDa(static_cast<std::size_t>(n_resp));
538 std::vector<Eigen::MatrixXd> dDb(static_cast<std::size_t>(n_resp));
539 for (Index k = 0; k < n_resp; ++k) {
540 dDa[std::size_t(k)] = box.ReadFromBigMatrix(response[std::size_t(k)][0]);
541 dDb[std::size_t(k)] = box.ReadFromBigMatrix(response[std::size_t(k)][1]);
542 }
543 const Index nf = box.Matrixsize();
544 const Index block = std::min(kPointBlock, box.size());
545 std::vector<Eigen::MatrixXd> fxc_a(static_cast<std::size_t>(n_resp),
546 Eigen::MatrixXd::Zero(nf, nf));
547 std::vector<Eigen::MatrixXd> fxc_b(static_cast<std::size_t>(n_resp),
548 Eigen::MatrixXd::Zero(nf, nf));
549 Eigen::MatrixXd phi(nf, block);
550 Eigen::MatrixXd dphi(nf, 3 * block);
551 Eigen::MatrixXd ya(nf, block);
552 Eigen::MatrixXd yb(nf, block);
553 Eigen::MatrixXd yka(nf, block);
554 Eigen::MatrixXd ykb(nf, block);
555 Eigen::MatrixXd aa(nf, block);
556 Eigen::MatrixXd ab(nf, block);
557 std::vector<Index> kept;
558 std::vector<double> rho, sigma, vsigma, v2rho2, v2rhosigma, v2sigma2;
559 std::vector<Eigen::Vector3d> grad_a, grad_b;
560 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
561 const std::vector<double>& weights = box.getGridWeights();
562
563 for (Index start = 0; start < box.size(); start += block) {
564 const Index nb = std::min(block, box.size() - start);
565 for (Index p = 0; p < nb; ++p) {
566 box.CalcAOValues(points[start + p], phi, dphi, p);
567 }
568 ya.leftCols(nb).noalias() = DMa * phi.leftCols(nb);
569 yb.leftCols(nb).noalias() = DMb * phi.leftCols(nb);
570 kept.clear();
571 rho.clear();
572 sigma.clear();
573 grad_a.clear();
574 grad_b.clear();
575 for (Index p = 0; p < nb; ++p) {
576 const double rho_a = phi.col(p).dot(ya.col(p));
577 const double rho_b = phi.col(p).dot(yb.col(p));
578 if ((rho_a + rho_b) * weights[start + p] < 1.e-20) {
579 continue;
580 }
581 const Eigen::Vector3d ga =
582 2.0 * (dphi.middleCols(3 * p, 3).transpose() * ya.col(p));
583 const Eigen::Vector3d gb =
584 2.0 * (dphi.middleCols(3 * p, 3).transpose() * yb.col(p));
585 kept.push_back(p);
586 rho.push_back(rho_a);
587 rho.push_back(rho_b);
588 sigma.push_back(ga.dot(ga));
589 sigma.push_back(ga.dot(gb));
590 sigma.push_back(gb.dot(gb));
591 grad_a.push_back(ga);
592 grad_b.push_back(gb);
593 }
594 const Index nk = Index(kept.size());
595 if (nk == 0) {
596 continue;
597 }
598 vsigma.resize(3 * nk);
599 v2rho2.resize(3 * nk);
600 v2rhosigma.resize(6 * nk);
601 v2sigma2.resize(6 * nk);
602 EvaluateFXCSpinBatch(nk, rho.data(), sigma.data(), vsigma.data(),
603 v2rho2.data(), v2rhosigma.data(), v2sigma2.data());
604 Eigen::MatrixXd phik(nf, nk);
605 for (Index q = 0; q < nk; ++q) {
606 phik.col(q) = phi.col(kept[q]);
607 }
608
609 for (Index k = 0; k < n_resp; ++k) {
610 yka.leftCols(nb).noalias() = dDa[std::size_t(k)] * phi.leftCols(nb);
611 ykb.leftCols(nb).noalias() = dDb[std::size_t(k)] * phi.leftCols(nb);
612 for (Index q = 0; q < nk; ++q) {
613 const Index p = kept[q];
614 const double w = weights[start + p];
615 const double dra = phi.col(p).dot(yka.col(p));
616 const double drb = phi.col(p).dot(ykb.col(p));
617 const double* r2 = &v2rho2[3 * q];
618 if (!is_gga_) {
619 const double dva = r2[0] * dra + r2[1] * drb;
620 const double dvb = r2[1] * dra + r2[2] * drb;
621 aa.col(q) = (w * 0.5 * dva) * phi.col(p);
622 ab.col(q) = (w * 0.5 * dvb) * phi.col(p);
623 continue;
624 }
625 const auto d = dphi.middleCols(3 * p, 3);
626 const Eigen::Vector3d dga = 2.0 * (d.transpose() * yka.col(p));
627 const Eigen::Vector3d dgb = 2.0 * (d.transpose() * ykb.col(p));
628 const Eigen::Vector3d& ga = grad_a[q];
629 const Eigen::Vector3d& gb = grad_b[q];
630 const double ds[3] = {2.0 * ga.dot(dga), ga.dot(dgb) + dga.dot(gb),
631 2.0 * gb.dot(dgb)};
632 const double* rs = &v2rhosigma[6 * q];
633 const double* s2 = &v2sigma2[6 * q];
634 const double* vs = &vsigma[3 * q];
635 // v2sigma2 as a symmetric 3x3 matrix
636 const double S[3][3] = {{s2[0], s2[1], s2[2]},
637 {s2[1], s2[3], s2[4]},
638 {s2[2], s2[4], s2[5]}};
639 const double dva = r2[0] * dra + r2[1] * drb + rs[0] * ds[0] +
640 rs[1] * ds[1] + rs[2] * ds[2];
641 const double dvb = r2[1] * dra + r2[2] * drb + rs[3] * ds[0] +
642 rs[4] * ds[1] + rs[5] * ds[2];
643 double dvs[3];
644 for (int c = 0; c < 3; ++c) {
645 dvs[c] = rs[c] * dra + rs[3 + c] * drb + S[c][0] * ds[0] +
646 S[c][1] * ds[1] + S[c][2] * ds[2];
647 }
648 const Eigen::Vector3d vec_a =
649 2.0 * dvs[0] * ga + 2.0 * vs[0] * dga + dvs[1] * gb + vs[1] * dgb;
650 const Eigen::Vector3d vec_b =
651 2.0 * dvs[2] * gb + 2.0 * vs[2] * dgb + dvs[1] * ga + vs[1] * dga;
652 aa.col(q) = (w * 0.5 * dva) * phi.col(p) + w * (d * vec_a);
653 ab.col(q) = (w * 0.5 * dvb) * phi.col(p) + w * (d * vec_b);
654 }
655 fxc_a[std::size_t(k)].noalias() += aa.leftCols(nk) * phik.transpose();
656 fxc_b[std::size_t(k)].noalias() += ab.leftCols(nk) * phik.transpose();
657 }
658 }
659 std::vector<const Eigen::MatrixXd*> blocks;
660 for (Index k = 0; k < n_resp; ++k) {
661 blocks.push_back(&fxc_a[std::size_t(k)]);
662 blocks.push_back(&fxc_b[std::size_t(k)]);
663 }
664 acc.Add(box, blocks);
665 }
666 acc.Finish();
667 for (std::array<Eigen::MatrixXd, 2>& m : result) {
668 m[0] = (m[0] + m[0].transpose()).eval();
669 m[1] = (m[1] + m[1].transpose()).eval();
670 }
671 return result;
672}
673
674// First-order change of IntegrateVXC. With sigma = |grad rho|^2, at a point
675// drho, dg = grad drho, dsigma = 2 g.dg
676// dv_rho = v2rho2 drho + v2rhosigma dsigma
677// dv_sigma = v2rhosigma drho + v2sigma2 dsigma
678// dV = int dv_rho chi chi + 2 (dv_sigma g + vsigma dg).grad(chi chi)
679// assembled like IntegrateVXC: a = w (dv_rho/2 phi + 2 dphi.(...)),
680// dV = a phi^T + transpose. The points IntegrateVXC skips are skipped.
681template <class Grid>
683 const Eigen::MatrixXd& density_matrix) const {
684 // fail before the grid loop for functionals without fxc
685 {
686 const double rho = 0.1;
687 const double sigma = 0.01;
688 double vs, rr, rs, ss;
689 EvaluateFXCBatch(1, &rho, &sigma, &vs, &rr, &rs, &ss);
690 }
691 FXCKernel kernel;
692 kernel.n_ao = density_matrix.rows();
693 kernel.boxes.resize(std::size_t(grid_.getBoxesSize()));
694#pragma omp parallel for schedule(guided)
695 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
696 const GridBox& box = grid_[i];
697 if (!box.Matrixsize()) {
698 continue;
699 }
700 typename FXCKernel::Box& kb = kernel.boxes[std::size_t(i)];
701 const Eigen::MatrixXd DMAT_here = 2 * box.ReadFromBigMatrix(density_matrix);
702 const Index nf = box.Matrixsize();
703 const Index block = std::min(kPointBlock, box.size());
704 Eigen::MatrixXd phi(nf, block);
705 Eigen::MatrixXd dphi(nf, 3 * block);
706 Eigen::MatrixXd y(nf, block);
707 std::vector<double> rho, sigma, w;
708 std::vector<Eigen::Vector3d> grad;
709 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
710 const std::vector<double>& weights = box.getGridWeights();
711 for (Index start = 0; start < box.size(); start += block) {
712 const Index nb = std::min(block, box.size() - start);
713 for (Index p = 0; p < nb; ++p) {
714 box.CalcAOValues(points[start + p], phi, dphi, p);
715 }
716 y.leftCols(nb).noalias() = DMAT_here * phi.leftCols(nb);
717 for (Index p = 0; p < nb; ++p) {
718 const double r = 0.5 * phi.col(p).dot(y.col(p));
719 if (r * weights[start + p] < 1.e-20) {
720 continue;
721 }
722 const Eigen::Vector3d g =
723 dphi.middleCols(3 * p, 3).transpose() * y.col(p);
724 kb.points.push_back(start + p);
725 rho.push_back(r);
726 sigma.push_back(g.squaredNorm());
727 grad.push_back(g);
728 w.push_back(weights[start + p]);
729 }
730 }
731 const Index nk = Index(kb.points.size());
732 kb.w = Eigen::Map<const Eigen::VectorXd>(w.data(), nk);
733 kb.vsigma.resize(nk);
734 kb.v2rho2.resize(nk);
735 kb.v2rhosigma.resize(nk);
736 kb.v2sigma2.resize(nk);
737 if (nk > 0) {
738 EvaluateFXCBatch(nk, rho.data(), sigma.data(), kb.vsigma.data(),
739 kb.v2rho2.data(), kb.v2rhosigma.data(),
740 kb.v2sigma2.data());
741 }
742 kb.grad.resize(3, nk);
743 for (Index q = 0; q < nk; ++q) {
744 kb.grad.col(q) = grad[std::size_t(q)];
745 }
746 }
747 return kernel;
748}
749
750template <class Grid>
751std::vector<Eigen::MatrixXd> Vxc_Potential<Grid>::ApplyFXC(
752 const FXCKernel& kernel,
753 const std::vector<Eigen::MatrixXd>& response_matrices) const {
754 const Index n_ao = kernel.n_ao;
755 const Index n_resp = Index(response_matrices.size());
756 std::vector<Eigen::MatrixXd> result(static_cast<std::size_t>(n_resp),
757 Eigen::MatrixXd::Zero(n_ao, n_ao));
758 if (n_resp == 0) {
759 return result;
760 }
761 if (std::any_of(response_matrices.begin(), response_matrices.end(),
762 [n_ao](const Eigen::MatrixXd& m) {
763 return m.rows() != n_ao || m.cols() != n_ao;
764 })) {
765 throw std::runtime_error(
766 "IntegrateFXC: response matrix does not match the density matrix");
767 }
768 std::vector<Eigen::MatrixXd*> targets;
769 for (Eigen::MatrixXd& m : result) {
770 targets.push_back(&m);
771 }
772 GridBoxAccumulator acc(targets);
773#pragma omp parallel for schedule(guided)
774 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
775 const GridBox& box = grid_[i];
776 const typename FXCKernel::Box& kb = kernel.boxes[std::size_t(i)];
777 const Index nk_box = Index(kb.points.size());
778 if (!box.Matrixsize() || nk_box == 0) {
779 continue;
780 }
781 const Index nf = box.Matrixsize();
782 std::vector<Eigen::MatrixXd> dmat_k(static_cast<std::size_t>(n_resp));
783 for (Index k = 0; k < n_resp; ++k) {
784 dmat_k[std::size_t(k)] =
785 2 * box.ReadFromBigMatrix(response_matrices[std::size_t(k)]);
786 }
787 std::vector<Eigen::MatrixXd> fxc_here(static_cast<std::size_t>(n_resp),
788 Eigen::MatrixXd::Zero(nf, nf));
789 const Index block = std::min(kPointBlock, nk_box);
790 Eigen::MatrixXd phi_buf(nf, block);
791 Eigen::MatrixXd dphi_buf(nf, 3 * block);
792 Eigen::MatrixXd yk(nf, block);
793 Eigen::MatrixXd a(nf, block);
794 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
795 for (Index start = 0; start < nk_box; start += block) {
796 const Index nb = std::min(block, nk_box - start);
797 for (Index q = 0; q < nb; ++q) {
798 box.CalcAOValues(points[kb.points[std::size_t(start + q)]], phi_buf,
799 dphi_buf, q);
800 }
801 const auto phi = phi_buf.leftCols(nb);
802 const auto dphi = dphi_buf.leftCols(3 * nb);
803 for (Index k = 0; k < n_resp; ++k) {
804 yk.leftCols(nb).noalias() = dmat_k[std::size_t(k)] * phi;
805 for (Index q = 0; q < nb; ++q) {
806 const Index kq = start + q;
807 const double w = kb.w(kq);
808 const double drho = 0.5 * phi.col(q).dot(yk.col(q));
809 if (is_gga_) {
810 const Eigen::Vector3d dg =
811 dphi.middleCols(3 * q, 3).transpose() * yk.col(q);
812 const Eigen::Vector3d g = kb.grad.col(kq);
813 const double dsigma = 2.0 * g.dot(dg);
814 const double dv_rho =
815 kb.v2rho2(kq) * drho + kb.v2rhosigma(kq) * dsigma;
816 const double dv_sigma =
817 kb.v2rhosigma(kq) * drho + kb.v2sigma2(kq) * dsigma;
818 const Eigen::Vector3d vec =
819 2.0 * (dv_sigma * g + kb.vsigma(kq) * dg);
820 a.col(q) = (w * 0.5 * dv_rho) * phi.col(q) +
821 w * (dphi.middleCols(3 * q, 3) * vec);
822 } else {
823 a.col(q) = (w * 0.5 * kb.v2rho2(kq) * drho) * phi.col(q);
824 }
825 }
826 fxc_here[std::size_t(k)].noalias() += a.leftCols(nb) * phi.transpose();
827 }
828 }
829 std::vector<const Eigen::MatrixXd*> blocks;
830 for (const Eigen::MatrixXd& m : fxc_here) {
831 blocks.push_back(&m);
832 }
833 acc.Add(box, blocks);
834 }
835 acc.Finish();
836 for (Eigen::MatrixXd& m : result) {
837 m = (m + m.transpose()).eval();
838 }
839 return result;
840}
841
842template <class Grid>
843std::vector<Eigen::MatrixXd> Vxc_Potential<Grid>::IntegrateFXC(
844 const Eigen::MatrixXd& density_matrix,
845 const std::vector<Eigen::MatrixXd>& response_matrices) const {
846 if (std::any_of(response_matrices.begin(), response_matrices.end(),
847 [&density_matrix](const Eigen::MatrixXd& m) {
848 return m.rows() != density_matrix.rows() ||
849 m.cols() != density_matrix.cols();
850 })) {
851 throw std::runtime_error(
852 "IntegrateFXC: response matrix does not match the density matrix");
853 }
854 if (response_matrices.empty()) {
855 return {};
856 }
857 return ApplyFXC(PrepareFXC(density_matrix), response_matrices);
858}
859
860// ===========================================================================
861// XC gradient at fixed grid weights: basis-function (Pulay) and grid-point
862// translation terms, LDA and GGA. The grid-weight (SSW partition) term is
863// in GridWeightGradient.
864//
865// E_xc = sum_p weight_p * e_xc(rho_p, sigma_p) (e_xc = rho*f_xc)
866//
867// dE_xc/dR_A = sum_p weight_p [v_rho d(rho_p)/dR_A + v_sigma d(sigma_p)/dR_A]
868//
869// with v_rho = xc.df_drho, v_sigma = xc.df_dsigma (LibXC vrho/vsigma, the
870// full derivatives of e_xc).
871//
872// Basis term: for chi_mu(r) = phi_mu(r - R_A), d(chi_mu)/dR_A =
873// -grad_r chi_mu for mu on A and zero otherwise, so with
874// temp = ao.values^T * DMAT_here (DMAT_here = 2P)
875// d(rho_p)/dR_A|_basis = -sum_{mu in A} temp(mu) (grad_r chi_mu)(r_p).
876// ===========================================================================
877template <class Grid>
879 const Eigen::MatrixXd& density_matrix, const AOBasis& dftbasis) const {
880 assert(density_matrix.isApprox(density_matrix.transpose()) &&
881 "Density matrix has to be symmetric!");
882
883 Index natoms = static_cast<Index>(dftbasis.getFuncPerAtom().size());
884 Index nthreads = OPENMP::getMaxThreads();
885 std::vector<Eigen::MatrixXd> grad_thread(nthreads,
886 Eigen::MatrixXd::Zero(natoms, 3));
887
888 std::exception_ptr eptr_pulay = nullptr;
889#pragma omp parallel for schedule(guided)
890 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
891 try {
892 Index thread_id = OPENMP::getThreadId();
893 const GridBox& box = grid_[i];
894 if (!box.Matrixsize()) {
895 continue;
896 }
897
898 const Eigen::MatrixXd DMAT_here =
899 2 * box.ReadFromBigMatrix(density_matrix);
900
901 double cutoff = 1.e-40 / double(density_matrix.rows()) /
902 double(density_matrix.rows());
903 if (DMAT_here.cwiseAbs2().maxCoeff() < cutoff) {
904 continue;
905 }
906
907 // box-local AO index -> atom index
908 std::vector<Index> local_idx_to_atom(box.Matrixsize());
909 const std::vector<const AOShell*>& shells = box.getShells();
910 const std::vector<GridboxRange>& ao_ranges = box.getAOranges();
911 for (size_t s = 0; s < shells.size(); ++s) {
912 Index atom = shells[s]->getAtomIndex();
913 for (Index k = 0; k < ao_ranges[s].size; ++k) {
914 local_idx_to_atom[ao_ranges[s].start + k] = atom;
915 }
916 }
917
918 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
919 const std::vector<double>& weights = box.getGridWeights();
920 // atom each grid point moves with, for the translation terms
921 const std::vector<Index>& owner_atoms = box.getOwnerAtoms();
922
923 for (Index p = 0; p < box.size(); ++p) {
925
926 Eigen::VectorXd temp = ao.values.transpose() * DMAT_here;
927 double rho = 0.5 * temp.dot(ao.values);
928 const double weight = weights[p];
929
930 if (rho * weight < 1.e-20) {
931 continue;
932 }
933
934 const Eigen::Vector3d rho_grad = temp.transpose() * ao.derivatives;
936 EvaluateXC(rho, rho_grad.squaredNorm());
937
938 // ===========================================================
939 // GGA sigma terms (need the AO Hessians, EvalAOspaceHessian).
940 // They vanish for LDA, where xc.df_dsigma stays 0.
941 //
942 // sigma_p = |grad_r(rho_p)|^2 = rho_grad . rho_grad
943 //
944 // Gmat(mu,l) = sum_nu DMAT_mu,nu grad_nu,l (DMAT_here*ao.derivatives)
945 // s_vec(mu) = sum_l Gmat(mu,l) rho_grad_l (Gmat*rho_grad)
946 //
947 // Basis term (mu in A):
948 // dsigma_p/dR_A|_basis = -2 sum_{mu in A} [grad_mu s_vec(mu)
949 // + temp_mu (Hessian_mu . rho_grad)]
950 //
951 // Translation term (A == owner(p) only), with the density Hessian:
952 // Hessian_rho = sum_mu temp_mu*Hessian_mu
953 // + symmetrized(ao.derivatives^T * Gmat)
954 // dsigma_p/dR_owner|_translation = 2 * (Hessian_rho * rho_grad)
955 //
956 // Both are contracted with weight_p * v_sigma.
957 Eigen::MatrixX3d Gmat = DMAT_here * ao.derivatives; // (Matrixsize x 3)
958 Eigen::VectorXd s_vec = Gmat * rho_grad; // (Matrixsize)
959
960 Eigen::Matrix3d Hessian_rho = Eigen::Matrix3d::Zero();
961 for (Index mu = 0; mu < box.Matrixsize(); ++mu) {
962 Hessian_rho += temp(mu) * ao.hessians[mu];
963 }
964 Eigen::Matrix3d M = ao.derivatives.transpose() * Gmat;
965 Hessian_rho += 0.5 * (M + M.transpose());
966
967 Index owner_of_point_sigma = owner_atoms[p];
968 Eigen::Vector3d dsigma_translation = 2.0 * (Hessian_rho * rho_grad);
969 grad_thread[thread_id].row(owner_of_point_sigma) +=
970 (weight * xc.df_dsigma * dsigma_translation).transpose();
971 // ===========================================================
972
973 // ===========================================================
974 // Grid-point translation term. Points move rigidly with their
975 // owner atom, r_p = R_owner + const, so
976 // d(rho_p)/dR_A|_translation = grad_r(rho_p) if A == owner(p),
977 // 0 otherwise,
978 // dE_xc/dR_A|_translation = sum_{p: owner(p)==A}
979 // weight_p v_rho(rho_p) grad_r(rho_p).
980 Index owner_of_point = owner_atoms[p];
981 grad_thread[thread_id].row(owner_of_point) +=
982 (weight * xc.df_drho * rho_grad).transpose();
983 // ===========================================================
984
985 // Basis terms, per local AO index mu, added to the atom of mu (the
986 // shells of a box are not necessarily grouped by atom).
987 for (Index mu = 0; mu < box.Matrixsize(); ++mu) {
988 Index atom = local_idx_to_atom[mu];
989 Eigen::Vector3d contribution = -weight * xc.df_drho * temp(mu) *
990 ao.derivatives.row(mu).transpose();
991 // GGA sigma basis term, see above
992 Eigen::Vector3d dsigma_basis_mu =
993 -2.0 * (ao.derivatives.row(mu).transpose() * s_vec(mu) +
994 temp(mu) * (ao.hessians[mu] * rho_grad));
995 contribution += weight * xc.df_dsigma * dsigma_basis_mu;
996 grad_thread[thread_id].row(atom) += contribution.transpose();
997 }
998 }
999 } catch (...) {
1000#pragma omp critical
1001 {
1002 if (!eptr_pulay) {
1003 eptr_pulay = std::current_exception();
1004 }
1005 }
1006 }
1007 }
1008 if (eptr_pulay) {
1009 std::rethrow_exception(eptr_pulay);
1010 }
1011
1012 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
1013 for (Index t = 0; t < nthreads; ++t) {
1014 grad += grad_thread[t];
1015 }
1016 return grad;
1017}
1018
1019// Blocked like IntegrateVXC, per spin channel. UKS density matrices are not
1020// pre-doubled: rho_s = phi^T D_s phi, grad rho_s = 2 dPhi^T D_s phi.
1021template <class Grid>
1023 const Eigen::MatrixXd& dmat_alpha, const Eigen::MatrixXd& dmat_beta) const {
1024 assert(dmat_alpha.isApprox(dmat_alpha.transpose()) &&
1025 "Alpha density matrix has to be symmetric!");
1026 assert(dmat_beta.isApprox(dmat_beta.transpose()) &&
1027 "Beta density matrix has to be symmetric!");
1028
1029 typename Vxc_Potential<Grid>::SpinResult result;
1030 result.vxc_alpha =
1031 Eigen::MatrixXd::Zero(dmat_alpha.rows(), dmat_alpha.cols());
1032 result.vxc_beta = Eigen::MatrixXd::Zero(dmat_beta.rows(), dmat_beta.cols());
1033
1034#pragma omp parallel
1035 {
1036 Eigen::MatrixXd vxc_alpha_private =
1037 Eigen::MatrixXd::Zero(dmat_alpha.rows(), dmat_alpha.cols());
1038 Eigen::MatrixXd vxc_beta_private =
1039 Eigen::MatrixXd::Zero(dmat_beta.rows(), dmat_beta.cols());
1040 double exc_private = 0.0;
1041
1042 std::vector<Index> kept;
1043 std::vector<double> rho, sigma, exc, vrho, vsigma;
1044 std::vector<Eigen::Vector3d> grad_a, grad_b;
1045
1046#pragma omp for schedule(guided)
1047 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
1048 const GridBox& box = grid_[i];
1049 if (!box.Matrixsize()) {
1050 continue;
1051 }
1052
1053 const Eigen::MatrixXd DMa = box.ReadFromBigMatrix(dmat_alpha);
1054 const Eigen::MatrixXd DMb = box.ReadFromBigMatrix(dmat_beta);
1055
1056 double cutoff =
1057 1.e-40 / double(dmat_alpha.rows()) / double(dmat_alpha.rows());
1058 if (std::max(DMa.cwiseAbs2().maxCoeff(), DMb.cwiseAbs2().maxCoeff()) <
1059 cutoff) {
1060 continue;
1061 }
1062
1063 const Index nf = box.Matrixsize();
1064 const Index block = std::min(kPointBlock, box.size());
1065 Eigen::MatrixXd Vxc_a_here = Eigen::MatrixXd::Zero(nf, nf);
1066 Eigen::MatrixXd Vxc_b_here = Eigen::MatrixXd::Zero(nf, nf);
1067 Eigen::MatrixXd phi(nf, block);
1068 Eigen::MatrixXd dphi(nf, 3 * block);
1069 Eigen::MatrixXd ya(nf, block);
1070 Eigen::MatrixXd yb(nf, block);
1071 Eigen::MatrixXd aa(nf, block);
1072 Eigen::MatrixXd ab(nf, block);
1073
1074 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
1075 const std::vector<double>& weights = box.getGridWeights();
1076
1077 for (Index start = 0; start < box.size(); start += block) {
1078 const Index nb = std::min(block, box.size() - start);
1079 for (Index p = 0; p < nb; ++p) {
1080 box.CalcAOValues(points[start + p], phi, dphi, p);
1081 }
1082 ya.leftCols(nb).noalias() = DMa * phi.leftCols(nb);
1083 yb.leftCols(nb).noalias() = DMb * phi.leftCols(nb);
1084
1085 kept.clear();
1086 rho.clear();
1087 sigma.clear();
1088 grad_a.clear();
1089 grad_b.clear();
1090 for (Index p = 0; p < nb; ++p) {
1091 const double rho_a = phi.col(p).dot(ya.col(p));
1092 const double rho_b = phi.col(p).dot(yb.col(p));
1093 if ((rho_a + rho_b) * weights[start + p] < 1.e-20) {
1094 continue;
1095 }
1096 const Eigen::Vector3d ga =
1097 2.0 * (dphi.middleCols(3 * p, 3).transpose() * ya.col(p));
1098 const Eigen::Vector3d gb =
1099 2.0 * (dphi.middleCols(3 * p, 3).transpose() * yb.col(p));
1100 kept.push_back(p);
1101 rho.push_back(rho_a);
1102 rho.push_back(rho_b);
1103 sigma.push_back(ga.dot(ga));
1104 sigma.push_back(ga.dot(gb));
1105 sigma.push_back(gb.dot(gb));
1106 grad_a.push_back(ga);
1107 grad_b.push_back(gb);
1108 }
1109 const Index nk = Index(kept.size());
1110 if (nk == 0) {
1111 continue;
1112 }
1113 exc.resize(nk);
1114 vrho.resize(2 * nk);
1115 vsigma.resize(3 * nk);
1116 EvaluateXCSpinBatch(nk, rho.data(), sigma.data(), exc.data(),
1117 vrho.data(), vsigma.data());
1118
1119 for (Index k = 0; k < nk; ++k) {
1120 const Index p = kept[k];
1121 const double w = weights[start + p];
1122 exc_private += w * (rho[2 * k] + rho[2 * k + 1]) * exc[k];
1123 // 0.5 because the result is symmetrized by adding the transpose
1124 aa.col(k) = (w * 0.5 * vrho[2 * k]) * phi.col(p);
1125 ab.col(k) = (w * 0.5 * vrho[2 * k + 1]) * phi.col(p);
1126 if (is_gga_) {
1127 const auto d = dphi.middleCols(3 * p, 3);
1128 const Eigen::VectorXd g_a = d * grad_a[k];
1129 const Eigen::VectorXd g_b = d * grad_b[k];
1130 const double vs_aa = vsigma[3 * k];
1131 const double vs_ab = vsigma[3 * k + 1];
1132 const double vs_bb = vsigma[3 * k + 2];
1133 aa.col(k).noalias() += w * (2.0 * vs_aa * g_a + vs_ab * g_b);
1134 ab.col(k).noalias() += w * (vs_ab * g_a + 2.0 * vs_bb * g_b);
1135 }
1136 if (k != p) {
1137 phi.col(k) = phi.col(p);
1138 }
1139 }
1140 Vxc_a_here.noalias() += aa.leftCols(nk) * phi.leftCols(nk).transpose();
1141 Vxc_b_here.noalias() += ab.leftCols(nk) * phi.leftCols(nk).transpose();
1142 }
1143
1144 box.AddtoBigMatrix(vxc_alpha_private, Vxc_a_here);
1145 box.AddtoBigMatrix(vxc_beta_private, Vxc_b_here);
1146 }
1147
1148#pragma omp critical
1149 {
1150 result.vxc_alpha += vxc_alpha_private + vxc_alpha_private.transpose();
1151 result.vxc_beta += vxc_beta_private + vxc_beta_private.transpose();
1152 result.energy += exc_private;
1153 }
1154 }
1155
1156 return result;
1157}
1158
1159namespace {
1160// SSW switching function and its derivative, restated from the private
1161// Vxc_Grid::erf1c (0.5*erfc(|x/(1-x^2)|*alpha), alpha = 1/0.30); must be kept
1162// consistent with it.
1163constexpr double kSSWAlpha = 1.0 / 0.30;
1164constexpr double kSSWCutoff = 0.725;
1165
1166constexpr double kSqrtPi = 1.7724538509055160273; // M_PI is not standard
1167
1168double SSWValue(double mu) {
1169 double val = 0.5 * std::erfc(std::abs(mu / (1.0 - mu * mu)) * kSSWAlpha);
1170 if (mu > 0.0) {
1171 val = 1.0 - val;
1172 }
1173 return val;
1174}
1175
1176// d(SSWValue)/d(mu), closed form.
1177double SSWDerivative(double mu) {
1178 double h = std::abs(mu) / (1.0 - mu * mu);
1179 double sign_mu = (mu > 0.0) ? 1.0 : ((mu < 0.0) ? -1.0 : 0.0);
1180 double one_minus_mu2 = 1.0 - mu * mu;
1181 double hprime = sign_mu * (1.0 + mu * mu) / (one_minus_mu2 * one_minus_mu2);
1182 double d_erf1c = -(kSSWAlpha / kSqrtPi) *
1183 std::exp(-(kSSWAlpha * h) * (kSSWAlpha * h)) * hprime;
1184 return (mu > 0.0) ? -d_erf1c : d_erf1c;
1185}
1186
1187// Adds e * C_p * d(w_owner)/dR_A for all atoms A to grad (natoms x 3), with
1188// the stored weight = C_p * w_owner, C_p the geometry-independent radial and
1189// angular quadrature weight and w_owner the SSW partition weight of the
1190// point's owner atom; e is the energy density at the point. The point moves
1191// with its owner. O(Natoms^2) per point: d(mu_ab)/dR_A is non-zero only for
1192// A in {owner, a, b}.
1193void AddSSWWeightDerivative(const Eigen::Vector3d& point, Index owner,
1194 double weight, double e, const QMMolecule& atoms,
1195 const Eigen::MatrixXd& Rij, Eigen::MatrixXd& grad) {
1196 const Index natoms = atoms.size();
1197 Eigen::VectorXd rq(natoms);
1198 for (Index k = 0; k < natoms; ++k) {
1199 rq(k) = (point - atoms[k].getPos()).norm();
1200 }
1201 // p[], mu_table, sk_table and hard-cutoff flags as in
1202 // Vxc_Grid::SSWpartition, keeping the per-pair values for the derivative.
1203 // hard(j,i): 0 = smooth, 1 = mu > cutoff (p[i] = 0), -1 = mu < -cutoff
1204 // (p[j] = 0); upper triangle (j < i) only.
1205 Eigen::VectorXd p = Eigen::VectorXd::Ones(natoms);
1206 Eigen::MatrixXd mu_table = Eigen::MatrixXd::Zero(natoms, natoms);
1207 Eigen::MatrixXd sk_table = Eigen::MatrixXd::Zero(natoms, natoms);
1208 Eigen::MatrixXi hard = Eigen::MatrixXi::Zero(natoms, natoms);
1209 for (Index ii = 1; ii < natoms; ++ii) {
1210 for (Index jj = 0; jj < ii; ++jj) {
1211 const double mu = (rq(ii) - rq(jj)) * Rij(jj, ii);
1212 mu_table(jj, ii) = mu;
1213 if (mu > kSSWCutoff) {
1214 p(ii) = 0.0;
1215 hard(jj, ii) = 1;
1216 } else if (mu < -kSSWCutoff) {
1217 p(jj) = 0.0;
1218 hard(jj, ii) = -1;
1219 } else {
1220 const double sk = SSWValue(mu);
1221 sk_table(jj, ii) = sk;
1222 p(jj) *= sk;
1223 p(ii) *= (1.0 - sk);
1224 }
1225 }
1226 }
1227 const double wsum = p.sum();
1228 const double w_owner = p(owner) / wsum;
1229 // points with negligible w_owner have negligible weight (C_p is bounded)
1230 constexpr double kNegligibleWOwner = 1.e-8;
1231 if (w_owner < kNegligibleWOwner) {
1232 return;
1233 }
1234 // d(rq(k))/dR_A: +-unit vector for A == owner or A == k, zero if both
1235 auto d_rq_dR = [&](Index k, Index A) -> Eigen::Vector3d {
1236 if (A == owner && A == k) {
1237 return Eigen::Vector3d::Zero();
1238 } else if (A == owner) {
1239 return (point - atoms[k].getPos()) / rq(k);
1240 } else if (A == k) {
1241 return -(point - atoms[k].getPos()) / rq(k);
1242 }
1243 return Eigen::Vector3d::Zero();
1244 };
1245 // coef * d(mu_ab)/dR_A (a < b) added to out for A in {owner, a, b}
1246 auto add_dmu = [&](Index a, Index b, double coef, Eigen::MatrixXd& out) {
1247 const double Rab = 1.0 / Rij(a, b);
1248 const Eigen::Vector3d rvec = atoms[a].getPos() - atoms[b].getPos();
1249 const double mu = mu_table(a, b);
1250 const Index cand[3] = {owner, a, b};
1251 for (Index c = 0; c < 3; ++c) {
1252 const Index A = cand[c];
1253 if ((c > 0 && A == cand[0]) || (c > 1 && A == cand[1])) {
1254 continue;
1255 }
1256 Eigen::Vector3d dRab = Eigen::Vector3d::Zero();
1257 if (A == a) {
1258 dRab = rvec / Rab;
1259 } else if (A == b) {
1260 dRab = -rvec / Rab;
1261 }
1262 const Eigen::Vector3d dmu =
1263 (d_rq_dR(b, A) - d_rq_dR(a, A)) / Rab - (mu / Rab) * dRab;
1264 out.row(A) += coef * dmu.transpose();
1265 }
1266 };
1267 // d p_k/dR = p_k sum over the smooth pairs of k of the log-derivatives of
1268 // s or (1-s); these divide by s or 1-s, so pairs (and p_k) near the SSW
1269 // saturation are treated as zero (threshold not tuned)
1270 constexpr double kNegligibleP = 1.e-8;
1271 Eigen::MatrixXd dp_owner = Eigen::MatrixXd::Zero(natoms, 3);
1272 Eigen::MatrixXd dp_sum = Eigen::MatrixXd::Zero(natoms, 3);
1273 Eigen::MatrixXd dp_k(natoms, 3);
1274 for (Index k = 0; k < natoms; ++k) {
1275 if (p(k) < kNegligibleP) {
1276 continue;
1277 }
1278 dp_k.setZero();
1279 for (Index b = k + 1; b < natoms; ++b) {
1280 if (hard(k, b) != 0) {
1281 continue;
1282 }
1283 const double skv = sk_table(k, b);
1284 if (skv < kNegligibleP) {
1285 continue;
1286 }
1287 add_dmu(k, b, SSWDerivative(mu_table(k, b)) / skv, dp_k);
1288 }
1289 for (Index a = 0; a < k; ++a) {
1290 if (hard(a, k) != 0) {
1291 continue;
1292 }
1293 const double one_minus_skv = 1.0 - sk_table(a, k);
1294 if (one_minus_skv < kNegligibleP) {
1295 continue;
1296 }
1297 add_dmu(a, k, -SSWDerivative(mu_table(a, k)) / one_minus_skv, dp_k);
1298 }
1299 dp_sum += p(k) * dp_k;
1300 if (k == owner) {
1301 dp_owner = p(k) * dp_k;
1302 }
1303 }
1304 const double C_p = weight / w_owner;
1305 grad += (C_p * e / wsum) * (dp_owner - w_owner * dp_sum);
1306}
1307} // namespace
1308
1309template <class Grid>
1311 const Eigen::MatrixXd& density_matrix, const QMMolecule& atoms) const {
1312 Index natoms = atoms.size();
1313 Eigen::MatrixXd Rij = grid_.CalcInverseAtomDist(atoms);
1314
1315 Index nthreads = OPENMP::getMaxThreads();
1316 std::vector<Eigen::MatrixXd> grad_thread(nthreads,
1317 Eigen::MatrixXd::Zero(natoms, 3));
1318
1319 std::exception_ptr eptr_weight = nullptr;
1320#pragma omp parallel for schedule(guided)
1321 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
1322 try {
1323 Index thread_id = OPENMP::getThreadId();
1324 const GridBox& box = grid_[i];
1325 if (!box.Matrixsize()) {
1326 continue;
1327 }
1328
1329 const Eigen::MatrixXd DMAT_here =
1330 2 * box.ReadFromBigMatrix(density_matrix);
1331 double cutoff = 1.e-40 / double(density_matrix.rows()) /
1332 double(density_matrix.rows());
1333 if (DMAT_here.cwiseAbs2().maxCoeff() < cutoff) {
1334 continue;
1335 }
1336
1337 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
1338 const std::vector<double>& weights = box.getGridWeights();
1339 const std::vector<Index>& owner_atoms = box.getOwnerAtoms();
1340
1341 for (Index pidx = 0; pidx < box.size(); ++pidx) {
1342 AOShell::AOValues ao = box.CalcAOValues(points[pidx]);
1343 Eigen::VectorXd temp = ao.values.transpose() * DMAT_here;
1344 double rho = 0.5 * temp.dot(ao.values);
1345 double weight = weights[pidx];
1346 if (rho * weight < 1.e-20) {
1347 continue;
1348 }
1349 const Eigen::Vector3d rho_grad = temp.transpose() * ao.derivatives;
1350 typename Vxc_Potential<Grid>::XC_entry xc =
1351 EvaluateXC(rho, rho_grad.squaredNorm());
1352
1353 Index owner = owner_atoms[pidx];
1354 if (owner < 0) {
1355 // Owner atoms are set by GridSetup; skipping the point would give
1356 // an incomplete gradient.
1357 throw std::runtime_error(
1358 "GridWeightGradient: grid point has no owner atom set; the "
1359 "grid must be built with Vxc_Grid::GridSetup.");
1360 }
1361
1362 AddSSWWeightDerivative(points[pidx], owner, weight, rho * xc.f_xc,
1363 atoms, Rij, grad_thread[thread_id]);
1364 }
1365 } catch (...) {
1366#pragma omp critical
1367 {
1368 if (!eptr_weight) {
1369 eptr_weight = std::current_exception();
1370 }
1371 }
1372 }
1373 }
1374 if (eptr_weight) {
1375 std::rethrow_exception(eptr_weight);
1376 }
1377
1378 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
1379 for (Index t = 0; t < nthreads; ++t) {
1380 grad += grad_thread[t];
1381 }
1382 return grad;
1383}
1384
1385// ===========================================================================
1386// d/dt [PulayGradient + GridWeightGradient](D + t P) at t = 0.
1387//
1388// With T = 2D and T' = 2P on the box, per grid point (phi, dphi, H_mu the AO
1389// values, gradients and Hessians):
1390// temp = phi^T T, g = dphi^T temp, Gm = T dphi, s = Gm g,
1391// Hrho = sum_mu temp_mu H_mu + sym(dphi^T Gm),
1392// and the primed objects from T'. With drho = temp'.phi / 2,
1393// dsigma = 2 g.g', dvr = v2rho2 drho + v2rhosigma dsigma,
1394// dvs = v2rhosigma drho + v2sigma2 dsigma, s' = Gm' g + Gm g':
1395// translation (owner):
1396// w [dvr g + vr g' + 2 dvs Hrho g + 2 vs (Hrho' g + Hrho g')]
1397// basis (mu on A):
1398// -w (dvr temp_mu + vr temp'_mu) dphi_mu
1399// -2w [dvs (dphi_mu s_mu + temp_mu H_mu g)
1400// + vs (dphi_mu s'_mu + temp'_mu H_mu g + temp_mu H_mu g')]
1401// grid weights: the SSW derivative with energy density
1402// d(rho f_xc) = vr drho + vs dsigma.
1403// ===========================================================================
1404template <class Grid>
1406 const Eigen::MatrixXd& density_matrix, const Eigen::MatrixXd& direction,
1407 const QMMolecule& atoms) const {
1408 const Index natoms = atoms.size();
1409 const Eigen::MatrixXd Rij = grid_.CalcInverseAtomDist(atoms);
1410 // fail before the grid loop for functionals without fxc
1411 {
1412 const double rho = 0.1;
1413 const double sigma = 0.01;
1414 double vr, vs, rr, rs, ss;
1415 EvaluateVXCFXCBatch(1, &rho, &sigma, &vr, &vs, &rr, &rs, &ss);
1416 }
1417 const Index nthreads = OPENMP::getMaxThreads();
1418 std::vector<Eigen::MatrixXd> grad_thread(nthreads,
1419 Eigen::MatrixXd::Zero(natoms, 3));
1420 std::exception_ptr eptr = nullptr;
1421#pragma omp parallel for schedule(guided)
1422 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
1423 try {
1424 const Index thread_id = OPENMP::getThreadId();
1425 Eigen::MatrixXd& gt = grad_thread[thread_id];
1426 const GridBox& box = grid_[i];
1427 if (!box.Matrixsize()) {
1428 continue;
1429 }
1430 const Eigen::MatrixXd T = 2 * box.ReadFromBigMatrix(density_matrix);
1431 const Eigen::MatrixXd Tp = 2 * box.ReadFromBigMatrix(direction);
1432 const double cutoff = 1.e-40 / double(density_matrix.rows()) /
1433 double(density_matrix.rows());
1434 if (T.cwiseAbs2().maxCoeff() < cutoff) {
1435 continue;
1436 }
1437 const Index nf = box.Matrixsize();
1438 std::vector<Index> local_idx_to_atom(nf);
1439 const std::vector<const AOShell*>& shells = box.getShells();
1440 const std::vector<GridboxRange>& ao_ranges = box.getAOranges();
1441 for (std::size_t sh = 0; sh < shells.size(); ++sh) {
1442 const Index atom = shells[sh]->getAtomIndex();
1443 for (Index k = 0; k < ao_ranges[sh].size; ++k) {
1444 local_idx_to_atom[ao_ranges[sh].start + k] = atom;
1445 }
1446 }
1447 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
1448 const std::vector<double>& weights = box.getGridWeights();
1449 const std::vector<Index>& owner_atoms = box.getOwnerAtoms();
1450
1451 for (Index pt = 0; pt < box.size(); ++pt) {
1452 const double w = weights[pt];
1453 const Index owner = owner_atoms[pt];
1454 if (owner < 0) {
1455 throw std::runtime_error(
1456 "GradientResponse: grid point has no owner atom set; the grid "
1457 "must be built with Vxc_Grid::GridSetup.");
1458 }
1460 ? box.CalcAOValuesHessian(points[pt])
1462 AOShell::AOValues aov(0);
1463 if (!is_gga_) {
1464 aov = box.CalcAOValues(points[pt]);
1465 }
1466 const Eigen::VectorXd& phi = is_gga_ ? ao.values : aov.values;
1467 const Eigen::MatrixX3d& dphi =
1468 is_gga_ ? ao.derivatives : aov.derivatives;
1469
1470 const Eigen::VectorXd temp = T * phi;
1471 const double rho = 0.5 * temp.dot(phi);
1472 if (rho * w < 1.e-20) {
1473 continue;
1474 }
1475 const Eigen::VectorXd tempP = Tp * phi;
1476 const double drho = 0.5 * tempP.dot(phi);
1477 const Eigen::Vector3d g = dphi.transpose() * temp;
1478 const Eigen::Vector3d gp = dphi.transpose() * tempP;
1479 const double sigma = g.squaredNorm();
1480 const double dsigma = 2.0 * g.dot(gp);
1481 double vr, vs, rr, rs, ss;
1482 EvaluateVXCFXCBatch(1, &rho, &sigma, &vr, &vs, &rr, &rs, &ss);
1483 const double dvr = rr * drho + rs * dsigma;
1484 const double dvs = rs * drho + ss * dsigma;
1485
1486 // LDA part: translation and basis terms
1487 gt.row(owner) += (w * (dvr * g + vr * gp)).transpose();
1488 for (Index mu = 0; mu < nf; ++mu) {
1489 gt.row(local_idx_to_atom[mu]) -=
1490 w * (dvr * temp(mu) + vr * tempP(mu)) * dphi.row(mu);
1491 }
1492 if (is_gga_) {
1493 const Eigen::MatrixX3d Gm = T * dphi;
1494 const Eigen::MatrixX3d Gp = Tp * dphi;
1495 const Eigen::VectorXd sv = Gm * g;
1496 const Eigen::VectorXd svp = Gp * g + Gm * gp;
1497 Eigen::Matrix3d Hrho = Eigen::Matrix3d::Zero();
1498 Eigen::Matrix3d Hp = Eigen::Matrix3d::Zero();
1499 for (Index mu = 0; mu < nf; ++mu) {
1500 Hrho += temp(mu) * ao.hessians[mu];
1501 Hp += tempP(mu) * ao.hessians[mu];
1502 }
1503 const Eigen::Matrix3d M = dphi.transpose() * Gm;
1504 const Eigen::Matrix3d Mp = dphi.transpose() * Gp;
1505 Hrho += 0.5 * (M + M.transpose());
1506 Hp += 0.5 * (Mp + Mp.transpose());
1507 gt.row(owner) +=
1508 (2.0 * w * (dvs * (Hrho * g) + vs * (Hp * g + Hrho * gp)))
1509 .transpose();
1510 for (Index mu = 0; mu < nf; ++mu) {
1511 const Eigen::Matrix3d& H = ao.hessians[mu];
1512 const Eigen::Vector3d d = dphi.row(mu).transpose();
1513 const Eigen::Vector3d c =
1514 dvs * (d * sv(mu) + temp(mu) * (H * g)) +
1515 vs * (d * svp(mu) + tempP(mu) * (H * g) + temp(mu) * (H * gp));
1516 gt.row(local_idx_to_atom[mu]) -= (2.0 * w * c).transpose();
1517 }
1518 }
1519 AddSSWWeightDerivative(points[pt], owner, w, vr * drho + vs * dsigma,
1520 atoms, Rij, gt);
1521 }
1522 } catch (...) {
1523#pragma omp critical
1524 {
1525 if (!eptr) {
1526 eptr = std::current_exception();
1527 }
1528 }
1529 }
1530 }
1531 if (eptr) {
1532 std::rethrow_exception(eptr);
1533 }
1534 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
1535 for (const Eigen::MatrixXd& gtt : grad_thread) {
1536 grad += gtt;
1537 }
1538 return grad;
1539}
1540
1541template <class Grid>
1543 const Eigen::MatrixXd& dmat_alpha, const Eigen::MatrixXd& dmat_beta,
1544 const AOBasis& dftbasis) const {
1545 // UKS version of PulayGradient (LDA and GGA). The three sigma terms
1546 // (sigma_aa, sigma_ab, sigma_bb) reduce to the restricted per-spin
1547 // expressions (Gmat_s, Hessian_rho_s), applied once per spin with the
1548 // effective gradient vectors
1549 // V_a = 2*vsigma_aa*rho_a_grad + vsigma_ab*rho_b_grad
1550 // V_b = 2*vsigma_bb*rho_b_grad + vsigma_ab*rho_a_grad.
1551 Index natoms = static_cast<Index>(dftbasis.getFuncPerAtom().size());
1552 Index nthreads = OPENMP::getMaxThreads();
1553 std::vector<Eigen::MatrixXd> grad_thread(nthreads,
1554 Eigen::MatrixXd::Zero(natoms, 3));
1555
1556 std::exception_ptr eptr_pulay_uks = nullptr;
1557#pragma omp parallel for schedule(guided)
1558 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
1559 try {
1560 Index thread_id = OPENMP::getThreadId();
1561 const GridBox& box = grid_[i];
1562 if (!box.Matrixsize()) {
1563 continue;
1564 }
1565
1566 const Eigen::MatrixXd DMa = box.ReadFromBigMatrix(dmat_alpha);
1567 const Eigen::MatrixXd DMb = box.ReadFromBigMatrix(dmat_beta);
1568
1569 // Box-local AO index -> atom index -- MUST use getAOranges() (start/
1570 // size per shell), not a naive sequential push_back per shell: a
1571 // single box's significant shells are not guaranteed to be grouped
1572 // contiguously by atom. Matches the exact construction already
1573 // validated in the restricted PulayGradient.
1574 std::vector<Index> local_idx_to_atom(box.Matrixsize());
1575 const std::vector<const AOShell*>& shells = box.getShells();
1576 const std::vector<GridboxRange>& ao_ranges = box.getAOranges();
1577 for (size_t s = 0; s < shells.size(); ++s) {
1578 Index atom = shells[s]->getAtomIndex();
1579 for (Index k = 0; k < ao_ranges[s].size; ++k) {
1580 local_idx_to_atom[ao_ranges[s].start + k] = atom;
1581 }
1582 }
1583 const std::vector<Index>& owner_atoms = box.getOwnerAtoms();
1584
1585 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
1586 const std::vector<double>& weights = box.getGridWeights();
1587
1588 for (Index p = 0; p < box.size(); ++p) {
1590
1591 Eigen::VectorXd temp_a = DMa * ao.values;
1592 Eigen::VectorXd temp_b = DMb * ao.values;
1593 const double rho_a = ao.values.dot(temp_a);
1594 const double rho_b = ao.values.dot(temp_b);
1595 const double rho = rho_a + rho_b;
1596 const double weight = weights[p];
1597
1598 if (rho * weight < 1.e-20) {
1599 continue;
1600 }
1601
1602 const Eigen::Vector3d rho_a_grad =
1603 2.0 * (ao.derivatives.transpose() * temp_a);
1604 const Eigen::Vector3d rho_b_grad =
1605 2.0 * (ao.derivatives.transpose() * temp_b);
1606 const double sigma_aa = rho_a_grad.dot(rho_a_grad);
1607 const double sigma_ab = rho_a_grad.dot(rho_b_grad);
1608 const double sigma_bb = rho_b_grad.dot(rho_b_grad);
1609
1611 EvaluateXCSpin(rho_a, rho_b, sigma_aa, sigma_ab, sigma_bb);
1612
1613 // translation term (A == owner(p) only), rho part
1614 Index owner_of_point = owner_atoms[p];
1615 grad_thread[thread_id].row(owner_of_point) +=
1616 (weight * (xc.vrho_a * rho_a_grad + xc.vrho_b * rho_b_grad))
1617 .transpose();
1618
1619 // GGA sigma terms: basis and translation terms as in the restricted
1620 // case, with Gmat_s/Hessian_rho_s per spin (from the spin density
1621 // matrices instead of DMAT_here), contracted with V_a/V_b.
1622 Eigen::MatrixX3d Gmat_a = 2.0 * (DMa * ao.derivatives);
1623 Eigen::MatrixX3d Gmat_b = 2.0 * (DMb * ao.derivatives);
1624 Eigen::Vector3d V_a =
1625 2.0 * xc.vsigma_aa * rho_a_grad + xc.vsigma_ab * rho_b_grad;
1626 Eigen::Vector3d V_b =
1627 2.0 * xc.vsigma_bb * rho_b_grad + xc.vsigma_ab * rho_a_grad;
1628
1629 // Translation-type sigma contribution: Hessian_rho_s * V_s,
1630 // summed over both spins.
1631 Eigen::Matrix3d Hessian_rho_a = Eigen::Matrix3d::Zero();
1632 Eigen::Matrix3d Hessian_rho_b = Eigen::Matrix3d::Zero();
1633 for (Index mu = 0; mu < box.Matrixsize(); ++mu) {
1634 Hessian_rho_a += 2.0 * temp_a(mu) * ao.hessians[mu];
1635 Hessian_rho_b += 2.0 * temp_b(mu) * ao.hessians[mu];
1636 }
1637 Eigen::Matrix3d Ma = ao.derivatives.transpose() * Gmat_a;
1638 Eigen::Matrix3d Mb = ao.derivatives.transpose() * Gmat_b;
1639 Hessian_rho_a += 0.5 * (Ma + Ma.transpose());
1640 Hessian_rho_b += 0.5 * (Mb + Mb.transpose());
1641
1642 grad_thread[thread_id].row(owner_of_point) +=
1643 (weight * (Hessian_rho_a * V_a + Hessian_rho_b * V_b)).transpose();
1644
1645 // Basis-type term (LDA + sigma), accumulated per local AO index
1646 // mu, scattered to the correct atom via local_idx_to_atom.
1647 Eigen::VectorXd Gmat_a_dot_Va = Gmat_a * V_a;
1648 Eigen::VectorXd Gmat_b_dot_Vb = Gmat_b * V_b;
1649 for (Index mu = 0; mu < box.Matrixsize(); ++mu) {
1650 Index atom = local_idx_to_atom[mu];
1651 Eigen::Vector3d lda_contribution =
1652 -2.0 * weight *
1653 (xc.vrho_a * temp_a(mu) + xc.vrho_b * temp_b(mu)) *
1654 ao.derivatives.row(mu).transpose();
1655 Eigen::Vector3d sigma_contribution =
1656 -weight *
1657 (ao.derivatives.row(mu).transpose() * Gmat_a_dot_Va(mu) +
1658 2.0 * temp_a(mu) * (ao.hessians[mu] * V_a) +
1659 ao.derivatives.row(mu).transpose() * Gmat_b_dot_Vb(mu) +
1660 2.0 * temp_b(mu) * (ao.hessians[mu] * V_b));
1661 grad_thread[thread_id].row(atom) +=
1662 (lda_contribution + sigma_contribution).transpose();
1663 }
1664 }
1665 } catch (...) {
1666#pragma omp critical
1667 {
1668 if (!eptr_pulay_uks) {
1669 eptr_pulay_uks = std::current_exception();
1670 }
1671 }
1672 }
1673 }
1674 if (eptr_pulay_uks) {
1675 std::rethrow_exception(eptr_pulay_uks);
1676 }
1677
1678 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
1679 for (Index t = 0; t < nthreads; ++t) {
1680 grad += grad_thread[t];
1681 }
1682 return grad;
1683}
1684
1685template <class Grid>
1687 const Eigen::MatrixXd& dmat_alpha, const Eigen::MatrixXd& dmat_beta,
1688 const QMMolecule& atoms) const {
1689 // UKS version of GridWeightGradient (LDA and GGA). The SSW weight
1690 // derivative (AddSSWWeightDerivative) is purely geometric and identical; only
1691 // the prefactor differs: rho_a, rho_b from the spin density matrices (not
1692 // pre-doubled, as in IntegrateVXCSpin) and f_xc from EvaluateXCSpin.
1693 Index natoms = atoms.size();
1694 Eigen::MatrixXd Rij = grid_.CalcInverseAtomDist(atoms);
1695
1696 Index nthreads = OPENMP::getMaxThreads();
1697 std::vector<Eigen::MatrixXd> grad_thread(nthreads,
1698 Eigen::MatrixXd::Zero(natoms, 3));
1699
1700 std::exception_ptr eptr_weight_uks = nullptr;
1701#pragma omp parallel for schedule(guided)
1702 for (Index i = 0; i < grid_.getBoxesSize(); ++i) {
1703 try {
1704 Index thread_id = OPENMP::getThreadId();
1705 const GridBox& box = grid_[i];
1706 if (!box.Matrixsize()) {
1707 continue;
1708 }
1709
1710 const Eigen::MatrixXd DMa = box.ReadFromBigMatrix(dmat_alpha);
1711 const Eigen::MatrixXd DMb = box.ReadFromBigMatrix(dmat_beta);
1712 double cutoff =
1713 1.e-40 / double(dmat_alpha.rows()) / double(dmat_alpha.rows());
1714 if (std::max(DMa.cwiseAbs2().maxCoeff(), DMb.cwiseAbs2().maxCoeff()) <
1715 cutoff) {
1716 continue;
1717 }
1718
1719 const std::vector<Eigen::Vector3d>& points = box.getGridPoints();
1720 const std::vector<double>& weights = box.getGridWeights();
1721 const std::vector<Index>& owner_atoms = box.getOwnerAtoms();
1722
1723 for (Index pidx = 0; pidx < box.size(); ++pidx) {
1724 AOShell::AOValues ao = box.CalcAOValues(points[pidx]);
1725 Eigen::VectorXd temp_a = DMa * ao.values;
1726 Eigen::VectorXd temp_b = DMb * ao.values;
1727 const double rho_a = ao.values.dot(temp_a);
1728 const double rho_b = ao.values.dot(temp_b);
1729 const double rho = rho_a + rho_b;
1730 double weight = weights[pidx];
1731 if (rho * weight < 1.e-20) {
1732 continue;
1733 }
1734 const Eigen::Vector3d rho_a_grad =
1735 2.0 * (ao.derivatives.transpose() * temp_a);
1736 const Eigen::Vector3d rho_b_grad =
1737 2.0 * (ao.derivatives.transpose() * temp_b);
1738 const double sigma_aa = rho_a_grad.dot(rho_a_grad);
1739 const double sigma_ab = rho_a_grad.dot(rho_b_grad);
1740 const double sigma_bb = rho_b_grad.dot(rho_b_grad);
1742 EvaluateXCSpin(rho_a, rho_b, sigma_aa, sigma_ab, sigma_bb);
1743
1744 Index owner = owner_atoms[pidx];
1745 if (owner < 0) {
1746 throw std::runtime_error(
1747 "GridWeightGradientUKS: grid point has no owner atom set; the "
1748 "grid must be built with Vxc_Grid::GridSetup.");
1749 }
1750
1751 AddSSWWeightDerivative(points[pidx], owner, weight, rho * xc.f_xc,
1752 atoms, Rij, grad_thread[thread_id]);
1753 }
1754 } catch (...) {
1755#pragma omp critical
1756 {
1757 if (!eptr_weight_uks) {
1758 eptr_weight_uks = std::current_exception();
1759 }
1760 }
1761 }
1762 }
1763 if (eptr_weight_uks) {
1764 std::rethrow_exception(eptr_weight_uks);
1765 }
1766
1767 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
1768 for (Index t = 0; t < nthreads; ++t) {
1769 grad += grad_thread[t];
1770 }
1771 return grad;
1772}
1773
1774template class Vxc_Potential<Vxc_Grid>;
1775
1776} // namespace xtp
1777} // namespace votca
break string into words
Definition tokenizer.h:72
std::vector< T > ToVector()
store all words in a vector of type T, does type conversion.
Definition tokenizer.h:109
Container to hold Basisfunctions for all atoms.
Definition aobasis.h:42
const std::vector< Index > & getFuncPerAtom() const
Definition aobasis.h:72
Adds per-grid-box blocks into a set of AO matrices from inside an OpenMP loop over grid boxes.
void Finish()
sums the thread-local copies into the targets (call outside the loop)
void Add(const GridBox &box, const std::vector< const Eigen::MatrixXd * > &small)
const std::vector< Eigen::Vector3d > & getGridPoints() const
Definition gridbox.h:55
Eigen::MatrixXd ReadFromBigMatrix(const Eigen::MatrixXd &bigmatrix) const
Definition gridbox.cc:97
void AddtoBigMatrix(Eigen::MatrixXd &bigmatrix, const Eigen::MatrixXd &smallmatrix) const
Definition gridbox.cc:84
const std::vector< const AOShell * > & getShells() const
Definition gridbox.h:65
const std::vector< GridboxRange > & getAOranges() const
Definition gridbox.h:69
const std::vector< double > & getGridWeights() const
Definition gridbox.h:57
const std::vector< Index > & getOwnerAtoms() const
Definition gridbox.h:63
AOShell::AOValuesHessian CalcAOValuesHessian(const Eigen::Vector3d &point) const
Definition gridbox.cc:68
AOShell::AOValues CalcAOValues(const Eigen::Vector3d &point) const
Definition gridbox.cc:44
Index size() const
Definition gridbox.h:71
Index Matrixsize() const
Definition gridbox.h:75
Eigen::MatrixXd & matrix()
Definition eigen.h:97
double & energy()
Definition eigen.h:98
conversion of functional string into integer
static constexpr Index kPointBlock
void EvaluateXCSpinBatch(Index n, const double *rho, const double *sigma, double *exc, double *vrho, double *vsigma) const
Eigen::MatrixXd GridWeightGradient(const Eigen::MatrixXd &density_matrix, const QMMolecule &atoms) const
void EvaluateVXCFXCBatch(Index n, const double *rho, const double *sigma, double *vrho, double *vsigma, double *v2rho2, double *v2rhosigma, double *v2sigma2) const
Eigen::MatrixXd PulayGradient(const Eigen::MatrixXd &density_matrix, const AOBasis &dftbasis) const
void EvaluateFXCSpinBatch(Index n, const double *rho, const double *sigma, double *vsigma, double *v2rho2, double *v2rhosigma, double *v2sigma2) const
XC_entry_spin EvaluateXCSpin(double rho_a, double rho_b, double sigma_aa, double sigma_ab, double sigma_bb) const
void EvaluateXCBatch(Index n, const double *rho, const double *sigma, double *exc, double *vrho, double *vsigma) 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
XC_entry EvaluateXC(double rho, double sigma) const
Eigen::MatrixXd GradientResponse(const Eigen::MatrixXd &density_matrix, const Eigen::MatrixXd &direction, const QMMolecule &atoms) const
void EvaluateFXCBatch(Index n, const double *rho, const double *sigma, double *vsigma, double *v2rho2, double *v2rhosigma, double *v2sigma2) 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
Index getMaxThreads()
Definition eigen.h:145
Index getThreadId()
Definition eigen.h:160
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
std::vector< Eigen::Matrix3d > hessians
Definition aoshell.h:180
Eigen::MatrixX3d derivatives
Definition aoshell.h:131
double vsigma_ab
double vrho_b
double vrho_a
double vsigma_aa
double vsigma_bb
double f_xc
double f_xc
double df_dsigma
double df_drho