votca 2026-dev
Loading...
Searching...
No Matches
libint2_derivative_calls.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2024 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// Nuclear-coordinate derivatives of AO integrals (overlap, kinetic, nuclear
21// attraction, two-centre Coulomb metric, three-centre RI) via libint2 engines
22// with deriv_order = 1, for the analytic DFT gradient. Derivatives are with
23// respect to atomic positions in Bohr.
24//
25// Conventions:
26// - libint2::Engine returns the derivatives with respect to every centre
27// explicitly (buffers ordered by centre, then x, y, z); none is omitted via
28// translational invariance.
29// - Shell-pair buffers are row-major and are mapped with MatrixLibInt, as in
30// libint2_calls.cc. A column-major map is indistinguishable for s shells
31// only.
32// - Each derivative category needs its own libint2 configure option (see the
33// compile guards below); missing support makes the functions throw.
34// - Exceptions inside OpenMP regions are captured and rethrown afterwards.
35
36// Local VOTCA includes
37#include "votca/xtp/aobasis.h"
38#include "votca/xtp/aomatrix.h"
42#include <algorithm>
43#include <atomic>
44#include <exception>
45#include <iostream>
46#include <stdexcept>
47#include <string>
48
49// include libint last otherwise it overrides eigen
51#define LIBINT2_CONSTEXPR_STATICS 0
52#if defined(__clang__)
53#pragma clang diagnostic push
54#pragma clang diagnostic ignored "-W#warnings"
55#elif defined(__GNUC__)
56#pragma GCC diagnostic push
57#pragma GCC diagnostic ignored "-Warray-bounds"
58#pragma GCC diagnostic ignored "-Wcpp"
59#endif
60#include <libint2.hpp>
61// <libint2/statics_definition.h> defines libint2's static tables and must be
62// included in exactly one translation unit; libint2_calls.cc does that.
63#if defined(__clang__)
64#pragma clang diagnostic pop
65#elif defined(__GNUC__)
66#pragma GCC diagnostic pop
67#endif
68
69// libint2 releases up to 2.9 (autotools-generated config.h) name the
70// per-category derivative orders INCLUDE_ONEBODY/_ERI2/_ERI3; newer CMake
71// builds use the LIBINT_ prefix. Without this mapping an older libint2 with
72// derivative integrals (e.g. the conda-forge build, 2.9.0, orders 2) is
73// treated as having none, and compute_forces is rejected.
74#if !defined(LIBINT_INCLUDE_ONEBODY) && defined(INCLUDE_ONEBODY)
75#define LIBINT_INCLUDE_ONEBODY INCLUDE_ONEBODY
76#endif
77#if !defined(LIBINT_INCLUDE_ERI2) && defined(INCLUDE_ERI2)
78#define LIBINT_INCLUDE_ERI2 INCLUDE_ERI2
79#endif
80#if !defined(LIBINT_INCLUDE_ERI) && defined(INCLUDE_ERI)
81#define LIBINT_INCLUDE_ERI INCLUDE_ERI
82#endif
83#if !defined(LIBINT_INCLUDE_ERI3) && defined(INCLUDE_ERI3)
84#define LIBINT_INCLUDE_ERI3 INCLUDE_ERI3
85#endif
86
87// libint2 < 2.9.0 computes the wrong build-function index for 3-centre
88// derivative integrals when the 3-centre AM limit is centre dependent
89// (engine.impl.h, BraKet::xs_xx: LIBINT2_CENTER_DEPENDENT_MAX_AM_3eri is
90// macro-expanded before being pasted with the derivative order, so the ket
91// stride is LIBINT2_MAX_AM_3eri1+1 instead of LIBINT2_MAX_AM_default1+1).
92// The engine then calls a wrong or null build function: a segfault at 0x0,
93// e.g. with Ubuntu's libint2 2.7.2 (--with-eri3-max-am=7,6, max-am 5).
94// Treat 3-centre derivatives as unavailable for such builds.
95#if (LIBINT_MAJOR_VERSION < 2 || \
96 (LIBINT_MAJOR_VERSION == 2 && LIBINT_MINOR_VERSION < 9)) && \
97 defined(LIBINT2_CENTER_DEPENDENT_MAX_AM_3eri1) && \
98 defined(LIBINT2_MAX_AM_3eri1) && defined(LIBINT2_MAX_AM_default1)
99#if LIBINT2_CENTER_DEPENDENT_MAX_AM_3eri1 == 1 && \
100 LIBINT2_MAX_AM_3eri1 != LIBINT2_MAX_AM_default1
101#define VOTCA_LIBINT_ERI3_DERIV_BROKEN 1
102#endif
103#endif
104#ifndef VOTCA_LIBINT_ERI3_DERIV_BROKEN
105#define VOTCA_LIBINT_ERI3_DERIV_BROKEN 0
106#endif
107
108// The libint2 headers compiled here must be those of the libint2 that CMake
109// found and links (CheckLibintFeatures.cmake passes its version and
110// derivative orders). Another libint2 earlier in the include path (e.g. a
111// Homebrew or conda one next to Boost's headers) would otherwise compile
112// against mismatched headers without any diagnostic.
113#ifdef VOTCA_LIBINT_EXPECT_MAJOR
114#ifdef LIBINT_INCLUDE_ONEBODY
115#define VOTCA_LIBINT_HAVE_ONEBODY LIBINT_INCLUDE_ONEBODY
116#else
117#define VOTCA_LIBINT_HAVE_ONEBODY -1
118#endif
119#ifdef LIBINT_INCLUDE_ERI
120#define VOTCA_LIBINT_HAVE_ERI LIBINT_INCLUDE_ERI
121#else
122#define VOTCA_LIBINT_HAVE_ERI -1
123#endif
124#ifdef LIBINT_INCLUDE_ERI2
125#define VOTCA_LIBINT_HAVE_ERI2 LIBINT_INCLUDE_ERI2
126#else
127#define VOTCA_LIBINT_HAVE_ERI2 -1
128#endif
129#ifdef LIBINT_INCLUDE_ERI3
130#define VOTCA_LIBINT_HAVE_ERI3 LIBINT_INCLUDE_ERI3
131#else
132#define VOTCA_LIBINT_HAVE_ERI3 -1
133#endif
134#if LIBINT_MAJOR_VERSION != VOTCA_LIBINT_EXPECT_MAJOR || \
135 LIBINT_MINOR_VERSION != VOTCA_LIBINT_EXPECT_MINOR || \
136 LIBINT_MICRO_VERSION != VOTCA_LIBINT_EXPECT_MICRO || \
137 VOTCA_LIBINT_HAVE_ONEBODY != VOTCA_LIBINT_EXPECT_ONEBODY || \
138 VOTCA_LIBINT_HAVE_ERI != VOTCA_LIBINT_EXPECT_ERI || \
139 VOTCA_LIBINT_HAVE_ERI2 != VOTCA_LIBINT_EXPECT_ERI2 || \
140 VOTCA_LIBINT_HAVE_ERI3 != VOTCA_LIBINT_EXPECT_ERI3
141#error \
142 "The libint2 headers found by the compiler are not those of the libint2 CMake configured (VOTCA_LIBINT_CONFIG_H in CMakeCache.txt). Another libint2 is earlier in the include path; remove it from there or uninstall it."
143#endif
144#endif
145
146namespace votca {
147namespace xtp {
148
149// Defined in libint2_calls.cc, not declared in any header; forward
150// declared here for use by ComputeThreeCenterIntegrals below, to avoid
151// re-deriving the same shell-iteration logic a third time.
152std::vector<Eigen::MatrixXd> ComputeAO3cBlock(const libint2::Shell& auxshell,
153 const AOBasis& dftbasis,
154 libint2::Engine& engine);
155
156// Result type: one entry per atom, each holding the three Cartesian
157// derivative matrices (d/dx, d/dy, d/dz) of the full AO matrix with respect
158// to that atom's nuclear coordinate. Matches the AO matrix convention used
159// elsewhere in this file (dense Eigen::MatrixXd, size AOBasisSize^2).
160using AOMatrixDerivative = std::array<Eigen::MatrixXd, 3>;
161
162// libint2 returns each shell-pair (derivative) buffer in row-major order,
163// n1 rows x n2 columns, as in libint2_calls.cc. Mapping it as column-major
164// transposes every block with p or higher shells; for s shells (1x1 blocks)
165// both agree, so tests on all-s bases cannot detect it.
166using MatrixLibInt =
167 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
168
169namespace {
170// Thrown by the stubs compiled when a derivative category (ONEBODY, ERI2,
171// ERI3; independent libint2 configure options) is unavailable.
172// [[maybe_unused]] because no stub is compiled if all three are supported
173// (-Werror -Wunused-function).
174[[noreturn, maybe_unused]] void ThrowNoDerivativeSupport(
175 const char* function_name, const char* configure_flag) {
176 throw std::runtime_error(
177 std::string(function_name) +
178 ": this libint2 build was compiled without derivative integral "
179 "support for this operator category, so analytic nuclear forces "
180 "are unavailable. Rebuild libint2 with " +
181 configure_flag +
182 " to use this feature. Many packaged libint2 builds (Homebrew, "
183 "Ubuntu apt, etc.) do not enable it; one-body, two-center Coulomb "
184 "metric and three-center RI integrals each have their own "
185 "configure option.");
186}
187
188// libint2::Engine only assert()s that a build function exists for the
189// angular momenta of a shell set; with NDEBUG a missing one becomes a call
190// through a null pointer (segfault at address 0x0, not an exception).
191// Packaged libint2 builds can generate derivative code for fewer angular
192// momenta than energy code, and the engine's own lmax check does not catch
193// every gap, so the generated tables are checked against the basis first.
194// Tables are indexed [l1][l2] (one-body, two-centre) and [lP][l1][l2]
195// (three-centre); for the latter libint2 generates only one ordering of the
196// ket pair and the engine swaps the shells, so either ordering suffices.
197template <class Fn, std::size_t N1, std::size_t N2>
198bool BuildTableCovers(Fn (&table)[N1][N2], Index lmax1, Index lmax2) {
199 if (lmax1 >= Index(N1) || lmax2 >= Index(N2)) {
200 return false;
201 }
202 for (Index l1 = 0; l1 <= lmax1; ++l1) {
203 for (Index l2 = 0; l2 <= lmax2; ++l2) {
204 if (table[l1][l2] == nullptr) {
205 return false;
206 }
207 }
208 }
209 return true;
210}
211
212template <class Fn, std::size_t NP, std::size_t N1, std::size_t N2>
213bool BuildTableCovers(Fn (&table)[NP][N1][N2], Index lmaxP, Index lmax) {
214 if (lmaxP >= Index(NP) || lmax >= Index(N1) || lmax >= Index(N2)) {
215 return false;
216 }
217 for (Index lP = 0; lP <= lmaxP; ++lP) {
218 for (Index l1 = 0; l1 <= lmax; ++l1) {
219 for (Index l2 = 0; l2 <= l1; ++l2) {
220 if (table[lP][l1][l2] == nullptr && table[lP][l2][l1] == nullptr) {
221 return false;
222 }
223 }
224 }
225 }
226 return true;
227}
228
229[[maybe_unused]] void CheckDerivativeTable(bool covered,
230 const char* function_name,
231 Index lmax) {
232 if (!covered) {
233 throw std::runtime_error(
234 std::string(function_name) +
235 ": this libint2 build has no first-derivative integrals for the "
236 "angular momenta of this basis (maximum l = " +
237 std::to_string(lmax) +
238 "), so analytic nuclear forces are unavailable. Rebuild libint2 "
239 "with a higher derivative angular-momentum limit (the second "
240 "entry of --with-max-am / --with-eri2-max-am / --with-eri3-max-am).");
241 }
242}
243} // namespace
244
245// Nuclear-coordinate derivatives of a two-centre one-electron integral
246// matrix for obtype = libint2::Operator::overlap or kinetic (operators with
247// parameters or more centres are not handled).
248//
249// Compile guard: LIBINT2_MAX_DERIV_ORDER is the maximum over all operator
250// categories, so it is not sufficient; a category built without derivatives
251// fails inside engine.compute() (null buffers or an uncatchable crash). The
252// per-category macros LIBINT_INCLUDE_ONEBODY/_ERI2/_ERI3 hold the configured
253// derivative order (LIBINT2_ENABLE_ONEBODY/_ERI2/_ERI3, -1 = off), so their
254// value must be checked, not just whether they are defined: ONEBODY defaults
255// to 0 (energies only), e.g. in the Homebrew formula, which only enables
256// ERI/ERI2/ERI3, while Psi4's default enables ONEBODY but not ERI2/ERI3.
257//
258// ONEBODY: computeOneBodyIntegralDerivatives,
259// ComputeNuclearAttractionDerivatives; ERI2: ComputeCoulombMetricDerivatives;
260// ERI3: the three-centre functions.
261#if defined(LIBINT2_MAX_DERIV_ORDER) && LIBINT2_MAX_DERIV_ORDER >= 1 && \
262 (LIBINT_INCLUDE_ONEBODY >= 1)
263template <libint2::Operator obtype>
264std::vector<AOMatrixDerivative> computeOneBodyIntegralDerivatives(
265 const AOBasis& aobasis) {
266
267 static_assert(
268 libint2::operator_traits<obtype>::nopers == 1,
269 "computeOneBodyIntegralDerivatives only supports single-operator "
270 "types (overlap, kinetic); multipole-type operators with multiple "
271 "result matrices are not handled.");
272 {
273 Index lmax = aobasis.getMaxL();
274 if constexpr (obtype == libint2::Operator::overlap) {
275 CheckDerivativeTable(
276 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_overlap1), lmax,
277 lmax),
278 "ComputeOverlapDerivatives", lmax);
279 } else {
280 CheckDerivativeTable(
281 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_kinetic1), lmax,
282 lmax),
283 "ComputeKineticDerivatives", lmax);
284 }
285 }
286
287 // AOBasis has no getNumofAtoms(); getFuncPerAtom() has one entry per atom.
288 Index natoms = static_cast<Index>(aobasis.getFuncPerAtom().size());
289 Index nthreads = OPENMP::getMaxThreads();
290 std::vector<libint2::Shell> shells = aobasis.GenerateLibintBasis();
291 std::vector<std::vector<Index>> shellpair_list = aobasis.ComputeShellPairs();
292 std::vector<Index> shell2bf = aobasis.getMapToBasisFunctions();
293
294 // shell -> atom index, to assign each derivative buffer to its atom
295 std::vector<Index> shell2atom;
296 shell2atom.reserve(shells.size());
297 for (Index s = 0; s < aobasis.getNumofShells(); ++s) {
298 shell2atom.push_back(aobasis.getShell(s).getAtomIndex());
299 }
300
301 Index nbf = aobasis.AOBasisSize();
302 std::vector<AOMatrixDerivative> result(natoms);
303 for (Index a = 0; a < natoms; ++a) {
304 for (Index xyz = 0; xyz < 3; ++xyz) {
305 result[a][xyz] = Eigen::MatrixXd::Zero(nbf, nbf);
306 }
307 }
308
309 std::vector<libint2::Engine> engines(nthreads);
310 // Same as computeOneBodyIntegrals(), but with deriv_order = 1.
311 engines[0] = libint2::Engine(obtype, aobasis.getMaxNprim(),
312 static_cast<int>(aobasis.getMaxL()), 1);
313 for (Index i = 1; i < nthreads; ++i) {
314 engines[i] = engines[0];
315 }
316
317 std::exception_ptr eptr = nullptr;
318 std::atomic<bool> any_nonnull_buffer{false};
319#pragma omp parallel for schedule(dynamic)
320 for (Index s1 = 0; s1 < aobasis.getNumofShells(); ++s1) {
321 try {
322 Index thread_id = OPENMP::getThreadId();
323 libint2::Engine& engine = engines[thread_id];
324 const libint2::Engine::target_ptr_vec& buf = engine.results();
325
326 Index bf1 = shell2bf[s1];
327 Index n1 = shells[s1].size();
328 Index atom1 = shell2atom[s1];
329
330 for (Index s2 : shellpair_list[s1]) {
331
332 engine.compute(shells[s1], shells[s2]);
333 // buf[0..2]: derivatives w.r.t. the centre of s1, buf[3..5]: w.r.t.
334 // the centre of s2. Both must be checked before dereferencing, since
335 // buf.size() reports 6 even if buf[3..5] are unpopulated.
336 if (buf[0] == nullptr || buf[3] == nullptr) {
337 continue; // screened out, or no derivative support (checked
338 // via any_nonnull_buffer after the loop)
339 }
340 any_nonnull_buffer.store(true, std::memory_order_relaxed);
341
342 Index bf2 = shell2bf[s2];
343 Index n2 = shells[s2].size();
344 Index atom2 = shell2atom[s2];
345
346 for (Index xyz = 0; xyz < 3; ++xyz) {
347 Eigen::Map<const MatrixLibInt> buf_mat1(buf[xyz], n1, n2);
348 result[atom1][xyz].block(bf1, bf2, n1, n2) += buf_mat1;
349 if (s1 != s2) {
350 result[atom1][xyz].block(bf2, bf1, n2, n1) += buf_mat1.transpose();
351 }
352
353 Eigen::Map<const MatrixLibInt> buf_mat2(buf[3 + xyz], n1, n2);
354 result[atom2][xyz].block(bf1, bf2, n1, n2) += buf_mat2;
355 if (s1 != s2) {
356 result[atom2][xyz].block(bf2, bf1, n2, n1) += buf_mat2.transpose();
357 }
358 }
359 }
360 } catch (...) {
361 // An exception escaping an OpenMP thread is undefined behaviour;
362 // keep the first one and rethrow after the parallel region.
363#pragma omp critical
364 {
365 if (!eptr) {
366 eptr = std::current_exception();
367 }
368 }
369 }
370 }
371 if (eptr) {
372 std::rethrow_exception(eptr);
373 }
374 if (!any_nonnull_buffer.load() && aobasis.getNumofShells() > 0) {
375 // Runtime counterpart of the compile guard: obtype never produced a
376 // non-null buffer.
377 throw std::runtime_error(
378 "computeOneBodyIntegralDerivatives: engine.results() returned a "
379 "null buffer for every shell pair; this libint2 build does not "
380 "support this operator's derivative integrals at runtime, even "
381 "though it may report LIBINT2_MAX_DERIV_ORDER >= 1 for other "
382 "operators. Rebuild libint2 with --enable-1body=1 to use this "
383 "feature.");
384 }
385 return result;
386}
387
388// Free-function counterparts of AOOverlap::Fill / AOKinetic::Fill.
389std::vector<AOMatrixDerivative> ComputeOverlapDerivatives(
390 const AOBasis& aobasis) {
391 return computeOneBodyIntegralDerivatives<libint2::Operator::overlap>(aobasis);
392}
393
394std::vector<AOMatrixDerivative> ComputeKineticDerivatives(
395 const AOBasis& aobasis) {
396 return computeOneBodyIntegralDerivatives<libint2::Operator::kinetic>(aobasis);
397}
398#else // !(LIBINT_INCLUDE_ONEBODY)
399// Stubs for overlap and kinetic without ONEBODY derivative support; ERI2 and
400// ERI3 are guarded separately below.
401std::vector<AOMatrixDerivative> ComputeOverlapDerivatives(const AOBasis&) {
402 ThrowNoDerivativeSupport("ComputeOverlapDerivatives", "--enable-1body=1");
403}
404std::vector<AOMatrixDerivative> ComputeKineticDerivatives(const AOBasis&) {
405 ThrowNoDerivativeSupport("ComputeKineticDerivatives", "--enable-1body=1");
406}
407#endif // LIBINT_INCLUDE_ONEBODY
408
409// ===========================================================================
410// Two-centre Coulomb metric derivatives d(P|Q)/dR for the RI-J/RI-K
411// gradient, dE_J/dR = sum_P c_P d(d_P)/dR - 1/2 sum_PQ c_P c_Q d(V_PQ)/dR.
412//
413// As in AOCoulomb::computeCoulombIntegrals, (P|Q) is computed as (P 1|Q 1)
414// with unit shells (BraKet::xs_xs), which have no centre; libint2 returns 6
415// buffers, the derivatives w.r.t. the centres of P and Q.
416//
417// Requires LIBINT_INCLUDE_ERI2 >= 1 (libint2 --enable-eri2), independent of
418// ONEBODY and ERI3.
419#if (LIBINT_INCLUDE_ERI2 >= 1)
420std::vector<AOMatrixDerivative> ComputeCoulombMetricDerivatives(
421 const AOBasis& aobasis) {
422 CheckDerivativeTable(
423 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_2eri1),
424 aobasis.getMaxL(), aobasis.getMaxL()),
425 "ComputeCoulombMetricDerivatives", aobasis.getMaxL());
426 Index natoms = static_cast<Index>(aobasis.getFuncPerAtom().size());
427 Index nthreads = OPENMP::getMaxThreads();
428 std::vector<libint2::Shell> shells = aobasis.GenerateLibintBasis();
429 std::vector<Index> shell2bf = aobasis.getMapToBasisFunctions();
430
431 std::vector<Index> shell2atom;
432 shell2atom.reserve(aobasis.getNumofShells());
433 for (Index s = 0; s < aobasis.getNumofShells(); ++s) {
434 shell2atom.push_back(aobasis.getShell(s).getAtomIndex());
435 }
436
437 Index nbf = aobasis.AOBasisSize();
438 std::vector<AOMatrixDerivative> result(natoms);
439 for (Index a = 0; a < natoms; ++a) {
440 for (Index xyz = 0; xyz < 3; ++xyz) {
441 result[a][xyz] = Eigen::MatrixXd::Zero(nbf, nbf);
442 }
443 }
444
445 std::vector<libint2::Engine> engines(nthreads);
446 engines[0] =
447 libint2::Engine(libint2::Operator::coulomb, aobasis.getMaxNprim(),
448 static_cast<int>(aobasis.getMaxL()), 1);
449 engines[0].set(libint2::BraKet::xs_xs);
450 for (Index i = 1; i < nthreads; ++i) {
451 engines[i] = engines[0];
452 }
453
454 std::exception_ptr eptr_coulmetric = nullptr;
455 std::atomic<bool> any_nonnull_buffer_coulmetric{false};
456#pragma omp parallel for schedule(dynamic)
457 for (Index s1 = 0; s1 < aobasis.getNumofShells(); ++s1) {
458 try {
459 libint2::Engine& engine = engines[OPENMP::getThreadId()];
460 const libint2::Engine::target_ptr_vec& buf = engine.results();
461
462 Index bf1 = shell2bf[s1];
463 Index n1 = shells[s1].size();
464 Index atom1 = shell2atom[s1];
465
466 // Same note as AOCoulomb::computeCoulombIntegrals: cannot use
467 // shellpairs here, this is a two-center integral and overlap
468 // screening would give the wrong result.
469 for (Index s2 = 0; s2 <= s1; ++s2) {
470 engine.compute2<libint2::Operator::coulomb, libint2::BraKet::xs_xs, 1>(
471 shells[s1], libint2::Shell::unit(), shells[s2],
472 libint2::Shell::unit());
473
474 // see computeOneBodyIntegralDerivatives
475 if (buf[0] == nullptr || buf[3] == nullptr) {
476 continue;
477 }
478 any_nonnull_buffer_coulmetric.store(true, std::memory_order_relaxed);
479
480 Index bf2 = shell2bf[s2];
481 Index n2 = shells[s2].size();
482 Index atom2 = shell2atom[s2];
483
484 for (Index xyz = 0; xyz < 3; ++xyz) {
485 Eigen::Map<const MatrixLibInt> buf_mat1(buf[xyz], n1, n2);
486 result[atom1][xyz].block(bf1, bf2, n1, n2) += buf_mat1;
487 if (s1 != s2) {
488 result[atom1][xyz].block(bf2, bf1, n2, n1) += buf_mat1.transpose();
489 }
490
491 Eigen::Map<const MatrixLibInt> buf_mat2(buf[3 + xyz], n1, n2);
492 result[atom2][xyz].block(bf1, bf2, n1, n2) += buf_mat2;
493 if (s1 != s2) {
494 result[atom2][xyz].block(bf2, bf1, n2, n1) += buf_mat2.transpose();
495 }
496 }
497 }
498 } catch (...) {
499#pragma omp critical
500 {
501 if (!eptr_coulmetric) {
502 eptr_coulmetric = std::current_exception();
503 }
504 }
505 }
506 }
507 if (eptr_coulmetric) {
508 std::rethrow_exception(eptr_coulmetric);
509 }
510 if (!any_nonnull_buffer_coulmetric.load() && aobasis.getNumofShells() > 0) {
511 throw std::runtime_error(
512 "ComputeCoulombMetricDerivatives: engine.results() returned a "
513 "null buffer for every shell pair; this libint2 build does not "
514 "support this operator's derivative integrals at runtime, even "
515 "though it may report LIBINT2_MAX_DERIV_ORDER >= 1 for other "
516 "operators. Rebuild libint2 with --enable-eri2=1 to use this "
517 "feature.");
518 }
519 return result;
520}
521#else // !(LIBINT_INCLUDE_ERI2)
522std::vector<AOMatrixDerivative> ComputeCoulombMetricDerivatives(
523 const AOBasis&) {
524 ThrowNoDerivativeSupport("ComputeCoulombMetricDerivatives",
525 "--enable-eri2=1");
526}
527#endif // LIBINT_INCLUDE_ERI2
528
529// sum_PQ G_PQ d(P|Q)/dR for symmetric G, see riderivatives.h. Shell pairs
530// s2 <= s1 as in ComputeCoulombMetricDerivatives, off-diagonal pairs
531// doubled; each pair is contracted as soon as it is computed, so no
532// natoms * 3 * Naux^2 derivative matrices are stored.
533#if (LIBINT_INCLUDE_ERI2 >= 1)
534Eigen::MatrixXd ContractCoulombMetricDerivatives(const AOBasis& auxbasis,
535 const Eigen::MatrixXd& G) {
536 CheckDerivativeTable(
537 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_2eri1),
538 auxbasis.getMaxL(), auxbasis.getMaxL()),
539 "ContractCoulombMetricDerivatives", auxbasis.getMaxL());
540 Index natoms = static_cast<Index>(auxbasis.getFuncPerAtom().size());
541 Index nthreads = OPENMP::getMaxThreads();
542 std::vector<libint2::Shell> shells = auxbasis.GenerateLibintBasis();
543 std::vector<Index> shell2bf = auxbasis.getMapToBasisFunctions();
544
545 std::vector<Index> shell2atom;
546 shell2atom.reserve(auxbasis.getNumofShells());
547 for (Index s = 0; s < auxbasis.getNumofShells(); ++s) {
548 shell2atom.push_back(auxbasis.getShell(s).getAtomIndex());
549 }
550
551 std::vector<Eigen::MatrixXd> partial(nthreads,
552 Eigen::MatrixXd::Zero(natoms, 3));
553
554 std::vector<libint2::Engine> engines(nthreads);
555 engines[0] =
556 libint2::Engine(libint2::Operator::coulomb, auxbasis.getMaxNprim(),
557 static_cast<int>(auxbasis.getMaxL()), 1);
558 engines[0].set(libint2::BraKet::xs_xs);
559 for (Index i = 1; i < nthreads; ++i) {
560 engines[i] = engines[0];
561 }
562
563 std::exception_ptr eptr_coulmetric = nullptr;
564 std::atomic<bool> any_nonnull_buffer_coulmetric{false};
565#pragma omp parallel for schedule(dynamic)
566 for (Index s1 = 0; s1 < auxbasis.getNumofShells(); ++s1) {
567 try {
568 Index thread = OPENMP::getThreadId();
569 libint2::Engine& engine = engines[thread];
570 Eigen::MatrixXd& acc = partial[thread];
571 const libint2::Engine::target_ptr_vec& buf = engine.results();
572
573 Index bf1 = shell2bf[s1];
574 Index n1 = shells[s1].size();
575 Index atom1 = shell2atom[s1];
576
577 for (Index s2 = 0; s2 <= s1; ++s2) {
578 engine.compute2<libint2::Operator::coulomb, libint2::BraKet::xs_xs, 1>(
579 shells[s1], libint2::Shell::unit(), shells[s2],
580 libint2::Shell::unit());
581
582 if (buf[0] == nullptr || buf[3] == nullptr) {
583 continue;
584 }
585 any_nonnull_buffer_coulmetric.store(true, std::memory_order_relaxed);
586
587 Index bf2 = shell2bf[s2];
588 Index n2 = shells[s2].size();
589 Index atom2 = shell2atom[s2];
590 const double factor = (s1 == s2) ? 1.0 : 2.0;
591 const auto Gblock = G.block(bf1, bf2, n1, n2);
592
593 for (Index xyz = 0; xyz < 3; ++xyz) {
594 Eigen::Map<const MatrixLibInt> buf_mat1(buf[xyz], n1, n2);
595 Eigen::Map<const MatrixLibInt> buf_mat2(buf[3 + xyz], n1, n2);
596 acc(atom1, xyz) += factor * (Gblock.array() * buf_mat1.array()).sum();
597 acc(atom2, xyz) += factor * (Gblock.array() * buf_mat2.array()).sum();
598 }
599 }
600 } catch (...) {
601#pragma omp critical
602 {
603 if (!eptr_coulmetric) {
604 eptr_coulmetric = std::current_exception();
605 }
606 }
607 }
608 }
609 if (eptr_coulmetric) {
610 std::rethrow_exception(eptr_coulmetric);
611 }
612 if (!any_nonnull_buffer_coulmetric.load() && auxbasis.getNumofShells() > 0) {
613 throw std::runtime_error(
614 "ContractCoulombMetricDerivatives: engine.results() returned a "
615 "null buffer for every shell pair; this libint2 build does not "
616 "support this operator's derivative integrals at runtime. Rebuild "
617 "libint2 with --enable-eri2=1 to use this feature.");
618 }
619 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
620 for (const Eigen::MatrixXd& p : partial) {
621 grad += p;
622 }
623 return grad;
624}
625#else // !(LIBINT_INCLUDE_ERI2)
627 const Eigen::MatrixXd&) {
628 ThrowNoDerivativeSupport("ContractCoulombMetricDerivatives",
629 "--enable-eri2=1");
630}
631#endif // LIBINT_INCLUDE_ERI2
632
633// ===========================================================================
634// Three-centre RI integral derivatives d(mu,nu|P)/dR. Same shell order as
635// ComputeAO3cBlock (auxshell, unit, shell_col, shell_row, BraKet::xs_xx);
636// libint2 returns 9 buffers, the derivatives w.r.t. the centres of the aux,
637// col and row shells, each x, y, z.
638//
639// ComputeThreeCenterDerivatives stores the full tensor,
640// O(natoms * 3 * Naux * Nao^2) memory, and is only meant for tests; the
641// gradients use the contracted variants below.
642//
643// Requires LIBINT_INCLUDE_ERI3 >= 1 (libint2 --enable-eri3), independent of
644// ONEBODY and ERI2.
645// ===========================================================================
646
647// One entry per Cartesian direction (x,y,z); each holds one matrix per
648// aux basis function (indexed by absolute aux AO index), each matrix
649// being (dftbasis size x dftbasis size).
650using ThreeCenterDerivative = std::array<std::vector<Eigen::MatrixXd>, 3>;
651
652#if (LIBINT_INCLUDE_ERI3 >= 1) && !VOTCA_LIBINT_ERI3_DERIV_BROKEN
653std::vector<ThreeCenterDerivative> ComputeThreeCenterDerivatives(
654 const AOBasis& auxbasis, const AOBasis& dftbasis) {
655 CheckDerivativeTable(
656 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_3eri1),
657 auxbasis.getMaxL(), dftbasis.getMaxL()),
658 "ComputeThreeCenterDerivatives",
659 std::max(auxbasis.getMaxL(), dftbasis.getMaxL()));
660 Index natoms = static_cast<Index>(dftbasis.getFuncPerAtom().size());
661 // assumes auxbasis and dftbasis are defined on the same molecule
662
663 Index nthreads = OPENMP::getMaxThreads();
664 std::vector<libint2::Shell> dftshells = dftbasis.GenerateLibintBasis();
665 std::vector<libint2::Shell> auxshells = auxbasis.GenerateLibintBasis();
666 std::vector<Index> shell2bf = dftbasis.getMapToBasisFunctions();
667 std::vector<Index> auxshell2bf = auxbasis.getMapToBasisFunctions();
668
669 std::vector<Index> dftshell2atom;
670 dftshell2atom.reserve(dftbasis.getNumofShells());
671 for (Index s = 0; s < dftbasis.getNumofShells(); ++s) {
672 dftshell2atom.push_back(dftbasis.getShell(s).getAtomIndex());
673 }
674 std::vector<Index> auxshell2atom;
675 auxshell2atom.reserve(auxbasis.getNumofShells());
676 for (Index s = 0; s < auxbasis.getNumofShells(); ++s) {
677 auxshell2atom.push_back(auxbasis.getShell(s).getAtomIndex());
678 }
679
680 Index n_dft_bf = dftbasis.AOBasisSize();
681 Index n_aux_bf = auxbasis.AOBasisSize();
682
683 std::vector<ThreeCenterDerivative> result(natoms);
684 for (Index a = 0; a < natoms; ++a) {
685 for (Index xyz = 0; xyz < 3; ++xyz) {
686 result[a][xyz] = std::vector<Eigen::MatrixXd>(
687 n_aux_bf, Eigen::MatrixXd::Zero(n_dft_bf, n_dft_bf));
688 }
689 }
690
691 std::vector<libint2::Engine> engines(nthreads);
692 engines[0] = libint2::Engine(
693 libint2::Operator::coulomb,
694 std::max(dftbasis.getMaxNprim(), auxbasis.getMaxNprim()),
695 static_cast<int>(std::max(dftbasis.getMaxL(), auxbasis.getMaxL())), 1);
696 engines[0].set(libint2::BraKet::xs_xx);
697 for (Index i = 1; i < nthreads; ++i) {
698 engines[i] = engines[0];
699 }
700
701 std::exception_ptr eptr_3c = nullptr;
702 std::atomic<bool> any_nonnull_buffer_3c{false};
703#pragma omp parallel for schedule(dynamic)
704 for (Index aux = 0; aux < auxbasis.getNumofShells(); ++aux) {
705 try {
706 libint2::Engine& engine = engines[OPENMP::getThreadId()];
707 const libint2::Engine::target_ptr_vec& buf = engine.results();
708
709 const libint2::Shell& auxshell = auxshells[aux];
710 Index aux_start = auxshell2bf[aux];
711 Index atom_aux = auxshell2atom[aux];
712
713 for (Index row = 0; row < dftbasis.getNumofShells(); ++row) {
714 const libint2::Shell& shell_row = dftshells[row];
715 Index row_start = shell2bf[row];
716 Index atom_row = dftshell2atom[row];
717
718 // Full col loop: the mu,nu symmetry of (mu,nu|P) is not exploited
719 // here, unlike in ComputeAO3cBlock.
720 for (Index col = 0; col < dftbasis.getNumofShells(); ++col) {
721 const libint2::Shell& shell_col = dftshells[col];
722 Index col_start = shell2bf[col];
723 Index atom_col = dftshell2atom[col];
724
725 engine
726 .compute2<libint2::Operator::coulomb, libint2::BraKet::xs_xx, 1>(
727 auxshell, libint2::Shell::unit(), shell_col, shell_row);
728
729 // see computeOneBodyIntegralDerivatives; three centres here
730 if (buf[0] == nullptr || buf[3] == nullptr || buf[6] == nullptr) {
731 continue;
732 }
733 any_nonnull_buffer_3c.store(true, std::memory_order_relaxed);
734
735 // buffers: [aux centre xyz][col centre xyz][row centre xyz], in
736 // the shell argument order of compute2
737 for (Index xyz = 0; xyz < 3; ++xyz) {
738 Eigen::TensorMap<
739 Eigen::Tensor<const double, 3, Eigen::RowMajor> const>
740 result_aux(buf[xyz], auxshell.size(), shell_col.size(),
741 shell_row.size());
742 Eigen::TensorMap<
743 Eigen::Tensor<const double, 3, Eigen::RowMajor> const>
744 result_col(buf[3 + xyz], auxshell.size(), shell_col.size(),
745 shell_row.size());
746 Eigen::TensorMap<
747 Eigen::Tensor<const double, 3, Eigen::RowMajor> const>
748 result_row(buf[6 + xyz], auxshell.size(), shell_col.size(),
749 shell_row.size());
750
751 for (size_t aux_c = 0; aux_c < auxshell.size(); ++aux_c) {
752 Index global_aux = aux_start + static_cast<Index>(aux_c);
753 for (size_t col_c = 0; col_c < shell_col.size(); ++col_c) {
754 for (size_t row_c = 0; row_c < shell_row.size(); ++row_c) {
755 double val_aux = result_aux(aux_c, col_c, row_c);
756 double val_col = result_col(aux_c, col_c, row_c);
757 double val_row = result_row(aux_c, col_c, row_c);
758 Index r = row_start + static_cast<Index>(row_c);
759 Index c = col_start + static_cast<Index>(col_c);
760 result[atom_aux][xyz][global_aux](r, c) += val_aux;
761 result[atom_col][xyz][global_aux](r, c) += val_col;
762 result[atom_row][xyz][global_aux](r, c) += val_row;
763 }
764 }
765 }
766 }
767 }
768 }
769 } catch (...) {
770#pragma omp critical
771 {
772 if (!eptr_3c) {
773 eptr_3c = std::current_exception();
774 }
775 }
776 }
777 }
778 if (eptr_3c) {
779 std::rethrow_exception(eptr_3c);
780 }
781 if (!any_nonnull_buffer_3c.load() && auxbasis.getNumofShells() > 0 &&
782 dftbasis.getNumofShells() > 0) {
783 throw std::runtime_error(
784 "ComputeThreeCenterDerivatives: engine.results() returned a null "
785 "buffer for every shell triple; this libint2 build does not "
786 "support this operator's derivative integrals at runtime, even "
787 "though it may report LIBINT2_MAX_DERIV_ORDER >= 1 for other "
788 "operators. Rebuild libint2 with --enable-eri3=1 to use this "
789 "feature.");
790 }
791 return result;
792}
793#else // !(LIBINT_INCLUDE_ERI3)
794std::vector<ThreeCenterDerivative> ComputeThreeCenterDerivatives(
795 const AOBasis&, const AOBasis&) {
796 ThrowNoDerivativeSupport(
797 "ComputeThreeCenterDerivatives",
799 ? "--enable-eri3=1 (libint2 >= 2.9.0: older releases index "
800 "centre-dependent 3-centre derivative code incorrectly)"
801 : "--enable-eri3=1");
802}
803#endif // LIBINT_INCLUDE_ERI3
804
805#if (LIBINT_INCLUDE_ERI3 >= 1) && !VOTCA_LIBINT_ERI3_DERIV_BROKEN
806// sum_P sum_{mu nu} Gamma^P_{mu nu} d(mu nu|P)/dR, see riderivatives.h.
807// Parallel over aux shells; each thread builds the Gamma^P of its aux shell
808// (symmetrized), computes the derivative integrals of the shell pairs
809// col <= row (doubling off-diagonal pairs, as Gamma^P and (mu nu|P) are
810// symmetric) and contracts them immediately. Memory: one aux shell of
811// Nao x Nao matrices and a (natoms x 3) accumulator per thread. Shell order
812// and buffer layout as in ComputeThreeCenterDerivatives.
813Eigen::MatrixXd ContractThreeCenterDerivatives(const AOBasis& auxbasis,
814 const AOBasis& dftbasis,
815 const AuxDensityFn& gamma) {
816 CheckDerivativeTable(
817 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_3eri1),
818 auxbasis.getMaxL(), dftbasis.getMaxL()),
819 "ContractThreeCenterDerivatives",
820 std::max(auxbasis.getMaxL(), dftbasis.getMaxL()));
821 Index natoms = static_cast<Index>(dftbasis.getFuncPerAtom().size());
822 Index nthreads = OPENMP::getMaxThreads();
823 std::vector<libint2::Shell> dftshells = dftbasis.GenerateLibintBasis();
824 std::vector<libint2::Shell> auxshells = auxbasis.GenerateLibintBasis();
825 std::vector<Index> shell2bf = dftbasis.getMapToBasisFunctions();
826 std::vector<Index> auxshell2bf = auxbasis.getMapToBasisFunctions();
827
828 std::vector<Index> dftshell2atom;
829 dftshell2atom.reserve(dftbasis.getNumofShells());
830 for (Index s = 0; s < dftbasis.getNumofShells(); ++s) {
831 dftshell2atom.push_back(dftbasis.getShell(s).getAtomIndex());
832 }
833 std::vector<Index> auxshell2atom;
834 auxshell2atom.reserve(auxbasis.getNumofShells());
835 for (Index s = 0; s < auxbasis.getNumofShells(); ++s) {
836 auxshell2atom.push_back(auxbasis.getShell(s).getAtomIndex());
837 }
838
839 std::vector<Eigen::MatrixXd> partial(nthreads,
840 Eigen::MatrixXd::Zero(natoms, 3));
841
842 std::vector<libint2::Engine> engines(nthreads);
843 engines[0] = libint2::Engine(
844 libint2::Operator::coulomb,
845 std::max(dftbasis.getMaxNprim(), auxbasis.getMaxNprim()),
846 static_cast<int>(std::max(dftbasis.getMaxL(), auxbasis.getMaxL())), 1);
847 engines[0].set(libint2::BraKet::xs_xx);
848 for (Index i = 1; i < nthreads; ++i) {
849 engines[i] = engines[0];
850 }
851
852 std::exception_ptr eptr_3c = nullptr;
853 std::atomic<bool> any_nonnull_buffer_3c{false};
854#pragma omp parallel for schedule(dynamic)
855 for (Index aux = 0; aux < auxbasis.getNumofShells(); ++aux) {
856 try {
857 Index thread = OPENMP::getThreadId();
858 libint2::Engine& engine = engines[thread];
859 Eigen::MatrixXd& acc = partial[thread];
860 const libint2::Engine::target_ptr_vec& buf = engine.results();
861
862 const libint2::Shell& auxshell = auxshells[aux];
863 Index aux_start = auxshell2bf[aux];
864 Index atom_aux = auxshell2atom[aux];
865 Index naux_c = static_cast<Index>(auxshell.size());
866
867 std::vector<Eigen::MatrixXd> gam(naux_c);
868 for (Index f = 0; f < naux_c; ++f) {
869 gamma(aux_start + f, gam[f]);
870 gam[f] = 0.5 * (gam[f] + gam[f].transpose()).eval();
871 }
872
873 for (Index row = 0; row < dftbasis.getNumofShells(); ++row) {
874 const libint2::Shell& shell_row = dftshells[row];
875 Index row_start = shell2bf[row];
876 Index atom_row = dftshell2atom[row];
877
878 for (Index col = 0; col <= row; ++col) {
879 const libint2::Shell& shell_col = dftshells[col];
880 Index col_start = shell2bf[col];
881 Index atom_col = dftshell2atom[col];
882
883 engine
884 .compute2<libint2::Operator::coulomb, libint2::BraKet::xs_xx, 1>(
885 auxshell, libint2::Shell::unit(), shell_col, shell_row);
886
887 if (buf[0] == nullptr || buf[3] == nullptr || buf[6] == nullptr) {
888 continue;
889 }
890 any_nonnull_buffer_3c.store(true, std::memory_order_relaxed);
891
892 const double factor = (row == col) ? 1.0 : 2.0;
893 for (Index xyz = 0; xyz < 3; ++xyz) {
894 Eigen::TensorMap<
895 Eigen::Tensor<const double, 3, Eigen::RowMajor> const>
896 result_aux(buf[xyz], auxshell.size(), shell_col.size(),
897 shell_row.size());
898 Eigen::TensorMap<
899 Eigen::Tensor<const double, 3, Eigen::RowMajor> const>
900 result_col(buf[3 + xyz], auxshell.size(), shell_col.size(),
901 shell_row.size());
902 Eigen::TensorMap<
903 Eigen::Tensor<const double, 3, Eigen::RowMajor> const>
904 result_row(buf[6 + xyz], auxshell.size(), shell_col.size(),
905 shell_row.size());
906
907 double s_aux = 0.0;
908 double s_col = 0.0;
909 double s_row = 0.0;
910 for (size_t aux_c = 0; aux_c < auxshell.size(); ++aux_c) {
911 const Eigen::MatrixXd& g = gam[aux_c];
912 for (size_t col_c = 0; col_c < shell_col.size(); ++col_c) {
913 Index c = col_start + static_cast<Index>(col_c);
914 for (size_t row_c = 0; row_c < shell_row.size(); ++row_c) {
915 Index r = row_start + static_cast<Index>(row_c);
916 double g_rc = g(r, c);
917 s_aux += g_rc * result_aux(aux_c, col_c, row_c);
918 s_col += g_rc * result_col(aux_c, col_c, row_c);
919 s_row += g_rc * result_row(aux_c, col_c, row_c);
920 }
921 }
922 }
923 acc(atom_aux, xyz) += factor * s_aux;
924 acc(atom_col, xyz) += factor * s_col;
925 acc(atom_row, xyz) += factor * s_row;
926 }
927 }
928 }
929 } catch (...) {
930#pragma omp critical
931 {
932 if (!eptr_3c) {
933 eptr_3c = std::current_exception();
934 }
935 }
936 }
937 }
938 if (eptr_3c) {
939 std::rethrow_exception(eptr_3c);
940 }
941 if (!any_nonnull_buffer_3c.load() && auxbasis.getNumofShells() > 0 &&
942 dftbasis.getNumofShells() > 0) {
943 throw std::runtime_error(
944 "ContractThreeCenterDerivatives: engine.results() returned a null "
945 "buffer for every shell triple; this libint2 build does not "
946 "support this operator's derivative integrals at runtime, even "
947 "though it may report LIBINT2_MAX_DERIV_ORDER >= 1 for other "
948 "operators. Rebuild libint2 with --enable-eri3=1 to use this "
949 "feature.");
950 }
951 Eigen::MatrixXd grad = Eigen::MatrixXd::Zero(natoms, 3);
952 for (const Eigen::MatrixXd& p : partial) {
953 grad += p;
954 }
955 return grad;
956}
957#else // !(LIBINT_INCLUDE_ERI3)
958Eigen::MatrixXd ContractThreeCenterDerivatives(const AOBasis&, const AOBasis&,
959 const AuxDensityFn&) {
960 ThrowNoDerivativeSupport(
961 "ContractThreeCenterDerivatives",
963 ? "--enable-eri3=1 (libint2 >= 2.9.0: older releases index "
964 "centre-dependent 3-centre derivative code incorrectly)"
965 : "--enable-eri3=1");
966}
967#endif // LIBINT_INCLUDE_ERI3
968
969// Three-centre integrals (mu,nu|P) (deriv_order = 0) for the RI gradients,
970// one Nao x Nao matrix per aux function, built with ComputeAO3cBlock. Kept
971// here so that libint2 is only used in this file and libint2_calls.cc. No
972// compile guard needed.
973std::vector<Eigen::MatrixXd> ComputeThreeCenterIntegrals(
974 const AOBasis& auxbasis, const AOBasis& dftbasis) {
975 std::vector<libint2::Shell> auxshells = auxbasis.GenerateLibintBasis();
976 std::vector<Index> auxshell2bf = auxbasis.getMapToBasisFunctions();
977
978 std::vector<Eigen::MatrixXd> tensor(
979 auxbasis.AOBasisSize(),
980 Eigen::MatrixXd::Zero(dftbasis.AOBasisSize(), dftbasis.AOBasisSize()));
981
982 libint2::Engine engine(
983 libint2::Operator::coulomb,
984 std::max(dftbasis.getMaxNprim(), auxbasis.getMaxNprim()),
985 static_cast<int>(std::max(dftbasis.getMaxL(), auxbasis.getMaxL())), 0);
986 engine.set(libint2::BraKet::xs_xx);
987
988 for (Index aux = 0; aux < auxbasis.getNumofShells(); ++aux) {
989 std::vector<Eigen::MatrixXd> block =
990 ComputeAO3cBlock(auxshells[aux], dftbasis, engine);
991 Index aux_start = auxshell2bf[aux];
992 for (size_t i = 0; i < block.size(); ++i) {
993 tensor[aux_start + static_cast<Index>(i)] = block[i];
994 }
995 }
996 return tensor;
997}
998
999// Visits (mu nu|P) for every aux function, see riderivatives.h. Parallel
1000// over aux shells with one engine per thread; memory one aux shell of
1001// Nao x Nao matrices per thread instead of the full Naux * Nao^2 tensor of
1002// ComputeThreeCenterIntegrals.
1004 const AOBasis& dftbasis,
1005 const ThreeCenterVisitor& use) {
1006 std::vector<libint2::Shell> auxshells = auxbasis.GenerateLibintBasis();
1007 std::vector<Index> auxshell2bf = auxbasis.getMapToBasisFunctions();
1008 Index nthreads = OPENMP::getMaxThreads();
1009
1010 std::vector<libint2::Engine> engines(nthreads);
1011 engines[0] = libint2::Engine(
1012 libint2::Operator::coulomb,
1013 std::max(dftbasis.getMaxNprim(), auxbasis.getMaxNprim()),
1014 static_cast<int>(std::max(dftbasis.getMaxL(), auxbasis.getMaxL())), 0);
1015 engines[0].set(libint2::BraKet::xs_xx);
1016 for (Index i = 1; i < nthreads; ++i) {
1017 engines[i] = engines[0];
1018 }
1019
1020 std::exception_ptr eptr = nullptr;
1021#pragma omp parallel for schedule(dynamic)
1022 for (Index aux = 0; aux < auxbasis.getNumofShells(); ++aux) {
1023 try {
1024 libint2::Engine& engine = engines[OPENMP::getThreadId()];
1025 std::vector<Eigen::MatrixXd> block =
1026 ComputeAO3cBlock(auxshells[aux], dftbasis, engine);
1027 Index aux_start = auxshell2bf[aux];
1028 for (size_t i = 0; i < block.size(); ++i) {
1029 use(aux_start + static_cast<Index>(i), block[i]);
1030 }
1031 } catch (...) {
1032#pragma omp critical
1033 {
1034 if (!eptr) {
1035 eptr = std::current_exception();
1036 }
1037 }
1038 }
1039 }
1040 if (eptr) {
1041 std::rethrow_exception(eptr);
1042 }
1043}
1044
1045// ===========================================================================
1046// Nuclear attraction integral derivatives d(V_ne)/dR,
1047// V_ne,munu = -sum_A Z_A int chi_mu(r) 1/|r - R_A| chi_nu(r) dr.
1048// For each point charge A this is a three-centre derivative (both basis
1049// function centres and R_A); as in libint2's
1050// compute_1body_ints_deriv<Operator::nuclear> (lcao/1body.h), each atom is
1051// set as a single point charge, giving 9 buffers ordered
1052// [shell1 centre][shell2 centre][R_A], each x, y, z.
1053//
1054// libint2::Operator::nuclear already includes the minus sign (attractive),
1055// consistent with AOMultipole::FillPotential/SetupH0, so the buffers are
1056// added without negation.
1057// ===========================================================================
1058#if defined(LIBINT2_MAX_DERIV_ORDER) && LIBINT2_MAX_DERIV_ORDER >= 1 && \
1059 (LIBINT_INCLUDE_ONEBODY >= 1)
1060std::vector<AOMatrixDerivative> ComputeNuclearAttractionDerivatives(
1061 const AOBasis& aobasis, const QMMolecule& mol) {
1062 CheckDerivativeTable(
1063 BuildTableCovers(LIBINT2_PREFIXED_NAME(libint2_build_elecpot1),
1064 aobasis.getMaxL(), aobasis.getMaxL()),
1065 "ComputeNuclearAttractionDerivatives", aobasis.getMaxL());
1066 Index natoms = mol.size();
1067 Index nthreads = OPENMP::getMaxThreads();
1068 std::vector<libint2::Shell> shells = aobasis.GenerateLibintBasis();
1069 std::vector<Index> shell2bf = aobasis.getMapToBasisFunctions();
1070
1071 std::vector<Index> shell2atom;
1072 shell2atom.reserve(aobasis.getNumofShells());
1073 for (Index s = 0; s < aobasis.getNumofShells(); ++s) {
1074 shell2atom.push_back(aobasis.getShell(s).getAtomIndex());
1075 }
1076
1077 Index nbf = aobasis.AOBasisSize();
1078 std::vector<std::vector<AOMatrixDerivative>> result_thread(nthreads);
1079 for (Index t = 0; t < nthreads; ++t) {
1080 result_thread[t].resize(natoms);
1081 for (Index a = 0; a < natoms; ++a) {
1082 for (Index xyz = 0; xyz < 3; ++xyz) {
1083 result_thread[t][a][xyz] = Eigen::MatrixXd::Zero(nbf, nbf);
1084 }
1085 }
1086 }
1087
1088 std::vector<libint2::Engine> engines(nthreads);
1089 for (Index i = 0; i < nthreads; ++i) {
1090 engines[i] =
1091 libint2::Engine(libint2::Operator::nuclear, aobasis.getMaxNprim(),
1092 static_cast<int>(aobasis.getMaxL()), 1);
1093 }
1094
1095 // Parallel over point charges (each needs engine.set_params()), with
1096 // per-thread result matrices summed afterwards.
1097 std::exception_ptr eptr_nucattr = nullptr;
1098 std::atomic<bool> any_nonnull_buffer_nucattr{false};
1099#pragma omp parallel for schedule(dynamic)
1100 for (Index A = 0; A < natoms; ++A) {
1101 try {
1102 Index thread_id = OPENMP::getThreadId();
1103 libint2::Engine& engine = engines[thread_id];
1104
1105 std::vector<libint2::Atom> single_atom(1);
1106 single_atom[0].atomic_number = static_cast<int>(mol[A].getNuccharge());
1107 single_atom[0].x = mol[A].getPos().x();
1108 single_atom[0].y = mol[A].getPos().y();
1109 single_atom[0].z = mol[A].getPos().z();
1110 engine.set_params(libint2::make_point_charges(single_atom));
1111
1112 const libint2::Engine::target_ptr_vec& buf = engine.results();
1113
1114 for (Index s1 = 0; s1 < aobasis.getNumofShells(); ++s1) {
1115 Index bf1 = shell2bf[s1];
1116 Index n1 = shells[s1].size();
1117 Index atom1 = shell2atom[s1];
1118
1119 for (Index s2 = 0; s2 <= s1; ++s2) {
1120 engine.compute(shells[s1], shells[s2]);
1121
1122 // see computeOneBodyIntegralDerivatives; three centres here.
1123 // Zero-filled (non-null) buffers are caught by the norm check
1124 // after the loop.
1125 if (buf[0] == nullptr || buf[3] == nullptr || buf[6] == nullptr) {
1126 continue;
1127 }
1128 any_nonnull_buffer_nucattr.store(true, std::memory_order_relaxed);
1129
1130 Index bf2 = shell2bf[s2];
1131 Index n2 = shells[s2].size();
1132 Index atom2 = shell2atom[s2];
1133
1134 for (Index xyz = 0; xyz < 3; ++xyz) {
1135 // no negation, see above
1136 Eigen::Map<const MatrixLibInt> buf_mat1(buf[xyz], n1, n2);
1137 result_thread[thread_id][atom1][xyz].block(bf1, bf2, n1, n2) +=
1138 buf_mat1;
1139 if (s1 != s2) {
1140 result_thread[thread_id][atom1][xyz].block(bf2, bf1, n2, n1) +=
1141 buf_mat1.transpose();
1142 }
1143
1144 Eigen::Map<const MatrixLibInt> buf_mat2(buf[3 + xyz], n1, n2);
1145 result_thread[thread_id][atom2][xyz].block(bf1, bf2, n1, n2) +=
1146 buf_mat2;
1147 if (s1 != s2) {
1148 result_thread[thread_id][atom2][xyz].block(bf2, bf1, n2, n1) +=
1149 buf_mat2.transpose();
1150 }
1151
1152 Eigen::Map<const MatrixLibInt> buf_mat3(buf[6 + xyz], n1, n2);
1153 result_thread[thread_id][A][xyz].block(bf1, bf2, n1, n2) +=
1154 buf_mat3;
1155 if (s1 != s2) {
1156 result_thread[thread_id][A][xyz].block(bf2, bf1, n2, n1) +=
1157 buf_mat3.transpose();
1158 }
1159 }
1160 }
1161 }
1162 } catch (...) {
1163#pragma omp critical
1164 {
1165 if (!eptr_nucattr) {
1166 eptr_nucattr = std::current_exception();
1167 }
1168 }
1169 }
1170 }
1171 if (eptr_nucattr) {
1172 std::rethrow_exception(eptr_nucattr);
1173 }
1174 if (!any_nonnull_buffer_nucattr.load() && natoms > 0 &&
1175 aobasis.getNumofShells() > 0) {
1176 // A build without derivative support for this operator can return
1177 // null buffers instead of throwing, which would silently give zero.
1178 throw std::runtime_error(
1179 "ComputeNuclearAttractionDerivatives: engine.results() returned "
1180 "a null buffer for every shell pair and point charge; this "
1181 "libint2 build does not support nuclear-attraction derivative "
1182 "integrals at runtime, even though it may report "
1183 "LIBINT2_MAX_DERIV_ORDER >= 1 for other operators. Rebuild "
1184 "libint2 with --enable-1body=1 to use this feature.");
1185 }
1186
1187 // Some builds instead return non-null but zero-filled buffers. The
1188 // derivative cannot vanish identically for a molecule with nonzero
1189 // nuclear charges.
1190 double total_norm_sq_nucattr = 0.0;
1191 for (Index a = 0; a < natoms; ++a) {
1192 for (Index xyz = 0; xyz < 3; ++xyz) {
1193 for (Index t = 0; t < nthreads; ++t) {
1194 total_norm_sq_nucattr += result_thread[t][a][xyz].squaredNorm();
1195 }
1196 }
1197 }
1198 if (total_norm_sq_nucattr < 1.e-20 && natoms > 0 &&
1199 aobasis.getNumofShells() > 0) {
1200 throw std::runtime_error(
1201 "ComputeNuclearAttractionDerivatives: the assembled result is "
1202 "exactly zero everywhere, which is impossible for a real "
1203 "molecule; this libint2 build likely returns zero-filled buffers "
1204 "for this operator. Rebuild libint2 with --enable-1body=1 to use "
1205 "this feature.");
1206 }
1207
1208 std::vector<AOMatrixDerivative> result(natoms);
1209 for (Index a = 0; a < natoms; ++a) {
1210 for (Index xyz = 0; xyz < 3; ++xyz) {
1211 result[a][xyz] = Eigen::MatrixXd::Zero(nbf, nbf);
1212 for (Index t = 0; t < nthreads; ++t) {
1213 result[a][xyz] += result_thread[t][a][xyz];
1214 }
1215 }
1216 }
1217 return result;
1218}
1219#else // !(LIBINT_INCLUDE_ONEBODY)
1220std::vector<AOMatrixDerivative> ComputeNuclearAttractionDerivatives(
1221 const AOBasis&, const QMMolecule&) {
1222 ThrowNoDerivativeSupport("ComputeNuclearAttractionDerivatives",
1223 "--enable-1body=1");
1224}
1225#endif // LIBINT_INCLUDE_ONEBODY
1226
1227// Lets code that does not include libint2 headers (e.g. dftengine.cc) check
1228// for derivative support. The forces need all three categories: ONEBODY
1229// (overlap, kinetic, nuclear attraction), ERI2 (Coulomb metric) and ERI3
1230// (three-centre RI).
1232#if defined(LIBINT2_MAX_DERIV_ORDER) && LIBINT2_MAX_DERIV_ORDER >= 1 && \
1233 (LIBINT_INCLUDE_ONEBODY >= 1) && (LIBINT_INCLUDE_ERI2 >= 1) && \
1234 (LIBINT_INCLUDE_ERI3 >= 1) && !VOTCA_LIBINT_ERI3_DERIV_BROKEN
1235 return true;
1236#else
1237 return false;
1238#endif
1239}
1240
1241} // namespace xtp
1242} // namespace votca
Container to hold Basisfunctions for all atoms.
Definition aobasis.h:42
Index getMaxL() const
Definition aobasis.cc:29
Index AOBasisSize() const
Definition aobasis.h:46
std::vector< Index > getMapToBasisFunctions() const
Definition aobasis.cc:45
const AOShell & getShell(Index idx) const
Definition aobasis.h:52
const std::vector< Index > & getFuncPerAtom() const
Definition aobasis.h:72
Index getNumofShells() const
Definition aobasis.h:56
Index getMaxNprim() const
Definition aobasis.cc:37
std::vector< libint2::Shell > GenerateLibintBasis() const
Definition aobasis.cc:119
Index getAtomIndex() const
Definition aoshell.h:108
#define VOTCA_LIBINT_ERI3_DERIV_BROKEN
Index getMaxThreads()
Definition eigen.h:145
Index getThreadId()
Definition eigen.h:160
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > MatrixLibInt
Definition aoecp.cc:56
void ForEachThreeCenterIntegral(const AOBasis &auxbasis, const AOBasis &dftbasis, const ThreeCenterVisitor &use)
Eigen::MatrixXd ContractCoulombMetricDerivatives(const AOBasis &auxbasis, const Eigen::MatrixXd &G)
std::vector< AOMatrixDerivative > ComputeNuclearAttractionDerivatives(const AOBasis &aobasis, const QMMolecule &mol)
std::array< std::vector< Eigen::MatrixXd >, 3 > ThreeCenterDerivative
std::vector< AOMatrixDerivative > ComputeKineticDerivatives(const AOBasis &aobasis)
std::vector< ThreeCenterDerivative > ComputeThreeCenterDerivatives(const AOBasis &, const AOBasis &)
std::vector< AOMatrixDerivative > ComputeOverlapDerivatives(const AOBasis &aobasis)
std::function< void(Index, const Eigen::MatrixXd &)> ThreeCenterVisitor
std::vector< Eigen::MatrixXd > ComputeThreeCenterIntegrals(const AOBasis &auxbasis, const AOBasis &dftbasis)
std::vector< Eigen::MatrixXd > ComputeAO3cBlock(const libint2::Shell &auxshell, const AOBasis &dftbasis, libint2::Engine &engine)
std::function< void(Index, Eigen::MatrixXd &)> AuxDensityFn
Eigen::MatrixXd ContractThreeCenterDerivatives(const AOBasis &auxbasis, const AOBasis &dftbasis, const AuxDensityFn &gamma)
std::vector< AOMatrixDerivative > ComputeCoulombMetricDerivatives(const AOBasis &)
std::array< Eigen::MatrixXd, 3 > AOMatrixDerivative
Provides a means for comparing floating point numbers.
Definition basebead.h:33
Eigen::Index Index
Definition types.h:26