MADNESS 0.10.1
operator.h
Go to the documentation of this file.
1/*
2 This file is part of MADNESS.
3
4 Copyright (C) 2007,2010 Oak Ridge National Laboratory
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 For more information please contact:
21
22 Robert J. Harrison
23 Oak Ridge National Laboratory
24 One Bethel Valley Road
25 P.O. Box 2008, MS-6367
26
27 email: harrisonrj@ornl.gov
28 tel: 865-241-3937
29 fax: 865-572-0680
30*/
31
32#ifndef MADNESS_MRA_OPERATOR_H__INCLUDED
33#define MADNESS_MRA_OPERATOR_H__INCLUDED
34
35/// \file mra/operator.h
36/// \brief Implements most functionality of separated operators
37
38/// \ingroup function
39
40#include <type_traits>
41#include <limits.h>
42#include <madness/mra/adquad.h>
45#include <madness/constants.h>
46
51#include <madness/mra/gfit.h>
53
54namespace madness {
55
56 template<typename T, std::size_t NDIM>
57 class Function;
58
59 template<typename T, std::size_t NDIM>
61
62 template<typename T, std::size_t NDIM>
63 class CCPairFunction;
64
65 template <typename T, typename R, std::size_t NDIM, std::size_t KDIM>
66 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
67 apply(const SeparatedConvolution<T,KDIM>& op, const std::vector< Function<R,NDIM> > f);
68
69 // NOTE the return type: applying the NDIM-dim operator collapses the vector
70 // to a single (pure) CCPairFunction; matches the definition in ccpairfunction.h.
71 template<typename T, std::size_t NDIM>
73
74 template<typename T, std::size_t NDIM>
75 std::vector<CCPairFunction<T,NDIM>> apply(const SeparatedConvolution<T,NDIM/2>& op, const std::vector<CCPairFunction<T,NDIM>>& argument);
76
77 template<typename T, std::size_t NDIM>
79
80 template<typename T, std::size_t NDIM>
82
83 /// SeparatedConvolutionInternal keeps data for 1 term and all dimensions and 1 displacement
84 /// Why is this here?? Why don't you just use ConvolutionND in SeparatedConvolutionData??
85 template <typename Q, std::size_t NDIM>
90
91 /// SeparatedConvolutionData keeps data for all terms, all dimensions
92
93 /// this struct is used to cache the data that are generated by
94 template <typename Q, std::size_t NDIM>
96 std::vector< SeparatedConvolutionInternal<Q,NDIM> > muops;
97 double norm;
98
99 SeparatedConvolutionData(int rank) : muops(rank), norm(0.0) {}
101 muops = q.muops;
102 norm = q.norm;
103 }
104 };
105
106
107 /// Convolutions in separated form (including Gaussian)
108
109 /* this stuff is very confusing, poorly commented, and extremely poorly named!
110
111 I think it works like this:
112 We try to apply transition matrices to the compressed form of function coefficients.
113 Most of the code is about caching these transition matrices. They are cached (key of the map is the displacement)
114 in the SimpleCache "data", which is of type SeparatedConvolutionData, which keeps the matrices
115 for all separated terms and dimensions. These SeparatedConvolutionData are constructed using
116 ConvolutionND "ops", which is constructed at the construction of the SeparatedConvolution.
117
118 SeparatedConvolution (all terms, all dim, all displacements)
119
120 construction storage
121
122 SimpleCache<SeparatedConvolutionData>
123 (all terms, all dim) / (all disp)
124 vector<ConvolutionND>
125 (1 term, all dim) / (all terms)
126 vector<SeparatedConvolutionInternal>
127 (1 term, all dim) / (all terms)
128
129
130 vector<ConvolutionData1D>
131 (1 term, 1 dim) / (all dim)
132
133 ConvolutionND and SeparatedConvolutionInternal both point to the same data in ConvolutionData1D.
134 Why we need SeparatedConvolutionInternal in the first place I have no idea. ConvolutionND has the global
135 factor, and SeparatedConvolutionInternal has a norm.
136
137
138 */
139
140 /// The largest distance a kernel must represent along the axes that are not summed over an
141 /// infinite lattice: within the cell, plus N cells along an axis summed over N images.
142 /// This is the accuracy range of the finite axes for GFit::truncate_mixed_expansion.
143 template <std::size_t NDIM>
144 inline double lattice_finite_reach(const std::array<LatticeRange, NDIM>& lattice_ranges,
145 const Tensor<double>& cell_width) {
146 double reach2 = 0.0, diag2 = 0.0;
147 for (std::size_t d = 0; d != NDIM; ++d) {
148 const double w = cell_width(long(d));
149 diag2 += w * w;
150 if (lattice_ranges[d].infinite()) continue;
151 const double r = (lattice_ranges[d].get_range() + 1) * w;
152 reach2 += r * r;
153 }
154 return reach2 > 0.0 ? std::sqrt(reach2) : std::sqrt(diag2);
155 }
156
157 template <typename Q, std::size_t NDIM>
158 class SeparatedConvolution : public WorldObject< SeparatedConvolution<Q,NDIM> > {
159 public:
160
161 typedef Q opT; ///< The apply function uses this to infer resultT=opT*inputT
162
164
165 /// cached Gaussian-expansion coefficients/exponents (for combine_generic
166 /// and introspection). Populated by the (coeff, expnt, ...) ctor and by
167 /// the OperatorInfo ctor. May be empty for ctors that do not have
168 /// access to the raw (c, α) data.
171
172 bool doleaves; ///< If should be applied to leaf coefficients ... false by default
173
174 private:
176 lattice_summed_; ///< If lattice_summed_[d] is true, sum over lattice translations along axis d
177 ///< N.B. the resulting kernel can be non-zero at both ends of the simulation cell along that axis
178 array_of_bools<NDIM> func_domain_is_periodic_{false}; ///< If domain_is_periodic_[d]==false and lattice_summed_[d]==false,
179 ///< ignore periodicity of BC when applying this to function
180 bool images_only_ = false; ///< OperatorInfo::images_only as consumed at construction; what the 1D factors were built with
181 std::array<KernelRange, NDIM> range; ///< kernel range is along axis d is limited by range[d] if it's nonnull
182
183 public:
184 bool modified_=false; ///< use modified NS form
185 int particle_=1; ///< must only be 1 or 2
186 bool destructive_=false; ///< destroy the argument or restore it (expensive for 6d functions)
187 bool print_timings=false;
188
190 const static size_t opdim=NDIM;
195
196 private:
197
198
199 mutable std::vector< ConvolutionND<Q,NDIM> > ops; ///< ConvolutionND keeps data for 1 term, all dimensions, 1 displacement
200 const int k;
202 int rank;
203 const std::vector<long> vk;
204 const std::vector<long> v2k;
205 const std::vector<Slice> s0;
206
207 // SeparatedConvolutionData keeps data for all terms and all dimensions and 1 displacement
208 mutable SimpleCache< SeparatedConvolutionData<Q,NDIM>, NDIM > data; ///< cache for all terms, dims and displacements
209 mutable SimpleCache< SeparatedConvolutionData<Q,NDIM>, 2*NDIM > mod_data; ///< cache for all terms, dims and displacements
210
211 public:
212
213 bool& modified() {return modified_;}
214 const bool& modified() const {return modified_;}
215
216 int& particle() {return particle_;}
217 const int& particle() const {return particle_;}
219 if (p!=1 and p!=2) throw std::runtime_error("particle must be 1 or 2");
220 particle_=p;
221 return *this;
222 }
223
224 bool& destructive() {return destructive_;}
225 const bool& destructive() const {return destructive_;}
226
227 const double& gamma() const {return info.mu;}
228 const double& mu() const {return info.mu;}
229 int get_rank() const { return rank; }
230 int get_k() const { return k; }
231 const std::vector<ConvolutionND<Q,NDIM>>& get_ops() const { return ops; }
232 const std::array<KernelRange, NDIM>& get_range() const { return range; }
233 bool range_restricted() const { return std::any_of(range.begin(), range.end(), [](const auto& v) { return v.finite(); }); }
234
235 private:
236
237 /// laziness for calling lists: which terms to apply
238 struct ApplyTerms {
239 ApplyTerms() : r_term(false), t_term(false) {}
240 bool r_term;
241 bool t_term;
242 bool any_terms() const {return r_term or t_term;}
243 };
244
245 /// too lazy for extended calling lists
247 long r; // Effective rank of transformation
248 const Q* U; // Ptr to matrix
249 const Q* VT;
250 };
251
252 /// the Gaussian fit of the kernel, and the low-exponent tail that a
253 /// lattice-summed operator drops from it (empty unless something was dropped)
258
259 static inline FitCoeffs
261 const std::array<LatticeRange, NDIM>& lattice_ranges) {
262
265 double hi = cell_width.normf(); // Diagonal width of cell
266 // Extend kernel range for lattice summation
267 // N.B. if have periodic boundaries, extend range just in case will be using periodic domain
268 bool lattice_summed_any = std::any_of(
269 lattice_ranges.begin(), lattice_ranges.end(), [](const LatticeRange& b){ return static_cast<bool>(b); });
270 bool infinite_summed_any = false;
271 for (size_t i = 0; i < NDIM; i++) {
272 if (lattice_ranges[i].infinite() && info.range[i].infinite()) {
273 infinite_summed_any = true;
274 break;
275 }
276 }
277 // A Gaussian's lattice sum is a gauge constant only if the kernel is summed over the
278 // whole lattice. An axis with an infinite lattice range but a finite kernel range is
279 // summed over the images the range reaches, so for the truncation it counts as a finite
280 // sum over that many images -- consistent with infinite_summed_any above.
281 std::array<LatticeRange, NDIM> summed_ranges = lattice_ranges;
282 for (size_t i = 0; i < NDIM; i++) {
283 if (lattice_ranges[i].infinite() && info.range[i].finite())
284 summed_ranges[i] = LatticeRange((info.range[i].iextent_x2() + 1) / 2);
285 }
286 const double hi_fin = lattice_finite_reach(summed_ranges, cell_width);
287 if (lattice_summed_any || FunctionDefaults<NDIM>::get_bc().is_periodic_any()) {
288 hi *= 100;
289 }
290
291 info.hi = hi;
293
294 FitCoeffs result;
295 Tensor<double> coeff = fit.coeffs();
296 Tensor<double> expnt = fit.exponents();
297
298 if (info.truncate_lowexp_gaussians.value_or(infinite_summed_any)) {
299 // deep copies: Tensor assignment shares the buffer, and the truncation edits
300 // coefficients in place (truncate_mixed_expansion folds the tail into its
301 // neighbours rather than dropping it)
302 const Tensor<double> full_coeff = copy(coeff), full_expnt = copy(expnt);
303 fit.truncate_mixed_expansion(coeff, expnt, summed_ranges, cell_width, info.lo, hi_fin, info.thresh);
304 info.truncate_lowexp_gaussians = true;
305 // what the truncation removed, as Gaussians: full fit minus truncated fit. The
306 // truncation only shortens the exponent list (and may rescale kept coefficients),
307 // so the difference lives on the full fit's exponents.
308 const long nkept = coeff.dim(0), nfull = full_coeff.dim(0);
309 MADNESS_CHECK(nkept <= nfull && (nkept == 0 || (expnt(nkept - 1) == full_expnt(nkept - 1))));
310 std::vector<double> dc, de;
311 for (long i = 0; i < nfull; ++i) {
312 const double diff = full_coeff(i) - (i < nkept ? coeff(i) : 0.0);
313 if (diff != 0.0) { dc.push_back(diff); de.push_back(full_expnt(i)); }
314 }
315 if (!dc.empty()) {
316 result.dropped_coeff = Tensor<double>(long(dc.size()));
317 result.dropped_expnt = Tensor<double>(long(de.size()));
318 for (std::size_t i = 0; i < dc.size(); ++i) { result.dropped_coeff(long(i)) = dc[i]; result.dropped_expnt(long(i)) = de[i]; }
319 }
320 }
321
322 result.coeff = coeff;
323 result.expnt = expnt;
324 return result;
325 }
326
327// /// return the right block of the upsampled operator (modified NS only)
328//
329// /// unlike the operator matrices on the natural level the upsampled operator
330// /// matrices are not Toeplitz, so we need more information than just the displacement
331// ///.@param[in] source the source key
332// /// @param[in] disp the displacement
333// /// @param[in] upop the unfiltered operator matrix from scale n-1
334// /// @return (k,k) patch of the upop(2k,2k) matrix
335// static Tensor<Q> operator_patch(const Translation& source, const Translation& disp, const Tensor<Q>& upop) {
336//
337// // which of the 4 upsampled matrices do we need?
338// Translation sx=source%2; // source offset
339// Translation tx=(source+disp)%2; // target offset
340//
341// Tensor<Q> rij(k,k);
342// // those two are equivalent:
343///*
344// if (sx==0 and tx==0) copy_2d_patch(rij.ptr(), k, upop.ptr(), 2*k, k, k);
345// if (sx==1 and tx==0) copy_2d_patch(rij.ptr() + k, k, upop.ptr(), 2*k, k, k);
346// if (sx==0 and tx==1) copy_2d_patch(rij.ptr() + 2*k*k, k, upop.ptr(), 2*k, k, k);
347// if (sx==1 and tx==1) copy_2d_patch(rij.ptr() + 2*k*k + k, k, upop.ptr(), 2*k, k, k);
348//*/
349// Slice s0(0,k-1), s1(k,2*k-1);
350// if (sx==0 and tx==0) rij=Rm(s0,s0);
351// if (sx==1 and tx==0) rij=Rm(s1,s0);
352// if (sx==0 and tx==1) rij=Rm(s0,s1);
353// if (sx==1 and tx==1) rij=Rm(s1,s1);
354//
355// return rij;
356// }
357
358
359
360 /// accumulate into result
361 template <typename T, typename R>
362 void apply_transformation(long dimk,
363 const Transformation trans[NDIM],
364 const Tensor<T>& f,
365 Tensor<R>& work1,
366 Tensor<R>& work2,
367 const Q mufac,
368 Tensor<R>& result) const {
369
370 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
371 long size = 1;
372 for (std::size_t i=0; i<NDIM; ++i) size *= dimk;
373 long dimi = size/dimk;
374
375 R* MADNESS_RESTRICT w1=work1.ptr();
376 R* MADNESS_RESTRICT w2=work2.ptr();
377
378 mTxmq(dimi, trans[0].r, dimk, w1, f.ptr(), trans[0].U, dimk);
379
380 size = trans[0].r * size / dimk;
381 dimi = size/dimk;
382 for (std::size_t d=1; d<NDIM; ++d) {
383 mTxmq(dimi, trans[d].r, dimk, w2, w1, trans[d].U, dimk);
384 size = trans[d].r * size / dimk;
385 dimi = size/dimk;
386 std::swap(w1,w2);
387 }
388
389 // If all blocks are full rank we can skip the transposes
390 bool doit = false;
391 for (std::size_t d=0; d<NDIM; ++d) doit = doit || trans[d].VT;
392
393 if (doit) {
394 for (std::size_t d=0; d<NDIM; ++d) {
395 if (trans[d].VT) {
396 dimi = size/trans[d].r;
397 mTxmq(dimi, dimk, trans[d].r, w2, w1, trans[d].VT);
398 size = dimk*size/trans[d].r;
399 }
400 else {
401 fast_transpose(dimk, dimi, w1, w2);
402 }
403 std::swap(w1,w2);
404 }
405 }
406 // Assuming here that result is contiguous and aligned
407 aligned_axpy(size, result.ptr(), w1, mufac);
408 }
409
410
411 /// accumulate into result
412 template <typename T, typename R>
414 const Tensor<T>& f,
415 const Q mufac,
416 Tensor<R>& result) const {
417
418 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
419
420 Tensor<R> result2=general_transform(f,trans2);
421 result2.scale(mufac);
422 result+=result2;
423
424 }
425
426
427
428 /// don't accumulate, since we want to do this at apply()
429 template <typename T, typename R>
430 void apply_transformation2(Level n, long dimk, double tol,
431 const Tensor<T> trans2[NDIM],
432 const GenTensor<T>& f,
433 GenTensor<R>& work1,
434 GenTensor<R>& work2,
435 const Q mufac,
436 GenTensor<R>& result) const {
437
438 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
439
440#if 1
441 result=general_transform(f,trans2);
442 result.scale(mufac);
443
444#else
445
446 long size = 1;
447 for (std::size_t i=0; i<NDIM; ++i) size *= dimk;
448 long dimi = size/dimk;
449
450 R* MADNESS_RESTRICT w1=work1.ptr();
451 R* MADNESS_RESTRICT w2=work2.ptr();
452
453 mTxmq(dimi, trans[0].r, dimk, w1, f.ptr(), trans[0].U, dimk);
454 size = trans[0].r * size / dimk;
455 dimi = size/dimk;
456 for (std::size_t d=1; d<NDIM; ++d) {
457 mTxmq(dimi, trans[d].r, dimk, w2, w1, trans[d].U, dimk);
458 size = trans[d].r * size / dimk;
459 dimi = size/dimk;
460 std::swap(w1,w2);
461 }
462
463 // If all blocks are full rank we can skip the transposes
464 bool doit = false;
465 for (std::size_t d=0; d<NDIM; ++d) doit = doit || trans[d].VT;
466
467 if (doit) {
468 for (std::size_t d=0; d<NDIM; ++d) {
469 if (trans[d].VT) {
470 dimi = size/trans[d].r;
471 mTxmq(dimi, dimk, trans[d].r, w2, w1, trans[d].VT);
472 size = dimk*size/trans[d].r;
473 }
474 else {
475 fast_transpose(dimk, dimi, w1, w2);
476 }
477 std::swap(w1,w2);
478 }
479 }
480 // Assuming here that result is contiguous and aligned
481 aligned_axpy(size, result.ptr(), w1, mufac);
482 // long one = 1;
483 //daxpy_(&size, &mufac, w1, &one, result.ptr(), &one);
484#endif
485 }
486
487
488 /// Apply one of the separated terms, accumulating into the result
489 template <typename T>
490 void muopxv_fast(ApplyTerms at,
491 const ConvolutionData1D<Q>* const ops_1d[NDIM],
492 const Tensor<T>& f, const Tensor<T>& f0,
493 Tensor<TENSOR_RESULT_TYPE(T,Q)>& result,
494 Tensor<TENSOR_RESULT_TYPE(T,Q)>& result0,
495 const double tol,
496 const Q mufac,
497 Tensor<TENSOR_RESULT_TYPE(T,Q)>& work1,
498 Tensor<TENSOR_RESULT_TYPE(T,Q)>& work2) const {
499
500 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
501 Transformation trans[NDIM];
502 Tensor<T> trans2[NDIM];
503
504 double Rnorm = 1.0;
505 for (std::size_t d=0; d<NDIM; ++d) Rnorm *= ops_1d[d]->Rnorm;
506
507 if (at.r_term and (Rnorm > 1.e-20)) {
508
509 const auto tol_Rs = tol/(Rnorm*NDIM); // Errors are relative within here
510
511 // Determine rank of SVD to use or if to use the full matrix
512 long twok = 2*k;
513 if (modified()) twok=k;
514
515 long break_even;
516 if (NDIM==1) break_even = long(0.5*twok);
517 else if (NDIM==2) break_even = long(0.6*twok);
518 else if (NDIM==3) break_even=long(0.65*twok);
519 else break_even=long(0.7*twok);
520 bool rank_is_zero = false;
521 for (std::size_t d=0; d<NDIM; ++d) {
522 long r;
523 for (r=0; r<twok; ++r) {
524 if (ops_1d[d]->Rs[r] < tol_Rs) break;
525 }
526 if (r >= break_even) {
527 trans[d].r = twok;
528 trans[d].U = ops_1d[d]->R.ptr();
529 trans[d].VT = 0;
530 }
531 else {
532
533#ifdef ENABLE_GENTENSOR
534 r = std::max(2L,r+(r&1L)); // (needed for 6D == when GENTENSOR is on) NOLONGER NEED TO FORCE OPERATOR RANK TO BE EVEN
535#endif
536 if (r == 0) {
537 rank_is_zero = true;
538 break;
539 }
540 trans[d].r = r;
541 trans[d].U = ops_1d[d]->RU.ptr();
542 trans[d].VT = ops_1d[d]->RVT.ptr();
543 }
544 trans2[d]=ops_1d[d]->R;
545 }
546
547 if (!rank_is_zero)
548 apply_transformation(twok, trans, f, work1, work2, mufac, result);
549
550 // apply_transformation2(n, twok, tol, trans2, f, work1, work2, mufac, result);
551// apply_transformation3(trans2, f, mufac, result);
552 }
553
554 double Tnorm = 1.0;
555 for (std::size_t d=0; d<NDIM; ++d) Tnorm *= ops_1d[d]->Tnorm;
556
557 if (at.t_term and (Tnorm>0.0)) {
558 const auto tol_Ts = tol/(Tnorm*NDIM); // Errors are relative within here
559
560 long break_even;
561 if (NDIM==1) break_even = long(0.5*k);
562 else if (NDIM==2) break_even = long(0.6*k);
563 else if (NDIM==3) break_even=long(0.65*k);
564 else break_even=long(0.7*k);
565 bool rank_is_zero = false;
566 for (std::size_t d=0; d<NDIM; ++d) {
567 long r;
568 for (r=0; r<k; ++r) {
569 if (ops_1d[d]->Ts[r] < tol_Ts) break;
570 }
571 if (r >= break_even) {
572 trans[d].r = k;
573 trans[d].U = ops_1d[d]->T.ptr();
574 trans[d].VT = 0;
575 }
576 else {
577
578#ifdef ENABLE_GENTENSOR
579 r = std::max(2L,r+(r&1L)); // (needed for 6D == GENTENSOR is USED) NOLONGER NEED TO FORCE OPERATOR RANK TO BE EVEN
580#endif
581 if (r == 0) {
582 rank_is_zero = true;
583 break;
584 }
585 trans[d].r = r;
586 trans[d].U = ops_1d[d]->TU.ptr();
587 trans[d].VT = ops_1d[d]->TVT.ptr();
588 }
589 trans2[d]=ops_1d[d]->T;
590 }
591 if (!rank_is_zero)
592 apply_transformation(k, trans, f0, work1, work2, -mufac, result0);
593// apply_transformation2(n, k, tol, trans2, f0, work1, work2, -mufac, result0);
594// apply_transformation3(trans2, f0, -mufac, result0);
595 }
596 }
597
598
599 /// Apply one of the separated terms, accumulating into the result
600 template <typename T>
602 const ConvolutionData1D<Q>* const ops_1d[NDIM],
603 const GenTensor<T>& f, const GenTensor<T>& f0,
604 GenTensor<TENSOR_RESULT_TYPE(T,Q)>& result,
605 GenTensor<TENSOR_RESULT_TYPE(T,Q)>& result0,
606 double tol,
607 const Q mufac,
608 GenTensor<TENSOR_RESULT_TYPE(T,Q)>& work1,
609 GenTensor<TENSOR_RESULT_TYPE(T,Q)>& work2) const {
610
612// Transformation trans[NDIM];
613 Tensor<T> trans2[NDIM];
614// MADNESS_EXCEPTION("no muopxv_fast2",1);
615
616 double Rnorm = 1.0;
617 for (std::size_t d=0; d<NDIM; ++d) Rnorm *= ops_1d[d]->Rnorm;
618 if (Rnorm == 0.0) return;
619
620 if (Rnorm > 1.e-20) {
621
622 tol = tol/(Rnorm*NDIM); // Errors are relative within here
623
624 // Determine rank of SVD to use or if to use the full matrix
625 long twok = 2*k;
626 if (modified()) twok=k;
627// long break_even;
628// if (NDIM==1) break_even = long(0.5*twok);
629// else if (NDIM==2) break_even = long(0.6*twok);
630// else if (NDIM==3) break_even=long(0.65*twok);
631// else break_even=long(0.7*twok);
632 for (std::size_t d=0; d<NDIM; ++d) {
633 // long r;
634 // for (r=0; r<twok; ++r) {
635 // if (ops_1d[d]->Rs[r] < tol) break;
636 // }
637// if (r >= break_even) {
638// trans[d].r = twok;
639// trans[d].U = ops_1d[d]->R.ptr();
640// trans[d].VT = 0;
641// }
642// else {
643// //r += std::max(2L,r&1L); // NOLONGER NEED TO FORCE OPERATOR RANK TO BE EVEN
644// trans[d].r = r;
645// trans[d].U = ops_1d[d]->RU.ptr();
646// trans[d].VT = ops_1d[d]->RVT.ptr();
647// }
648 trans2[d]=ops_1d[d]->R;
649 }
650 apply_transformation2(n, twok, tol, trans2, f, work1, work2, mufac, result);
651 }
652
653 double Tnorm = 1.0;
654 for (std::size_t d=0; d<NDIM; ++d) Tnorm *= ops_1d[d]->Tnorm;
655
656 if (n > 0 and (Tnorm>1.e-20)) {
657// long break_even;
658//
659// if (NDIM==1) break_even = long(0.5*k);
660// else if (NDIM==2) break_even = long(0.6*k);
661// else if (NDIM==3) break_even=long(0.65*k);
662// else break_even=long(0.7*k);
663 for (std::size_t d=0; d<NDIM; ++d) {
664 // long r;
665 // for (r=0; r<k; ++r) {
666 // if (ops_1d[d]->Ts[r] < tol) break;
667 // }
668// if (r >= break_even) {
669// trans[d].r = k;
670// trans[d].U = ops_1d[d]->T.ptr();
671// trans[d].VT = 0;
672// }
673// else {
674// //r += std::max(2L,r&1L); // NOLONGER NEED TO FORCE OPERATOR RANK TO BE EVEN
675// trans[d].r = r;
676// trans[d].U = ops_1d[d]->TU.ptr();
677// trans[d].VT = ops_1d[d]->TVT.ptr();
678// }
679 trans2[d]=ops_1d[d]->T;
680 }
681 apply_transformation2(n, k, tol, trans2, f0, work1, work2, -mufac, result0);
682 }
683 }
684
685
686 /// Computes the Frobenius norm of one of the separated terms ... WITHOUT FACTOR INCLUDED
687 /// compute for 1 term, all dim, 1 disp, essentially for SeparatedConvolutionInternal
688 double munorm2(Level n, const ConvolutionData1D<Q>* ops[]) const {
689 if (modified()) return munorm2_modified(n,ops);
690 return munorm2_ns(n,ops);
691 }
692
693 /// Computes the Frobenius norm of one of the separated terms for the NS form
694 /// ... WITHOUT FACTOR INCLUDED
695 /// compute for 1 term, all dim, 1 disp, essentially for SeparatedConvolutionInternal
696 double munorm2_ns(Level n, const ConvolutionData1D<Q>* ops[]) const {
697 //PROFILE_MEMBER_FUNC(SeparatedConvolution);
698
699 double prod=1.0, sum=0.0;
700 for (std::size_t d=0; d<NDIM; ++d) {
701 double a = ops[d]->NSnormf;
702 double b = ops[d]->Tnormf;
703 double aa = std::min(a,b);
704 double bb = std::max(a,b);
705 prod *= bb;
706 if (bb > 0.0) sum +=(aa/bb);
707 }
708 if (n) prod *= sum;
709
710 return prod;
711 }
712
713
714 /// Computes the operator norm of one of the separated terms of the modified NS form
715 /// ... WITHOUT FACTOR INCLUDED
716 /// compute for 1 term, all dim, 1 disp, essentially for SeparatedConvolutionInternal
717 double munorm2_modified(Level n, const ConvolutionData1D<Q>* ops_1d[]) const {
719
720 // follows Eq. (21) ff of Beylkin 2008 (Beylkin Appl. Comput. Harmon. Anal. 24, pp 354)
721
722 // we have all combinations of difference, upsampled, F terms (d, u, f),
723 // with the constraint that d is in each term exactly once. In the mixed terms (udf)
724 // we just get all possible combinations, in the pure terms (dff, duu) we have
725 // to multiply each term (dff, fdf, ffd) with (NDIM-1)!, to get the right number.
726
727 double dff = 0.0;
728 double duu = 0.0;
729 double udf = 0.0;
730
731 // loop over d shifting over the dimensions dxx, xdx, xxd,
732 for (size_t d=0; d<NDIM; ++d) {
733 double dff_tmp = ops_1d[d]->N_diff;
734 double duu_tmp = ops_1d[d]->N_diff;
735 double udf_tmp = ops_1d[d]->N_diff;
736
737
738 for (size_t dd=0; dd<NDIM; ++dd) {
739 if (dd!=d) {
740 dff_tmp *= ops_1d[dd]->N_F;
741 duu_tmp *= ops_1d[dd]->N_up;
742
743 udf_tmp *= ops_1d[dd]->N_F;
744 for (size_t ddd=0; ddd<NDIM; ++ddd) {
745 if (ddd!=dd) udf += udf_tmp * ops_1d[ddd]->N_up;
746 }
747 }
748 }
749
750 dff+=dff_tmp;
751 duu+=duu_tmp;
752 }
753
754 // finalize with the factorial
755 double factorial=1.0;
756 for (int i=1; i<static_cast<int>(NDIM)-1; ++i) factorial*=double(i);
757 dff*=factorial;
758 duu*=factorial;
759
760 // Eq. (23) of Beylkin 2008, for one separated term WITHOUT the factor
761 double norm=(dff + udf + duu) /(factorial * double(NDIM));
762
763// // double check
764// if (NDIM==3) {
765// Tensor<Q> R_full=outer(ops_1d[0]->R,outer(ops_1d[1]->R,ops_1d[2]->R));
766// Tensor<Q> T_full=outer(ops_1d[0]->T,outer(ops_1d[1]->T,ops_1d[2]->T));
767// double n2=(R_full-T_full).normf();
768//// print("norm estimate, norm",norm, n2, norm<n2);
769// norm=n2;
770// }
771
772 return norm;
773
774 }
775
776
777 /// get the transformation matrices for 1 term and all dimensions and one displacement
778
779 /// use ConvolutionND, which uses ConvolutionData1D to collect the transformation matrices
781 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
783 for (std::size_t d=0; d<NDIM; ++d) {
784 op.ops[d] = ops[mu].getop(d)->nonstandard(n, disp.translation()[d]);
785 }
786 op.norm = munorm2(n, op.ops)*std::abs(ops[mu].getfac());
787
788// double newnorm = munorm2(n, op.ops);
789// // This rescaling empirically based upon BSH separated expansion
790// // ... needs more testing. OK also for TDSE.
791// // All is good except for some 000 blocks which are up to sqrt(k^d) off.
792// for (int d=0; d<NDIM; ++d) {
793// if (disp[d] == 0) newnorm *= 0.5;
794// else if (std::abs(disp[d]) == 1) newnorm *= 0.8;
795// }
796// double oldnorm = munorm(n, op.ops);
797// if (oldnorm > 1e-13 && (newnorm < 0.5*oldnorm || newnorm > 2.0*oldnorm) )
798// print("munorm", n, disp, mu, newnorm, oldnorm, newnorm/oldnorm);
799
800 return op;
801 }
802
803
804
805 /// get the transformation matrices for 1 term and all dimensions and one displacement
806
807 /// use ConvolutionND, which uses ConvolutionData1D to collect the transformation matrices
809 getmuop_modified(int mu, Level n, const Key<NDIM>& disp, const Key<NDIM>& source) const {
810 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
811
812
813 // SeparatedConvolutionInternal keeps data for 1 term and all dimensions
815
816 // in the modified NS form we need not only the displacement, but also the source Translation
817 // for correctly constructing the operator, b/c the operator is not Toeplitz
818
819 // op.ops is of type ConvolutionData1D (1 term, 1 dim, 1 disp)
820 // ops[mu] is of type ConvolutionND (1 term, all dim, 1 disp)
821 for (std::size_t d=0; d<NDIM; ++d) {
822 Translation sx=source.translation()[d]; // source translation
823 Translation tx=source.translation()[d]+disp.translation()[d]; // target translation
824
825 Key<2> op_key(n,Vector<Translation,2>{sx,tx});
826 op.ops[d] = ops[mu].getop(d)->mod_nonstandard(op_key);
827 }
828
829 // works for both modified and not modified NS form
830 op.norm = munorm2(n, op.ops)*std::abs(ops[mu].getfac());
831// op.norm=1.0;
832 return op;
833 }
834
835 /// get the data for all terms and all dimensions for one displacement
837
838 // in the NS form the operator depends only on the displacement
839 if (not modified()) return getop_ns(n,d);
840 return getop_modified(n, d, source);
841 }
842
843
844 /// get the data for all terms and all dimensions for one displacement
845
846 /// uses SeparatedConvolutionInternal (ConvolutionND, ConvolutionData1D) to construct
847 /// the transformation matrices.
848 /// @param[in] d displacement
849 /// @return pointer to cached operator
851 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
852 const SeparatedConvolutionData<Q,NDIM>* p = data.getptr(n,d);
853 if (p) return p;
854
855 // get the data for each term
857 for (int mu=0; mu<rank; ++mu) {
858 // op.muops is of type SeparatedConvolutionInternal (1 term, all dim, 1 disp)
859 // getmuop uses ConvolutionND
860 op.muops[mu] = getmuop(mu, n, d);
861 }
862
863 double norm = 0.0;
864 for (int mu=0; mu<rank; ++mu) {
865 const double munorm = op.muops[mu].norm;
866 norm += munorm*munorm;
867 }
868 //print("getop", n, d, norm);
869 op.norm = sqrt(norm);
870 return data.set(n, d, op);
871 }
872
873
874
875 /// get the data for all terms and all dimensions for one displacement (modified NS form)
876
877 /// remember that the operator in the modified NS form is not Toeplitz, so we need
878 /// information about the displacement and the source key
879 /// @param[in] n level (=scale) (actually redundant, since included in source)
880 /// @param[in] disp displacement key
881 /// @param[in] source source key
882 /// @return pointer to cached operator
884 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
885
886 // in the modified NS form the upsampled part of the operator depends on the modulus of the source
887 Vector<Translation,NDIM> t=source.translation();
888 for (size_t i=0; i<NDIM; ++i) t[i]=t[i]%2;
889 Key<2*NDIM> key=disp.merge_with(Key<NDIM>(source.level(),t));
890
891 const SeparatedConvolutionData<Q,NDIM>* p = mod_data.getptr(n,key);
892 if (p) return p;
893
894 // get the data for each term
895 // op.muops is of type SeparatedConvolutionInternal (1 term, all dim, 1 disp)
896 // getmuop uses ConvolutionND
898 for (int mu=0; mu<rank; ++mu) op.muops[mu] = getmuop_modified(mu, n, disp, source);
899
900 double norm = 0.0;
901 for (int mu=0; mu<rank; ++mu) {
902 const double munorm = op.muops[mu].norm;
903 norm += munorm*munorm;
904 }
905
906 op.norm = sqrt(norm);
907 return mod_data.set(n, key, op);
908 }
909
910
911 void check_cubic() {
912 // !!! NB ... cell volume obtained from global defaults
914 // Check that the cell is cubic since currently is assumed
915 for (std::size_t d=1; d<NDIM; ++d) {
917 }
918 }
919
920
921 /// upsample some of the dimensions of coeff to its child indicated by key
922
923 /// @param[in] coeff the coeffs of dim 2*NDIM that will be upsampled
924 /// @param[in] key the key indicating the child -- only some dimensions will be "reproductive"
925 /// @param[in] particle if 0: upsample dimensions 0-2
926 /// if 1: upsample dimensions 3-5
927 /// @return a partially upsampled coefficient tensor
928 template<typename T, size_t FDIM>
929 GenTensor<T> partial_upsample(const Key<FDIM>& key, const GenTensor<T>& coeff, const int particle) const {
930
931 if (coeff.rank()==0) return GenTensor<T>();
932 MADNESS_ASSERT(coeff.dim(0)==k);
933 if (NDIM==coeff.ndim()) {
934 MADNESS_ASSERT(particle==1); // other particle, leave this particle unchanged
935 return coeff;
936 }
937
938 MADNESS_ASSERT(coeff.ndim()==FDIM);
939 MADNESS_ASSERT(particle==0 or (2*NDIM==FDIM));
940
941 // the twoscale coefficients: for upsampling use h0/h1; see Alpert Eq (3.35a/b)
942 // handle the spectator dimensions with the identity matrix
943 const Tensor<T> h[2] = {cdata.h0, cdata.h1};
944 Tensor<T> identity(k,k);
945 for (int i=0; i<k; ++i) identity(i,i)=1.0;
946 Tensor<T> matrices[2*NDIM];
947
948 // get the appropriate twoscale coefficients for each dimension
949 if (particle==0) {
950 for (size_t ii=0; ii<NDIM; ++ii) matrices[ii]=h[key.translation()[ii]%2];
951 for (size_t ii=0; ii<NDIM; ++ii) matrices[ii+NDIM]=identity;
952 } else if (particle==1) {
953 for (size_t ii=0; ii<NDIM; ++ii) matrices[ii]=identity;
954 for (size_t ii=0; ii<NDIM; ++ii) matrices[ii+NDIM]=h[key.translation()[ii+NDIM]%2];
955 } else {
956 MADNESS_EXCEPTION("unknown particle",1);
957 }
958
959 // transform and accumulate on the result
960 const GenTensor<T> result=general_transform(coeff,matrices);
961 return result;
962 }
963
964
965 /// upsample the sum coefficients of level 1 to sum coeffs on level n+1
966
967 /// specialization of the unfilter method, will transform only the sum coefficients
968 /// @param[in] key key of level n+1
969 /// @param[in] coeff sum coefficients of level n (does NOT belong to key!!)
970 /// @return sum coefficients on level n+1
971 template<typename T, size_t FDIM>
972 GenTensor<T> upsample(const Key<FDIM>& key, const GenTensor<T>& coeff) const {
973
974 // the twoscale coefficients: for upsampling use h0/h1; see Alpert Eq (3.35a/b)
975 // note there are no difference coefficients; if you want that use unfilter
976 const Tensor<T> h[2] = {cdata.h0, cdata.h1};
977 Tensor<T> matrices[FDIM];
978
979 // get the appropriate twoscale coefficients for each dimension
980 for (size_t ii=0; ii<FDIM; ++ii) matrices[ii]=h[key.translation()[ii]%2];
981
982 // transform and accumulate on the result
983 const GenTensor<T> result=general_transform(coeff,matrices);
984 return result;
985 }
986
987 /// initializes range using range of ops[0]
988 /// @pre `ops[i].range == ops[0].range`
989 void init_range() {
990 if (!ops.empty()) {
991 for (int d = 0; d != NDIM; ++d) {
992 for(const auto & op: ops) {
993 MADNESS_ASSERT(op.getop(d)->range == ops[0].getop(d)->range);
994 }
995 range[d] = ops[0].getop(d)->range;
996 }
997 }
998 }
999
1000 /// initializes lattice_sum using `ops[0].lattice_summed()`
1001 /// @pre `ops[i].lattice_summed() == ops[0].lattice_summed()`
1003 if (!ops.empty()) {
1004 for (int d = 0; d != NDIM; ++d) {
1005 for (const auto &op : ops) {
1006 MADNESS_ASSERT(op.lattice_summed() ==
1007 ops[0].lattice_summed());
1008 }
1009 lattice_summed_ = ops[0].lattice_summed();
1010 }
1011 // a term whose 1D factors omit lattice images is part of a rest-of-crystal operator, which only
1012 // initialize_images_only builds: assembled any other way (e.g. from the terms of one) the operator
1013 // would be applied with the source-ordered displacements and screening and give a wrong potential
1014 for (const auto& op : ops)
1015 for (std::size_t d = 0; d != NDIM; ++d) {
1016 const auto op1d = op.getop(d);
1017 MADNESS_CHECK_THROW(images_only_ || !op1d || op1d->images == LatticeImages::all,
1018 "SeparatedConvolution: a term omits lattice images (LatticeImages), but the operator was not built as rest-of-crystal (OperatorInfo::images_only)");
1019 }
1020 // build the displacement lists this operator applies with now, on the constructing thread,
1021 // rather than in the first apply task to request them
1022 if (lattice_summed_.any()) get_disp(0);
1023 }
1024 }
1025
1026 public:
1027
1028 // For separated convolutions with same operator in each direction (isotropic)
1030 const std::vector< std::shared_ptr< Convolution1D<Q> > >& argops,
1032 bool doleaves = false)
1034 , info()
1036 , lattice_summed_(false) // this will be overridden by init_lattice_summed below
1037 , modified_(false)
1038 , particle_(1)
1039 , destructive_(false)
1040 , k(k)
1041 , cdata(FunctionCommonData<Q,NDIM>::get(k))
1042 , rank(argops.size())
1043 , vk(NDIM,k)
1044 , v2k(NDIM,2*k)
1045 , s0(std::max<std::size_t>(2,NDIM),Slice(0,k-1))
1046 {
1047
1048 for (unsigned int mu=0; mu < argops.size(); ++mu) {
1049 this->ops.push_back(ConvolutionND<Q,NDIM>(argops[mu]));
1050 }
1051 init_range();
1053
1054 this->process_pending();
1055 }
1056
1057 // For general convolutions
1059 const std::vector< ConvolutionND<Q,NDIM> >& argops,
1061 bool doleaves = false)
1063 , info()
1065 , lattice_summed_(false) // this will be overridden by init_lattice_summed below
1066 , modified_(false)
1067 , particle_(1)
1068 , destructive_(false)
1069 , ops(argops)
1070 , k(k)
1071 , cdata(FunctionCommonData<Q,NDIM>::get(k))
1072 , rank(argops.size())
1073 , vk(NDIM,k)
1074 , v2k(NDIM,2*k)
1075 , s0(std::max<std::size_t>(2,NDIM),Slice(0,k-1))
1076 {
1077 init_range();
1079 this->process_pending();
1080 }
1081
1082 /// Constructor for Gaussian Convolutions
1083 /// WARNING! bloch_k should only ever be nonzero if `Q` is a complex type.
1085 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
1087 bool doleaves = false,
1088 const Vector<double, NDIM>& bloch_k = Vector<double, NDIM>(0.0))
1089 : SeparatedConvolution(world,Tensor<double>(0l),Tensor<double>(0l),info1.lo,info1.thresh,lattice_ranges,k,doleaves,info1.mu) {
1090 info.type=info1.type;
1091 info.truncate_lowexp_gaussians = info1.truncate_lowexp_gaussians;
1092 info.range = info1.range;
1093 info.images_only = info1.images_only;
1094 images_only_ = info1.images_only;
1095 auto [coeff, expnt, dropped_coeff, dropped_expnt] = make_coeff_for_operator(world, info, lattice_ranges);
1096 rank=coeff.dim(0);
1097 range = info.template range_as_array<NDIM>();
1098 if (info.images_only) {
1099 initialize_images_only(coeff,expnt,dropped_coeff,dropped_expnt,lattice_ranges,range,bloch_k);
1100 } else {
1101 ops.resize(rank);
1102 initialize(coeff,expnt,lattice_ranges,range,bloch_k);
1103 }
1105 stored_coeffs = copy(coeff);
1106 stored_exponents = copy(expnt);
1107 }
1108
1109 /// the rest-of-crystal operator: the lattice sum with the home cell (L = 0) removed
1110
1111 /// Removing one lattice vector is not "drop R = 0 on every axis": that also
1112 /// drops every image with any zero component, and for a chain periodic along
1113 /// z the only images at all are (0, 0, n_z). Sum instead over the 2^p - 1
1114 /// nonzero bit patterns of the p lattice-summed axes; in each pattern an axis
1115 /// whose bit is set sums R != 0 and one whose bit is clear takes R = 0 only.
1116 /// Term by term the fit is the one the full lattice sum uses, so
1117 /// full == home + images exactly, with no cancellation anywhere. Every term
1118 /// keeps the same lattice_summed() pattern, so init_lattice_summed() holds and
1119 /// the displacements stay on the non-periodic domain. Non-periodic axes get the
1120 /// ordinary plain factor.
1121 ///
1122 /// An infinite lattice sum drops the low-exponent Gaussians of the fit
1123 /// (make_coeff_for_operator): their lattice sum is flat over the cell, a
1124 /// gauge constant. Their home-cell part is not flat, and a home operator
1125 /// built from the full fit keeps it. So that home(full fit) + images still
1126 /// equals the lattice sum up to that gauge constant, the dropped terms enter
1127 /// here as home-only terms with negated coefficients: the operator is then
1128 /// exactly (lattice sum as MADNESS computes it) - (home cell with the full
1129 /// kernel). Measured on a 1D-periodic H10 chain, L = 18 bohr: without this,
1130 /// the 15 dropped terms shift the periodic energy correction by 3e-5 Ha.
1131 ///
1132 /// The identity is term by term only if the home operator is built from the
1133 /// same fit. make_coeff_for_operator extends the fit range when either the
1134 /// operator or the default boundary conditions are periodic, so build the home
1135 /// operator under the same default boundary conditions as this one (as
1136 /// test_images_operator does); otherwise the identity holds to the fit accuracy.
1137 void initialize_images_only(const Tensor<Q>& coeff, const Tensor<double>& expnt,
1138 const Tensor<double>& dropped_coeff, const Tensor<double>& dropped_expnt,
1139 const std::array<LatticeRange, NDIM>& lattice_range,
1140 const std::array<KernelRange, NDIM>& range,
1141 const Vector<double, NDIM>& bloch_k) {
1143 const double pi = constants::pi;
1144 const int rank0 = coeff.dim(0);
1145
1146 std::vector<std::size_t> per; // the lattice-summed axes
1147 for (std::size_t d = 0; d < NDIM; ++d) if (lattice_range[d]) per.push_back(d);
1148 MADNESS_CHECK_THROW(!per.empty(),
1149 "images_only: the operator has no lattice-summed axis, so there are no images to sum");
1150 // FunctionImpl::do_apply places the displacements to the boundary of a finite kernel range around
1151 // the source and screens them against the reach of the standard displacements measured with
1152 // Key::real_distsq_bc; neither holds for a kernel whose range is centered on the images
1153 for (std::size_t d = 0; d < NDIM; ++d)
1154 MADNESS_CHECK_THROW(range[d].infinite(),
1155 "images_only: a range-restricted kernel is not supported");
1156 const int npat = (1 << per.size()) - 1;
1157 const int ndropped = dropped_coeff.size() ? int(dropped_coeff.dim(0)) : 0;
1158
1159 ops.resize(std::size_t(rank0) * npat + ndropped);
1160 rank = int(ops.size());
1161 // pattern 0 (every lattice-summed axis R = 0 only) is the home cell; it is
1162 // used only for the dropped terms below
1163 auto set_term = [&](ConvolutionND<Q,NDIM>& term, Q c_mu, double e_mu, int pat) {
1164 const Q c = std::pow(sqrt(e_mu/pi), static_cast<int>(NDIM));
1165 term.setfac(c_mu/c);
1166 for (std::size_t d = 0; d < NDIM; ++d) {
1168 if (lattice_range[d]) {
1169 const int bit = int(std::find(per.begin(), per.end(), d) - per.begin());
1170 images = ((pat >> bit) & 1) ? LatticeImages::exclude_home : LatticeImages::home_only;
1171 }
1172 term.setop(d, GaussianConvolution1DCache<Q>::get(k, e_mu*width[d]*width[d], 0,
1173 lattice_range[d], bloch_k[d], range[d], images));
1174 }
1175 };
1176 for (int pat = 1; pat <= npat; ++pat)
1177 for (int mu = 0; mu < rank0; ++mu)
1178 set_term(ops[std::size_t(pat - 1) * rank0 + mu], coeff(mu), expnt(mu), pat);
1179 for (int mu = 0; mu < ndropped; ++mu)
1180 set_term(ops[std::size_t(rank0) * npat + mu], -dropped_coeff(mu), dropped_expnt(mu), 0);
1181 }
1182
1183 /// Constructor for Gaussian Convolutions (mostly for backward compatability)
1185 const Tensor<Q>& coeff, const Tensor<double>& expnt,
1186 double lo, double thresh,
1187 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
1189 bool doleaves = false,
1190 double mu=0.0)
1194 ,
1195 lattice_summed_(false) // will be updated by init_lattice_summed
1196 , ops(coeff.dim(0))
1197 , k(k)
1198 , cdata(FunctionCommonData<Q,NDIM>::get(k))
1199 , rank(coeff.dim(0))
1200 , vk(NDIM,k)
1201 , v2k(NDIM,2*k)
1202 , s0(std::max<std::size_t>(2,NDIM),Slice(0,k-1)) {
1203 initialize(coeff,expnt,lattice_ranges);
1204 init_range();
1206 stored_coeffs = copy(coeff);
1207 stored_exponents = copy(expnt);
1208 }
1209
1210 void initialize(const Tensor<Q>& coeff, const Tensor<double>& expnt, std::array<LatticeRange, NDIM> lattice_range, std::array<KernelRange, NDIM> range = {}, const Vector<double, NDIM>& bloch_k = Vector<double, NDIM>(0.0)) {
1212 const double pi = constants::pi;
1213
1214 for (int mu=0; mu<rank; ++mu) {
1215 Q c = std::pow(sqrt(expnt(mu)/pi),static_cast<int>(NDIM)); // Normalization coeff
1216
1217 // We cache the normalized operator so the factor is the value we must multiply
1218 // by to recover the coeff we want.
1219 ops[mu].setfac(coeff(mu)/c);
1220
1221 for (std::size_t d=0; d<NDIM; ++d) {
1222 ops[mu].setop(d,GaussianConvolution1DCache<Q>::get(k, expnt(mu)*width[d]*width[d], 0,
1223 lattice_range[d], bloch_k[d], range[d]));
1224 }
1225 }
1226 }
1227
1229
1230 void print_timer() const {
1231 if (this->get_world().rank()==0) {
1232 timer_full.print("op full tensor ");
1233 timer_low_transf.print("op low rank transform");
1234 timer_low_accumulate.print("op low rank addition ");
1235 }
1236 }
1237
1238 void reset_timer() const {
1239 if (this->get_world().rank()==0) {
1240 timer_full.reset();
1241 timer_low_transf.reset();
1242 timer_low_accumulate.reset();
1243 }
1244 }
1245
1246 /// the displacements in the order FunctionImpl::do_apply visits them: of increasing distance in the metric
1247 /// the kernel decays with, see displacement_real_distsq()
1248 const std::vector< Key<NDIM> >& get_disp(Level n) const {
1251 }
1252
1253 /// @return true if this is the rest-of-crystal operator (OperatorInfo::images_only at construction)
1254 bool images_only() const { return images_only_; }
1255
1256 /// the real-space distance (squared, in the units of Key::real_distsq) between the source and a displaced
1257 /// target, in the metric the kernel decays with
1258
1259 /// FunctionImpl::do_apply groups get_disp() into shells of this distance and stops at the first shell
1260 /// that contributes nothing. For a kernel that decays away from the source that is the distance modulo
1261 /// the lattice (Key::real_distsq_bc). The rest-of-crystal kernel (OperatorInfo::images_only) vanishes
1262 /// near the source and decays away from the nearest lattice image other than the home cell, so its
1263 /// distance is to that image (Key::real_distsq_images). get_disp() is ordered by the same metric.
1265 const auto& widths = FunctionDefaults<NDIM>::get_cell_width();
1266 return images_only_ ? displacement.real_distsq_images(lattice_summed(), widths)
1267 : displacement.real_distsq_bc(lattice_summed(), widths);
1268 }
1269
1270 /// like displacement_real_distsq() but in boxes (Key::distsq_bc / Key::distsq_images); do_apply
1271 /// subdivides the shell of touching boxes (real distance 0) by it
1272 std::uint64_t displacement_distsq(const Key<NDIM>& displacement) const {
1273 return images_only_ ? displacement.distsq_images(lattice_summed())
1274 : displacement.distsq_bc(lattice_summed());
1275 }
1276
1277 /// @return flag for each axis indicating whether lattice summation is performed in that direction
1279 /// @return flag for each axis indicating whether functions that this op acts on are periodic on the box in that direction (false by default)
1280 /// it is normally preferred to lattice sum, obtaining an equivalent problem with a lattice-summed operator on a non-periodic function
1282 /// changes domain periodicity
1283 /// \param domain_is_periodic
1284 void set_domain_periodicity(const array_of_bools<NDIM>& domain_is_periodic) { func_domain_is_periodic_ = domain_is_periodic;}
1285
1286 /// return the operator norm for all terms, all dimensions and 1 displacement
1287 double norm(Level n, const Key<NDIM>& d, const Key<NDIM>& source_key) const {
1288 // SeparatedConvolutionData keeps data for all terms and all dimensions and 1 displacement
1289// return 1.0;
1290 return getop(n, d, source_key)->norm;
1291 }
1292
1293 /// the largest of norm(n, d, source_key) over the displacements d: a bound on what any one displacement
1294 /// can contribute from a source node at level n
1295
1296 /// FunctionImpl screens a source node against this before visiting any displacement. For a kernel that
1297 /// decays away from the source it is the block at the zero displacement. The rest-of-crystal kernel
1298 /// (OperatorInfo::images_only) is largest one box from an image, and on which axis depends on the cell:
1299 /// the axis-adjacent blocks all touch their image, and the narrower the axis the smaller the separations
1300 /// its block integrates over. So take the max over the image-adjacent displacements, which lead get_disp(n)
1301 /// (real distance 0, one box; see Displacements::sort_displacements_images).
1302 double norm_bound(Level n, const Key<NDIM>& source_key) const {
1303 const auto& disp = get_disp(n);
1304 if (!images_only_) return norm(n, disp.front(), source_key); // the zero displacement
1305 // image-adjacent = touching an image (real distance 0, since Key::real_distsq_images measures the least
1306 // distance between points of the boxes) and one box from it along one axis (box distance 1); corner
1307 // neighbours, also at real distance 0, have box distance 2 or 3 and follow them in the list
1308 double result = 0.0;
1309 std::size_t nadjacent = 0;
1310 for (const auto& d : disp) {
1311 if (displacement_real_distsq(d) != 0.0 || displacement_distsq(d) != 1) break;
1312 result = std::max(result, norm(n, d, source_key));
1313 ++nadjacent;
1314 }
1315 // an empty run would make this 0 and screen out every source node: the images potential would vanish
1316 MADNESS_CHECK_THROW(nadjacent > 0, "SeparatedConvolution::norm_bound: the rest-of-crystal displacements do not start with the image-adjacent ones (see Displacements::sort_displacements_images)");
1317 return result;
1318 }
1319
1320 /// return that part of a hi-dim key that serves as the base for displacements of this operator
1321
1322 /// if the function and the operator have the same dimension return key
1323 /// if the function has a higher dimension than the operator (e.g. in the exchange operator)
1324 /// return only that part of key that corresponds to the particle this operator works on
1325 /// @param[in] key hi-dim key
1326 /// @return a lo-dim part of key; typically first or second half
1327 template<size_t FDIM>
1328 typename std::enable_if<FDIM!=NDIM, Key<NDIM> >::type
1329 get_source_key(const Key<FDIM> key) const {
1331 Key<FDIM-NDIM> dummykey;
1332 if (particle()==1) key.break_apart(source,dummykey);
1333 if (particle()==2) key.break_apart(dummykey,source);
1334 return source;
1335 }
1336
1337 /// return that part of a hi-dim key that serves as the base for displacements of this operator
1338
1339 /// if the function and the operator have the same dimension return key
1340 /// if the function has a higher dimension than the operator (e.g. in the exchange operator)
1341 /// return only that part of key that corresponds to the particle this operator works on
1342 /// @param[in] key hi-dim key
1343 /// @return a lo-dim part of key; typically first or second half
1344 template<size_t FDIM>
1345 typename std::enable_if<FDIM==NDIM, Key<NDIM> >::type
1346 get_source_key(const Key<FDIM> key) const {
1347 return key;
1348 }
1349
1350 /// apply this operator on a function f
1351
1352 /// the operator does not need to have the same dimension as the function, e,g,
1353 /// the Poisson kernel for the exchange operator acts only on 1 electron of a
1354 /// given (pair) function.
1355 /// @param[in] f a function of same or different dimension as this operator
1356 /// @return the result function of the same dimensionality as the input function f
1357 template <typename T, size_t FDIM>
1359 return madness::apply(*this, f);
1360 }
1361
1362 /// apply this on a vector of functions
1363 template <typename T, size_t FDIM>
1364 std::vector<Function<TENSOR_RESULT_TYPE(T,Q),FDIM>> operator()(const std::vector<Function<T,FDIM>>& f) const {
1365 return madness::apply(*this, f);
1366 }
1367
1368 /// apply this operator on a separable function f(1,2) = f(1) f(2)
1369
1370 /// @param[in] f1 a function of dim LDIM
1371 /// @param[in] f2 a function of dim LDIM
1372 /// @return the result function of dim NDIM=2*LDIM: g(1,2) = G(1,1',2,2') f(1',2')
1373 template <typename T, size_t LDIM>
1374 Function<TENSOR_RESULT_TYPE(T,Q),LDIM+LDIM>
1376 return madness::apply(*this, std::vector<Function<Q,LDIM>>({f1}),
1377 std::vector<Function<Q,LDIM>>({f2}));
1378 }
1379
1380 /// apply this operator on a sum of separable functions f(1,2) = \sum_i f_i(1) f_i(2)
1381
1382 /// @param[in] f1 a function of dim LDIM
1383 /// @param[in] f2 a function of dim LDIM
1384 /// @return the result function of dim NDIM=2*LDIM: g(1,2) = G(1,1',2,2') f(1',2')
1385 template <typename T, size_t LDIM>
1386 Function<TENSOR_RESULT_TYPE(T,Q),LDIM+LDIM>
1387 operator()(const std::vector<Function<T,LDIM>>& f1, const std::vector<Function<Q,LDIM>>& f2) const {
1388 return madness::apply(*this, f1, f2);
1389 }
1390
1391 /// apply this onto another suitable argument, returning the same type
1392
1393 /// argT must implement argT::apply(const SeparatedConvolution& op, const argT& arg)
1394 template<typename argT>
1395 argT operator()(const argT& argument) const {
1396 return madness::apply(*this,argument);
1397 }
1398
1399
1400 /// apply this operator on coefficients in full rank form
1401
1402 /// @param[in] coeff source coeffs in full rank
1403 /// @param[in] source the source key
1404 /// @param[in] shift the displacement, where the source coeffs come from
1405 /// @param[in] tol thresh/#neigh*cnorm
1406 /// @return a tensor of full rank with the result op(coeff)
1407 template <typename T>
1409 const Key<NDIM>& shift,
1410 const Tensor<T>& coeff,
1411 double tol) const {
1412 //PROFILE_MEMBER_FUNC(SeparatedConvolution); // Too fine grain for routine profiling
1413 MADNESS_ASSERT(coeff.ndim()==NDIM);
1414
1415 double cpu0=cpu_time();
1416
1417 typedef TENSOR_RESULT_TYPE(T,Q) resultT;
1418 const Tensor<T>* input = &coeff;
1419 Tensor<T> dummy;
1420
1421 if (not modified()) {
1422 if (coeff.dim(0) == k) {
1423 // This processes leaf nodes with only scaling
1424 // coefficients ... FuncImpl::apply by default does not
1425 // apply the operator to these since for smoothing operators
1426 // it is not necessary. It is necessary for operators such
1427 // as differentiation and time evolution and will also occur
1428 // if the application of the operator widens the tree.
1429 dummy = Tensor<T>(v2k);
1430 dummy(s0) = coeff;
1431 input = &dummy;
1432 }
1433 else {
1434 MADNESS_ASSERT(coeff.dim(0)==2*k);
1435 }
1436 }
1437
1438 tol = 0.01*tol/rank; // Error is per separated term
1439 ApplyTerms at;
1440 at.r_term=true;
1441 at.t_term=(source.level()>0);
1442
1443 /// SeparatedConvolutionData keeps data for all terms and all dimensions and 1 displacement
1445
1446 //print("sepop",source,shift,op->norm,tol);
1447
1448 Tensor<resultT> r(v2k), r0(vk);
1449 Tensor<resultT> work1(v2k,false), work2(v2k,false);
1450
1451 if (modified()) {
1453 work1=Tensor<resultT>(vk,false);
1454 work2=Tensor<resultT>(vk,false);
1455 }
1456
1457 const Tensor<T> f0 = copy(coeff(s0));
1458 for (int mu=0; mu<rank; ++mu) {
1459 // SeparatedConvolutionInternal keeps data for 1 term and all dimensions and 1 displacement
1460 const SeparatedConvolutionInternal<Q,NDIM>& muop = op->muops[mu];
1461 if (muop.norm > tol) {
1462 // ops is of ConvolutionND, returns data for 1 term and all dimensions
1463 Q fac = ops[mu].getfac();
1464 muopxv_fast(at, muop.ops, *input, f0, r, r0, tol/std::abs(fac), fac,
1465 work1, work2);
1466 }
1467 }
1468
1469 r(s0).gaxpy(1.0,r0,1.0);
1470 double cpu1=cpu_time();
1471 timer_full.accumulate(cpu1-cpu0);
1472
1473 return r;
1474 }
1475
1476
1477 /// apply this operator on only 1 particle of the coefficients in low rank form
1478
1479 /// note the unfortunate mess with NDIM: here NDIM is the operator dimension, and FDIM is the
1480 /// function's dimension, whereas in the function we have OPDIM for the operator and NDIM for
1481 /// the function
1482 /// @tparam T the dimension of the function this operator is applied on. \todo MGR: Make sure info on T is correct. Was previously labeled FDIM.
1483 /// @param[in] coeff source coeffs in SVD (=optimal!) form, in high dimensionality (FDIM)
1484 /// @param[in] source the source key in low dimensionality (NDIM)
1485 /// @param[in] shift the displacement in low dimensionality (NDIM)
1486 /// @param[in] tol thresh/(#neigh*cnorm)
1487 /// @param[in] tol2 thresh/#neigh
1488 /// @return coeff result
1489 template<typename T>
1491 const Key<NDIM>& shift, const GenTensor<T>& coeff, double tol, double tol2) const {
1492
1493 typedef TENSOR_RESULT_TYPE(T,Q) resultT;
1494
1495 // prepare access to the singular vectors
1496 const SVDTensor<T>& svdcoeff=coeff.get_svdtensor();
1497// std::vector<Slice> s(coeff.config().dim_per_vector()+1,_);
1498 std::vector<Slice> s(svdcoeff.dim_per_vector(particle()-1)+1,_);
1499 // can't use predefined slices and vectors -- they have the wrong dimension
1500 const std::vector<Slice> s00(coeff.ndim(),Slice(0,k-1));
1501
1502 // some checks
1503 MADNESS_ASSERT(coeff.is_svd_tensor()); // for now
1504 MADNESS_ASSERT(not modified());
1506 MADNESS_ASSERT(coeff.dim(0)==2*k);
1507 MADNESS_ASSERT(2*NDIM==coeff.ndim());
1508
1509 double cpu0=cpu_time();
1511
1512 // some workspace
1513 Tensor<resultT> work1(v2k,false), work2(v2k,false);
1514
1515 // sliced input and final result
1516 const GenTensor<T> f0 = copy(coeff(s00));
1517 GenTensor<resultT> final=copy(coeff);
1518 GenTensor<resultT> final0=copy(f0);
1519
1520 tol = tol/rank*0.01; // Error is per separated term
1521 tol2= tol2/rank;
1522
1523 // the operator norm is missing the identity working on the other particle
1524 // use as (muop.norm*exchange_norm < tol)
1525 // for some reason the screening is not working at all..
1526// double exchange_norm=std::pow(2.0*k,1.5);
1527
1528 for (int r=0; r<coeff.rank(); ++r) {
1529
1530 // get the appropriate singular vector (left or right depends on particle)
1531 // and apply the full tensor muopxv_fast on it, term by term
1532 s[0]=Slice(r,r);
1533 const Tensor<T> chunk=svdcoeff.ref_vector(particle()-1)(s).reshape(v2k);
1534 const Tensor<T> chunk0=f0.get_svdtensor().ref_vector(particle()-1)(s).reshape(vk);
1535// const double weight=std::abs(coeff.config().weights(r));
1536
1537 // accumulate all terms of the operator for a specific term of the function
1538 Tensor<resultT> result(v2k), result0(vk);
1539
1540 ApplyTerms at;
1541 at.r_term=true;
1542 at.t_term=source.level()>0;
1543
1544 // this loop will return on result and result0 the terms [(P+Q) G (P+Q)]_1,
1545 // and [P G P]_1, respectively
1546 for (int mu=0; mu<rank; ++mu) {
1547 const SeparatedConvolutionInternal<Q,NDIM>& muop = op->muops[mu];
1548 Q fac = ops[mu].getfac();
1549 muopxv_fast(at, muop.ops, chunk, chunk0, result, result0,
1550 tol/std::abs(fac), fac, work1, work2);
1551 }
1552
1553 // reinsert the transformed terms into result, leaving the other particle unchanged
1554 MADNESS_ASSERT(final.get_svdtensor().has_structure());
1555 final.get_svdtensor().ref_vector(particle()-1)(s)=result;
1556
1557 if (source.level()>0) {
1558 final0.get_svdtensor().ref_vector(particle()-1)(s)=result0;
1559 } else {
1560 final0.get_svdtensor().ref_vector(0)(s)=0.0;
1561 final0.get_svdtensor().ref_vector(1)(s)=0.0;
1562 }
1563
1564 }
1565 double cpu1=cpu_time();
1566 timer_low_transf.accumulate(cpu1-cpu0);
1567
1568 double cpu00=cpu_time();
1569
1570 final.reduce_rank(tol2*0.5);
1571 final0.reduce_rank(tol2*0.5);
1572 final(s00)+=final0;
1573 final.reduce_rank(tol2);
1574
1575 double cpu11=cpu_time();
1576 timer_low_accumulate.accumulate(cpu11-cpu00);
1577 return final;
1578 }
1579
1580 /// apply this operator on coefficients in low rank form
1581
1582 /// @param[in] coeff source coeffs in SVD (=optimal!) form
1583 /// @param[in] tol thresh/#neigh*cnorm
1584 /// @param[in] tol2 thresh/#neigh
1585 template <typename T>
1587 const Key<NDIM>& shift,
1588 const GenTensor<T>& coeff,
1589 double tol, double tol2) const {
1591 typedef TENSOR_RESULT_TYPE(T,Q) resultT;
1592
1593 MADNESS_ASSERT(coeff.ndim()==NDIM);
1594 MADNESS_ASSERT(coeff.is_svd_tensor()); // we use the rank below
1595// MADNESS_EXCEPTION("no apply2",1);
1596 const TensorType tt=TT_2D;
1597
1598 const GenTensor<T>* input = &coeff;
1599 GenTensor<T> dummy;
1600
1601 if (not modified()) {
1602 if (coeff.dim(0) == k) {
1603 // This processes leaf nodes with only scaling
1604 // coefficients ... FuncImpl::apply by default does not
1605 // apply the operator to these since for smoothing operators
1606 // it is not necessary. It is necessary for operators such
1607 // as differentiation and time evolution and will also occur
1608 // if the application of the operator widens the tree.
1609 dummy = GenTensor<T>(v2k,TT_2D);
1610 dummy(s0) += coeff;
1611 input = &dummy;
1612 }
1613 else {
1614 MADNESS_ASSERT(coeff.dim(0)==2*k);
1615 }
1616 }
1617
1618 tol = tol/rank; // Error is per separated term
1619 tol2= tol2/rank;
1620
1622
1623 GenTensor<resultT> r, r0, result, result0;
1624 GenTensor<resultT> work1(v2k,tt), work2(v2k,tt);
1625
1626 if (modified()) {
1628 work1=GenTensor<resultT>(vk,tt);
1629 work2=GenTensor<resultT>(vk,tt);
1630 }
1631
1632 // collect the results of the individual operator terms
1633 std::list<GenTensor<T> > r_list;
1634 std::list<GenTensor<T> > r0_list;
1635
1636// const GenTensor<T> f0 = copy(coeff(s0));
1637 const GenTensor<T> f0 = copy((*input)(s0));
1638 for (int mu=0; mu<rank; ++mu) {
1639 const SeparatedConvolutionInternal<Q,NDIM>& muop = op->muops[mu];
1640 //print("muop",source, shift, mu, muop.norm);
1641
1642 // delta(g) < delta(T) * || f ||
1643 if (muop.norm > tol) {
1644
1645 // get maximum rank of coeff to contribute:
1646 // delta(g) < eps < || T || * delta(f)
1647 // delta(coeff) * || T || < tol2
1648 const int r_max=SRConf<T>::max_sigma(tol2/muop.norm,coeff.rank(),coeff.get_svdtensor().weights_);
1649 // print("r_max",coeff.config().weights(r_max));
1650
1651 // note that max_sigma is inclusive!
1652 if (r_max>=0) {
1653 const GenTensor<resultT> chunk=SVDTensor<resultT>(input->get_svdtensor().get_configs(0,r_max));
1654 const GenTensor<resultT> chunk0=SVDTensor<resultT>(f0.get_svdtensor().get_configs(0,r_max));
1655
1656 double cpu0=cpu_time();
1657
1658 Q fac = ops[mu].getfac();
1659 muopxv_fast2(source.level(), muop.ops, chunk, chunk0, r, r0,
1660 tol/std::abs(fac), fac, work1, work2);
1661 double cpu1=cpu_time();
1662 timer_low_transf.accumulate(cpu1-cpu0);
1663
1664 r_list.push_back(r);
1665 r0_list.push_back(r0);
1666 }
1667 }
1668 }
1669
1670 // finally accumulate all the resultant terms into one tensor
1671 double cpu0=cpu_time();
1672
1673 result0=reduce(r0_list,tol2*rank);
1674 if (r_list.size()>0) r_list.front()(s0)+=result0;
1675 result=reduce(r_list,tol2*rank);
1676// result.reduce_rank(tol2*rank);
1677
1678 double cpu1=cpu_time();
1679 timer_low_accumulate.accumulate(cpu1-cpu0);
1680 timer_stats_accumulate.accumulate(result.rank());
1681 return result;
1682 }
1683
1684 /// estimate the ratio of cost of full rank versus low rank
1685
1686 /// @param[in] source source key
1687 /// @param[in] shift displacement
1688 /// @param[in] tol thresh/#neigh/cnorm
1689 /// @param[in] tol2 thresh/#neigh
1690 /// @return cost_ratio r=-1: no terms left
1691 /// 0<r<1: better to do full rank
1692 /// 1<r: better to do low rank
1693 template<typename T>
1695 const Key<NDIM>& shift,
1696 const GenTensor<T>& coeff,
1697 double tol, double tol2) const {
1698
1699 if (coeff.is_full_tensor()) return 0.5;
1700 if (2*NDIM==coeff.ndim()) return 1.5;
1701 MADNESS_ASSERT(NDIM==coeff.ndim());
1703
1705
1706 tol = tol/rank; // Error is per separated term
1707 tol2= tol2/rank;
1708
1709 const double full_operator_cost=pow(coeff.dim(0),NDIM+1);
1710 const double low_operator_cost=pow(coeff.dim(0),NDIM/2+1);
1711 const double low_reduction_cost=pow(coeff.dim(0),NDIM/2);
1712
1713 double full_cost=0.0;
1714 double low_cost=0.0;
1715
1716 long initial_rank=0;
1717 long final_rank=sqrt(coeff.size())*0.05; // size=ncol*nrow; final rank is 5% of max rank
1718
1719 for (int mu=0; mu<rank; ++mu) {
1720 const SeparatedConvolutionInternal<Q,NDIM>& muop = op->muops[mu];
1721
1722 // delta(g) < delta(T) * || f ||
1723 if (muop.norm > tol) {
1724 // note that max_sigma is inclusive: it returns a slice w(Slice(0,i))
1725 long nterms=SRConf<T>::max_sigma(tol2/muop.norm,coeff.rank(),coeff.get_svdtensor().weights_)+1;
1726
1727 // take only the first overlap computation of rank reduction into account
1728// low_cost+=nterms*low_operator_cost + 2.0*nterms*nterms*low_reduction_cost;
1729 initial_rank+=nterms;
1730
1731 full_cost+=full_operator_cost;
1732 }
1733 }
1734 low_cost=initial_rank*low_operator_cost + initial_rank*final_rank*low_reduction_cost;
1735
1736 // include random empirical factor of 2
1737 double ratio=-1.0;
1738 if (low_cost>0.0) ratio=full_cost/low_cost;
1739// print("nterms, full, low, full/low", full_cost, low_cost,shift.distsq(), ratio);
1740 return ratio;
1741
1742 }
1743
1744 /// construct the tensortrain representation of the operator
1745
1746 /// @param[in] source source coefficient box
1747 /// @param[in] shift displacement
1748 /// @param[in] tol threshold for the TT truncation
1749 /// @param[in] do_R compute the R term of the operator (2k^d)
1750 /// @param[in] do_T compute the T term of the operator (k^d), including factor -1
1751 /// Both do_R and do_T may be used simultaneously, then the final
1752 /// operator will have dimensions (2k^d)
1754 const Key<NDIM>& shift, double tol, bool do_R, bool do_T) const {
1755
1756 if (not (do_R or do_T)) {
1757 print("no operator requested in make_tt_representation??");
1758 MADNESS_EXCEPTION("you're sure you know what you're doing?",1);
1759 }
1760
1761
1763
1764 // check for significant ranks since the R/T matrices' construction
1765 // might have been omitted. Tnorm is always smaller than Rnorm
1766 long lo=0,hi=rank;
1767 for (int mu=0; mu<rank; ++mu) {
1768 double Rnorm=1.0;
1769 for (std::size_t d=0; d<NDIM; ++d) Rnorm *= op->muops[mu].ops[d]->Rnorm;
1770 if (Rnorm>1.e-20) hi=mu;
1771 if ((Rnorm<1.e-20) and (mu<hi)) lo=mu;
1772 }
1773 hi++;lo++;
1774
1775 // think about dimensions
1776 long rank_eff=(hi-lo); // R or T matrices
1777 long step=1;
1778 if (do_R and do_T) { // R and T matrices
1779 rank_eff*=2;
1780 step*=2;
1781 }
1782
1783 long k2k=k; // T matrices
1784 if (do_R) k2k=2*k; // R matrices
1785
1786
1787 // construct empty TT cores and fill them with the significant R/T matrices
1788 std::vector<Tensor<double> > cores(NDIM,Tensor<double>(rank_eff,k2k,k2k,rank_eff));
1789 cores[0]=Tensor<double>(k2k,k2k,rank_eff);
1790 cores[NDIM-1]=Tensor<double>(rank_eff,k2k,k2k);
1791
1792
1793 for (int mu=lo, r=0; mu<hi; ++mu, ++r) {
1794 const SeparatedConvolutionInternal<Q,NDIM>& muop = op->muops[mu];
1795 const Q fac = ops[mu].getfac();
1796 const Slice sr0(step*r, step*r, 0);
1797 const Slice sr1(step*r+step-1,step*r+step-1,0);
1798 const Slice s00(0,k-1,1);
1799
1800 if (do_R) {
1801 cores[0](_, _ ,sr0)=muop.ops[0]->R;
1802 for (std::size_t idim=1; idim<NDIM-1; ++idim) {
1803 cores[idim](sr0,_ ,_ ,sr0)=muop.ops[idim]->R;
1804 }
1805 cores[NDIM-1](sr0,_ ,_ )=muop.ops[NDIM-1]->R*fac;
1806 }
1807
1808 if (do_T) {
1809 cores[0](s00,s00,sr1)=muop.ops[0]->T;
1810 for (std::size_t idim=1; idim<NDIM-1; ++idim) {
1811 cores[idim](sr1,s00,s00,sr1)=muop.ops[idim]->T;
1812 }
1813 cores[NDIM-1](sr1,s00,s00)=muop.ops[NDIM-1]->T*(-fac);
1814 }
1815 }
1816
1817 // construct TT representation
1818 TensorTrain<double> tt(cores);
1819
1820 // need to reshape for the TT truncation
1821 tt.make_tensor();
1822 tt.truncate(tol*GenTensor<double>::fac_reduce());
1823 tt.make_operator();
1824
1825 return tt;
1826 }
1827
1828
1830 return (combine_OT(left,right).type!=OT_UNDEFINED);
1831 }
1832
1833 /// return operator type and other info of the combined operator (e.g. fg = f(1,2)* g(1,2)
1835 OperatorInfo info=left.info;
1836 if ((left.info.type==OT_F12) and (right.info.type==OT_G12)) {
1837 info.type=OT_FG12;
1838 } else if ((left.info.type==OT_G12) and (right.info.type==OT_G12)) {
1839 // 1/r · 1/r = 1/r^2
1840 info=right.info;
1841 info.type=OT_INVRSQ;
1842 info.mu=0.0;
1843 } else if ((left.info.type==OT_GAUSS) and (right.info.type==OT_GAUSS)) {
1844 info=right.info;
1845 info.type=OT_GAUSS;
1846 info.mu=2.0*right.info.mu;
1847 } else if ((left.info.type==OT_SLATER) and (right.info.type==OT_SLATER)) {
1848 info=right.info;
1849 info.type=OT_SLATER;
1850 info.mu=2.0*right.info.mu;
1851 } else if ((left.info.type==OT_G12) and (right.info.type==OT_F12)) {
1852 info=right.info;
1853 info.type=OT_FG12;
1854 } else if ((left.info.type==OT_G12) and (right.info.type==OT_F212)) {
1855 info=right.info;
1856 info.type=OT_F2G12;
1857 } else if (((left.info.type==OT_F212) and (right.info.type==OT_G12)) or
1858 ((left.info.type==OT_F12) and (right.info.type==OT_FG12)) or
1859 ((left.info.type==OT_FG12) and (right.info.type==OT_F12))) {
1860 info=right.info;
1861 info.type=OT_F2G12;
1862 if (right.info.type!=OT_G12) MADNESS_CHECK(right.info.mu == left.info.mu);
1863 } else if ((left.info.type==OT_F12) and (right.info.type==OT_F12)) {
1864 info.type=OT_F212;
1865 // keep the original gamma
1866 // (f12)^2 = (1- slater12)^2 = 1/(4 gamma) (1 - 2 exp(-gamma) + exp(-2 gamma))
1867 MADNESS_CHECK(right.info.mu == left.info.mu);
1868 } else {
1869 info.type=OT_UNDEFINED;
1870 }
1871 return info;
1872 }
1873
1874
1875 /// combine 2 convolution operators to one
1876 /// There's some information loss with this constructor - not recommended
1878 const SeparatedConvolution<Q,NDIM>& right) {
1879 MADNESS_CHECK(can_combine(left,right));
1880 MADNESS_CHECK(left.get_world().id()==right.get_world().id());
1881 MADNESS_CHECK(left.lattice_summed() == right.lattice_summed());
1882 // combine_OT takes info from one side or the other depending on the types, so the flag of a
1883 // rest-of-crystal operand would survive or vanish by accident; and the product of a kernel
1884 // restricted to the images with another kernel is not what any of the combined types mean
1885 MADNESS_CHECK_THROW(!left.images_only() && !right.images_only(),
1886 "SeparatedConvolution::combine: a rest-of-crystal operator (OperatorInfo::images_only) cannot be combined");
1887 std::array<LatticeRange, NDIM> lattice_summed;
1888 for (std::size_t i = 0; i < NDIM; ++i) {
1889 if (left.lattice_summed()[i]) lattice_summed[i].set_infinite();
1890 }
1891
1892 auto info=combine_OT(left,right);
1894 }
1895
1896 /// Generic product of two Gaussian expansions: (c, α) tensors only
1897 ///
1898 /// For
1899 /// A(r) = Σ_i cA[i] exp(-αA[i] r²),
1900 /// B(r) = Σ_j cB[j] exp(-αB[j] r²)
1901 /// the exact product is
1902 /// (A·B)(r) = Σ_{i,j} (cA[i] cB[j]) exp(-(αA[i]+αB[j]) r²).
1903 /// Rank before pruning is rank(A)·rank(B). Terms whose contribution
1904 /// |c| · exp(-α lo²) falls below 0.01·thresh are dropped when prune
1905 /// is true.
1906 ///
1907 /// @param[in] cA, aA coefficient / exponent tensors of operator A
1908 /// @param[in] cB, aB coefficient / exponent tensors of operator B
1909 /// @param[in] lo length scale (used only for the pruning bound)
1910 /// @param[in] thresh precision threshold (controls pruning)
1911 /// @param[in] prune enable coefficient-threshold pruning (default on)
1912 /// @return (c, α) tensors of the combined operator
1913 static std::pair<Tensor<Q>, Tensor<double>>
1915 const Tensor<Q>& cB, const Tensor<double>& aB,
1916 double lo, double thresh, bool prune = true) {
1917 MADNESS_CHECK(cA.size() == aA.size());
1918 MADNESS_CHECK(cB.size() == aB.size());
1919 long nA = cA.size(), nB = cB.size();
1920
1921 std::vector<Q> c_keep;
1922 std::vector<double> a_keep;
1923 c_keep.reserve(nA * nB);
1924 a_keep.reserve(nA * nB);
1925 const double cutoff = prune ? (thresh * 1.e-2) : 0.0;
1926 for (long i = 0; i < nA; ++i) {
1927 for (long j = 0; j < nB; ++j) {
1928 Q c = cA[i] * cB[j];
1929 double a = aA[i] + aB[j];
1930 if (prune) {
1931 double contrib = std::abs(c) * std::exp(-a * lo * lo);
1932 if (contrib <= cutoff) continue;
1933 }
1934 c_keep.push_back(c);
1935 a_keep.push_back(a);
1936 }
1937 }
1938 Tensor<Q> c_out(long(c_keep.size()));
1939 Tensor<double> a_out(long(a_keep.size()));
1940 for (size_t k = 0; k < c_keep.size(); ++k) {
1941 c_out[k] = c_keep[k];
1942 a_out[k] = a_keep[k];
1943 }
1944 return {c_out, a_out};
1945 }
1946
1947 /// Generic product of two SepConvs via outer product of their (c, α)
1948 ///
1949 /// Thin wrapper around combine_generic_coeffs that wraps the result
1950 /// into a SeparatedConvolution. The resulting operator has
1951 /// info.type = OT_UNDEFINED; specialized combine rules are preferred
1952 /// where available. See combine_generic_coeffs for semantics.
1953 ///
1954 /// @param[in] world world for the resulting SepConv
1955 /// @param[in] cA, aA operator A's (c, α)
1956 /// @param[in] cB, aB operator B's (c, α)
1957 /// @param[in] lo length scale to pass to the resulting SepConv
1958 /// @param[in] thresh precision of the resulting SepConv
1959 /// @param[in] prune enable coefficient-threshold pruning
1960 /// @return SepConv representing A·B as a sum of Gaussians
1963 const Tensor<Q>& cA, const Tensor<double>& aA,
1964 const Tensor<Q>& cB, const Tensor<double>& aB,
1965 double lo, double thresh, bool prune = true) {
1966 auto [c, a] = combine_generic_coeffs(cA, aA, cB, aB, lo, thresh, prune);
1968 }
1969
1970 /// combine 2 convolution operators to one
1972 const std::shared_ptr<SeparatedConvolution<Q,NDIM>> right) {
1974 if (left and right) {
1975 return combine(*left, *right);
1976 } else if (left) {
1977 return *left;
1978 } else if (right) {
1979 return *right;
1980 } else {
1981 MADNESS_EXCEPTION("can't combine empty SeparatedConvolutions",1);
1982 }
1983 return result;
1984 }
1985 };
1986
1987
1988
1989 /// Factory function generating separated kernel for convolution with 1/r in 3D.
1990 /// N.B. bloch_k species how the function's phase changes as the **operator** translates,
1991 /// which (by translational invariance) is the additive inverse of how the function's
1992 /// phase changes as the **cell** shifts
1993 static
1994 inline
1996 Vector<double,3> bloch_k,
1997 double lo,
1998 double eps,
1999 const std::array<KernelRange, 3>& kernel_ranges = std::array<KernelRange, 3>(),
2000 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2002 return SeparatedConvolution<double_complex, 3>(world, OperatorInfo(0.0, lo, eps, OT_G12, std::nullopt, kernel_ranges),
2003 lattice_ranges, k, false, bloch_k);
2004 }
2005
2006 /// Factory function generating separated kernel for convolution with 1/r in 3D.
2007 /// N.B. bloch_k species how the function's phase changes as the **operator** translates,
2008 /// which (by translational invariance) is the additive inverse of how the function's
2009 /// phase changes as the **cell** shifts
2010 static
2011 inline
2013 Vector<double,3> bloch_k,
2014 double lo,
2015 double eps,
2016 const std::array<KernelRange, 3>& kernel_ranges = std::array<KernelRange, 3>(),
2017 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2019 return new SeparatedConvolution<double_complex, 3>(world, OperatorInfo(0.0, lo, eps, OT_G12, std::nullopt, kernel_ranges),
2020 lattice_ranges, k, false, bloch_k);
2021 }
2022
2023 /// Factory function generating separated kernel for convolution with 1/r in 3D.
2024 static
2025 inline
2027 double lo,
2028 double eps,
2029 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2031 {
2032 return SeparatedConvolution<double,3>(world,OperatorInfo(0.0,lo,eps,OT_G12),lattice_ranges,k);
2033 }
2034
2035
2036 /// Factory function generating separated kernel for convolution with 1/r in 3D.
2037 static
2038 inline
2040 double lo,
2041 double eps,
2042 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2044 {
2045 return new SeparatedConvolution<double,3>(world,OperatorInfo(0.0,lo,eps,OT_G12),lattice_ranges,k);
2046 }
2047
2048
2049 /// Factory function generating separated kernel for convolution with BSH kernel in general NDIM
2050 template <std::size_t NDIM>
2051 static inline
2052 SeparatedConvolution<double,NDIM>
2053 BSHOperator(World& world, double mu, double lo, double eps,
2054 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2056 if (eps>1.e-4) {
2057 if (world.rank()==0) print("the accuracy in BSHOperator is too small, tighten the threshold",eps);
2058 MADNESS_EXCEPTION("0",1);
2059 }
2060 return SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_BSH),lattice_ranges,k);
2061 }
2062
2063 /// Factory function generating separated kernel for convolution with BSH kernel in general NDIM
2064 template <std::size_t NDIM>
2065 static inline
2066 SeparatedConvolution<double,NDIM>*
2067 BSHOperatorPtr(World& world, double mu, double lo, double eps,
2068 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2070 if (eps>1.e-4) {
2071 if (world.rank()==0) print("the accuracy in BSHOperator is too small, tighten the threshold",eps);
2072 MADNESS_EXCEPTION("0",1);
2073 }
2074 return new SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_BSH),lattice_ranges,k);
2075 }
2076
2077
2078 /// Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D
2079 static inline SeparatedConvolution<double,3>
2080 BSHOperator3D(World& world, double mu, double lo, double eps,
2081 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2083 return SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_BSH),lattice_ranges,k);
2084 }
2085
2086 /// Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D
2087 static
2088 inline
2090 Vector<double,3> bloch_k,
2091 double mu,
2092 double lo,
2093 double eps,
2094 const std::array<KernelRange, 3>& kernel_ranges = std::array<KernelRange, 3>(),
2095 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2097
2098 {
2099 return SeparatedConvolution<double_complex, 3>(world, OperatorInfo(mu, lo, eps, OT_BSH, std::nullopt, kernel_ranges),
2100 lattice_ranges, k, false, bloch_k);
2101 }
2102
2103 /// Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D
2104 static inline
2106 Vector<double,3> bloch_k,
2107 double mu,
2108 double lo,
2109 double eps,
2110 const std::array<KernelRange, 3>& kernel_ranges = std::array<KernelRange, 3>(),
2111 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2113
2114 {
2115 return new SeparatedConvolution<double_complex, 3>(world, OperatorInfo(mu, lo, eps, OT_BSH, std::nullopt, kernel_ranges),
2116 lattice_ranges, k, false, bloch_k);
2117 }
2118
2119
2120 static inline SeparatedConvolution<double,3>
2121 SlaterF12Operator(World& world, double mu, double lo, double eps,
2122 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2124 return SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_F12),lattice_ranges,k);
2125 }
2126
2128 double mu, double lo, double eps,
2129 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2131 return SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_F212),lattice_ranges,k);
2132 }
2133
2135 double mu, double lo, double eps,
2136 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2138 return new SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_F212),lattice_ranges,k);
2139 }
2140
2141 /// Factory function generating separated kernel for convolution with exp(-mu*r) in 3D
2142 template<std::size_t NDIM=3>
2144 double mu, double lo, double eps,
2145 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2147 return SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_SLATER),lattice_ranges,k);
2148 }
2149
2150 /// Factory function generating separated kernel for convolution with exp(-mu*r*r)
2151
2152 /// lo and eps are not used here
2153 template<std::size_t NDIM>
2155 double mu, double lo=0.0, double eps=0.0,
2156 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2158 return SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_GAUSS),lattice_ranges,k);
2159 }
2160
2161 /// Factory function generating separated kernel for convolution with exp(-mu*r*r) in 3D
2162
2163 /// lo and eps are not used here
2164 template<std::size_t NDIM>
2166 double mu, double lo=0.0, double eps=0.0,
2167 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2169 return new SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_GAUSS),lattice_ranges,k);
2170 }
2171
2172
2173 /// Factory function generating separated kernel for convolution with exp(-mu*r) in 3D
2174 /// Note that the 1/(2mu) factor of SlaterF12Operator is not included, this is just the exponential function
2175 template<std::size_t NDIM>
2177 double mu, double lo, double eps,
2178 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2180 return new SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_SLATER),lattice_ranges,k);
2181 }
2182
2183 /// Factory function generating separated kernel for convolution with exp(-mu*r) in 3D
2184 /// Note that the 1/(2mu) factor of SlaterF12Operator is not included, this is just the exponential function
2186 double mu, double lo, double eps,
2187 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2188 int k = FunctionDefaults<3>::get_k()) {
2189 return new SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_SLATER),lattice_ranges,k);
2190 }
2191
2192 /// Factory function generating separated kernel for convolution with (1 - exp(-mu*r))/(2 mu) in 3D
2193
2194 /// includes the factor 1/(2 mu)
2196 double mu, double lo, double eps,
2197 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2199 return new SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_F12),lattice_ranges,k);
2200 }
2201
2202 /// Factory function generating separated kernel for convolution with (1 - exp(-mu*r))/(2 mu) in ND
2203
2204 /// includes the factor 1/(2 mu)
2205 template<std::size_t NDIM>
2207 double mu, double lo, double eps,
2208 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2210 return new SeparatedConvolution<double,NDIM>(world,OperatorInfo(mu,lo,eps,OT_F12),lattice_ranges,k);
2211 }
2212
2213 /// Factory function generating separated kernel for convolution with 1/(2 mu)*(1 - exp(-mu*r))/r in 3D
2214
2215 /// fg = (1 - exp(-gamma r12)) / r12 = 1/r12 - exp(-gamma r12)/r12 = coulomb - bsh
2216 /// includes the factor 1/(2 mu)
2217 static inline SeparatedConvolution<double,3>
2218 FGOperator(World& world, double mu, double lo, double eps,
2219 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2221 return SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_FG12),lattice_ranges,k);
2222 }
2223
2224 /// Factory function generating separated kernel for convolution with 1/(2 mu)*(1 - exp(-mu*r))/r in 3D
2225
2226 /// fg = (1 - exp(-gamma r12)) / r12 = 1/r12 - exp(-gamma r12)/r12 = coulomb - bsh
2227 /// includes the factor 1/(2 mu)
2228 static inline SeparatedConvolution<double,3>*
2229 FGOperatorPtr(World& world, double mu, double lo, double eps,
2230 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2232 return new SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_FG12),lattice_ranges,k);
2233 }
2234
2235 /// Factory function generating separated kernel for convolution with (1/(2 mu)*(1 - exp(-mu*r)))^2/r in 3D
2236
2237 /// f2g = (1/(2 gamma) (1 - exp(-gamma r12)))^2 / r12
2238 /// = 1/(4 gamma) * [ 1/r12 - 2 exp(-gamma r12)/r12 + exp(-2 gamma r12)/r12 ]
2239 /// includes the factor 1/(2 mu)^2
2240 static inline SeparatedConvolution<double,3>*
2241 F2GOperatorPtr(World& world, double mu, double lo, double eps,
2242 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2244 return new SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_F2G12),lattice_ranges,k);
2245 }
2246
2247 /// Factory function generating separated kernel for convolution with (1/(2 mu)*(1 - exp(-mu*r)))^2/r in 3D
2248
2249 /// f2g = (1/(2 gamma) (1 - exp(-gamma r12)))^2 / r12
2250 /// = 1/(4 gamma) * [ 1/r12 - 2 exp(-gamma r12)/r12 + exp(-2 gamma r12)/r12 ]
2251 /// includes the factor 1/(2 mu)^2
2252 static inline SeparatedConvolution<double,3>
2253 F2GOperator(World& world, double mu, double lo, double eps,
2254 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2256 return SeparatedConvolution<double,3>(world,OperatorInfo(mu,lo,eps,OT_F2G12),lattice_ranges,k);
2257 }
2258
2259
2260 /// Factory function generating separated kernel for convolution a normalized
2261 /// Gaussian (aka a widened delta function)
2263 double eps,
2264 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2266
2267 double exponent = 1.0/(2.0*eps);
2268 Tensor<double> coeffs(1), exponents(1);
2269 exponents(0L) = exponent;
2270 coeffs(0L)=pow(exponent/M_PI,0.5*3.0); // norm of the gaussian
2271 return SeparatedConvolution<double,3>(world, coeffs, exponents, 1.e-8, eps, lattice_ranges, k);
2272 }
2273
2274 /// Factory function generating separated kernel for convolution a normalized
2275 /// Gaussian (aka a widened delta function)
2276 template<std::size_t NDIM>
2278 double eps,
2279 const std::array<LatticeRange, NDIM>& lattice_ranges = FunctionDefaults<NDIM>::get_bc().lattice_range(),
2281
2282 double exponent = 1.0/(2.0*eps);
2283 Tensor<double> coeffs(1), exponents(1);
2284 exponents(0L) = exponent;
2285 coeffs(0L)=pow(exponent/M_PI,0.5*NDIM); // norm of the gaussian
2286 return SeparatedConvolution<double,NDIM>(world, coeffs, exponents, 1.e-8, eps, lattice_ranges, k);
2287 }
2288
2289 /// Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D
2290 static
2291 inline
2293 double mu,
2294 double lo,
2295 double eps,
2296 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2299 double hi = cell_width.normf(); // Diagonal width of cell
2300 // Extend kernel range for lattice summation
2301 // N.B. if have periodic boundaries, extend range just in case will be using periodic domain
2302 const auto lattice_summed_any = std::any_of(lattice_ranges.begin(), lattice_ranges.end(), [](const auto& b) { return static_cast<bool>(b);});
2303 const auto infinite_any = std::any_of(lattice_ranges.begin(), lattice_ranges.end(), [](const auto& b) { return b.infinite();});
2304 const double hi_fin = lattice_finite_reach(lattice_ranges, cell_width);
2305 if (lattice_summed_any) {
2306 hi *= 100;
2307 }
2308
2309 GFit<double, 3> fit = GFit<double, 3>::BSHFit(mu, lo, hi, eps, false);
2310 Tensor<double> coeff = fit.coeffs();
2311 Tensor<double> expnt = fit.exponents();
2312
2313 if (infinite_any) {
2314 fit.truncate_mixed_expansion(coeff, expnt, lattice_ranges, cell_width, lo, hi_fin, eps);
2315 }
2316 return new SeparatedConvolution<double, 3>(world, coeff, expnt, lo, eps,
2317 lattice_ranges, k);
2318 }
2319
2320
2321 /// Factory function generating operator for convolution with grad(1/r) in 3D
2322
2323 /// Returns a 3-vector containing the convolution operator for the
2324 /// x, y, and z components of grad(1/r)
2325 static
2326 inline
2327 std::vector< std::shared_ptr< SeparatedConvolution<double,3> > >
2329 double lo,
2330 double eps,
2331 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2334 typedef std::shared_ptr<real_convolution_3d> real_convolution_3d_ptr;
2335 const double pi = constants::pi;
2337 double hi = width.normf(); // Diagonal width of cell
2338 // Extend kernel range for lattice summation
2339 const auto lattice_sum_any = std::any_of(lattice_ranges.begin(), lattice_ranges.end(), [](const LatticeRange& b){ return static_cast<bool>(b); });
2340 const auto infinite_any = std::any_of(lattice_ranges.begin(), lattice_ranges.end(), [](const LatticeRange& b){ return b.infinite(); });
2341 if (lattice_sum_any) {
2342 hi *= 100;
2343 }
2344
2346 Tensor<double> coeff = fit.coeffs();
2347 Tensor<double> expnt = fit.exponents();
2348
2349 if (infinite_any) {
2350 fit.truncate_mixed_expansion(coeff, expnt, lattice_ranges, width, lo, lattice_finite_reach(lattice_ranges, width), eps);
2351 }
2352
2353 int rank = coeff.dim(0);
2354
2355 std::vector<real_convolution_3d_ptr> gradG(3);
2356
2357 for (int dir = 0; dir < 3; dir++) {
2358 std::vector<ConvolutionND<double, 3>> ops(rank);
2359 for (int mu = 0; mu < rank; mu++) {
2360 // We cache the normalized operator so the factor is the value we must multiply by to recover the coeff we want.
2361 double c = std::pow(sqrt(expnt(mu) / pi), 3); // Normalization coeff
2362 ops[mu].setfac(coeff(mu) / c / width[dir]);
2363
2364 for (int d = 0; d < 3; d++) {
2365 if (d != dir)
2367 k, expnt(mu) * width[d] * width[d], 0,
2368 lattice_ranges[d]));
2369 }
2371 k, expnt(mu) * width[dir] * width[dir], 1,
2372 lattice_ranges[dir]));
2373 }
2375 new SeparatedConvolution<double, 3>(world, ops));
2376 }
2377
2378 return gradG;
2379 }
2380
2381 /// Factory function generating operator for convolution with grad(bsh) in 3D
2382
2383 /// Returns a 3-vector containing the convolution operator for the
2384 /// x, y, and z components of grad(bsh)
2385 static
2386 inline
2387 std::vector< std::shared_ptr< SeparatedConvolution<double,3> > >
2389 double mu,
2390 double lo,
2391 double eps,
2392 const std::array<LatticeRange, 3>& lattice_ranges = FunctionDefaults<3>::get_bc().lattice_range(),
2395 typedef std::shared_ptr<real_convolution_3d> real_convolution_3d_ptr;
2396 const double pi = constants::pi;
2398 double hi = width.normf(); // Diagonal width of cell
2399 // Extend kernel range for lattice summation
2400 bool lattice_sum_any = std::any_of(lattice_ranges.begin(), lattice_ranges.end(), [](const LatticeRange& b){ return b.get_range(); });
2401 const auto infinite_any = std::any_of(lattice_ranges.begin(), lattice_ranges.end(), [](const LatticeRange& b){ return b.infinite(); });
2402 if (lattice_sum_any) {
2403 hi *= 100;
2404 }
2405
2406 GFit<double, 3> fit = GFit<double, 3>::BSHFit(mu, lo, hi, eps, false);
2407 Tensor<double> coeff = fit.coeffs();
2408 Tensor<double> expnt = fit.exponents();
2409
2410 if (infinite_any) {
2411 fit.truncate_mixed_expansion(coeff, expnt, lattice_ranges, width, lo, lattice_finite_reach(lattice_ranges, width), eps);
2412 }
2413
2414 int rank = coeff.dim(0);
2415
2416 std::vector<real_convolution_3d_ptr> gradG(3);
2417
2418 for (int dir = 0; dir < 3; dir++) {
2419 std::vector<ConvolutionND<double, 3>> ops(rank);
2420 for (int mu = 0; mu < rank; mu++) {
2421 // We cache the normalized operator so the factor is the value we must multiply by to recover the coeff we want.
2422 double c = std::pow(sqrt(expnt(mu) / pi), 3); // Normalization coeff
2423 ops[mu].setfac(coeff(mu) / c / width[dir]);
2424
2425 for (int d = 0; d < 3; d++) {
2426 if (d != dir)
2428 k, expnt(mu) * width[d] * width[d], 0,
2429 lattice_ranges[d]));
2430 }
2432 k, expnt(mu) * width[dir] * width[dir], 1,
2433 lattice_ranges[dir]));
2434 }
2436 new SeparatedConvolution<double, 3>(world, ops));
2437 }
2438
2439 return gradG;
2440 }
2441
2442
2443
2444 namespace archive {
2445 template <class Archive, class T, std::size_t NDIM>
2446 struct ArchiveLoadImpl<Archive,const SeparatedConvolution<T,NDIM>*> {
2447 static inline void load(const Archive& ar, const SeparatedConvolution<T,NDIM>*& ptr) {
2449 ar & p;
2450 ptr = static_cast< const SeparatedConvolution<T,NDIM>* >(p);
2451 }
2452 };
2453
2454 template <class Archive, class T, std::size_t NDIM>
2455 struct ArchiveStoreImpl<Archive,const SeparatedConvolution<T,NDIM>*> {
2456 static inline void store(const Archive& ar, const SeparatedConvolution<T,NDIM>*const& ptr) {
2457 ar & static_cast< const WorldObject< SeparatedConvolution<T,NDIM> >* >(ptr);
2458 }
2459 };
2460 }
2461
2462}
2463
2464
2465
2466
2467#endif // MADNESS_MRA_OPERATOR_H__INCLUDED
double w(double t, double eps)
Definition DKops.h:22
double q(double t)
Definition DKops.h:18
Provides routines for internal use optimized for aligned data.
long dim(int i) const
Returns the size of dimension i.
Definition basetensor.h:147
long ndim() const
Returns the number of dimensions in the tensor.
Definition basetensor.h:144
long size() const
Returns the number of elements in the tensor.
Definition basetensor.h:138
a 6D function, either in full or low rank form, possibly including an 2-particle function
Definition ccpairfunction.h:373
Provides the common functionality/interface of all 1D convolutions.
Definition convolution1d.h:273
Array of 1D convolutions (one / dimension).
Definition convolution1d.h:612
void setop(int dim, const std::shared_ptr< Convolution1D< Q > > &op)
Definition convolution1d.h:629
void setfac(Q value)
Definition convolution1d.h:637
Holds displacements for applying operators to avoid replicating for all operators.
Definition displacements.h:80
const std::vector< Key< NDIM > > & get_disp(Level n, const array_of_bools< NDIM > &kernel_lattice_sum_axes)
Definition displacements.h:352
const std::vector< Key< NDIM > > & get_disp_images(Level n, const array_of_bools< NDIM > &kernel_lattice_sum_axes)
Definition displacements.h:371
FunctionCommonData holds all Function data common for given k.
Definition function_common_data.h:52
static int get_k()
Returns the default wavelet order.
Definition funcdefaults.h:170
static const Tensor< double > & get_cell_width()
Returns the width of each user cell dimension.
Definition funcdefaults.h:390
static const BoundaryConditions< NDIM > & get_bc()
Returns the default boundary conditions.
Definition funcdefaults.h:315
A multiresolution adaptive numerical function.
Definition mra.h:141
Definition gfit.h:59
static GFit BSHFit(double mu, double lo, double hi, double eps, bool prnt=false)
return a fit for the bound-state Helmholtz function
Definition gfit.h:179
static GFit CoulombFit(double lo, double hi, double eps, bool prnt=false)
return a fit for the Coulomb function
Definition gfit.h:105
Definition lowranktensor.h:59
long dim(const int i) const
return the number of entries in dimension i
Definition lowranktensor.h:391
long ndim() const
Definition lowranktensor.h:386
constexpr bool is_full_tensor() const
Definition gentensor.h:224
void reduce_rank(const double &)
Definition gentensor.h:217
long rank() const
Definition gentensor.h:212
long size() const
Definition lowranktensor.h:490
SVDTensor< T > & get_svdtensor()
Definition gentensor.h:228
const BaseTensor * ptr() const
might return a NULL pointer!
Definition lowranktensor.h:717
static double fac_reduce()
return the additional safety for rank reduction
Definition gentensor.h:241
IsSupported< TensorTypeData< Q >, GenTensor< T > & >::type scale(Q fac)
Inplace multiplication by scalar of supported type (legacy name).
Definition lowranktensor.h:428
constexpr bool is_svd_tensor() const
Definition gentensor.h:222
Key is the index for a node of the 2^NDIM-tree.
Definition key.h:71
Key< NDIM+LDIM > merge_with(const Key< LDIM > &rhs) const
merge with other key (ie concatenate), use level of rhs, not of this
Definition key.h:563
const Vector< Translation, NDIM > & translation() const
Definition key.h:175
void break_apart(Key< LDIM > &key1, Key< KDIM > &key2) const
break key into two low-dimensional keys
Definition key.h:500
Denotes lattice summation over range [-N, N]; N=0 is equivalent to including the simulation cell only...
Definition kernelrange.h:17
Tensor< T > & ref_vector(const unsigned int &idim)
return reference to one of the vectors F
Definition srconf.h:538
int dim_per_vector(int idim) const
return the number of physical dimensions
Definition srconf.h:673
static int max_sigma(const double &thresh, const long &rank, const Tensor< double > &w)
Definition srconf.h:109
Definition SVDTensor.h:42
Definition operator.h:158
double norm_bound(Level n, const Key< NDIM > &source_key) const
Definition operator.h:1302
SeparatedConvolution(World &world, const Tensor< Q > &coeff, const Tensor< double > &expnt, double lo, double thresh, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k(), bool doleaves=false, double mu=0.0)
Constructor for Gaussian Convolutions (mostly for backward compatability).
Definition operator.h:1184
Timer timer_low_transf
Definition operator.h:192
bool destructive_
Definition operator.h:186
GenTensor< TENSOR_RESULT_TYPE(T, Q)> apply2(const Key< NDIM > &source, const Key< NDIM > &shift, const GenTensor< T > &coeff, double tol, double tol2) const
apply this operator on coefficients in low rank form
Definition operator.h:1586
std::array< KernelRange, NDIM > range
Definition operator.h:181
const array_of_bools< NDIM > & lattice_summed() const
Definition operator.h:1278
Tensor< double > stored_coeffs
Definition operator.h:169
int particle_
Definition operator.h:185
void muopxv_fast2(Level n, const ConvolutionData1D< Q > *const ops_1d[NDIM], const GenTensor< T > &f, const GenTensor< T > &f0, GenTensor< TENSOR_RESULT_TYPE(T, Q)> &result, GenTensor< TENSOR_RESULT_TYPE(T, Q)> &result0, double tol, const Q mufac, GenTensor< TENSOR_RESULT_TYPE(T, Q)> &work1, GenTensor< TENSOR_RESULT_TYPE(T, Q)> &work2) const
Apply one of the separated terms, accumulating into the result.
Definition operator.h:601
const double & gamma() const
Definition operator.h:227
GenTensor< TENSOR_RESULT_TYPE(T, Q)> apply2_lowdim(const Key< NDIM > &source, const Key< NDIM > &shift, const GenTensor< T > &coeff, double tol, double tol2) const
apply this operator on only 1 particle of the coefficients in low rank form
Definition operator.h:1490
std::vector< ConvolutionND< double, NDIM > > ops
Definition operator.h:199
Function< TENSOR_RESULT_TYPE(T, Q), LDIM+LDIM > operator()(const Function< T, LDIM > &f1, const Function< Q, LDIM > &f2) const
apply this operator on a separable function f(1,2) = f(1) f(2)
Definition operator.h:1375
const SeparatedConvolutionData< Q, NDIM > * getop(Level n, const Key< NDIM > &d, const Key< NDIM > &source) const
get the data for all terms and all dimensions for one displacement
Definition operator.h:836
void set_domain_periodicity(const array_of_bools< NDIM > &domain_is_periodic)
Definition operator.h:1284
const double & mu() const
Definition operator.h:228
double munorm2(Level n, const ConvolutionData1D< Q > *ops[]) const
Definition operator.h:688
const bool & destructive() const
Definition operator.h:225
Timer timer_stats_accumulate
Definition operator.h:194
static SeparatedConvolution< Q, NDIM > combine_generic(World &world, const Tensor< Q > &cA, const Tensor< double > &aA, const Tensor< Q > &cB, const Tensor< double > &aB, double lo, double thresh, bool prune=true)
Definition operator.h:1962
SimpleCache< SeparatedConvolutionData< double, NDIM >, NDIM > data
Definition operator.h:208
std::enable_if< FDIM!=NDIM, Key< NDIM > >::type get_source_key(const Key< FDIM > key) const
return that part of a hi-dim key that serves as the base for displacements of this operator
Definition operator.h:1329
double munorm2_ns(Level n, const ConvolutionData1D< Q > *ops[]) const
Definition operator.h:696
std::enable_if< FDIM==NDIM, Key< NDIM > >::type get_source_key(const Key< FDIM > key) const
return that part of a hi-dim key that serves as the base for displacements of this operator
Definition operator.h:1346
static FitCoeffs make_coeff_for_operator(World &world, OperatorInfo &info, const std::array< LatticeRange, NDIM > &lattice_ranges)
Definition operator.h:260
virtual ~SeparatedConvolution()
Definition operator.h:1228
void muopxv_fast(ApplyTerms at, const ConvolutionData1D< Q > *const ops_1d[NDIM], const Tensor< T > &f, const Tensor< T > &f0, Tensor< TENSOR_RESULT_TYPE(T, Q)> &result, Tensor< TENSOR_RESULT_TYPE(T, Q)> &result0, const double tol, const Q mufac, Tensor< TENSOR_RESULT_TYPE(T, Q)> &work1, Tensor< TENSOR_RESULT_TYPE(T, Q)> &work2) const
Apply one of the separated terms, accumulating into the result.
Definition operator.h:490
SimpleCache< SeparatedConvolutionData< double, NDIM >, 2 *NDIM > mod_data
Definition operator.h:209
argT operator()(const argT &argument) const
apply this onto another suitable argument, returning the same type
Definition operator.h:1395
Timer timer_full
Definition operator.h:191
const array_of_bools< NDIM > & func_domain_is_periodic() const
Definition operator.h:1281
SeparatedConvolution< Q, NDIM > & set_particle(const int p)
Definition operator.h:218
bool images_only_
Definition operator.h:180
SeparatedConvolution(World &world, const std::vector< std::shared_ptr< Convolution1D< Q > > > &argops, long k=FunctionDefaults< NDIM >::get_k(), bool doleaves=false)
Definition operator.h:1029
Function< TENSOR_RESULT_TYPE(T, Q), LDIM+LDIM > operator()(const std::vector< Function< T, LDIM > > &f1, const std::vector< Function< Q, LDIM > > &f2) const
apply this operator on a sum of separable functions f(1,2) = \sum_i f_i(1) f_i(2)
Definition operator.h:1387
void init_lattice_summed()
Definition operator.h:1002
double opT
Definition operator.h:161
void initialize(const Tensor< Q > &coeff, const Tensor< double > &expnt, std::array< LatticeRange, NDIM > lattice_range, std::array< KernelRange, NDIM > range={}, const Vector< double, NDIM > &bloch_k=Vector< double, NDIM >(0.0))
Definition operator.h:1210
const SeparatedConvolutionInternal< Q, NDIM > getmuop(int mu, Level n, const Key< NDIM > &disp) const
get the transformation matrices for 1 term and all dimensions and one displacement
Definition operator.h:780
const SeparatedConvolutionData< Q, NDIM > * getop_ns(Level n, const Key< NDIM > &d) const
get the data for all terms and all dimensions for one displacement
Definition operator.h:850
const std::vector< long > v2k
Definition operator.h:204
static std::pair< Tensor< Q >, Tensor< double > > combine_generic_coeffs(const Tensor< Q > &cA, const Tensor< double > &aA, const Tensor< Q > &cB, const Tensor< double > &aB, double lo, double thresh, bool prune=true)
Definition operator.h:1914
const std::array< KernelRange, NDIM > & get_range() const
Definition operator.h:232
int get_rank() const
Definition operator.h:229
Function< TENSOR_RESULT_TYPE(T, Q), FDIM > operator()(const Function< T, FDIM > &f) const
apply this operator on a function f
Definition operator.h:1358
bool doleaves
Definition operator.h:172
void print_timer() const
Definition operator.h:1230
SeparatedConvolution(World &world, const std::vector< ConvolutionND< Q, NDIM > > &argops, long k=FunctionDefaults< NDIM >::get_k(), bool doleaves=false)
Definition operator.h:1058
const std::vector< Key< NDIM > > & get_disp(Level n) const
Definition operator.h:1248
void apply_transformation3(const Tensor< T > trans2[NDIM], const Tensor< T > &f, const Q mufac, Tensor< R > &result) const
accumulate into result
Definition operator.h:413
static SeparatedConvolution< Q, NDIM > combine(const SeparatedConvolution< Q, NDIM > &left, const SeparatedConvolution< Q, NDIM > &right)
Definition operator.h:1877
const std::vector< long > vk
Definition operator.h:203
double norm(Level n, const Key< NDIM > &d, const Key< NDIM > &source_key) const
Definition operator.h:1287
TensorTrain< double > make_tt_representation(const Key< NDIM > &source, const Key< NDIM > &shift, double tol, bool do_R, bool do_T) const
construct the tensortrain representation of the operator
Definition operator.h:1753
void reset_timer() const
Definition operator.h:1238
static OperatorInfo combine_OT(const SeparatedConvolution< Q, NDIM > &left, const SeparatedConvolution< Q, NDIM > &right)
return operator type and other info of the combined operator (e.g. fg = f(1,2)* g(1,...
Definition operator.h:1834
GenTensor< T > upsample(const Key< FDIM > &key, const GenTensor< T > &coeff) const
upsample the sum coefficients of level 1 to sum coeffs on level n+1
Definition operator.h:972
bool print_timings
Definition operator.h:187
Timer timer_low_accumulate
Definition operator.h:193
double estimate_costs(const Key< NDIM > &source, const Key< NDIM > &shift, const GenTensor< T > &coeff, double tol, double tol2) const
estimate the ratio of cost of full rank versus low rank
Definition operator.h:1694
bool range_restricted() const
Definition operator.h:233
int get_k() const
Definition operator.h:230
Tensor< TENSOR_RESULT_TYPE(T, Q)> apply(const Key< NDIM > &source, const Key< NDIM > &shift, const Tensor< T > &coeff, double tol) const
apply this operator on coefficients in full rank form
Definition operator.h:1408
double displacement_real_distsq(const Key< NDIM > &displacement) const
Definition operator.h:1264
const std::vector< Slice > s0
Definition operator.h:205
array_of_bools< NDIM > lattice_summed_
Definition operator.h:176
void apply_transformation2(Level n, long dimk, double tol, const Tensor< T > trans2[NDIM], const GenTensor< T > &f, GenTensor< R > &work1, GenTensor< R > &work2, const Q mufac, GenTensor< R > &result) const
don't accumulate, since we want to do this at apply()
Definition operator.h:430
const int & particle() const
Definition operator.h:217
std::vector< Function< TENSOR_RESULT_TYPE(T, Q), FDIM > > operator()(const std::vector< Function< T, FDIM > > &f) const
apply this on a vector of functions
Definition operator.h:1364
const bool & modified() const
Definition operator.h:214
const FunctionCommonData< double, NDIM > & cdata
Definition operator.h:201
bool & modified()
Definition operator.h:213
const int k
Definition operator.h:200
friend SeparatedConvolution< Q, NDIM > combine(const std::shared_ptr< SeparatedConvolution< Q, NDIM > > left, const std::shared_ptr< SeparatedConvolution< Q, NDIM > > right)
combine 2 convolution operators to one
Definition operator.h:1971
OperatorInfo info
Definition operator.h:163
Key< NDIM > keyT
Definition operator.h:189
void init_range()
Definition operator.h:989
static const size_t opdim
Definition operator.h:190
bool & destructive()
Definition operator.h:224
void apply_transformation(long dimk, const Transformation trans[NDIM], const Tensor< T > &f, Tensor< R > &work1, Tensor< R > &work2, const Q mufac, Tensor< R > &result) const
Definition operator.h:362
void check_cubic()
Definition operator.h:911
void initialize_images_only(const Tensor< Q > &coeff, const Tensor< double > &expnt, const Tensor< double > &dropped_coeff, const Tensor< double > &dropped_expnt, const std::array< LatticeRange, NDIM > &lattice_range, const std::array< KernelRange, NDIM > &range, const Vector< double, NDIM > &bloch_k)
the rest-of-crystal operator: the lattice sum with the home cell (L = 0) removed
Definition operator.h:1137
bool modified_
Definition operator.h:184
int rank
Definition operator.h:202
SeparatedConvolution(World &world, const OperatorInfo info1, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k(), bool doleaves=false, const Vector< double, NDIM > &bloch_k=Vector< double, NDIM >(0.0))
Definition operator.h:1084
GenTensor< T > partial_upsample(const Key< FDIM > &key, const GenTensor< T > &coeff, const int particle) const
upsample some of the dimensions of coeff to its child indicated by key
Definition operator.h:929
double munorm2_modified(Level n, const ConvolutionData1D< Q > *ops_1d[]) const
Definition operator.h:717
int & particle()
Definition operator.h:216
static bool can_combine(const SeparatedConvolution< Q, NDIM > &left, const SeparatedConvolution< Q, NDIM > &right)
Definition operator.h:1829
const std::vector< ConvolutionND< Q, NDIM > > & get_ops() const
Definition operator.h:231
std::uint64_t displacement_distsq(const Key< NDIM > &displacement) const
Definition operator.h:1272
Tensor< double > stored_exponents
Definition operator.h:170
const SeparatedConvolutionData< Q, NDIM > * getop_modified(Level n, const Key< NDIM > &disp, const Key< NDIM > &source) const
get the data for all terms and all dimensions for one displacement (modified NS form)
Definition operator.h:883
bool images_only() const
Definition operator.h:1254
array_of_bools< NDIM > func_domain_is_periodic_
Definition operator.h:178
const SeparatedConvolutionInternal< Q, NDIM > getmuop_modified(int mu, Level n, const Key< NDIM > &disp, const Key< NDIM > &source) const
get the transformation matrices for 1 term and all dimensions and one displacement
Definition operator.h:809
Simplified interface around hash_map to cache stuff for 1D.
Definition simplecache.h:46
A slice defines a sub-range or patch of a dimension.
Definition slice.h:103
Definition tensortrain.h:123
A tensor is a multidimensional array.
Definition tensor.h:313
float_scalar_type normf() const
Returns the Frobenius norm of the tensor.
Definition tensor.h:1731
T * ptr()
Returns a pointer to the internal data.
Definition tensor.h:1845
IsSupported< TensorTypeData< Q >, Tensor< T > & >::type scale(Q x)
Inplace multiplication by scalar of supported type (legacy name).
Definition tensor.h:691
Definition function_common_data.h:169
void print(std::string line="") const
print timer
Definition function_common_data.h:216
void reset() const
Definition function_common_data.h:210
A simple, fixed dimension vector.
Definition vector.h:64
Implements most parts of a globally addressable object (via unique ID).
Definition world_object.h:491
WorldObject(const WorldObject &other)
Definition world_object.h:500
void process_pending()
Definition world_object.h:787
A parallel world class.
Definition world.h:134
ProcessID rank() const
Returns the process rank in this World (same as MPI_Comm_rank()).
Definition world.h:344
unsigned long id() const
Definition world.h:324
syntactic sugar for std::array<bool, N>
Definition array_of_bools.h:19
Defines common mathematical and physical constants.
Computes most matrix elements over 1D operators (including Gaussians).
static const double R
Definition csqrt.cc:46
double(* f1)(const coord_3d &)
Definition derivatives.cc:55
char * p(char *buf, const char *name, int k, int initial_level, double thresh, int order)
Definition derivatives.cc:72
double(* f2)(const coord_3d &)
Definition derivatives.cc:56
static double lo
Definition dirac-hatom.cc:23
static double shift
Definition dirac-hatom.cc:19
fit isotropic functions to a set of Gaussians with controlled precision
static const double v
Definition hatom_sf_dirac.cc:20
Tensor< double > op(const Tensor< double > &x)
Definition kain.cc:508
static double pow(const double *a, const double *b)
Definition lda.h:74
#define max(a, b)
Definition lda.h:51
#define MADNESS_RESTRICT
Definition mTxmq.h:37
#define MADNESS_CHECK(condition)
Check a condition — even in a release build the condition is always evaluated so it can have side eff...
Definition madness_exception.h:182
#define MADNESS_EXCEPTION(msg, value)
Macro for throwing a MADNESS exception.
Definition madness_exception.h:119
#define MADNESS_ASSERT(condition)
Assert a condition that should be free of side-effects since in release builds this might be a no-op.
Definition madness_exception.h:134
#define MADNESS_CHECK_THROW(condition, msg)
Check a condition — even in a release build the condition is always evaluated so it can have side eff...
Definition madness_exception.h:207
constexpr double pi
Mathematical constant .
Definition constants.h:48
Namespace for all elements and tools of MADNESS.
Definition DFConvergence.h:9
static SeparatedConvolution< double, 3 > SlaterF12Operator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:2121
static SeparatedConvolution< double_complex, 3 > PeriodicBSHOperator3D(World &world, Vector< double, 3 > bloch_k, double mu, double lo, double eps, const std::array< KernelRange, 3 > &kernel_ranges=std::array< KernelRange, 3 >(), const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D.
Definition operator.h:2089
double FunctionDefaults< NDIM >::thresh
Definition mraimpl.h:3879
double lattice_finite_reach(const std::array< LatticeRange, NDIM > &lattice_ranges, const Tensor< double > &cell_width)
Convolutions in separated form (including Gaussian).
Definition operator.h:144
std::shared_ptr< real_convolution_3d > real_convolution_3d_ptr
Definition functypedefs.h:150
static double cpu_time()
Returns the cpu time in seconds relative to an arbitrary origin.
Definition timers.h:128
SeparatedConvolution< double, 3 > real_convolution_3d
Definition functypedefs.h:136
GenTensor< TENSOR_RESULT_TYPE(R, Q)> general_transform(const GenTensor< R > &t, const Tensor< Q > c[])
Definition gentensor.h:274
void fast_transpose(long n, long m, const T *a, T *MADNESS_RESTRICT b)
a(n,m) --> b(m,n) ... optimized for smallish matrices
Definition convolution1d.h:71
static SeparatedConvolution< double, NDIM > SmoothingOperator(World &world, double eps, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Definition operator.h:2277
int FunctionDefaults< NDIM >::k
Definition mraimpl.h:3878
static SeparatedConvolution< double, 3 > F2GOperator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with (1/(2 mu)*(1 - exp(-mu*r)))^2/r in ...
Definition operator.h:2253
static SeparatedConvolution< double, 3 > CoulombOperator(World &world, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with 1/r in 3D.
Definition operator.h:2026
static SeparatedConvolution< double_complex, 3 > * PeriodicHFExchangeOperatorPtr(World &world, Vector< double, 3 > bloch_k, double lo, double eps, const std::array< KernelRange, 3 > &kernel_ranges=std::array< KernelRange, 3 >(), const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:2012
static SeparatedConvolution< double, NDIM > * BSHOperatorPtr(World &world, double mu, double lo, double eps, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Factory function generating separated kernel for convolution with BSH kernel in general NDIM.
Definition operator.h:2067
static SeparatedConvolution< double, 3 > * F2GOperatorPtr(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with (1/(2 mu)*(1 - exp(-mu*r)))^2/r in ...
Definition operator.h:2241
int64_t Translation
Definition key.h:59
Key< NDIM > displacement(const Key< NDIM > &source, const Key< NDIM > &target)
given a source and a target, return the displacement in translation
Definition key.h:609
static SeparatedConvolution< double, 3 > * SlaterOperatorPtr(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:2185
static SeparatedConvolution< double, 3 > SlaterF12sqOperator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:2127
static SeparatedConvolution< double, 3 > SmoothingOperator3D(World &world, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:2262
static SeparatedConvolution< double, NDIM > * SlaterOperatorPtr_ND(World &world, double mu, double lo, double eps, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Definition operator.h:2176
Function< T, NDIM > sum(World &world, const std::vector< Function< T, NDIM > > &f, bool fence=true)
Returns new function — q = sum_i f[i].
Definition vmra.h:1774
static const Slice _(0,-1, 1)
static SeparatedConvolution< double, 3 > * SlaterF12OperatorPtr(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with (1 - exp(-mu*r))/(2 mu) in 3D.
Definition operator.h:2195
int Level
Definition key.h:60
@ OT_FG12
1-exp(-r)
Definition operatorinfo.h:18
@ OT_SLATER
1/r
Definition operatorinfo.h:15
@ OT_GAUSS
exp(-r)
Definition operatorinfo.h:16
@ OT_BSH
(1-exp(-r))^2/r = 1/r + exp(-2r)/r - 2 exp(-r)/r
Definition operatorinfo.h:21
@ OT_INVRSQ
exp(-r)/r
Definition operatorinfo.h:22
@ OT_F12
exp(-r2)
Definition operatorinfo.h:17
@ OT_F212
(1-exp(-r))/r
Definition operatorinfo.h:19
@ OT_UNDEFINED
Definition operatorinfo.h:12
@ OT_G12
indicates the identity
Definition operatorinfo.h:14
@ OT_F2G12
(1-exp(-r))^2
Definition operatorinfo.h:20
static SeparatedConvolution< double_complex, 3 > PeriodicHFExchangeOperator(World &world, Vector< double, 3 > bloch_k, double lo, double eps, const std::array< KernelRange, 3 > &kernel_ranges=std::array< KernelRange, 3 >(), const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:1995
Tensor< double > FunctionDefaults< NDIM >::cell_width
Definition mraimpl.h:3893
static std::vector< std::shared_ptr< SeparatedConvolution< double, 3 > > > GradBSHOperator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating operator for convolution with grad(bsh) in 3D.
Definition operator.h:2388
static SeparatedConvolution< double, NDIM > * SlaterF12OperatorPtr_ND(World &world, double mu, double lo, double eps, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Factory function generating separated kernel for convolution with (1 - exp(-mu*r))/(2 mu) in ND.
Definition operator.h:2206
static SeparatedConvolution< double, 3 > * SlaterF12sqOperatorPtr(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Definition operator.h:2134
TensorType
low rank representations of tensors (see gentensor.h)
Definition gentensor.h:120
@ TT_2D
Definition gentensor.h:120
NDIM & f
Definition mra.h:2817
static SeparatedConvolution< double, NDIM > SlaterOperator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r) in 3D.
Definition operator.h:2143
GenTensor< T > reduce(std::list< GenTensor< T > > &addends, double, bool=false)
add all the GenTensors of a given list
Definition gentensor.h:246
TensorType FunctionDefaults< NDIM >::tt
Definition mraimpl.h:3891
LatticeImages
Which lattice translations a lattice-summed 1D kernel includes.
Definition convolution1d.h:260
@ home_only
R = 0 only; still lattice_summed(), so the displacements stay on the non-periodic domain.
Definition convolution1d.h:263
@ exclude_home
R != 0 only.
Definition convolution1d.h:262
@ all
R = -maxR..maxR, the ordinary lattice sum.
Definition convolution1d.h:261
void print(const T &t, Ts &&... ts)
Print items to std::cout (items separated by spaces) and terminate with a new line.
Definition print.h:232
static SeparatedConvolution< double, NDIM > BSHOperator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Factory function generating separated kernel for convolution with BSH kernel in general NDIM.
Definition operator.h:2053
static SeparatedConvolution< double, 3 > * CoulombOperatorPtr(World &world, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with 1/r in 3D.
Definition operator.h:2039
CCPairFunction< T, NDIM > apply(const SeparatedConvolution< T, NDIM/2 > &op, const CCPairFunction< T, NDIM > &arg)
apply the operator to the argument
Definition ccpairfunction.h:901
static SeparatedConvolution< double, 3 > FGOperator(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with 1/(2 mu)*(1 - exp(-mu*r))/r in 3D.
Definition operator.h:2218
static SeparatedConvolution< double_complex, 3 > * PeriodicBSHOperatorPtr3D(World &world, Vector< double, 3 > bloch_k, double mu, double lo, double eps, const std::array< KernelRange, 3 > &kernel_ranges=std::array< KernelRange, 3 >(), const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D.
Definition operator.h:2105
static SeparatedConvolution< double, NDIM > GaussOperator(World &world, double mu, double lo=0.0, double eps=0.0, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r*r).
Definition operator.h:2154
static SeparatedConvolution< double, 3 > * BSHOperatorPtr3D(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D.
Definition operator.h:2292
static SeparatedConvolution< double, NDIM > * GaussOperatorPtr(World &world, double mu, double lo=0.0, double eps=0.0, const std::array< LatticeRange, NDIM > &lattice_ranges=FunctionDefaults< NDIM >::get_bc().lattice_range(), int k=FunctionDefaults< NDIM >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r*r) in 3D.
Definition operator.h:2165
static SeparatedConvolution< double, 3 > BSHOperator3D(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with exp(-mu*r)/(4*pi*r) in 3D.
Definition operator.h:2080
static SeparatedConvolution< double, 3 > * FGOperatorPtr(World &world, double mu, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating separated kernel for convolution with 1/(2 mu)*(1 - exp(-mu*r))/r in 3D.
Definition operator.h:2229
static std::vector< std::shared_ptr< SeparatedConvolution< double, 3 > > > GradCoulombOperator(World &world, double lo, double eps, const std::array< LatticeRange, 3 > &lattice_ranges=FunctionDefaults< 3 >::get_bc().lattice_range(), int k=FunctionDefaults< 3 >::get_k())
Factory function generating operator for convolution with grad(1/r) in 3D.
Definition operator.h:2328
Function< T, NDIM > copy(const Function< T, NDIM > &f, const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > &pmap, bool fence=true)
Create a new copy of the function with different distribution and optional fence.
Definition mra.h:2239
void mTxmq(long dimi, long dimj, long dimk, double *MADNESS_RESTRICT c, const double *a, const double *b, long ldb)
Explicit template specializations for homogeneous types (implemented in mTxmq.cc).
Definition mTxmq.cc:551
static const string dir
Definition corepotential.cc:249
static void aligned_axpy(long n, T *MADNESS_RESTRICT a, const T *MADNESS_RESTRICT b, Q s)
Definition aligned.h:75
Definition mraimpl.h:53
static long abs(long a)
Definition tensor.h:214
static Function< T, NDIM > diff(const Function< T, NDIM > &f, int axis)
Definition navstokes_cosines.cc:119
const double mu
Definition navstokes_cosines.cc:95
static const double b
Definition nonlinschro.cc:119
static const double d
Definition nonlinschro.cc:121
static const double a
Definition nonlinschro.cc:118
double Q(double a)
Definition relops.cc:20
static const double c
Definition relops.cc:10
static const double L
Definition rk.cc:46
!!! Note that if Rnormf is zero then ALL of the tensors are empty
Definition convolution1d.h:163
double N_up
Definition convolution1d.h:174
double N_F
the norms according to Beylkin 2008, Eq. (21) ff
Definition convolution1d.h:174
double N_diff
Definition convolution1d.h:174
static std::shared_ptr< GaussianConvolution1D< Q > > get(int k, double expnt, int m, const LatticeRange &lattice_range, double bloch_k=0.0, const KernelRange &range={}, LatticeImages images=LatticeImages::all)
Definition convolution1d.h:1022
Definition operatorinfo.h:61
OpType type
introspection
Definition operatorinfo.h:69
double mu
some introspection
Definition operatorinfo.h:66
bool images_only
Definition operatorinfo.h:77
std::vector< KernelRange > range
Definition operatorinfo.h:71
std::optional< bool > truncate_lowexp_gaussians
Definition operatorinfo.h:73
SeparatedConvolutionData keeps data for all terms, all dimensions.
Definition operator.h:95
std::vector< SeparatedConvolutionInternal< Q, NDIM > > muops
Definition operator.h:96
SeparatedConvolutionData(int rank)
Definition operator.h:99
double norm
Definition operator.h:97
SeparatedConvolutionData(const SeparatedConvolutionData< Q, NDIM > &q)
Definition operator.h:100
double norm
Definition operator.h:87
const ConvolutionData1D< Q > * ops[NDIM]
Definition operator.h:88
bool t_term
Definition operator.h:241
bool r_term
Definition operator.h:240
bool any_terms() const
Definition operator.h:242
ApplyTerms()
Definition operator.h:239
Tensor< double > coeff
Definition operator.h:255
Tensor< double > expnt
Definition operator.h:255
Tensor< double > dropped_expnt
Definition operator.h:256
Tensor< double > dropped_coeff
Definition operator.h:256
too lazy for extended calling lists
Definition operator.h:246
const Q * VT
Definition operator.h:249
const Q * U
Definition operator.h:248
World & world
Memoized reference to the world to which this object belongs.
Definition world_object.h:348
World & get_world() const
Definition world_object.h:446
static void load(const Archive &ar, const SeparatedConvolution< T, NDIM > *&ptr)
Definition operator.h:2447
Default load of an object via serialize(ar, t).
Definition archive.h:667
static void store(const Archive &ar, const SeparatedConvolution< T, NDIM > *const &ptr)
Definition operator.h:2456
Default store of an object via serialize(ar, t).
Definition archive.h:612
void doit(World &world)
Definition tdse.cc:921
Prototypes for a partial interface from Tensor to LAPACK.
int factorial(int n)
Definition test_BSHApply.cc:14
void e()
Definition test_sig.cc:75
double aa
Definition testbsh.cc:68
static const double pi
Definition testcosine.cc:6
std::vector< double > fit(size_t m, size_t n, const std::vector< double > N, const std::vector< double > &f)
Definition testfuns.cc:36
constexpr std::size_t NDIM
Definition testgconv.cc:54
double h(const coord_1d &r)
Definition testgconv.cc:175
double source(const coordT &r)
Definition testperiodic.cc:48
#define TENSOR_RESULT_TYPE(L, R)
This macro simplifies access to TensorResultType.
Definition type_data.h:205
#define PROFILE_MEMBER_FUNC(classname)
Definition worldprofile.h:210