MADNESS 0.10.1
funcimpl.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_FUNCIMPL_H__INCLUDED
33#define MADNESS_MRA_FUNCIMPL_H__INCLUDED
34
35/// \file funcimpl.h
36/// \brief Provides FunctionCommonData, FunctionImpl and FunctionFactory
37
39#include <madness/world/print.h>
40#include <madness/misc/misc.h>
43
45#include <madness/mra/indexit.h>
46#include <madness/mra/key.h>
50
51#include <madness/mra/leafop.h>
52
53#include <array>
54#include <iostream>
55#include <type_traits>
56
57namespace madness {
58 template <typename T, std::size_t NDIM>
59 class DerivativeBase;
60
61 template<typename T, std::size_t NDIM>
62 class FunctionImpl;
63
64 template<typename T, std::size_t NDIM>
65 class FunctionNode;
66
67 template<typename T, std::size_t NDIM>
68 class Function;
69
70 template<typename T, std::size_t NDIM>
71 class FunctionFactory;
72
73 template<typename T, std::size_t NDIM, std::size_t MDIM>
74 class CompositeFunctorInterface;
75
76 template<int D>
78
79}
80
81namespace madness {
82
83
84 /// A simple process map
85 template<typename keyT>
86 class SimplePmap : public WorldDCPmapInterface<keyT> {
87 private:
88 const int nproc;
90
91 public:
92 SimplePmap(World& world) : nproc(world.nproc()), me(world.rank())
93 { }
94
95 ProcessID owner(const keyT& key) const {
96 if (key.level() == 0)
97 return 0;
98 else
99 return key.hash() % nproc;
100 }
101 };
102
103 /// A pmap that locates children on odd levels with their even level parents
104 template <typename keyT>
105 class LevelPmap : public WorldDCPmapInterface<keyT> {
106 private:
107 const int nproc;
108 public:
109 LevelPmap() : nproc(0) {};
110
111 LevelPmap(World& world) : nproc(world.nproc()) {}
112
113 /// Find the owner of a given key
114 ProcessID owner(const keyT& key) const {
115 Level n = key.level();
116 if (n == 0) return 0;
117 hashT hash;
118 if (n <= 3 || (n&0x1)) hash = key.hash();
119 else hash = key.parent().hash();
120 return hash%nproc;
121 }
122 };
123
124
125 /// Sentinel for norm_tree/dnorm_tree meaning "not computed". Overflows the screening
126 /// criterion, so nodes carrying it are descended rather than screened.
127 static constexpr double NORM_TREE_UNCOMPUTED = 1e300;
128
129 /// Safety margin on the tolerance of the screened multiplication: the criterion estimates
130 /// the neglected cross terms rather than bounding them. Tightening is cheap and buys
131 /// accuracy, hence the extra factor. Applied once, in mulXXvec.
132 static constexpr double MUL_SCREENING_SAFETY = 0.1;
133
134 /// FunctionNode holds the coefficients, etc., at each node of the 2^NDIM-tree
135 template<typename T, std::size_t NDIM>
137 public:
140 private:
141 // Should compile OK with these volatile but there should
142 // be no need to set as volatile since the container internally
143 // stores the entire entry as volatile
144
145 coeffT _coeffs; ///< The coefficients, if any
146 double _norm_tree; ///< After norm_tree will contain norm of sum coefficients summed up tree
147 double _dnorm_tree=NORM_TREE_UNCOMPUTED; ///< norm of the difference coefficients summed up the tree
148 bool _has_children; ///< True if there are children
149 coeffT buffer; ///< The coefficients, if any
150 double dnorm=-1.0; ///< norm of the d coefficients, also defined if there are no d coefficients
151 double snorm=-1.0; ///< norm of the s coefficients
152
153 public:
154 typedef WorldContainer<Key<NDIM> , FunctionNode<T, NDIM> > dcT; ///< Type of container holding the nodes
155 /// Default constructor makes node without coeff or children
159
160 /// Constructor from given coefficients with optional children
161
162 /// Note that only a shallow copy of the coeff are taken so
163 /// you should pass in a deep copy if you want the node to
164 /// take ownership.
165 explicit
169
170 explicit
174
175 explicit
176 FunctionNode(const coeffT& coeff, double norm_tree, double dnorm_tree, double snorm, double dnorm, bool has_children) :
178 }
179
182 _has_children(other._has_children), dnorm(other.dnorm), snorm(other.snorm) {
183 }
184
187 if (this != &other) {
188 coeff() = copy(other.coeff());
189 _norm_tree = other._norm_tree;
190 _dnorm_tree = other._dnorm_tree;
192 dnorm=other.dnorm;
193 snorm=other.snorm;
194 }
195 return *this;
196 }
197
198 /// Copy with possible type conversion of coefficients, copying all other state
199
200 /// Choose to not overload copy and type conversion operators
201 /// so there are no automatic type conversions.
202 template<typename Q>
204 convert() const {
205 return FunctionNode<Q, NDIM> (madness::convert<Q,T>(coeff()), _norm_tree, _dnorm_tree, snorm, dnorm, _has_children);
206 }
207
208 /// Returns true if there are coefficients in this node
209 bool
210 has_coeff() const {
211 return _coeffs.has_data();
212 }
213
214
215 /// Returns true if this node has children
216 bool
217 has_children() const {
218 return _has_children;
219 }
220
221 /// Returns true if this does not have children
222 bool
223 is_leaf() const {
224 return !_has_children;
225 }
226
227 /// Returns true if this node is invalid (no coeffs and no children)
228 bool
229 is_invalid() const {
230 return !(has_coeff() || has_children());
231 }
232
233 /// Returns a non-const reference to the tensor containing the coeffs
234
235 /// Returns an empty tensor if there are no coefficients.
236 coeffT&
238 MADNESS_ASSERT(_coeffs.ndim() == -1 || (_coeffs.dim(0) <= 2
239 * MAXK && _coeffs.dim(0) >= 0));
240 return const_cast<coeffT&>(_coeffs);
241 }
242
243 /// Returns a const reference to the tensor containing the coeffs
244
245 /// Returns an empty tensor if there are no coefficeints.
246 const coeffT&
247 coeff() const {
248 return const_cast<const coeffT&>(_coeffs);
249 }
250
251 /// Returns the number of coefficients in this node
252 size_t size() const {
253 return _coeffs.size();
254 }
255
256 public:
257
258 /// reduces the rank of the coefficients (if applicable)
259 void reduceRank(const double& eps) {
260 _coeffs.reduce_rank(eps);
261 }
262
263 /// Sets \c has_children attribute to value of \c flag.
264 void set_has_children(bool flag) {
265 _has_children = flag;
266 }
267
268 /// Sets \c has_children attribute to true recurring up to ensure connected
270 //madness::print(" set_chi_recu: ", key, *this);
271 //PROFILE_MEMBER_FUNC(FunctionNode); // Too fine grain for routine profiling
272 if (!(has_children() || has_coeff() || key.level()==0)) {
273 // If node already knows it has children or it has
274 // coefficients then it must already be connected to
275 // its parent. If not, the node was probably just
276 // created for this operation and must be connected to
277 // its parent.
278 Key<NDIM> parent = key.parent();
279 // Task on next line used to be TaskAttributes::hipri()) ... but deferring execution of this
280 // makes sense since it is not urgent and lazy connection will likely mean that less forwarding
281 // will happen since the upper level task will have already made the connection.
282 const_cast<dcT&>(c).task(parent, &FunctionNode<T,NDIM>::set_has_children_recursive, c, parent);
283 //const_cast<dcT&>(c).send(parent, &FunctionNode<T,NDIM>::set_has_children_recursive, c, parent);
284 //madness::print(" set_chi_recu: forwarding",key,parent);
285 }
286 _has_children = true;
287 }
288
289 /// Sets \c has_children attribute to value of \c !flag
290 void set_is_leaf(bool flag) {
291 _has_children = !flag;
292 }
293
294 /// Takes a \em shallow copy of the coeff --- same as \c this->coeff()=coeff
295 void set_coeff(const coeffT& coeffs) {
296 coeff() = coeffs;
297 if ((_coeffs.has_data()) and ((_coeffs.dim(0) < 0) || (_coeffs.dim(0)>2*MAXK))) {
298 print("set_coeff: may have a problem");
299 print("set_coeff: coeff.dim[0] =", coeffs.dim(0), ", 2* MAXK =", 2*MAXK);
300 }
301 MADNESS_ASSERT(coeffs.dim(0)<=2*MAXK && coeffs.dim(0)>=0);
302 }
303
304 /// Clears the coefficients (has_coeff() will subsequently return false)
305 void clear_coeff() {
306 coeff()=coeffT();
307 }
308
309 /// Scale the coefficients of this node
310 template <typename Q>
311 void scale(Q a) {
312 _coeffs.scale(a);
313 }
314
315 /// Sets the value of norm_tree
318 }
319
320 /// Sets the value of dnorm_tree
321 void set_dnorm_tree(double dnorm_tree) {
322 _dnorm_tree = dnorm_tree;
323 }
324
325 /// Gets the value of norm_tree
326 double get_norm_tree() const {
327 return _norm_tree;
328 }
329
330 /// Gets the value of dnorm_tree
331 double get_dnorm_tree() const {
332 return _dnorm_tree;
333 }
334
335 /// return the precomputed norm of the (virtual) d coefficients
336 double get_dnorm() const {
337 return dnorm;
338 }
339
340 /// set the precomputed norm of the (virtual) s coefficients
341 void set_snorm(const double sn) {
342 snorm=sn;
343 }
344
345 /// set the precomputed norm of the (virtual) d coefficients
346 void set_dnorm(const double dn) {
347 dnorm=dn;
348 }
349
350 /// get the precomputed norm of the (virtual) s coefficients
351 double get_snorm() const {
352 return snorm;
353 }
354
356 snorm = 0.0;
357 dnorm = 0.0;
358 if (coeff().size() == 0) { ;
359 } else if (coeff().dim(0) == cdata.vk[0]) {
360 snorm = coeff().normf();
361
362 } else if (coeff().is_full_tensor()) {
363 Tensor<T> c = copy(coeff().get_tensor());
364 snorm = c(cdata.s0).normf();
365 c(cdata.s0) = 0.0;
366 dnorm = c.normf();
367
368 } else if (coeff().is_svd_tensor()) {
369 coeffT c= coeff()(cdata.s0);
370 snorm = c.normf();
371 double norm = coeff().normf();
372 dnorm = sqrt(norm * norm - snorm * snorm);
373
374 } else {
375 MADNESS_EXCEPTION("cannot use compute_dnorm", 1);
376 }
377 }
378
379
380 /// General bi-linear operation --- this = this*alpha + other*beta
381
382 /// This/other may not have coefficients. Has_children will be
383 /// true in the result if either this/other have children.
384 template <typename Q, typename R>
385 void gaxpy_inplace(const T& alpha, const FunctionNode<Q,NDIM>& other, const R& beta) {
386 //PROFILE_MEMBER_FUNC(FuncNode); // Too fine grain for routine profiling
387 if (other.has_children())
388 _has_children = true;
389 if (has_coeff()) {
390 if (other.has_coeff()) {
391 coeff().gaxpy(alpha,other.coeff(),beta);
392 }
393 else {
394 coeff().scale(alpha);
395 }
396 }
397 else if (other.has_coeff()) {
398 coeff() = other.coeff()*beta; //? Is this the correct type conversion?
399 }
400 }
401
402 /// Accumulate inplace and if necessary connect node to parent
403 void accumulate2(const tensorT& t, const typename FunctionNode<T,NDIM>::dcT& c,
404 const Key<NDIM>& key) {
405 // double cpu0=cpu_time();
406 if (has_coeff()) {
407 MADNESS_ASSERT(coeff().is_full_tensor());
408 // if (coeff().type==TT_FULL) {
409 coeff() += coeffT(t,-1.0,TT_FULL);
410 // } else {
411 // tensorT cc=coeff().full_tensor_copy();;
412 // cc += t;
413 // coeff()=coeffT(cc,args);
414 // }
415 }
416 else {
417 // No coeff and no children means the node is newly
418 // created for this operation and therefore we must
419 // tell its parent that it exists.
420 coeff() = coeffT(t,-1.0,TT_FULL);
421 // coeff() = copy(t);
422 // coeff() = coeffT(t,args);
423 if ((!_has_children) && key.level()> 0) {
424 Key<NDIM> parent = key.parent();
425 if (c.is_local(parent))
426 const_cast<dcT&>(c).send(parent, &FunctionNode<T,NDIM>::set_has_children_recursive, c, parent);
427 else
428 const_cast<dcT&>(c).task(parent, &FunctionNode<T,NDIM>::set_has_children_recursive, c, parent);
429 }
430 }
431 //double cpu1=cpu_time();
432 }
433
434
435 /// Accumulate inplace and if necessary connect node to parent
436 void accumulate(const coeffT& t, const typename FunctionNode<T,NDIM>::dcT& c,
437 const Key<NDIM>& key, const TensorArgs& args) {
438 if (has_coeff()) {
439 coeff().add_SVD(t,args.thresh);
440 if (buffer.rank()<coeff().rank()) {
441 if (buffer.has_data()) {
442 buffer.add_SVD(coeff(),args.thresh);
443 } else {
444 buffer=copy(coeff());
445 }
446 coeff()=coeffT();
447 }
448
449 } else {
450 // No coeff and no children means the node is newly
451 // created for this operation and therefore we must
452 // tell its parent that it exists.
453 coeff() = copy(t);
454 if ((!_has_children) && key.level()> 0) {
455 Key<NDIM> parent = key.parent();
456 if (c.is_local(parent))
457 const_cast<dcT&>(c).send(parent, &FunctionNode<T,NDIM>::set_has_children_recursive, c, parent);
458 else
459 const_cast<dcT&>(c).task(parent, &FunctionNode<T,NDIM>::set_has_children_recursive, c, parent);
460 }
461 }
462 }
463
464 void consolidate_buffer(const TensorArgs& args) {
465 if ((coeff().has_data()) and (buffer.has_data())) {
466 coeff().add_SVD(buffer,args.thresh);
467 } else if (buffer.has_data()) {
468 coeff()=buffer;
469 }
470 buffer=coeffT();
471 }
472
473 T trace_conj(const FunctionNode<T,NDIM>& rhs) const {
474 return this->_coeffs.trace_conj((rhs._coeffs));
475 }
476
477 template <typename Archive>
478 void serialize(Archive& ar) {
479 // changing this list changes the on-disk format: bump FUNCTION_ARCHIVE_MAGIC
481 }
482
483 /// like operator<<(ostream&, const FunctionNode<T,NDIM>&) but
484 /// produces a sequence JSON-formatted key-value pairs
485 /// @warning enclose the output in curly braces to make
486 /// a valid JSON object
487 void print_json(std::ostream& s) const {
488 s << "\"has_coeff\":" << this->has_coeff()
489 << ",\"has_children\":" << this->has_children() << ",\"norm\":";
490 double norm = this->has_coeff() ? this->coeff().normf() : 0.0;
491 if (norm < 1e-12)
492 norm = 0.0;
493 double nt = this->get_norm_tree();
494 if (nt == NORM_TREE_UNCOMPUTED)
495 nt = 0.0;
496 s << norm << ",\"norm_tree\":" << nt << ",\"snorm\":"
497 << this->get_snorm() << ",\"dnorm\":" << this->get_dnorm()
498 << ",\"rank\":" << this->coeff().rank();
499 if (this->coeff().is_assigned())
500 s << ",\"dim\":" << this->coeff().dim(0);
501 }
502
503 };
504
505 template <typename T, std::size_t NDIM>
506 std::ostream& operator<<(std::ostream& s, const FunctionNode<T,NDIM>& node) {
507 s << "(has_coeff=" << node.has_coeff() << ", has_children=" << node.has_children() << ", norm=";
508 double norm = node.has_coeff() ? node.coeff().normf() : 0.0;
509 if (norm < 1e-12)
510 norm = 0.0;
511 double nt = node.get_norm_tree();
512 double dnt = node.get_dnorm_tree();
513 if (nt == NORM_TREE_UNCOMPUTED) nt = 0.0;
514 if (dnt == NORM_TREE_UNCOMPUTED) dnt = 0.0;
515 s << norm << ", norm_tree = " << nt << ", dnorm_tree = " << dnt << ", s/dnorm =" << node.get_snorm() << " " << node.get_dnorm() << "), rank="<< node.coeff().rank()<<")";
516 if (node.coeff().is_assigned()) s << " dim " << node.coeff().dim(0) << " ";
517 return s;
518 }
519
520
521 /// returns true if the result of a hartree_product is a leaf node (compute norm & error)
522 template<typename T, size_t NDIM>
524
527 long k;
528 bool do_error_leaf_op() const {return false;}
529
530 hartree_leaf_op() = default;
531 hartree_leaf_op(const implT* f, const long& k) : f(f), k(k) {}
532
533 /// no pre-determination
534 bool operator()(const Key<NDIM>& key) const {return false;}
535
536 /// no post-determination
537 bool operator()(const Key<NDIM>& key, const GenTensor<T>& coeff) const {
538 MADNESS_EXCEPTION("no post-determination in hartree_leaf_op",1);
539 return true;
540 }
541
542 /// post-determination: true if f is a leaf and the result is well-represented
543
544 /// @param[in] key the hi-dimensional key (breaks into keys for f and g)
545 /// @param[in] fcoeff coefficients of f of its appropriate key in NS form
546 /// @param[in] gcoeff coefficients of g of its appropriate key in NS form
547 bool operator()(const Key<NDIM>& key, const Tensor<T>& fcoeff, const Tensor<T>& gcoeff) const {
548
549 if (key.level()<2) return false;
550 Slice s = Slice(0,k-1);
551 std::vector<Slice> s0(NDIM/2,s);
552
553 const double tol=f->get_thresh();
554 const double thresh=f->truncate_tol(tol, key)*0.3; // custom factor to "ensure" accuracy
555 // include the wavelets in the norm, makes it much more accurate
556 const double fnorm=fcoeff.normf();
557 const double gnorm=gcoeff.normf();
558
559 // if the final norm is small, perform the hartree product and return
560 const double norm=fnorm*gnorm; // computing the outer product
561 if (norm < thresh) return true;
562
563 // norm of the scaling function coefficients
564 const double sfnorm=fcoeff(s0).normf();
565 const double sgnorm=gcoeff(s0).normf();
566
567 // get the error of both functions and of the pair function;
568 // need the abs for numerics: sfnorm might be equal fnorm.
569 const double ferror=sqrt(std::abs(fnorm*fnorm-sfnorm*sfnorm));
570 const double gerror=sqrt(std::abs(gnorm*gnorm-sgnorm*sgnorm));
571
572 // if the expected error is small, perform the hartree product and return
573 const double error=fnorm*gerror + ferror*gnorm + ferror*gerror;
574 // const double error=sqrt(fnorm*fnorm*gnorm*gnorm - sfnorm*sfnorm*sgnorm*sgnorm);
575
576 if (error < thresh) return true;
577 return false;
578 }
579 template <typename Archive> void serialize (Archive& ar) {
580 ar & f & k;
581 }
582 };
583
584 /// returns true if the result of the convolution operator op with some provided
585 /// coefficients will be small
586 template<typename T, size_t NDIM, typename opT>
587 struct op_leaf_op {
589
590 const opT* op; ///< the convolution operator
591 const implT* f; ///< the source or result function, needed for truncate_tol
592 bool do_error_leaf_op() const {return true;}
593
594 op_leaf_op() = default;
595 op_leaf_op(const opT* op, const implT* f) : op(op), f(f) {}
596
597 /// pre-determination: we can't know if this will be a leaf node before we got the final coeffs
598 bool operator()(const Key<NDIM>& key) const {return true;}
599
600 /// post-determination: return true if operator and coefficient norms are small
601 bool operator()(const Key<NDIM>& key, const GenTensor<T>& coeff) const {
602 if (key.level()<2) return false;
603 const double cnorm=coeff.normf();
604 return this->operator()(key,cnorm);
605 }
606
607 /// post-determination: return true if operator and coefficient norms are small
608 bool operator()(const Key<NDIM>& key, const double& cnorm) const {
609 if (key.level()<2) return false;
610
611 typedef Key<opT::opdim> opkeyT;
612 const opkeyT source=op->get_source_key(key);
613
614 const double thresh=f->truncate_tol(f->get_thresh(),key);
615 const std::vector<opkeyT>& disp = op->get_disp(key.level());
616 const opkeyT& d = *disp.begin(); // use the zero-displacement for screening
617 const double opnorm = op->norm(key.level(), d, source);
618 const double norm=opnorm*cnorm;
619 return norm<thresh;
620
621 }
622
623 template <typename Archive> void serialize (Archive& ar) {
624 ar & op & f;
625 }
626
627 };
628
629
630 /// returns true if the result of a hartree_product is a leaf node
631 /// criteria are error, norm and its effect on a convolution operator
632 template<typename T, size_t NDIM, size_t LDIM, typename opT>
634
637
639 const implL* g; // for use of its cdata only
640 const opT* op;
641 bool do_error_leaf_op() const {return false;}
642
644 hartree_convolute_leaf_op(const implT* f, const implL* g, const opT* op)
645 : f(f), g(g), op(op) {}
646
647 /// no pre-determination
648 bool operator()(const Key<NDIM>& key) const {return true;}
649
650 /// no post-determination
651 bool operator()(const Key<NDIM>& key, const GenTensor<T>& coeff) const {
652 MADNESS_EXCEPTION("no post-determination in hartree_convolute_leaf_op",1);
653 return true;
654 }
655
656 /// post-determination: true if f is a leaf and the result is well-represented
657
658 /// @param[in] key the hi-dimensional key (breaks into keys for f and g)
659 /// @param[in] fcoeff coefficients of f of its appropriate key in NS form
660 /// @param[in] gcoeff coefficients of g of its appropriate key in NS form
661 bool operator()(const Key<NDIM>& key, const Tensor<T>& fcoeff, const Tensor<T>& gcoeff) const {
662 // bool operator()(const Key<NDIM>& key, const GenTensor<T>& coeff) const {
663
664 if (key.level()<2) return false;
665
666 const double tol=f->get_thresh();
667 const double thresh=f->truncate_tol(tol, key);
668 // include the wavelets in the norm, makes it much more accurate
669 const double fnorm=fcoeff.normf();
670 const double gnorm=gcoeff.normf();
671
672 // norm of the scaling function coefficients
673 const double sfnorm=fcoeff(g->get_cdata().s0).normf();
674 const double sgnorm=gcoeff(g->get_cdata().s0).normf();
675
676 // if the final norm is small, perform the hartree product and return
677 const double norm=fnorm*gnorm; // computing the outer product
678 if (norm < thresh) return true;
679
680 // get the error of both functions and of the pair function
681 const double ferror=sqrt(fnorm*fnorm-sfnorm*sfnorm);
682 const double gerror=sqrt(gnorm*gnorm-sgnorm*sgnorm);
683
684 // if the expected error is small, perform the hartree product and return
685 const double error=fnorm*gerror + ferror*gnorm + ferror*gerror;
686 if (error < thresh) return true;
687
688 // now check if the norm of this and the norm of the operator are significant
689 const std::vector<Key<NDIM> >& disp = op->get_disp(key.level());
690 const Key<NDIM>& d = *disp.begin(); // use the zero-displacement for screening
691 const double opnorm = op->norm(key.level(), d, key);
692 const double final_norm=opnorm*sfnorm*sgnorm;
693 if (final_norm < thresh) return true;
694
695 return false;
696 }
697 template <typename Archive> void serialize (Archive& ar) {
698 ar & f & op;
699 }
700 };
701
702 template<typename T, size_t NDIM>
703 struct noop {
704 void operator()(const Key<NDIM>& key, const GenTensor<T>& coeff, const bool& is_leaf) const {}
705 bool operator()(const Key<NDIM>& key, const GenTensor<T>& fcoeff, const GenTensor<T>& gcoeff) const {
706 MADNESS_EXCEPTION("in noop::operator()",1);
707 return true;
708 }
709 template <typename Archive> void serialize (Archive& ar) {}
710
711 };
712
713 /// insert/replaces the coefficients into the function
714 template<typename T, std::size_t NDIM>
715 struct insert_op {
720
724 insert_op(const insert_op& other) : impl(other.impl) {}
725 void operator()(const keyT& key, const coeffT& coeff, const bool& is_leaf) const {
727 impl->get_coeffs().replace(key,nodeT(coeff,not is_leaf));
728 }
729 template <typename Archive> void serialize (Archive& ar) {
730 ar & impl;
731 }
732
733 };
734
735 /// inserts/accumulates coefficients into impl's tree
736
737 /// NOTE: will use buffer and will need consolidation after operation ended !! NOTE !!
738 template<typename T, std::size_t NDIM>
742
744 accumulate_op() = default;
746 accumulate_op(const accumulate_op& other) = default;
747 void operator()(const Key<NDIM>& key, const coeffT& coeff, const bool& is_leaf) const {
748 if (coeff.has_data())
749 impl->get_coeffs().task(key, &nodeT::accumulate, coeff, impl->get_coeffs(), key, impl->get_tensor_args());
750 }
751 template <typename Archive> void serialize (Archive& ar) {
752 ar & impl;
753 }
754
755 };
756
757
758template<size_t NDIM>
759 struct true_op {
760
761 template<typename T>
762 bool operator()(const Key<NDIM>& key, const T& t) const {return true;}
763
764 template<typename T, typename R>
765 bool operator()(const Key<NDIM>& key, const T& t, const R& r) const {return true;}
766 template <typename Archive> void serialize (Archive& ar) {}
767
768 };
769
770 /// shallow-copy, pared-down version of FunctionNode, for special purpose only
771 template<typename T, std::size_t NDIM>
772 struct ShallowNode {
776 double dnorm=-1.0;
779 : _coeffs(node.coeff()), _has_children(node.has_children()),
780 dnorm(node.get_dnorm()) {}
782 : _coeffs(node.coeff()), _has_children(node._has_children),
783 dnorm(node.dnorm) {}
784
785 const coeffT& coeff() const {return _coeffs;}
786 coeffT& coeff() {return _coeffs;}
787 bool has_children() const {return _has_children;}
788 bool is_leaf() const {return not _has_children;}
789 template <typename Archive>
790 void serialize(Archive& ar) {
791 ar & coeff() & _has_children & dnorm;
792 }
793 };
794
795
796 /// a class to track where relevant (parent) coeffs are
797
798 /// E.g. if a 6D function is composed of two 3D functions their coefficients must be tracked.
799 /// We might need coeffs from a box that does not exist, and to avoid searching for
800 /// parents we track which are their required respective boxes.
801 /// - CoeffTracker will refer either to a requested key, if it exists, or to its
802 /// outermost parent.
803 /// - Children must be made in sequential order to be able to track correctly.
804 ///
805 /// Usage: 1. make the child of a given CoeffTracker.
806 /// If the parent CoeffTracker refers to a leaf node (flag is_leaf)
807 /// the child will refer to the same node. Otherwise it will refer
808 /// to the child node.
809 /// 2. retrieve its coefficients (possible communication/ returns a Future).
810 /// Member variable key always refers to an existing node,
811 /// so we can fetch it. Once we have the node we can determine
812 /// if it has children which allows us to make a child (see 1. )
813 template<typename T, size_t NDIM>
815
819 typedef std::pair<Key<NDIM>,ShallowNode<T,NDIM> > datumT;
821
822 /// the funcimpl that has the coeffs
823 const implT* impl;
824 /// the current key, which must exists in impl
826 /// flag if key is a leaf node
828 /// the coefficients belonging to key
830 /// norm of d coefficients corresponding to key
831 double dnorm_=-1.0;
832
833 public:
834
835 /// default ctor
836 CoeffTracker() : impl(), key_(0), is_leaf_(unknown), coeff_() {} // Initialize key to avoid warnings of possible unititialied use
837
838 /// the initial ctor making the root key
840 if (impl) key_=impl->get_cdata().key0;
841 }
842
843 /// ctor with a pair<keyT,nodeT>
844 explicit CoeffTracker(const CoeffTracker& other, const datumT& datum)
845 : impl(other.impl), key_(other.key_), coeff_(datum.second.coeff()),
846 dnorm_(datum.second.dnorm) {
847 if (datum.second.is_leaf()) is_leaf_=yes;
848 else is_leaf_=no;
849 }
850
851 /// copy ctor
852 CoeffTracker(const CoeffTracker& other) : impl(other.impl), key_(other.key_),
853 is_leaf_(other.is_leaf_), coeff_(other.coeff_), dnorm_(other.dnorm_) {};
854
855 CoeffTracker& operator=(const CoeffTracker& other) = default;
856
857 /// const reference to impl
858 const implT* get_impl() const {return impl;}
859
860 /// const reference to the coeffs
861 const coeffT& coeff() const {return coeff_;}
862
863 /// const reference to the key
864 const keyT& key() const {return key_;}
865
866 /// return the coefficients belonging to the passed-in key
867
868 /// if key equals tracked key just return the coeffs, otherwise
869 /// make the child coefficients.
870 /// @param[in] key return coeffs corresponding to this key
871 /// @return coefficients belonging to key
879
880 /// return the s and dnorm belonging to the passed-in key
881 double dnorm(const keyT& key) const {
882 if (key==key_) return dnorm_;
883 MADNESS_ASSERT(key.is_child_of(key_));
884 return 0.0;
885 }
886
887 /// const reference to is_leaf flag
888 const LeafStatus& is_leaf() const {return is_leaf_;}
889
890 /// make a child of this, ignoring the coeffs
891 CoeffTracker make_child(const keyT& child) const {
892
893 // fast return
894 if ((not impl) or impl->is_on_demand()) return CoeffTracker(*this);
895
896 // can't make a child without knowing if this is a leaf -- activate first
898
899 CoeffTracker result;
900 if (impl) {
901 result.impl=impl;
902 if (is_leaf_==yes) result.key_=key_;
903 if (is_leaf_==no) {
904 result.key_=child;
905 // check if child is direct descendent of this, but root node is special case
906 if (child.level()>0) MADNESS_ASSERT(result.key().level()==key().level()+1);
907 }
908 result.is_leaf_=unknown;
909 }
910 return result;
911 }
912
913 /// find the coefficients
914
915 /// this involves communication to a remote node
916 /// @return a Future<CoeffTracker> with the coefficients that key refers to
918
919 // fast return
920 if (not impl) return Future<CoeffTracker>(CoeffTracker());
922
923 // this will return a <keyT,nodeT> from a remote node
926
927 // construct a new CoeffTracker locally
928 return impl->world.taskq.add(*const_cast<CoeffTracker*> (this),
929 &CoeffTracker::forward_ctor,*this,datum1);
930 }
931
932 private:
933 /// taskq-compatible forwarding to the ctor
934 CoeffTracker forward_ctor(const CoeffTracker& other, const datumT& datum) const {
935 return CoeffTracker(other,datum);
936 }
937
938 public:
939 /// serialization
940 template <typename Archive> void serialize(const Archive& ar) {
941 int il=int(is_leaf_);
942 ar & impl & key_ & il & coeff_ & dnorm_;
944 }
945 };
946
947 template<typename T, std::size_t NDIM>
948 std::ostream&
949 operator<<(std::ostream& s, const CoeffTracker<T,NDIM>& ct) {
950 s << ct.key() << ct.is_leaf() << " " << ct.get_impl();
951 return s;
952 }
953
954 /// FunctionImpl holds all Function state to facilitate shallow copy semantics
955
956 /// Since Function assignment and copy constructors are shallow it
957 /// greatly simplifies maintaining consistent state to have all
958 /// (permanent) state encapsulated in a single class. The state
959 /// is shared between instances using a shared_ptr<FunctionImpl>.
960 ///
961 /// The FunctionImpl inherits all of the functionality of WorldContainer
962 /// (to store the coefficients) and WorldObject<WorldContainer> (used
963 /// for RMI and for its unqiue id).
964 ///
965 /// The class methods are public to avoid painful multiple friend template
966 /// declarations for Function and FunctionImpl ... but this trust should not be
967 /// abused ... NOTHING except FunctionImpl methods should mess with FunctionImplData.
968 /// The LB stuff might have to be an exception.
969 template <typename T, std::size_t NDIM>
970 class FunctionImpl : public WorldObject< FunctionImpl<T,NDIM> > {
971 private:
972 typedef WorldObject< FunctionImpl<T,NDIM> > woT; ///< Base class world object type
973 public:
974 typedef T typeT;
975 typedef FunctionImpl<T,NDIM> implT; ///< Type of this class (implementation)
976 typedef std::shared_ptr< FunctionImpl<T,NDIM> > pimplT; ///< pointer to this class
977 typedef Tensor<T> tensorT; ///< Type of tensor for anything but to hold coeffs
978 typedef Vector<Translation,NDIM> tranT; ///< Type of array holding translation
979 typedef Key<NDIM> keyT; ///< Type of key
980 typedef FunctionNode<T,NDIM> nodeT; ///< Type of node
981 typedef GenTensor<T> coeffT; ///< Type of tensor used to hold coeffs
982 typedef WorldContainer<keyT,nodeT> dcT; ///< Type of container holding the coefficients
983 typedef std::pair<const keyT,nodeT> datumT; ///< Type of entry in container
984 typedef Vector<double,NDIM> coordT; ///< Type of vector holding coordinates
985
986 //template <typename Q, int D> friend class Function;
987 template <typename Q, std::size_t D> friend class FunctionImpl;
988
990
991 /// getter
994 const std::vector<Vector<double,NDIM> >& get_special_points()const{return special_points;}
995
996 private:
997 int k; ///< Wavelet order
998 double thresh; ///< Screening threshold
999 int initial_level; ///< Initial level for refinement
1000 int special_level; ///< Minimium level for refinement on special points
1001 std::vector<Vector<double,NDIM> > special_points; ///< special points for further refinement (needed for composite functions or multiplication)
1002 const Tensor<double> cell; ///< the size of the root cell in each dimension, unchangeable
1003 int max_refine_level; ///< Do not refine below this level
1004 int truncate_mode; ///< 0=default=(|d|<thresh), 1=(|d|<thresh/2^n), 2=(|d|<thresh/4^n);
1005 bool autorefine; ///< If true, autorefine where appropriate
1006 bool truncate_on_project; ///< If true projection inserts at level n-1 not n
1007 TensorArgs targs; ///< type of tensor to be used in the FunctionNodes
1008
1010
1011 std::shared_ptr< FunctionFunctorInterface<T,NDIM> > functor;
1013
1014 dcT coeffs; ///< The coefficients
1015
1016 /// Neighbor coefficients pushed here by whoever owns them; null until something stages.
1017
1018 /// Values mirror what `sock_it_to_me` returns for the same key: coefficients for a same-level
1019 /// leaf, empty for an interior node, absent when the neighbor is coarser and the consumer
1020 /// must walk up. Which nodes get pushed is the operator's business, not the table's --- see
1021 /// `DerivativeBase::stage_halo`.
1022 ///
1023 /// Allocated on the first push, so functions that never stage one do not carry it: a
1024 /// `ConcurrentHashMap` default-constructs 1021 bins, ~32 kB per function.
1025 mutable std::atomic<ConcurrentHashMap<keyT,coeffT>*> neighbor_halo_{nullptr};
1026
1027 // Disable the default copy constructor
1029
1030 public:
1031 /// Is a neighbor halo staged on this function?
1032 bool halo_enabled() const {
1033 return neighbor_halo_.load(std::memory_order_acquire) != nullptr;
1034 }
1035
1036 /// Discard the neighbor halo, freeing the staged coefficients.
1037
1038 /// Requires a quiescent window: it frees a table that `halo_probe` may be reading.
1039 void halo_clear() const {
1040 delete neighbor_halo_.exchange(nullptr, std::memory_order_acq_rel);
1041 }
1042
1043 /// How many neighbor nodes are staged on this rank; zero if no halo.
1044 std::size_t halo_size() const {
1045 const auto* h = neighbor_halo_.load(std::memory_order_acquire);
1046 return h ? h->size() : 0;
1047 }
1048
1049 /// Insert pushed neighbor nodes into the halo; runs as a task, concurrently with other pushes.
1050
1051 /// Allocates the table on the first push, so staging needs no collective set-up.
1052 void receive_halo(const std::vector<std::pair<keyT,coeffT> >& buf) const {
1053 auto* h = neighbor_halo_.load(std::memory_order_acquire);
1054 if (!h) {
1055 auto* fresh = new ConcurrentHashMap<keyT,coeffT>();
1056 if (neighbor_halo_.compare_exchange_strong(h, fresh, std::memory_order_acq_rel,
1057 std::memory_order_acquire))
1058 h = fresh;
1059 else
1060 delete fresh; // lost the race; the failed CAS put the winner's table in h
1061 }
1062 for (const auto& kv : buf) {
1064 (void) h->insert(acc, kv.first);
1065 acc->second = kv.second;
1066 }
1067 }
1068
1069 /// Look up a staged neighbor; on a hit copy its coefficients, which are empty for an interior node.
1070 bool halo_probe(const keyT& key, coeffT& out) const {
1071 const auto* h = neighbor_halo_.load(std::memory_order_acquire);
1072 if (!h) return false;
1074 if (h->find(acc, key)) { out = acc->second; return true; }
1075 return false;
1076 }
1077
1086
1087 /// Initialize function impl from data in factory
1089 : WorldObject<implT>(factory._world)
1090 , world(factory._world)
1091 , k(factory._k)
1092 , thresh(factory._thresh)
1093 , initial_level(factory._initial_level)
1094 , special_level(factory._special_level)
1095 , special_points(factory._special_points)
1097 , max_refine_level(factory._max_refine_level)
1098 , truncate_mode(factory._truncate_mode)
1099 , autorefine(factory._autorefine)
1100 , truncate_on_project(factory._truncate_on_project)
1101 , targs(factory._thresh,FunctionDefaults<NDIM>::get_tensor_type())
1102 , cdata(FunctionCommonData<T,NDIM>::get(k))
1103 , functor(factory.get_functor())
1104 , tree_state(factory._tree_state)
1105 , coeffs(world,factory._pmap,false)
1106 //, bc(factory._bc)
1107 {
1108 // PROFILE_MEMBER_FUNC(FunctionImpl); // No need to profile this
1109 // !!! Ensure that all local state is correctly formed
1110 // before invoking process_pending for the coeffs and
1111 // for this. Otherwise, there is a race condition.
1112 MADNESS_ASSERT(k>0 && k<=MAXK);
1113
1114 bool empty = (factory._empty or is_on_demand());
1115 bool do_refine = factory._refine;
1116
1117 if (do_refine)
1118 initial_level = std::max(0,initial_level - 1);
1119
1120 if (empty) { // Do not set any coefficients at all
1121 // additional functors are only evaluated on-demand
1122 } else if (functor) { // Project function and optionally refine
1124 // set the union of the special points of functor and the ones explicitly given to FunctionFactory
1125 std::vector<coordT> functor_special_points=functor->special_points();
1126 if (!functor_special_points.empty()) special_points.insert(special_points.end(), functor_special_points.begin(), functor_special_points.end());
1127 // near special points refine as deeply as requested by the factory AND the functor
1128 special_level = std::max(special_level, functor->special_level());
1129
1130 typename dcT::const_iterator end = coeffs.end();
1131 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
1132 if (it->second.is_leaf())
1133 woT::task(coeffs.owner(it->first), &implT::project_refine_op, it->first, do_refine,
1135 }
1136 }
1137 else { // Set as if a zero function
1138 initial_level = 1;
1140 }
1141
1143 this->process_pending();
1144 if (factory._fence && (functor || !empty)) world.gop.fence();
1145 }
1146
1147 /// Copy constructor
1148
1149 /// Allocates a \em new function in preparation for a deep copy
1150 ///
1151 /// By default takes pmap from other but can also specify a different pmap.
1152 /// Does \em not copy the coefficients ... creates an empty container.
1153 template <typename Q>
1155 const std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > >& pmap,
1156 bool dozero) : FunctionImpl(other.world, other, pmap, dozero) {
1157 }
1158
1159 /// Copy constructor
1160
1161 /// Allocates a \em new function in preparation for a deep copy
1162 ///
1163 /// By default takes pmap from other but can also specify a different pmap.
1164 /// Does \em not copy the coefficients ... creates an empty container.
1165 ///
1166 /// uses a different world for the new function
1167 template <typename Q>
1169 const FunctionImpl<Q,NDIM>& other,
1170 const std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > >& pmap,
1171 bool dozero)
1173 , world(world)
1174 , k(other.k)
1175 , thresh(other.thresh)
1179 , cell(other.cell)
1182 , autorefine(other.autorefine)
1184 , targs(other.targs)
1185 , cdata(FunctionCommonData<T,NDIM>::get(k))
1186 , functor()
1187 , tree_state(other.tree_state)
1188 , coeffs(world, pmap ? pmap : other.coeffs.get_pmap())
1189 {
1190 if (dozero) {
1191 initial_level = 1;
1193 //world.gop.fence(); <<<<<<<<<<<<<<<<<<<<<< needs a fence argument
1194 }
1196 this->process_pending();
1197 }
1198
1199 virtual ~FunctionImpl() { halo_clear(); }
1200
1201 const std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > >& get_pmap() const;
1202
1203 void replicate(bool fence=true) {
1204 coeffs.replicate(fence);
1205 }
1206
1207 void replicate_on_hosts(bool fence=true) {
1209 }
1210
1211 // remove all coeffs that are not local according to pmap
1212 void undo_replicate(bool fence=true) {
1213 std::list<keyT> keys;
1214 for (const auto& [key, node] : coeffs) if (not coeffs.is_local(key)) keys.push_back(key);
1215 for (const auto& key : keys) coeffs.erase(key);
1216 if (fence) world.gop.fence();
1217 }
1218
1219 void distribute(std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > > newmap) const {
1220 auto currentmap=coeffs.get_pmap();
1221 currentmap->redistribute(world,newmap);
1222 }
1223
1224 /// Copy coeffs from other into self
1225
1226 /// this and other might live in different worlds
1227 template <typename Q>
1228 void copy_coeffs(const FunctionImpl<Q,NDIM>& other, bool fence) {
1229 if (world.id()==other.world.id())
1230 copy_coeffs_same_world(other,false);
1231 else
1233 if (fence) world.gop.fence();
1234 }
1235
1236 /// Copy coefficients from other funcimpl with possibly different world and on a different node
1237 template<typename Q>
1239
1240 // copy coeffs from (a subset of) other's world
1241
1242 // single-owner pmap: fetch from that rank only -- the all-ranks poll costs
1243 // N-1 empty round-trips queued behind the owner's compute
1244 const ProcessID single_owner = other.get_pmap()->single_owner();
1245 if (single_owner >= 0) {
1246 copy_remote_coeffs_from_pid<Q>(single_owner, other);
1247
1248 // if other's data is distributed, we need to fetch from all ranks
1249 } else if (other.get_coeffs().is_distributed()) {
1250 for (ProcessID pid=0; pid<other.world.size(); ++pid) {
1251 copy_remote_coeffs_from_pid<Q>(pid, other);
1252 }
1253
1254 // if other's data is replicated, all coeffs are on the rank that owns key0
1255 } else if (other.get_coeffs().is_replicated() or other.get_coeffs().is_host_replicated()) {
1256 auto key0=other.cdata.key0;
1257 copy_remote_coeffs_from_pid<Q>(other.get_pmap()->owner(key0), other);
1258 }
1259 }
1260
1261 /// Copy coefficients from other funcimpl with possibly different world and on a different node
1262 /// to this
1263 template <typename Q>
1265 typedef FunctionImpl<Q,NDIM> implQ; ///< Type of this class (implementation)
1266 if (pid == other.world.rank()) {
1267 // the shard is local: copy nodes directly, no serialize round-trip
1268 copy_coeffs_same_world(other, false);
1269 } else {
1270 auto v=other.task(pid, &implQ::serialize_remote_coeffs);
1272 }
1273 }
1274
1275 /// invoked by copy_remote_coeffs_from_pid to serialize *local* coeffs
1276 std::vector<unsigned char> serialize_remote_coeffs() {
1277 std::vector<unsigned char> v;
1279 ar & get_coeffs();
1280 return v;
1281 }
1282
1283 /// insert coeffs from vector archive into this
1284 void insert_serialized_coeffs(std::vector<unsigned char>& v) {
1286 ar & get_coeffs();
1287 }
1288
1289 /// Copy coeffs from other into self
1290 template <typename Q>
1291 void copy_coeffs_same_world(const FunctionImpl<Q,NDIM>& other, bool fence) {
1292 for (const auto& [key, node] : other.coeffs) { // iterate over all entries in other
1293 coeffs.replace(key,node. template convert<T>());
1294 }
1295 if (fence)
1296 world.gop.fence();
1297 }
1298
1299 /// perform inplace gaxpy: this = alpha*this + beta*other
1300 /// @param[in] alpha prefactor for this
1301 /// @param[in] beta prefactor for other
1302 /// @param[in] g the other function, reconstructed
1303 /// @return *this = alpha*this + beta*other, in either reconstructed or redundant_after_merge state
1304 template<typename Q, typename R>
1305 void gaxpy_inplace_reconstructed(const T& alpha, const FunctionImpl<Q,NDIM>& g, const R& beta, const bool fence) {
1306 // merge g's tree into this' tree
1307 gaxpy_inplace(alpha,g,beta,fence);
1309 // this->merge_trees(beta,g,alpha,fence);
1310 // tree is now redundant_after_merge
1311 // sum down the sum coeffs into the leafs if possible to keep the state most clean
1312 if (fence) sum_down(fence);
1313 }
1314
1315 /// merge the trees of this and other, while multiplying them with the alpha or beta, resp
1316
1317 /// first step in an inplace gaxpy operation for reconstructed functions; assuming the same
1318 /// distribution for this and other
1319
1320 /// on output, *this = alpha* *this + beta * other
1321 /// @param[in] alpha prefactor for this
1322 /// @param[in] beta prefactor for other
1323 /// @param[in] other the other function, reconstructed
1324 template<typename Q, typename R>
1325 void merge_trees(const T alpha, const FunctionImpl<Q,NDIM>& other, const R beta, const bool fence=true) {
1326 MADNESS_ASSERT(get_pmap() == other.get_pmap());
1329 }
1330
1331 /// merge the trees of this and other, while multiplying them with the alpha or beta, resp
1332
1333 /// result and rhs do not have to have the same distribution or live in the same world
1334 /// result+=alpha* this
1335 /// @param[in] alpha prefactor for this
1336 template<typename Q, typename R>
1337 void accumulate_trees(FunctionImpl<Q,NDIM>& result, const R alpha, const bool fence=true) const {
1339 }
1340
1341 /// perform: this= alpha*f + beta*g, invoked by result
1342
1343 /// f and g are reconstructed, so we can save on the compress operation,
1344 /// walk down the joint tree, and add leaf coefficients; effectively refines
1345 /// to common finest level.
1346
1347 /// nothing returned, but leaves this's tree reconstructed and as sum of f and g
1348 /// @param[in] alpha prefactor for f
1349 /// @param[in] f first addend
1350 /// @param[in] beta prefactor for g
1351 /// @param[in] g second addend
1352 void gaxpy_oop_reconstructed(const double alpha, const implT& f,
1353 const double beta, const implT& g, const bool fence);
1354
1355 /// functor for the gaxpy_inplace method
1356 template <typename Q, typename R>
1359 FunctionImpl<T,NDIM>* f; ///< prefactor for current function impl
1360 T alpha; ///< the current function impl
1361 R beta; ///< prefactor for other function impl
1362 do_gaxpy_inplace() = default;
1364 bool operator()(typename rangeT::iterator& it) const {
1365 const keyT& key = it->first;
1366 const FunctionNode<Q,NDIM>& other_node = it->second;
1367 // Use send to get write accessor and automated construction if missing
1368 f->coeffs.send(key, &nodeT:: template gaxpy_inplace<Q,R>, alpha, other_node, beta);
1369 return true;
1370 }
1371 template <typename Archive>
1372 void serialize(Archive& ar) {
1373 ar & f & alpha & beta;
1374 }
1375 };
1376
1377 /// Inplace general bilinear operation
1378
1379 /// this's world can differ from other's world
1380 /// this = alpha * this + beta * other
1381 /// @param[in] alpha prefactor for the current function impl
1382 /// @param[in] other the other function impl
1383 /// @param[in] beta prefactor for other
1384 template <typename Q, typename R>
1385 void gaxpy_inplace(const T& alpha,const FunctionImpl<Q,NDIM>& other, const R& beta, bool fence) {
1386// MADNESS_ASSERT(get_pmap() == other.get_pmap());
1387 if (alpha != T(1.0)) scale_inplace(alpha,false);
1389 typedef do_gaxpy_inplace<Q,R> opT;
1390 other.world.taskq. template for_each<rangeT,opT>(rangeT(other.coeffs.begin(), other.coeffs.end()), opT(this, T(1.0), beta));
1391 if (fence)
1392 other.world.gop.fence();
1393 }
1394
1395 // loads a function impl from persistence
1396 // @param[in] ar the archive where the function impl is stored
1397 template <typename Archive>
1398 void load(Archive& ar) {
1399 // WE RELY ON K BEING STORED FIRST
1400 int kk = 0;
1401 ar & kk;
1402
1403 MADNESS_ASSERT(kk==k);
1404
1405 // note that functor should not be (re)stored
1407 & autorefine & truncate_on_project & tree_state;//nonstandard & compressed ; //& bc;
1408
1409 ar & coeffs;
1410 world.gop.fence();
1411 }
1412
1413 // saves a function impl to persistence
1414 // @param[in] ar the archive where the function impl is to be stored
1415 template <typename Archive>
1416 void store(Archive& ar) {
1417 // WE RELY ON K BEING STORED FIRST
1418
1419 // note that functor should not be (re)stored
1421 & autorefine & truncate_on_project & tree_state;//nonstandard & compressed ; //& bc;
1422
1423 ar & coeffs;
1424 world.gop.fence();
1425 }
1426
1427 /// Returns true if the function is compressed.
1428 bool is_compressed() const;
1429
1430 /// Returns true if the function is compressed.
1431 bool is_reconstructed() const;
1432
1433 /// Returns true if the function is redundant.
1434 bool is_redundant() const;
1435
1436 /// Returns true if the function is redundant_after_merge.
1437 bool is_redundant_after_merge() const;
1438
1439 bool is_nonstandard() const;
1440
1441 bool is_nonstandard_with_leaves() const;
1442
1443 bool is_on_demand() const;
1444
1445 bool has_leaves() const;
1446
1447 void set_tree_state(const TreeState& state) {
1448 tree_state=state;
1449 }
1450
1452
1453 void set_functor(const std::shared_ptr<FunctionFunctorInterface<T,NDIM> > functor1);
1454
1455 std::shared_ptr<FunctionFunctorInterface<T,NDIM> > get_functor();
1456
1457 std::shared_ptr<FunctionFunctorInterface<T,NDIM> > get_functor() const;
1458
1459 void unset_functor();
1460
1461
1463
1465 void set_tensor_args(const TensorArgs& t);
1466
1467 double get_thresh() const;
1468
1469 /// return the simulation cell
1470 const Tensor<double>& get_cell() const { return cell; }
1471
1472 void set_thresh(double value);
1473
1474 bool get_autorefine() const;
1475
1476 void set_autorefine(bool value);
1477
1478 int get_k() const;
1479
1480 const dcT& get_coeffs() const;
1481
1482 dcT& get_coeffs();
1483
1485
1486 void accumulate_timer(const double time) const; // !!!!!!!!!!!! REDUNDANT !!!!!!!!!!!!!!!
1487
1488 void print_timer() const;
1489
1490 void reset_timer();
1491
1492 /// Adds a constant to the function. Local operation, optional fence
1493
1494 /// In scaling function basis must add value to first polyn in
1495 /// each box with appropriate scaling for level. In wavelet basis
1496 /// need only add at level zero.
1497 /// @param[in] t the scalar to be added
1498 void add_scalar_inplace(T t, bool fence);
1499
1500 /// Initialize nodes to zero function at initial_level of refinement.
1501
1502 /// Works for either basis. No communication.
1503 void insert_zero_down_to_initial_level(const keyT& key);
1504
1505 /// Truncate according to the threshold with optional global fence
1506
1507 /// If thresh<=0 the default value of this->thresh is used
1508 /// @param[in] tol the truncation tolerance
1509 void truncate(double tol, bool fence);
1510
1511 /// Returns true if after truncation this node has coefficients
1512
1513 /// Assumed to be invoked on process owning key. Possible non-blocking
1514 /// communication.
1515 /// @param[in] key the key of the current function node
1516 Future<bool> truncate_spawn(const keyT& key, double tol);
1517
1518 /// Actually do the truncate operation
1519 /// @param[in] key the key to the current function node being evaluated for truncation
1520 /// @param[in] tol the tolerance for thresholding
1521 /// @param[in] v vector of Future<bool>'s that specify whether the current nodes children have coeffs
1522 bool truncate_op(const keyT& key, double tol, const std::vector< Future<bool> >& v);
1523
1524 /// Evaluate function at quadrature points in the specified box
1525
1526 /// @param[in] key the key indicating where the quadrature points are located
1527 /// @param[in] f the interface to the elementary function
1528 /// @param[in] qx quadrature points on a level=0 box
1529 /// @param[out] fval values
1530 void fcube(const keyT& key, const FunctionFunctorInterface<T,NDIM>& f, const Tensor<double>& qx, tensorT& fval) const;
1531
1532 /// Evaluate function at quadrature points in the specified box
1533
1534 /// @param[in] key the key indicating where the quadrature points are located
1535 /// @param[in] f the interface to the elementary function
1536 /// @param[in] qx quadrature points on a level=0 box
1537 /// @param[out] fval values
1538 void fcube(const keyT& key, T (*f)(const coordT&), const Tensor<double>& qx, tensorT& fval) const;
1539
1540 /// Returns cdata.key0
1541 const keyT& key0() const;
1542
1543 /// Prints the coeffs tree of the current function impl
1544 /// @param[in] maxlevel the maximum level of the tree for printing
1545 /// @param[out] os the ostream to where the output is sent
1546 void print_tree(std::ostream& os = std::cout, Level maxlevel = 10000) const;
1547
1548 /// Functor for the do_print_tree method
1549 void do_print_tree(const keyT& key, std::ostream& os, Level maxlevel) const;
1550
1551 /// Prints the coeffs tree of the current function impl (using GraphViz)
1552 /// @param[in] maxlevel the maximum level of the tree for printing
1553 /// @param[out] os the ostream to where the output is sent
1554 void print_tree_graphviz(std::ostream& os = std::cout, Level maxlevel = 10000) const;
1555
1556 /// Functor for the do_print_tree method (using GraphViz)
1557 void do_print_tree_graphviz(const keyT& key, std::ostream& os, Level maxlevel) const;
1558
1559 /// Same as print_tree() but in JSON format
1560 /// @param[out] os the ostream to where the output is sent
1561 /// @param[in] maxlevel the maximum level of the tree for printing
1562 void print_tree_json(std::ostream& os = std::cout, Level maxlevel = 10000) const;
1563
1564 /// Functor for the do_print_tree_json method
1565 void do_print_tree_json(const keyT& key, std::multimap<Level, std::tuple<tranT, std::string>>& data, Level maxlevel) const;
1566
1567 /// convert a number [0,limit] to a hue color code [blue,red],
1568 /// or, if log is set, a number [1.e-10,limit]
1570 double limit;
1571 bool log;
1572 static double lower() {return 1.e-10;};
1574 do_convert_to_color(const double limit, const bool log) : limit(limit), log(log) {}
1575 double operator()(double val) const {
1576 double color=0.0;
1577
1578 if (log) {
1579 double val2=log10(val) - log10(lower()); // will yield >0.0
1580 double upper=log10(limit) -log10(lower());
1581 val2=0.7-(0.7/upper)*val2;
1582 color= std::max(0.0,val2);
1583 color= std::min(0.7,color);
1584 } else {
1585 double hue=0.7-(0.7/limit)*(val);
1586 color= std::max(0.0,hue);
1587 }
1588 return color;
1589 }
1590 };
1591
1592
1593 /// Print a plane ("xy", "xz", or "yz") containing the point x to file
1594
1595 /// works for all dimensions; we walk through the tree, and if a leaf node
1596 /// inside the sub-cell touches the plane we print it in pstricks format
1597 void print_plane(const std::string filename, const int xaxis, const int yaxis, const coordT& el2);
1598
1599 /// collect the data for a plot of the MRA structure locally on each node
1600
1601 /// @param[in] xaxis the x-axis in the plot (can be any axis of the MRA box)
1602 /// @param[in] yaxis the y-axis in the plot (can be any axis of the MRA box)
1603 /// @param[in] el2 needs a description
1604 /// \todo Provide a description for el2
1605 Tensor<double> print_plane_local(const int xaxis, const int yaxis, const coordT& el2);
1606
1607 /// Functor for the print_plane method
1608 /// @param[in] filename the filename for the output
1609 /// @param[in] plotinfo plotting parameters
1610 /// @param[in] xaxis the x-axis in the plot (can be any axis of the MRA box)
1611 /// @param[in] yaxis the y-axis in the plot (can be any axis of the MRA box)
1612 void do_print_plane(const std::string filename, std::vector<Tensor<double> > plotinfo,
1613 const int xaxis, const int yaxis, const coordT el2);
1614
1615 /// print the grid (the roots of the quadrature of each leaf box)
1616 /// of this function in user xyz coordinates
1617 /// @param[in] filename the filename for the output
1618 void print_grid(const std::string filename) const;
1619
1620 /// return the keys of the local leaf boxes
1621 std::vector<keyT> local_leaf_keys() const;
1622
1623 /// print the grid in xyz format
1624
1625 /// the quadrature points and the key information will be written to file,
1626 /// @param[in] filename where the quadrature points will be written to
1627 /// @param[in] keys all leaf keys
1628 void do_print_grid(const std::string filename, const std::vector<keyT>& keys) const;
1629
1630 /// read data from a grid
1631
1632 /// @param[in] keyfile file with keys and grid points for each key
1633 /// @param[in] gridfile file with grid points, w/o key, but with same ordering
1634 /// @param[in] vnuc_functor subtract the values of this functor if regularization is needed
1635 template<size_t FDIM>
1636 typename std::enable_if<NDIM==FDIM>::type
1637 read_grid(const std::string keyfile, const std::string gridfile,
1638 std::shared_ptr< FunctionFunctorInterface<double,NDIM> > vnuc_functor) {
1639
1640 std::ifstream kfile(keyfile.c_str());
1641 std::ifstream gfile(gridfile.c_str());
1642 std::string line;
1643
1644 long ndata,ndata1;
1645 if (not (std::getline(kfile,line))) MADNESS_EXCEPTION("failed reading 1st line of key data",0);
1646 if (not (std::istringstream(line) >> ndata)) MADNESS_EXCEPTION("failed reading k",0);
1647 if (not (std::getline(gfile,line))) MADNESS_EXCEPTION("failed reading 1st line of grid data",0);
1648 if (not (std::istringstream(line) >> ndata1)) MADNESS_EXCEPTION("failed reading k",0);
1649 MADNESS_CHECK(ndata==ndata1);
1650 if (not (std::getline(kfile,line))) MADNESS_EXCEPTION("failed reading 2nd line of key data",0);
1651 if (not (std::getline(gfile,line))) MADNESS_EXCEPTION("failed reading 2nd line of grid data",0);
1652
1653 // the quadrature points in simulation coordinates of the root node
1654 const Tensor<double> qx=cdata.quad_x;
1655 const size_t npt = qx.dim(0);
1656
1657 // the number of coordinates (grid point tuples) per box ({x1},{x2},{x3},..,{xNDIM})
1658 long npoints=power<NDIM>(npt);
1659 // the number of boxes
1660 long nboxes=ndata/npoints;
1661 MADNESS_ASSERT(nboxes*npoints==ndata);
1662 print("reading ",nboxes,"boxes from file",gridfile,keyfile);
1663
1664 // these will be the data
1665 Tensor<T> values(cdata.vk,false);
1666
1667 int ii=0;
1668 std::string gline,kline;
1669 // while (1) {
1670 while (std::getline(kfile,kline)) {
1671
1672 double x,y,z,x1,y1,z1,val;
1673
1674 // get the key
1675 long nn;
1676 Translation l1,l2,l3;
1677 // line looks like: # key: n l1 l2 l3
1678 kline.erase(0,7);
1679 std::stringstream(kline) >> nn >> l1 >> l2 >> l3;
1680 // kfile >> s >> nn >> l1 >> l2 >> l3;
1681 const Vector<Translation,3> ll{ l1,l2,l3 };
1682 Key<3> key(nn,ll);
1683
1684 // this is borrowed from fcube
1685 const Vector<Translation,3>& l = key.translation();
1686 const Level n = key.level();
1687 const double h = std::pow(0.5,double(n));
1688 coordT c; // will hold the point in user coordinates
1691
1692
1693 if (NDIM == 3) {
1694 for (size_t i=0; i<npt; ++i) {
1695 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
1696 for (size_t j=0; j<npt; ++j) {
1697 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
1698 for (size_t k=0; k<npt; ++k) {
1699 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
1700 // fprintf(pFile,"%18.12f %18.12f %18.12f\n",c[0],c[1],c[2]);
1701 auto& success1 = std::getline(gfile,gline); MADNESS_CHECK(success1);
1702 auto& success2 = std::getline(kfile,kline); MADNESS_CHECK(success2);
1703 std::istringstream(gline) >> x >> y >> z >> val;
1704 std::istringstream(kline) >> x1 >> y1 >> z1;
1705 MADNESS_CHECK(std::fabs(x-c[0])<1.e-4);
1706 MADNESS_CHECK(std::fabs(x1-c[0])<1.e-4);
1707 MADNESS_CHECK(std::fabs(y-c[1])<1.e-4);
1708 MADNESS_CHECK(std::fabs(y1-c[1])<1.e-4);
1709 MADNESS_CHECK(std::fabs(z-c[2])<1.e-4);
1710 MADNESS_CHECK(std::fabs(z1-c[2])<1.e-4);
1711
1712 // regularize if a functor is given
1713 if (vnuc_functor) val-=(*vnuc_functor)(c);
1714 values(i,j,k)=val;
1715 }
1716 }
1717 }
1718 } else {
1719 MADNESS_EXCEPTION("only NDIM=3 in print_grid",0);
1720 }
1721
1722 // insert the new leaf node
1723 const bool has_children=false;
1724 coeffT coeff=coeffT(this->values2coeffs(key,values),targs);
1725 nodeT node(coeff,has_children);
1726 coeffs.replace(key,node);
1728 ii++;
1729 }
1730
1731 kfile.close();
1732 gfile.close();
1733 MADNESS_CHECK(ii==nboxes);
1734
1735 }
1736
1737
1738 /// read data from a grid
1739
1740 /// @param[in] gridfile file with keys and grid points and values for each key
1741 /// @param[in] vnuc_functor subtract the values of this functor if regularization is needed
1742 template<size_t FDIM>
1743 typename std::enable_if<NDIM==FDIM>::type
1744 read_grid2(const std::string gridfile,
1745 std::shared_ptr< FunctionFunctorInterface<double,NDIM> > vnuc_functor) {
1746
1747 std::ifstream gfile(gridfile.c_str());
1748 std::string line;
1749
1750 long ndata;
1751 if (not (std::getline(gfile,line))) MADNESS_EXCEPTION("failed reading 1st line of grid data",0);
1752 if (not (std::istringstream(line) >> ndata)) MADNESS_EXCEPTION("failed reading k",0);
1753 if (not (std::getline(gfile,line))) MADNESS_EXCEPTION("failed reading 2nd line of grid data",0);
1754
1755 // the quadrature points in simulation coordinates of the root node
1756 const Tensor<double> qx=cdata.quad_x;
1757 const size_t npt = qx.dim(0);
1758
1759 // the number of coordinates (grid point tuples) per box ({x1},{x2},{x3},..,{xNDIM})
1760 long npoints=power<NDIM>(npt);
1761 // the number of boxes
1762 long nboxes=ndata/npoints;
1763 MADNESS_CHECK(nboxes*npoints==ndata);
1764 print("reading ",nboxes,"boxes from file",gridfile);
1765
1766 // these will be the data
1767 Tensor<T> values(cdata.vk,false);
1768
1769 int ii=0;
1770 std::string gline;
1771 // while (1) {
1772 while (std::getline(gfile,gline)) {
1773
1774 double x1,y1,z1,val;
1775
1776 // get the key
1777 long nn;
1778 Translation l1,l2,l3;
1779 // line looks like: # key: n l1 l2 l3
1780 gline.erase(0,7);
1781 std::stringstream(gline) >> nn >> l1 >> l2 >> l3;
1782 const Vector<Translation,3> ll{ l1,l2,l3 };
1783 Key<3> key(nn,ll);
1784
1785 // this is borrowed from fcube
1786 const Vector<Translation,3>& l = key.translation();
1787 const Level n = key.level();
1788 const double h = std::pow(0.5,double(n));
1789 coordT c; // will hold the point in user coordinates
1792
1793
1794 if (NDIM == 3) {
1795 for (int i=0; i<npt; ++i) {
1796 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
1797 for (int j=0; j<npt; ++j) {
1798 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
1799 for (int k=0; k<npt; ++k) {
1800 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
1801
1802 auto& success = std::getline(gfile,gline);
1803 MADNESS_CHECK(success);
1804 std::istringstream(gline) >> x1 >> y1 >> z1 >> val;
1805 MADNESS_CHECK(std::fabs(x1-c[0])<1.e-4);
1806 MADNESS_CHECK(std::fabs(y1-c[1])<1.e-4);
1807 MADNESS_CHECK(std::fabs(z1-c[2])<1.e-4);
1808
1809 // regularize if a functor is given
1810 if (vnuc_functor) val-=(*vnuc_functor)(c);
1811 values(i,j,k)=val;
1812 }
1813 }
1814 }
1815 } else {
1816 MADNESS_EXCEPTION("only NDIM=3 in print_grid",0);
1817 }
1818
1819 // insert the new leaf node
1820 const bool has_children=false;
1821 coeffT coeff=coeffT(this->values2coeffs(key,values),targs);
1822 nodeT node(coeff,has_children);
1823 coeffs.replace(key,node);
1824 const_cast<dcT&>(coeffs).send(key.parent(),
1826 coeffs, key.parent());
1827 ii++;
1828 }
1829
1830 gfile.close();
1831 MADNESS_CHECK(ii==nboxes);
1832
1833 }
1834
1835
1836 /// Compute by projection the scaling function coeffs in specified box
1837 /// @param[in] key the key to the current function node (box)
1838 tensorT project(const keyT& key) const;
1839
1840 /// Returns the truncation threshold according to truncate_method
1841
1842 /// here is our handwaving argument:
1843 /// this threshold will give each FunctionNode an error of less than tol. The
1844 /// total error can then be as high as sqrt(#nodes) * tol. Therefore in order
1845 /// to account for higher dimensions: divide tol by about the root of number
1846 /// of siblings (2^NDIM) that have a large error when we refine along a deep
1847 /// branch of the tree.
1848 double truncate_tol(double tol, const keyT& key) const;
1849
1850 int get_truncate_mode() const { return truncate_mode; };
1851 void set_truncate_mode(int mode) { truncate_mode = mode; };
1852
1853
1854 /// Returns patch referring to coeffs of child in parent box
1855 /// @param[in] child the key to the child function node (box)
1856 std::vector<Slice> child_patch(const keyT& child) const;
1857
1858 /// Projection with optional refinement w/ special points
1859 /// @param[in] key the key to the current function node (box)
1860 /// @param[in] do_refine should we continue refinement?
1861 /// @param[in] specialpts vector of special points in the function where we need
1862 /// to refine at a much finer level
1863 void project_refine_op(const keyT& key, bool do_refine,
1864 const std::vector<Vector<double,NDIM> >& specialpts);
1865
1866 /// Compute the Legendre scaling functions for multiplication
1867
1868 /// Evaluate parent polyn at quadrature points of a child. The prefactor of
1869 /// 2^n/2 is included. The tensor must be preallocated as phi(k,npt).
1870 /// Refer to the implementation notes for more info.
1871 /// @todo Robert please verify this comment. I don't understand this method.
1872 /// @param[in] np level of the parent function node (box)
1873 /// @param[in] nc level of the child function node (box)
1874 /// @param[in] lp translation of the parent function node (box)
1875 /// @param[in] lc translation of the child function node (box)
1876 /// @param[out] phi tensor of the legendre scaling functions
1877 void phi_for_mul(Level np, Translation lp, Level nc, Translation lc, Tensor<double>& phi) const;
1878
1879 /// Directly project parent coeffs to child coeffs
1880
1881 /// Currently used by diff, but other uses can be anticipated
1882
1883 /// @todo is this documentation correct?
1884 /// @param[in] child the key whose coeffs we are requesting
1885 /// @param[in] parent the (leaf) key of our function
1886 /// @param[in] s the (leaf) coeffs belonging to parent
1887 /// @return coeffs
1888 const coeffT parent_to_child(const coeffT& s, const keyT& parent, const keyT& child) const;
1889
1890 /// Directly project parent NS coeffs to child NS coeffs
1891
1892 /// return the NS coefficients if parent and child are the same,
1893 /// or construct sum coeffs from the parents and "add" zero wavelet coeffs
1894 /// @param[in] child the key whose coeffs we are requesting
1895 /// @param[in] parent the (leaf) key of our function
1896 /// @param[in] coeff the (leaf) coeffs belonging to parent
1897 /// @return coeffs in NS form
1898 coeffT parent_to_child_NS(const keyT& child, const keyT& parent,
1899 const coeffT& coeff) const;
1900
1901 /// Return the values when given the coeffs in scaling function basis
1902 /// @param[in] key the key of the function node (box)
1903 /// @param[in] coeff the tensor of scaling function coefficients for function node (box)
1904 /// @return function values for function node (box)
1905 template <typename Q>
1906 GenTensor<Q> coeffs2values(const keyT& key, const GenTensor<Q>& coeff) const {
1907 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
1908 double scale = pow(2.0,0.5*NDIM*key.level())/sqrt(FunctionDefaults<NDIM>::get_cell_volume());
1909 return transform(coeff,cdata.quad_phit).scale(scale);
1910 }
1911
1912 /// convert S or NS coeffs to values on a 2k grid of the children
1913
1914 /// equivalent to unfiltering the NS coeffs and then converting all child S-coeffs
1915 /// to values in their respective boxes. If only S coeffs are provided d coeffs are
1916 /// assumed to be zero. Reverse operation to values2NScoeffs().
1917 /// @param[in] key the key of the current S or NS coeffs, level n
1918 /// @param[in] coeff coeffs in S or NS form; if S then d coeffs are assumed zero
1919 /// @param[in] s_only sanity check to avoid unintended discard of d coeffs
1920 /// @return function values on the quadrature points of the children of child (!)
1921 template <typename Q>
1923 const bool s_only) const {
1924 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
1925
1926 // sanity checks
1927 MADNESS_ASSERT((coeff.dim(0)==this->get_k()) == s_only);
1928 MADNESS_ASSERT((coeff.dim(0)==this->get_k()) or (coeff.dim(0)==2*this->get_k()));
1929
1930 // this is a block-diagonal matrix with the quadrature points on the diagonal
1931 Tensor<double> quad_phit_2k(2*cdata.k,2*cdata.npt);
1932 quad_phit_2k(cdata.s[0],cdata.s[0])=cdata.quad_phit;
1933 quad_phit_2k(cdata.s[1],cdata.s[1])=cdata.quad_phit;
1934
1935 // the transformation matrix unfilters (cdata.hg) and transforms to values in one step
1936 const Tensor<double> transf = (s_only)
1937 ? inner(cdata.hg(Slice(0,k-1),_),quad_phit_2k) // S coeffs
1938 : inner(cdata.hg,quad_phit_2k); // NS coeffs
1939
1940 // increment the level since the coeffs2values part happens on level n+1
1941 const double scale = pow(2.0,0.5*NDIM*(key.level()+1))/
1943
1944 return transform(coeff,transf).scale(scale);
1945 }
1946
1947 /// Compute the function values for multiplication
1948
1949 /// Given S or NS coefficients from a parent cell, compute the value of
1950 /// the functions at the quadrature points of a child
1951 /// currently restricted to special cases
1952 /// @param[in] child key of the box in which we compute values
1953 /// @param[in] parent key of the parent box holding the coeffs
1954 /// @param[in] coeff coeffs of the parent box
1955 /// @param[in] s_only sanity check to avoid unintended discard of d coeffs
1956 /// @return function values on the quadrature points of the children of child (!)
1957 template <typename Q>
1958 GenTensor<Q> NS_fcube_for_mul(const keyT& child, const keyT& parent,
1959 const GenTensor<Q>& coeff, const bool s_only) const {
1960 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
1961
1962 // sanity checks
1963 MADNESS_ASSERT((coeff.dim(0)==this->get_k()) == s_only);
1964 MADNESS_ASSERT((coeff.dim(0)==this->get_k()) or (coeff.dim(0)==2*this->get_k()));
1965
1966 // fast return if possible
1967 // if (child.level()==parent.level()) return NScoeffs2values(child,coeff,s_only);
1968
1969 if (s_only) {
1970
1971 Tensor<double> quad_phi[NDIM];
1972 // tmp tensor
1973 Tensor<double> phi1(cdata.k,cdata.npt);
1974
1975 for (std::size_t d=0; d<NDIM; ++d) {
1976
1977 // input is S coeffs (dimension k), output is values on 2*npt grid points
1978 quad_phi[d]=Tensor<double>(cdata.k,2*cdata.npt);
1979
1980 // for both children of "child" evaluate the Legendre polynomials
1981 // first the left child on level n+1 and translations 2l
1982 phi_for_mul(parent.level(),parent.translation()[d],
1983 child.level()+1, 2*child.translation()[d], phi1);
1984 quad_phi[d](_,Slice(0,k-1))=phi1;
1985
1986 // next the right child on level n+1 and translations 2l+1
1987 phi_for_mul(parent.level(),parent.translation()[d],
1988 child.level()+1, 2*child.translation()[d]+1, phi1);
1989 quad_phi[d](_,Slice(k,2*k-1))=phi1;
1990 }
1991
1992 const double scale = 1.0/sqrt(FunctionDefaults<NDIM>::get_cell_volume());
1993 return general_transform(coeff,quad_phi).scale(scale);
1994 }
1995 MADNESS_EXCEPTION("you should not be here in NS_fcube_for_mul",1);
1996 return GenTensor<Q>();
1997 }
1998
1999 /// convert function values of the a child generation directly to NS coeffs
2000
2001 /// equivalent to converting the function values to 2^NDIM S coeffs and then
2002 /// filtering them to NS coeffs. Reverse operation to NScoeffs2values().
2003 /// @param[in] key key of the parent of the generation
2004 /// @param[in] values tensor holding function values of the 2^NDIM children of key
2005 /// @return NS coeffs belonging to key
2006 template <typename Q>
2007 GenTensor<Q> values2NScoeffs(const keyT& key, const GenTensor<Q>& values) const {
2008 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2009
2010 // sanity checks
2011 MADNESS_ASSERT(values.dim(0)==2*this->get_k());
2012
2013 // this is a block-diagonal matrix with the quadrature points on the diagonal
2014 Tensor<double> quad_phit_2k(2*cdata.npt,2*cdata.k);
2015 quad_phit_2k(cdata.s[0],cdata.s[0])=cdata.quad_phiw;
2016 quad_phit_2k(cdata.s[1],cdata.s[1])=cdata.quad_phiw;
2017
2018 // the transformation matrix unfilters (cdata.hg) and transforms to values in one step
2019 const Tensor<double> transf=inner(quad_phit_2k,cdata.hgT);
2020
2021 // increment the level since the values2coeffs part happens on level n+1
2022 const double scale = pow(0.5,0.5*NDIM*(key.level()+1))
2024
2025 return transform(values,transf).scale(scale);
2026 }
2027
2028 /// Return the scaling function coeffs when given the function values at the quadrature points
2029 /// @param[in] key the key of the function node (box)
2030 /// @return function values for function node (box)
2031 template <typename Q>
2032 Tensor<Q> coeffs2values(const keyT& key, const Tensor<Q>& coeff) const {
2033 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2034 double scale = pow(2.0,0.5*NDIM*key.level())/sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2035 return transform(coeff,cdata.quad_phit).scale(scale);
2036 }
2037
2038 template <typename Q>
2039 GenTensor<Q> values2coeffs(const keyT& key, const GenTensor<Q>& values) const {
2040 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2041 double scale = pow(0.5,0.5*NDIM*key.level())*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2042 return transform(values,cdata.quad_phiw).scale(scale);
2043 }
2044
2045 template <typename Q>
2046 Tensor<Q> values2coeffs(const keyT& key, const Tensor<Q>& values) const {
2047 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2048 double scale = pow(0.5,0.5*NDIM*key.level())*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2049 return transform(values,cdata.quad_phiw).scale(scale);
2050 }
2051
2052 /// Compute the function values for multiplication
2053
2054 /// Given coefficients from a parent cell, compute the value of
2055 /// the functions at the quadrature points of a child
2056 /// @param[in] child the key for the child function node (box)
2057 /// @param[in] parent the key for the parent function node (box)
2058 /// @param[in] coeff the coefficients of scaling function basis of the parent box
2059 template <typename Q>
2060 Tensor<Q> fcube_for_mul(const keyT& child, const keyT& parent, const Tensor<Q>& coeff) const {
2061 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2062 if (child.level() == parent.level()) {
2063 return coeffs2values(parent, coeff);
2064 }
2065 else if (child.level() < parent.level()) {
2066 MADNESS_EXCEPTION("FunctionImpl: fcube_for_mul: child-parent relationship bad?",0);
2067 }
2068 else {
2069 Tensor<double> phi[NDIM];
2070 for (std::size_t d=0; d<NDIM; ++d) {
2071 phi[d] = Tensor<double>(cdata.k,cdata.npt);
2072 phi_for_mul(parent.level(),parent.translation()[d],
2073 child.level(), child.translation()[d], phi[d]);
2074 }
2075 return general_transform(coeff,phi).scale(1.0/sqrt(FunctionDefaults<NDIM>::get_cell_volume()));;
2076 }
2077 }
2078
2079
2080 /// Compute the function values for multiplication
2081
2082 /// Given coefficients from a parent cell, compute the value of
2083 /// the functions at the quadrature points of a child
2084 /// @param[in] child the key for the child function node (box)
2085 /// @param[in] parent the key for the parent function node (box)
2086 /// @param[in] coeff the coefficients of scaling function basis of the parent box
2087 template <typename Q>
2088 GenTensor<Q> fcube_for_mul(const keyT& child, const keyT& parent, const GenTensor<Q>& coeff) const {
2089 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2090 if (child.level() == parent.level()) {
2091 return coeffs2values(parent, coeff);
2092 }
2093 else if (child.level() < parent.level()) {
2094 MADNESS_EXCEPTION("FunctionImpl: fcube_for_mul: child-parent relationship bad?",0);
2095 }
2096 else {
2097 Tensor<double> phi[NDIM];
2098 for (size_t d=0; d<NDIM; d++) {
2099 phi[d] = Tensor<double>(cdata.k,cdata.npt);
2100 phi_for_mul(parent.level(),parent.translation()[d],
2101 child.level(), child.translation()[d], phi[d]);
2102 }
2103 return general_transform(coeff,phi).scale(1.0/sqrt(FunctionDefaults<NDIM>::get_cell_volume()));
2104 }
2105 }
2106
2107
2108 /// Functor for the mul method
2109 template <typename L, typename R>
2110 void do_mul(const keyT& key, const Tensor<L>& left, const std::pair< keyT, Tensor<R> >& arg) {
2111 // PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2112 const keyT& rkey = arg.first;
2113 const Tensor<R>& rcoeff = arg.second;
2114 //madness::print("do_mul: r", rkey, rcoeff.size());
2115 Tensor<R> rcube = fcube_for_mul(key, rkey, rcoeff);
2116 //madness::print("do_mul: l", key, left.size());
2117 Tensor<L> lcube = fcube_for_mul(key, key, left);
2118
2119 Tensor<T> tcube(cdata.vk,false);
2120 TERNARY_OPTIMIZED_ITERATOR(T, tcube, L, lcube, R, rcube, *_p0 = *_p1 * *_p2;);
2121 double scale = pow(0.5,0.5*NDIM*key.level())*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2122 tcube = transform(tcube,cdata.quad_phiw).scale(scale);
2123 coeffs.replace(key, nodeT(coeffT(tcube,targs),false));
2124 }
2125
2126
2127 /// multiply the values of two coefficient tensors using a custom number of grid points
2128
2129 /// note both coefficient tensors have to refer to the same key!
2130 /// @param[in] c1 a tensor holding coefficients
2131 /// @param[in] c2 another tensor holding coeffs
2132 /// @param[in] npt number of grid points (optional, default is cdata.npt)
2133 /// @return coefficient tensor holding the product of the values of c1 and c2
2134 template<typename R>
2136 const int npt, const keyT& key) const {
2137 typedef TENSOR_RESULT_TYPE(T,R) resultT;
2138
2140
2141 // construct a tensor with the npt coeffs
2142 Tensor<T> c11(cdata2.vk), c22(cdata2.vk);
2143 c11(this->cdata.s0)=c1;
2144 c22(this->cdata.s0)=c2;
2145
2146 // it's sufficient to scale once
2147 double scale = pow(2.0,0.5*NDIM*key.level())/sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2148 Tensor<T> c1value=transform(c11,cdata2.quad_phit).scale(scale);
2149 Tensor<R> c2value=transform(c22,cdata2.quad_phit);
2150 Tensor<resultT> resultvalue(cdata2.vk,false);
2151 TERNARY_OPTIMIZED_ITERATOR(resultT, resultvalue, T, c1value, R, c2value, *_p0 = *_p1 * *_p2;);
2152
2153 Tensor<resultT> result=transform(resultvalue,cdata2.quad_phiw);
2154
2155 // return a copy of the slice to have the tensor contiguous
2156 return copy(result(this->cdata.s0));
2157 }
2158
2159
2160 /// Functor for the binary_op method
2161 template <typename L, typename R, typename opT>
2162 void do_binary_op(const keyT& key, const Tensor<L>& left,
2163 const std::pair< keyT, Tensor<R> >& arg,
2164 const opT& op) {
2165 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2166 const keyT& rkey = arg.first;
2167 const Tensor<R>& rcoeff = arg.second;
2168 Tensor<R> rcube = fcube_for_mul(key, rkey, rcoeff);
2169 Tensor<L> lcube = fcube_for_mul(key, key, left);
2170
2171 Tensor<T> tcube(cdata.vk,false);
2172 op(key, tcube, lcube, rcube);
2173 double scale = pow(0.5,0.5*NDIM*key.level())*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2174 tcube = transform(tcube,cdata.quad_phiw).scale(scale);
2175 coeffs.replace(key, nodeT(coeffT(tcube,targs),false));
2176 }
2177
2178 /// Invoked by result to perform result += alpha*left+beta*right in wavelet basis
2179
2180 /// Does not assume that any of result, left, right have the same distribution.
2181 /// For most purposes result will start as an empty so actually are implementing
2182 /// out of place gaxpy. If all functions have the same distribution there is
2183 /// no communication except for the optional fence.
2184 template <typename L, typename R>
2185 void gaxpy(T alpha, const FunctionImpl<L,NDIM>& left,
2186 T beta, const FunctionImpl<R,NDIM>& right, bool fence) {
2187 // Loop over local nodes in both functions. Add in left and subtract right.
2188 // Not that efficient in terms of memory bandwidth but ensures we do
2189 // not miss any nodes.
2190 typename FunctionImpl<L,NDIM>::dcT::const_iterator left_end = left.coeffs.end();
2192 it!=left_end;
2193 ++it) {
2194 const keyT& key = it->first;
2195 const typename FunctionImpl<L,NDIM>::nodeT& other_node = it->second;
2196 coeffs.send(key, &nodeT:: template gaxpy_inplace<T,L>, 1.0, other_node, alpha);
2197 }
2198 typename FunctionImpl<R,NDIM>::dcT::const_iterator right_end = right.coeffs.end();
2200 it!=right_end;
2201 ++it) {
2202 const keyT& key = it->first;
2203 const typename FunctionImpl<L,NDIM>::nodeT& other_node = it->second;
2204 coeffs.send(key, &nodeT:: template gaxpy_inplace<T,R>, 1.0, other_node, beta);
2205 }
2206 if (fence)
2207 world.gop.fence();
2208 }
2209
2210 /// Unary operation applied inplace to the coefficients WITHOUT refinement, optional fence
2211 /// @param[in] op the unary operator for the coefficients
2212 template <typename opT>
2213 void unary_op_coeff_inplace(const opT& op, bool fence) {
2214 typename dcT::iterator end = coeffs.end();
2215 for (typename dcT::iterator it=coeffs.begin(); it!=end; ++it) {
2216 const keyT& parent = it->first;
2217 nodeT& node = it->second;
2218 if (node.has_coeff()) {
2219 // op(parent, node.coeff());
2220 TensorArgs full(-1.0,TT_FULL);
2221 change_tensor_type(node.coeff(),full);
2222 op(parent, node.coeff().full_tensor());
2224 // op(parent,node);
2225 }
2226 }
2227 if (fence)
2228 world.gop.fence();
2229 }
2230
2231 /// Unary operation applied inplace to the coefficients WITHOUT refinement, optional fence
2232 /// @param[in] op the unary operator for the coefficients
2233 template <typename opT>
2234 void unary_op_node_inplace(const opT& op, bool fence) {
2235 typename dcT::iterator end = coeffs.end();
2236 for (typename dcT::iterator it=coeffs.begin(); it!=end; ++it) {
2237 const keyT& parent = it->first;
2238 nodeT& node = it->second;
2239 op(parent, node);
2240 }
2241 if (fence)
2242 world.gop.fence();
2243 }
2244
2245 /// Integrate over one particle of a two particle function and get a one particle function
2246 /// bsp \int g(1,2) \delta(2-1) d2 = f(1)
2247 /// The overall dimension of g should be even
2248
2249 /// The operator
2250 template<std::size_t LDIM>
2251 void dirac_convolution_op(const keyT &key, const nodeT &node, FunctionImpl<T,LDIM>* f) const {
2252 // fast return if the node has children (not a leaf node)
2253 if(node.has_children()) return;
2254
2255 const implT* g=this;
2256
2257 // break the 6D key into two 3D keys (may also work for every even dimension)
2258 Key<LDIM> key1, key2;
2259 key.break_apart(key1,key2);
2260
2261 // get the coefficients of the 6D function g
2262 const coeffT& g_coeff = node.coeff();
2263
2264 // get the values of the 6D function g
2265 coeffT g_values = g->coeffs2values(key,g_coeff);
2266
2267 // Determine rank and k
2268 const long rank=g_values.rank();
2269 const long maxk=f->get_k();
2270 MADNESS_ASSERT(maxk==g_coeff.dim(0));
2271
2272 // get tensors for particle 1 and 2 (U and V in SVD)
2273 tensorT vec1=copy(g_values.get_svdtensor().ref_vector(0).reshape(rank,maxk,maxk,maxk));
2274 tensorT vec2=g_values.get_svdtensor().ref_vector(1).reshape(rank,maxk,maxk,maxk);
2275 tensorT result(maxk,maxk,maxk); // should give zero tensor
2276 // Multiply the values of each U and V vector
2277 for (long i=0; i<rank; ++i) {
2278 tensorT c1=vec1(Slice(i,i),_,_,_); // shallow copy (!)
2279 tensorT c2=vec2(Slice(i,i),_,_,_);
2280 c1.emul(c2); // this changes vec1 because of shallow copy, but not the g function because of the deep copy made above
2281 double singular_value_i = g_values.get_svdtensor().weights(i);
2282 result += (singular_value_i*c1);
2283 }
2284
2285 // accumulate coefficients (since only diagonal boxes are used the coefficients get just replaced, but accumulate is needed to create the right tree structure
2286 tensorT f_coeff = f->values2coeffs(key1,result);
2287 f->coeffs.task(key1, &FunctionNode<T,LDIM>::accumulate2, f_coeff, f->coeffs, key1, TaskAttributes::hipri());
2288// coeffs.task(dest, &nodeT::accumulate2, result, coeffs, dest, TaskAttributes::hipri());
2289
2290
2291 return;
2292 }
2293
2294
2295 template<std::size_t LDIM>
2297 typename dcT::const_iterator end = this->coeffs.end();
2298 for (typename dcT::const_iterator it=this->coeffs.begin(); it!=end; ++it) {
2299 // looping through all the leaf(!) coefficients in the NDIM function ("this")
2300 const keyT& key = it->first;
2301 const FunctionNode<T,NDIM>& node = it->second;
2302 if (node.is_leaf()) {
2303 // only process the diagonal boxes
2304 Key<LDIM> key1, key2;
2305 key.break_apart(key1,key2);
2306 if(key1 == key2){
2307 ProcessID p = coeffs.owner(key);
2308 woT::task(p, &implT:: template dirac_convolution_op<LDIM>, key, node, f);
2309 }
2310 }
2311 }
2312 world.gop.fence(); // fence is necessary if trickle down is used afterwards
2313 // trickle down and undo redundand shouldnt change anything if only the diagonal elements are considered above -> check this
2314 f->trickle_down(true); // fence must be true otherwise undo_redundant will have trouble
2315// f->undo_redundant(true);
2316 f->verify_tree();
2317 //if (fence) world.gop.fence(); // unnecessary, fence is activated in undo_redundant
2318
2319 }
2320
2321
2322 /// Unary operation applied inplace to the coefficients WITHOUT refinement, optional fence
2323 /// @param[in] op the unary operator for the coefficients
2324 template <typename opT>
2325 void flo_unary_op_node_inplace(const opT& op, bool fence) {
2327// typedef do_unary_op_value_inplace<opT> xopT;
2329 if (fence) world.gop.fence();
2330 }
2331
2332 /// Unary operation applied inplace to the coefficients WITHOUT refinement, optional fence
2333 /// @param[in] op the unary operator for the coefficients
2334 template <typename opT>
2335 void flo_unary_op_node_inplace(const opT& op, bool fence) const {
2337// typedef do_unary_op_value_inplace<opT> xopT;
2339 if (fence)
2340 world.gop.fence();
2341 }
2342
2343 /// truncate tree at a certain level
2344 /// @param[in] max_level truncate tree below this level
2345 void erase(const Level& max_level);
2346
2347 /// Returns some asymmetry measure ... no comms
2348 double check_symmetry_local() const;
2349
2350 /// given an NS tree resulting from a convolution, truncate leafs if appropriate
2353 const implT* f; // for calling its member functions
2354
2356
2357 bool operator()(typename rangeT::iterator& it) const {
2358
2359 const keyT& key = it->first;
2360 nodeT& node = it->second;
2361
2362 if (node.is_leaf() and node.coeff().has_data()) {
2363 coeffT d = copy(node.coeff());
2364 d(f->cdata.s0)=0.0;
2365 const double error=d.normf();
2366 const double tol=f->truncate_tol(f->get_thresh(),key);
2367 if (error<tol) node.coeff()=copy(node.coeff()(f->cdata.s0));
2368 }
2369 return true;
2370 }
2371 template <typename Archive> void serialize(const Archive& ar) {}
2372
2373 };
2374
2375 /// remove all coefficients of internal nodes
2378
2379 /// constructor need impl for cdata
2381
2382 bool operator()(typename rangeT::iterator& it) const {
2383
2384 nodeT& node = it->second;
2385 if (node.has_children()) node.clear_coeff();
2386 return true;
2387 }
2388 template <typename Archive> void serialize(const Archive& ar) {}
2389
2390 };
2391
2392 /// remove all coefficients of leaf nodes
2395
2396 /// constructor need impl for cdata
2398
2399 bool operator()(typename rangeT::iterator& it) const {
2400 nodeT& node = it->second;
2401 if (not node.has_children()) node.clear_coeff();
2402 return true;
2403 }
2404 template <typename Archive> void serialize(const Archive& ar) {}
2405
2406 };
2407
2408
2409 /// keep only the sum coefficients in each node
2413
2414 /// constructor need impl for cdata
2416
2417 bool operator()(typename rangeT::iterator& it) const {
2418
2419 nodeT& node = it->second;
2420 coeffT s=copy(node.coeff()(impl->cdata.s0));
2421 node.coeff()=s;
2422 return true;
2423 }
2424 template <typename Archive> void serialize(const Archive& ar) {}
2425
2426 };
2427
2428
2429 /// reduce the rank of the nodes, optional fence
2432
2433 // threshold for rank reduction / SVD truncation
2435
2436 // constructor takes target precision
2437 do_reduce_rank() = default;
2439 do_reduce_rank(const double& thresh) {
2441 }
2442
2443 //
2444 bool operator()(typename rangeT::iterator& it) const {
2445
2446 nodeT& node = it->second;
2447 node.reduceRank(args.thresh);
2448 return true;
2449 }
2450 template <typename Archive> void serialize(const Archive& ar) {}
2451 };
2452
2453
2454
2455 /// check symmetry wrt particle exchange
2458 const implT* f;
2461
2462 /// return the norm of the difference of this node and its "mirror" node
2463 double operator()(typename rangeT::iterator& it) const {
2464
2465 // Temporary fix to GCC whining about out of range access for NDIM!=6
2466 if constexpr(NDIM==6) {
2467 const keyT& key = it->first;
2468 const nodeT& fnode = it->second;
2469
2470 // skip internal nodes
2471 if (fnode.has_children()) return 0.0;
2472
2473 if (f->world.size()>1) return 0.0;
2474
2475 // exchange particles
2476 std::vector<long> map(NDIM);
2477 map[0]=3; map[1]=4; map[2]=5;
2478 map[3]=0; map[4]=1; map[5]=2;
2479
2480 // make mapped key
2482 for (std::size_t i=0; i<NDIM; ++i) l[map[i]] = key.translation()[i];
2483 const keyT mapkey(key.level(),l);
2484
2485 double norm=0.0;
2486
2487
2488 // hope it's local
2489 if (f->get_coeffs().probe(mapkey)) {
2490 MADNESS_ASSERT(f->get_coeffs().probe(mapkey));
2491 const nodeT& mapnode=f->get_coeffs().find(mapkey).get()->second;
2492
2493// bool have_c1=fnode.coeff().has_data() and fnode.coeff().config().has_data();
2494// bool have_c2=mapnode.coeff().has_data() and mapnode.coeff().config().has_data();
2495 bool have_c1=fnode.coeff().has_data();
2496 bool have_c2=mapnode.coeff().has_data();
2497
2498 if (have_c1 and have_c2) {
2499 tensorT c1=fnode.coeff().full_tensor_copy();
2500 tensorT c2=mapnode.coeff().full_tensor_copy();
2501 c2 = copy(c2.mapdim(map));
2502 norm=(c1-c2).normf();
2503 } else if (have_c1) {
2504 tensorT c1=fnode.coeff().full_tensor_copy();
2505 norm=c1.normf();
2506 } else if (have_c2) {
2507 tensorT c2=mapnode.coeff().full_tensor_copy();
2508 norm=c2.normf();
2509 } else {
2510 norm=0.0;
2511 }
2512 } else {
2513 norm=fnode.coeff().normf();
2514 }
2515 return norm*norm;
2516 }
2517 else {
2518 MADNESS_EXCEPTION("ONLY FOR DIM 6!", 1);
2519 }
2520 }
2521
2522 double operator()(double a, double b) const {
2523 return (a+b);
2524 }
2525
2526 template <typename Archive> void serialize(const Archive& ar) {
2527 MADNESS_EXCEPTION("no serialization of do_check_symmetry yet",1);
2528 }
2529
2530
2531 };
2532
2533 /// merge the coefficent boxes of this into result's tree
2534
2535 /// result+= alpha*this
2536 /// this and result don't have to have the same distribution or live in the same world
2537 /// no comm, and the tree should be in an consistent state by virtue
2538 template<typename Q, typename R>
2542 T alpha=T(1.0);
2546
2547 /// return the norm of the difference of this node and its "mirror" node
2548 bool operator()(typename rangeT::iterator& it) const {
2549
2550 const keyT& key = it->first;
2551 const nodeT& node = it->second;
2552 if (node.has_coeff()) result->get_coeffs().task(key, &nodeT::accumulate,
2553 alpha*node.coeff(), result->get_coeffs(), key, result->targs);
2554 return true;
2555 }
2556
2557 template <typename Archive> void serialize(const Archive& ar) {
2558 MADNESS_EXCEPTION("no serialization of do_accumulate_trees",1);
2559 }
2560 };
2561
2562
2563 /// merge the coefficient boxes of this into other's tree
2564
2565 /// no comm, and the tree should be in an consistent state by virtue
2566 /// of FunctionNode::gaxpy_inplace
2567 template<typename Q, typename R>
2576
2577 /// return the norm of the difference of this node and its "mirror" node
2578 bool operator()(typename rangeT::iterator& it) const {
2579
2580 const keyT& key = it->first;
2581 const nodeT& fnode = it->second;
2582
2583 // if other's node exists: add this' coeffs to it
2584 // otherwise insert this' node into other's tree
2585 typename dcT::accessor acc;
2586 if (other->get_coeffs().find(acc,key)) {
2587 nodeT& gnode=acc->second;
2588 gnode.gaxpy_inplace(beta,fnode,alpha);
2589 } else {
2590 nodeT gnode=fnode;
2591 gnode.scale(alpha);
2592 other->get_coeffs().replace(key,gnode);
2593 }
2594 return true;
2595 }
2596
2597 template <typename Archive> void serialize(const Archive& ar) {
2598 MADNESS_EXCEPTION("no serialization of do_merge_trees",1);
2599 }
2600 };
2601
2602
2603 /// map this on f
2604 struct do_mapdim {
2606
2607 std::vector<long> map;
2609
2610 do_mapdim() : f(0) {};
2611 do_mapdim(const std::vector<long> map, implT& f) : map(map), f(&f) {}
2612
2613 bool operator()(typename rangeT::iterator& it) const {
2614
2615 const keyT& key = it->first;
2616 const nodeT& node = it->second;
2617
2619 for (std::size_t i=0; i<NDIM; ++i) l[map[i]] = key.translation()[i];
2620 tensorT c = node.coeff().reconstruct_tensor();
2621 if (c.size()) c = copy(c.mapdim(map));
2623 f->get_coeffs().replace(keyT(key.level(),l), nodeT(cc,node.has_children()));
2624
2625 return true;
2626 }
2627 template <typename Archive> void serialize(const Archive& ar) {
2628 MADNESS_EXCEPTION("no serialization of do_mapdim",1);
2629 }
2630
2631 };
2632
2633 /// mirror dimensions of this, write result on f
2634 struct do_mirror {
2636
2637 std::vector<long> mirror;
2639
2640 do_mirror() : f(0) {};
2641 do_mirror(const std::vector<long> mirror, implT& f) : mirror(mirror), f(&f) {}
2642
2643 bool operator()(typename rangeT::iterator& it) const {
2644
2645 const keyT& key = it->first;
2646 const nodeT& node = it->second;
2647
2648 // mirror translation index: l_new + l_old = l_max
2650 Translation lmax = (Translation(1)<<key.level()) - 1;
2651 for (std::size_t i=0; i<NDIM; ++i) {
2652 if (mirror[i]==-1) l[i]= lmax - key.translation()[i];
2653 }
2654
2655 // mirror coefficients: multiply all odd-k slices with -1
2656 tensorT c = node.coeff().full_tensor_copy();
2657 if (c.size()) {
2658 std::vector<Slice> s(___);
2659
2660 // loop over dimensions and over k
2661 for (size_t i=0; i<NDIM; ++i) {
2662 std::size_t kmax=c.dim(i);
2663 if (mirror[i]==-1) {
2664 for (size_t k=1; k<kmax; k+=2) {
2665 s[i]=Slice(k,k,1);
2666 c(s)*=(-1.0);
2667 }
2668 s[i]=_;
2669 }
2670 }
2671 }
2673 f->get_coeffs().replace(keyT(key.level(),l), nodeT(cc,node.has_children()));
2674
2675 return true;
2676 }
2677 template <typename Archive> void serialize(const Archive& ar) {
2678 MADNESS_EXCEPTION("no serialization of do_mirror",1);
2679 }
2680
2681 };
2682
2683 /// mirror dimensions of this, write result on f
2686
2687 std::vector<long> map,mirror;
2689
2691 do_map_and_mirror(const std::vector<long> map, const std::vector<long> mirror, implT& f)
2692 : map(map), mirror(mirror), f(&f) {}
2693
2694 bool operator()(typename rangeT::iterator& it) const {
2695
2696 const keyT& key = it->first;
2697 const nodeT& node = it->second;
2698
2699 tensorT c = node.coeff().full_tensor_copy();
2701
2702 // do the mapping first (if present)
2703 if (map.size()>0) {
2705 for (std::size_t i=0; i<NDIM; ++i) l1[map[i]] = l[i];
2706 std::swap(l,l1);
2707 if (c.size()) c = copy(c.mapdim(map));
2708 }
2709
2710 if (mirror.size()>0) {
2711 // mirror translation index: l_new + l_old = l_max
2713 Translation lmax = (Translation(1)<<key.level()) - 1;
2714 for (std::size_t i=0; i<NDIM; ++i) {
2715 if (mirror[i]==-1) l1[i]= lmax - l[i];
2716 }
2717 std::swap(l,l1);
2718
2719 // mirror coefficients: multiply all odd-k slices with -1
2720 if (c.size()) {
2721 std::vector<Slice> s(___);
2722
2723 // loop over dimensions and over k
2724 for (size_t i=0; i<NDIM; ++i) {
2725 std::size_t kmax=c.dim(i);
2726 if (mirror[i]==-1) {
2727 for (size_t k=1; k<kmax; k+=2) {
2728 s[i]=Slice(k,k,1);
2729 c(s)*=(-1.0);
2730 }
2731 s[i]=_;
2732 }
2733 }
2734 }
2735 }
2736
2738 f->get_coeffs().replace(keyT(key.level(),l), nodeT(cc,node.has_children()));
2739 return true;
2740 }
2741 template <typename Archive> void serialize(const Archive& ar) {
2742 MADNESS_EXCEPTION("no serialization of do_mirror",1);
2743 }
2744
2745 };
2746
2747
2748
2749 /// "put" this on g
2750 struct do_average {
2752
2754
2755 do_average() : g(0) {}
2757
2758 /// iterator it points to this
2759 bool operator()(typename rangeT::iterator& it) const {
2760
2761 const keyT& key = it->first;
2762 const nodeT& fnode = it->second;
2763
2764 // fast return if rhs has no coeff here
2765 if (fnode.has_coeff()) {
2766
2767 // check if there is a node already existing
2768 typename dcT::accessor acc;
2769 if (g->get_coeffs().find(acc,key)) {
2770 nodeT& gnode=acc->second;
2771 if (gnode.has_coeff()) gnode.coeff()+=fnode.coeff();
2772 } else {
2773 g->get_coeffs().replace(key,fnode);
2774 }
2775 }
2776
2777 return true;
2778 }
2779 template <typename Archive> void serialize(const Archive& ar) {}
2780 };
2781
2782 /// change representation of nodes' coeffs to low rank, optional fence
2785
2786 // threshold for rank reduction / SVD truncation
2789
2790 // constructor takes target precision
2792 // do_change_tensor_type(const TensorArgs& targs) : targs(targs) {}
2794
2795 //
2796 bool operator()(typename rangeT::iterator& it) const {
2797
2798 double cpu0=cpu_time();
2799 nodeT& node = it->second;
2801 double cpu1=cpu_time();
2803
2804 return true;
2805
2806 }
2807 template <typename Archive> void serialize(const Archive& ar) {}
2808 };
2809
2812
2813 // threshold for rank reduction / SVD truncation
2815
2816 // constructor takes target precision
2819 bool operator()(typename rangeT::iterator& it) const {
2820 it->second.consolidate_buffer(targs);
2821 return true;
2822 }
2823 template <typename Archive> void serialize(const Archive& ar) {}
2824 };
2825
2826
2827
2828 template <typename opT>
2832 opT op;
2834 bool operator()(typename rangeT::iterator& it) const {
2835 const keyT& key = it->first;
2836 nodeT& node = it->second;
2837 if (node.has_coeff()) {
2838 const TensorArgs full_args(-1.0,TT_FULL);
2839 change_tensor_type(node.coeff(),full_args);
2840 tensorT& t= node.coeff().full_tensor();
2841 //double before = t.normf();
2842 tensorT values = impl->fcube_for_mul(key, key, t);
2843 op(key, values);
2844 double scale = pow(0.5,0.5*NDIM*key.level())*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2845 t = transform(values,impl->cdata.quad_phiw).scale(scale);
2846 node.coeff()=coeffT(t,impl->get_tensor_args());
2847 //double after = t.normf();
2848 //madness::print("XOP:", key, before, after);
2849 }
2850 return true;
2851 }
2852 template <typename Archive> void serialize(const Archive& ar) {}
2853 };
2854
2855 template <typename Q, typename R>
2856 /// @todo I don't know what this does other than a trasform
2857 void vtransform_doit(const std::shared_ptr< FunctionImpl<R,NDIM> >& right,
2858 const Tensor<Q>& c,
2859 const std::vector< std::shared_ptr< FunctionImpl<T,NDIM> > >& vleft,
2860 double tol) {
2861 // To reduce crunch on vectors being transformed each task
2862 // does them in a random order
2863 std::vector<unsigned int> ind(vleft.size());
2864 for (unsigned int i=0; i<vleft.size(); ++i) {
2865 ind[i] = i;
2866 }
2867 for (unsigned int i=0; i<vleft.size(); ++i) {
2868 unsigned int j = RandomValue<int>()%vleft.size();
2869 std::swap(ind[i],ind[j]);
2870 }
2871
2872 for (const auto& [key, rnode] : right->coeffs) {
2873 if (rnode.has_coeff()) {
2874 const GenTensor<R>& r = rnode.coeff();
2875 double norm = r.normf();
2876 double keytol = truncate_tol(tol,key);
2877
2878 for (unsigned int j=0; j<vleft.size(); ++j) {
2879 unsigned int i = ind[j]; // Random permutation
2880 if (std::abs(norm*c(i)) > keytol) {
2881 implT* left = vleft[i].get();
2882 typename dcT::accessor acc;
2883 bool new_node = left->coeffs.insert(acc,key);
2884 if (new_node) {
2885 /* Notify parent nodes that a new child exists. */
2886 Key<NDIM> parent = key.parent();
2887 if (left->coeffs.is_local(parent))
2888 left->coeffs.send(parent, &nodeT::set_has_children_recursive, left->coeffs, parent);
2889 else
2890 left->coeffs.task(parent, &nodeT::set_has_children_recursive, left->coeffs, parent);
2891 }
2892 nodeT& node = acc->second;
2893 node.gaxpy_inplace(1.0, rnode, c(i));
2894 }
2895 }
2896 }
2897 }
2898 }
2899
2900 /// Refine multiple functions down to the same finest level
2901
2902 /// @param v the vector of functions we are refining.
2903 /// @param key the current node.
2904 /// @param c the vector of coefficients passed from above.
2905 void refine_to_common_level(const std::vector<FunctionImpl<T,NDIM>*>& v,
2906 const std::vector<tensorT>& c,
2907 const keyT key);
2908
2909 /// Inplace operate on many functions (impl's) with an operator within a certain box
2910 /// @param[in] key the key of the current function node (box)
2911 /// @param[in] op the operator
2912 /// @param[in] v the vector of function impl's on which to be operated
2913 template <typename opT>
2914 void multiop_values_doit(const keyT& key, const opT& op, const std::vector<implT*>& v) {
2915 std::vector<tensorT> c(v.size());
2916 for (unsigned int i=0; i<v.size(); i++) {
2917 if (v[i]) {
2918 coeffT cc = coeffs2values(key, v[i]->coeffs.find(key).get()->second.coeff());
2919 c[i]=cc.full_tensor();
2920 }
2921 }
2922 tensorT r = op(key, c);
2923 coeffs.replace(key, nodeT(coeffT(values2coeffs(key, r),targs),false));
2924 }
2925
2926 /// Inplace operate on many functions (impl's) with an operator within a certain box
2927 /// Assumes all functions have been refined down to the same level
2928 /// @param[in] op the operator
2929 /// @param[in] v the vector of function impl's on which to be operated
2930 template <typename opT>
2931 void multiop_values(const opT& op, const std::vector<implT*>& v) {
2932 // rough check on refinement level (ignore non-initialized functions
2933 for (std::size_t i=1; i<v.size(); ++i) {
2934 if (v[i] and v[i-1]) {
2935 MADNESS_ASSERT(v[i]->coeffs.size()==v[i-1]->coeffs.size());
2936 }
2937 }
2938 typename dcT::iterator end = v[0]->coeffs.end();
2939 for (typename dcT::iterator it=v[0]->coeffs.begin(); it!=end; ++it) {
2940 const keyT& key = it->first;
2941 if (it->second.has_coeff())
2942 world.taskq.add(*this, &implT:: template multiop_values_doit<opT>, key, op, v);
2943 else
2944 coeffs.replace(key, nodeT(coeffT(),true));
2945 }
2946 world.gop.fence();
2947 }
2948
2949 /// Inplace operate on many functions (impl's) with an operator within a certain box
2950
2951 /// @param[in] key the key of the current function node (box)
2952 /// @param[in] op the operator
2953 /// @param[in] vin the vector of function impl's on which to be operated
2954 /// @param[out] vout the resulting vector of function impl's
2955 template <typename opT>
2956 void multi_to_multi_op_values_doit(const keyT& key, const opT& op,
2957 const std::vector<implT*>& vin, std::vector<implT*>& vout) {
2958 std::vector<tensorT> c(vin.size());
2959 for (unsigned int i=0; i<vin.size(); i++) {
2960 if (vin[i]) {
2961 coeffT cc = coeffs2values(key, vin[i]->coeffs.find(key).get()->second.coeff());
2962 c[i]=cc.full_tensor();
2963 }
2964 }
2965 std::vector<tensorT> r = op(key, c);
2966 MADNESS_ASSERT(r.size()==vout.size());
2967 for (std::size_t i=0; i<vout.size(); ++i) {
2968 vout[i]->coeffs.replace(key, nodeT(coeffT(values2coeffs(key, r[i]),targs),false));
2969 }
2970 }
2971
2972 /// Inplace operate on many functions (impl's) with an operator within a certain box
2973
2974 /// Assumes all functions have been refined down to the same level
2975 /// @param[in] op the operator
2976 /// @param[in] vin the vector of function impl's on which to be operated
2977 /// @param[out] vout the resulting vector of function impl's
2978 template <typename opT>
2979 void multi_to_multi_op_values(const opT& op, const std::vector<implT*>& vin,
2980 std::vector<implT*>& vout, const bool fence=true) {
2981 // rough check on refinement level (ignore non-initialized functions
2982 for (std::size_t i=1; i<vin.size(); ++i) {
2983 if (vin[i] and vin[i-1]) {
2984 MADNESS_ASSERT(vin[i]->coeffs.size()==vin[i-1]->coeffs.size());
2985 }
2986 }
2987 typename dcT::iterator end = vin[0]->coeffs.end();
2988 for (typename dcT::iterator it=vin[0]->coeffs.begin(); it!=end; ++it) {
2989 const keyT& key = it->first;
2990 if (it->second.has_coeff())
2991 world.taskq.add(*this, &implT:: template multi_to_multi_op_values_doit<opT>,
2992 key, op, vin, vout);
2993 else {
2994 // fill result functions with empty box in this key
2995 for (implT* it2 : vout) {
2996 it2->coeffs.replace(key, nodeT(coeffT(),true));
2997 }
2998 }
2999 }
3000 if (fence) world.gop.fence();
3001 }
3002
3003 /// Transforms a vector of functions left[i] = sum[j] right[j]*c[j,i] using sparsity
3004 /// @param[in] vright vector of functions (impl's) on which to be transformed
3005 /// @param[in] c the tensor (matrix) transformer
3006 /// @param[in] vleft vector of of the *newly* transformed functions (impl's)
3007 template <typename Q, typename R>
3008 void vtransform(const std::vector< std::shared_ptr< FunctionImpl<R,NDIM> > >& vright,
3009 const Tensor<Q>& c,
3010 const std::vector< std::shared_ptr< FunctionImpl<T,NDIM> > >& vleft,
3011 double tol,
3012 bool fence) {
3013 for (unsigned int j=0; j<vright.size(); ++j) {
3014 world.taskq.add(*this, &implT:: template vtransform_doit<Q,R>, vright[j], copy(c(j,_)), vleft, tol);
3015 }
3016 if (fence)
3017 world.gop.fence();
3018 }
3019
3020 /// Unary operation applied inplace to the values with optional refinement and fence
3021 /// @param[in] op the unary operator for the values
3022 template <typename opT>
3023 void unary_op_value_inplace(const opT& op, bool fence) {
3025 typedef do_unary_op_value_inplace<opT> xopT;
3026 world.taskq.for_each<rangeT,xopT>(rangeT(coeffs.begin(), coeffs.end()), xopT(this,op));
3027 if (fence)
3028 world.gop.fence();
3029 }
3030
3031 // Multiplication assuming same distribution and recursive descent
3032 /// Both left and right functions are in the scaling function basis
3033 /// @param[in] key the key to the current function node (box)
3034 /// @param[in] left the function impl associated with the left function
3035 /// @param[in] lcin the scaling function coefficients associated with the
3036 /// current box in the left function
3037 /// @param[in] vrightin the vector of function impl's associated with
3038 /// the vector of right functions
3039 /// @param[in] vrcin the vector scaling function coefficients associated with the
3040 /// current box in the right functions
3041 /// @param[out] vresultin the vector of resulting functions (impl's)
3042 template <typename L, typename R>
3043 void mulXXveca(const keyT& key,
3044 const FunctionImpl<L,NDIM>* left, const Tensor<L>& lcin,
3045 const std::vector<const FunctionImpl<R,NDIM>*> vrightin,
3046 const std::vector< Tensor<R> >& vrcin,
3047 const std::vector<FunctionImpl<T,NDIM>*> vresultin,
3048 double tol) {
3049 typedef typename FunctionImpl<L,NDIM>::dcT::const_iterator literT;
3050 typedef typename FunctionImpl<R,NDIM>::dcT::const_iterator riterT;
3051
3052 double lnorm = 1e99;
3053 double ldnorm = 1e99;
3054 bool l_is_leaf = false;
3055 Tensor<L> lc = lcin;
3056 literT lit = left->coeffs.find(key).get();
3057
3058 if (lc.size() == 0) {
3059 MADNESS_CHECK(lit != left->coeffs.end());
3060 lnorm = lit->second.get_norm_tree();
3061 ldnorm = lit->second.get_dnorm_tree();
3062 l_is_leaf = !lit->second.has_children();
3063 }
3064 else {
3065 lnorm = lc.normf();
3066 ldnorm = 0.0; // node created to match trees; leaves carry no detail
3067 l_is_leaf = true;
3068 }
3069
3070 // Loop thru RHS functions seeing if anything can be multiplied
3071 std::vector<FunctionImpl<T,NDIM>*> vresult;
3072 std::vector<const FunctionImpl<R,NDIM>*> vright;
3073 std::vector< Tensor<R> > vrc;
3074 vresult.reserve(vrightin.size());
3075 vright.reserve(vrightin.size());
3076 vrc.reserve(vrightin.size());
3077
3078 // fetched at most once and shared by every right function; do_mul only reads it
3079 Tensor<L> lc_shared;
3080 bool lc_shared_set = false;
3081 auto left_coeffs = [&]() -> const Tensor<L>& {
3082 if (!lc_shared_set) {
3083 lc_shared = lc.size() ? lc : lit->second.coeff().full_tensor_copy();
3084 lc_shared_set = true;
3085 }
3086 return lc_shared;
3087 };
3088
3089 for (unsigned int i=0; i<vrightin.size(); ++i) {
3090 FunctionImpl<T,NDIM>* result = vresultin[i];
3091 const FunctionImpl<R,NDIM>* right = vrightin[i];
3092 Tensor<R> rc = vrcin[i];
3093 double rnorm, rdnorm;
3094 riterT rit = right->coeffs.find(key).get();
3095 if (rc.size() == 0) {
3096 MADNESS_CHECK(rit != right->coeffs.end());
3097 rnorm = rit->second.get_norm_tree();
3098 rdnorm = rit->second.get_dnorm_tree();
3099 }
3100 else {
3101 rnorm = rc.normf();
3102 rdnorm = 0.0;
3103 }
3104
3105 if (ldnorm >= NORM_TREE_UNCOMPUTED || rdnorm >= NORM_TREE_UNCOMPUTED) {
3106 static std::atomic<bool> warned{false};
3107 bool expected = false;
3108 if (warned.compare_exchange_strong(expected, true))
3109 print("WARNING: mul_sparse operand has an uncomputed dnorm_tree; "
3110 "screening is disabled for those nodes (missing make_redundant?)");
3111 }
3112
3113 // the neglected cross terms are below threshold: multiply here (requires redundant form)
3114 if (rnorm*ldnorm + lnorm*rdnorm + ldnorm*rdnorm <= truncate_tol(tol, key)) {
3115 // lc/rc must keep their size for the recursion logic, so pass separate tensors
3116 Tensor<R> rc_data = (rc.size() == 0) ? rit->second.coeff().full_tensor_copy() : rc;
3117 result->task(world.rank(), &implT:: template do_mul<L,R>, key, left_coeffs(), std::make_pair(key,rc_data));
3118 }
3119 else { // Interior node
3120 result->coeffs.replace(key, nodeT(coeffT(),true));
3121 vresult.push_back(result);
3122 vright.push_back(right);
3123 vrc.push_back(rc);
3124 }
3125 }
3126
3127 if (vresult.size()) {
3128 Tensor<L> lss;
3129 if (lc.size() || l_is_leaf) {
3130 Tensor<L> ld(cdata.v2k);
3131 ld(cdata.s0) = left_coeffs()(___);
3132 lss = left->unfilter(ld);
3133 }
3134
3135 // invariant across the child loop below, so look it up once per right function
3136 std::vector<char> r_unfiltered(vresult.size(), 0);
3137 std::vector< Tensor<R> > vrss(vresult.size());
3138 for (unsigned int i=0; i<vresult.size(); ++i) {
3139 riterT rit = vright[i]->coeffs.find(key).get();
3140 if (vrc[i].size() || !rit->second.has_children()) {
3141 Tensor<R> rd(cdata.v2k);
3142 rd(cdata.s0) = (vrc[i].size() ? vrc[i] : rit->second.coeff().full_tensor_copy())(___);
3143 vrss[i] = vright[i]->unfilter(rd);
3144 r_unfiltered[i] = 1;
3145 }
3146 }
3147
3148 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
3149 const keyT& child = kit.key();
3150 Tensor<L> ll;
3151
3152 std::vector<Slice> cp = child_patch(child);
3153
3154 if (lc.size() || l_is_leaf)
3155 ll = copy(lss(cp));
3156
3157 std::vector< Tensor<R> > vv(vresult.size());
3158 for (unsigned int i=0; i<vresult.size(); ++i) {
3159 if (r_unfiltered[i])
3160 vv[i] = copy(vrss[i](cp));
3161 }
3162
3163 woT::task(coeffs.owner(child), &implT:: template mulXXveca<L,R>, child, left, ll, vright, vv, vresult, tol);
3164 }
3165 }
3166 }
3167
3168 /// Multiplication using recursive descent and assuming same distribution
3169 /// Both left and right functions are in the scaling function basis
3170 /// @param[in] key the key to the current function node (box)
3171 /// @param[in] left the function impl associated with the left function
3172 /// @param[in] lcin the scaling function coefficients associated with the
3173 /// current box in the left function
3174 /// @param[in] right the function impl associated with the right function
3175 /// @param[in] rcin the scaling function coefficients associated with the
3176 /// current box in the right function
3177 template <typename L, typename R>
3178 void mulXXa(const keyT& key,
3179 const FunctionImpl<L,NDIM>* left, const Tensor<L>& lcin,
3180 const FunctionImpl<R,NDIM>* right,const Tensor<R>& rcin,
3181 double tol) {
3182 typedef typename FunctionImpl<L,NDIM>::dcT::const_iterator literT;
3183 typedef typename FunctionImpl<R,NDIM>::dcT::const_iterator riterT;
3184
3185 double lnorm=1e99, rnorm=1e99;
3186
3187 Tensor<L> lc = lcin;
3188 if (lc.size() == 0) {
3189 literT it = left->coeffs.find(key).get();
3190 MADNESS_ASSERT(it != left->coeffs.end());
3191 lnorm = it->second.get_norm_tree();
3192 if (it->second.has_coeff())
3193 lc = it->second.coeff().reconstruct_tensor();
3194 }
3195
3196 Tensor<R> rc = rcin;
3197 if (rc.size() == 0) {
3198 riterT it = right->coeffs.find(key).get();
3199 MADNESS_ASSERT(it != right->coeffs.end());
3200 rnorm = it->second.get_norm_tree();
3201 if (it->second.has_coeff())
3202 rc = it->second.coeff().reconstruct_tensor();
3203 }
3204
3205 // both nodes are leaf nodes: multiply and return
3206 if (rc.size() && lc.size()) { // Yipee!
3207 do_mul<L,R>(key, lc, std::make_pair(key,rc));
3208 return;
3209 }
3210
3211 if (tol) {
3212 if (lc.size())
3213 lnorm = lc.normf(); // Otherwise got from norm tree above
3214 if (rc.size())
3215 rnorm = rc.normf();
3216 if (lnorm*rnorm < truncate_tol(tol, key)) {
3217 coeffs.replace(key, nodeT(coeffT(cdata.vk,targs),false)); // Zero leaf node
3218 return;
3219 }
3220 }
3221
3222 // Recur down
3223 coeffs.replace(key, nodeT(coeffT(),true)); // Interior node
3224
3225 Tensor<L> lss;
3226 if (lc.size()) {
3227 Tensor<L> ld(cdata.v2k);
3228 ld(cdata.s0) = lc(___);
3229 lss = left->unfilter(ld);
3230 }
3231
3232 Tensor<R> rss;
3233 if (rc.size()) {
3234 Tensor<R> rd(cdata.v2k);
3235 rd(cdata.s0) = rc(___);
3236 rss = right->unfilter(rd);
3237 }
3238
3239 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
3240 const keyT& child = kit.key();
3241 Tensor<L> ll;
3242 Tensor<R> rr;
3243 if (lc.size())
3244 ll = copy(lss(child_patch(child)));
3245 if (rc.size())
3246 rr = copy(rss(child_patch(child)));
3247
3248 woT::task(coeffs.owner(child), &implT:: template mulXXa<L,R>, child, left, ll, right, rr, tol);
3249 }
3250 }
3251
3252
3253 // Binary operation on values using recursive descent and assuming same distribution
3254 /// Both left and right functions are in the scaling function basis
3255 /// @param[in] key the key to the current function node (box)
3256 /// @param[in] left the function impl associated with the left function
3257 /// @param[in] lcin the scaling function coefficients associated with the
3258 /// current box in the left function
3259 /// @param[in] right the function impl associated with the right function
3260 /// @param[in] rcin the scaling function coefficients associated with the
3261 /// current box in the right function
3262 /// @param[in] op the binary operator
3263 template <typename L, typename R, typename opT>
3264 void binaryXXa(const keyT& key,
3265 const FunctionImpl<L,NDIM>* left, const Tensor<L>& lcin,
3266 const FunctionImpl<R,NDIM>* right,const Tensor<R>& rcin,
3267 const opT& op) {
3268 typedef typename FunctionImpl<L,NDIM>::dcT::const_iterator literT;
3269 typedef typename FunctionImpl<R,NDIM>::dcT::const_iterator riterT;
3270
3271 Tensor<L> lc = lcin;
3272 if (lc.size() == 0) {
3273 literT it = left->coeffs.find(key).get();
3274 MADNESS_ASSERT(it != left->coeffs.end());
3275 if (it->second.has_coeff())
3276 lc = it->second.coeff().reconstruct_tensor();
3277 }
3278
3279 Tensor<R> rc = rcin;
3280 if (rc.size() == 0) {
3281 riterT it = right->coeffs.find(key).get();
3282 MADNESS_ASSERT(it != right->coeffs.end());
3283 if (it->second.has_coeff())
3284 rc = it->second.coeff().reconstruct_tensor();
3285 }
3286
3287 if (rc.size() && lc.size()) { // Yipee!
3288 do_binary_op<L,R>(key, lc, std::make_pair(key,rc), op);
3289 return;
3290 }
3291
3292 // Recur down
3293 coeffs.replace(key, nodeT(coeffT(),true)); // Interior node
3294
3295 Tensor<L> lss;
3296 if (lc.size()) {
3297 Tensor<L> ld(cdata.v2k);
3298 ld(cdata.s0) = lc(___);
3299 lss = left->unfilter(ld);
3300 }
3301
3302 Tensor<R> rss;
3303 if (rc.size()) {
3304 Tensor<R> rd(cdata.v2k);
3305 rd(cdata.s0) = rc(___);
3306 rss = right->unfilter(rd);
3307 }
3308
3309 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
3310 const keyT& child = kit.key();
3311 Tensor<L> ll;
3312 Tensor<R> rr;
3313 if (lc.size())
3314 ll = copy(lss(child_patch(child)));
3315 if (rc.size())
3316 rr = copy(rss(child_patch(child)));
3317
3318 woT::task(coeffs.owner(child), &implT:: template binaryXXa<L,R,opT>, child, left, ll, right, rr, op);
3319 }
3320 }
3321
3322 template <typename Q, typename opT>
3324 typedef typename opT::resultT resultT;
3326 opT op;
3327
3332
3333 Tensor<resultT> operator()(const Key<NDIM>& key, const Tensor<Q>& t) const {
3334 Tensor<Q> invalues = impl_func->coeffs2values(key, t);
3335
3336 Tensor<resultT> outvalues = op(key, invalues);
3337
3338 return impl_func->values2coeffs(key, outvalues);
3339 }
3340
3341 template <typename Archive>
3342 void serialize(Archive& ar) {
3343 ar & impl_func & op;
3344 }
3345 };
3346
3347 /// Out of place unary operation on function impl
3348 /// The skeleton algorithm should resemble something like
3349 ///
3350 /// *this = op(*func)
3351 ///
3352 /// @param[in] key the key of the current function node (box)
3353 /// @param[in] func the function impl on which to be operated
3354 /// @param[in] op the unary operator
3355 template <typename Q, typename opT>
3356 void unaryXXa(const keyT& key,
3357 const FunctionImpl<Q,NDIM>* func, const opT& op) {
3358
3359 // const Tensor<Q>& fc = func->coeffs.find(key).get()->second.full_tensor_copy();
3360 const Tensor<Q> fc = func->coeffs.find(key).get()->second.coeff().reconstruct_tensor();
3361
3362 if (fc.size() == 0) {
3363 // Recur down
3364 coeffs.replace(key, nodeT(coeffT(),true)); // Interior node
3365 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
3366 const keyT& child = kit.key();
3367 woT::task(coeffs.owner(child), &implT:: template unaryXXa<Q,opT>, child, func, op);
3368 }
3369 }
3370 else {
3371 tensorT t=op(key,fc);
3372 coeffs.replace(key, nodeT(coeffT(t,targs),false)); // Leaf node
3373 }
3374 }
3375
3376 /// Multiplies two functions (impl's) together. Delegates to the mulXXa() method
3377 /// @param[in] left pointer to the left function impl
3378 /// @param[in] right pointer to the right function impl
3379 /// @param[in] tol numerical tolerance
3380 template <typename L, typename R>
3381 void mulXX(const FunctionImpl<L,NDIM>* left, const FunctionImpl<R,NDIM>* right, double tol, bool fence) {
3382 if (world.rank() == coeffs.owner(cdata.key0))
3383 mulXXa(cdata.key0, left, Tensor<L>(), right, Tensor<R>(), tol);
3384 if (fence)
3385 world.gop.fence();
3386
3387 //verify_tree();
3388 }
3389
3390 /// Performs binary operation on two functions (impl's). Delegates to the binaryXXa() method
3391 /// @param[in] left pointer to the left function impl
3392 /// @param[in] right pointer to the right function impl
3393 /// @param[in] op the binary operator
3394 template <typename L, typename R, typename opT>
3396 const opT& op, bool fence) {
3397 if (world.rank() == coeffs.owner(cdata.key0))
3398 binaryXXa(cdata.key0, left, Tensor<L>(), right, Tensor<R>(), op);
3399 if (fence)
3400 world.gop.fence();
3401
3402 //verify_tree();
3403 }
3404
3405 /// Performs unary operation on function impl. Delegates to the unaryXXa() method
3406 /// @param[in] func function impl of the operand
3407 /// @param[in] op the unary operator
3408 template <typename Q, typename opT>
3409 void unaryXX(const FunctionImpl<Q,NDIM>* func, const opT& op, bool fence) {
3410 if (world.rank() == coeffs.owner(cdata.key0))
3411 unaryXXa(cdata.key0, func, op);
3412 if (fence)
3413 world.gop.fence();
3414
3415 //verify_tree();
3416 }
3417
3418 /// Performs unary operation on function impl. Delegates to the unaryXXa() method
3419 /// @param[in] func function impl of the operand
3420 /// @param[in] op the unary operator
3421 template <typename Q, typename opT>
3422 void unaryXXvalues(const FunctionImpl<Q,NDIM>* func, const opT& op, bool fence) {
3423 if (world.rank() == coeffs.owner(cdata.key0))
3425 if (fence)
3426 world.gop.fence();
3427
3428 //verify_tree();
3429 }
3430
3431 /// Multiplies a function (impl) with a vector of functions (impl's). Delegates to the
3432 /// mulXXveca() method.
3433 /// @param[in] left pointer to the left function impl
3434 /// @param[in] vright vector of pointers to the right function impl's
3435 /// @param[in] tol numerical tolerance
3436 /// @param[out] vresult vector of pointers to the resulting function impl's
3437 template <typename L, typename R>
3439 const std::vector<const FunctionImpl<R,NDIM>*>& vright,
3440 const std::vector<FunctionImpl<T,NDIM>*>& vresult,
3441 double tol,
3442 bool fence) {
3443 std::vector< Tensor<R> > vr(vright.size());
3444 if (world.rank() == coeffs.owner(cdata.key0))
3445 mulXXveca(cdata.key0, left, Tensor<L>(), vright, vr, vresult,
3447 if (fence)
3448 world.gop.fence();
3449 }
3450
3452
3453 mutable long box_leaf[1000];
3454 mutable long box_interior[1000];
3455
3456 // horrifically non-scalable
3457 void put_in_box(ProcessID from, long nl, long ni) const;
3458
3459 /// Prints summary of data distribution
3460 void print_info() const;
3461
3462 /// Verify tree is properly constructed ... global synchronization involved
3463
3464 /// If an inconsistency is detected, prints a message describing the error and
3465 /// then throws a madness exception.
3466 ///
3467 /// This is a reasonably quick and scalable operation that is
3468 /// useful for debugging and paranoia.
3469 void verify_tree() const;
3470
3471 /// check that parents and children are consistent
3472
3473 /// will not check proper size of coefficients
3474 /// global communication
3475 bool verify_parents_and_children() const;
3476
3477 /// check that the tree state and the coeffs are consistent
3478
3479 /// will not check existence of children and/or parents
3480 /// no communication
3481 bool verify_tree_state_local() const;
3482
3483 /// Walk up the tree returning pair(key,node) for first node with coefficients
3484
3485 /// Three possibilities.
3486 ///
3487 /// 1) The coeffs are present and returned with the key of the containing node.
3488 ///
3489 /// 2) The coeffs are further up the tree ... the request is forwarded up.
3490 ///
3491 /// 3) The coeffs are futher down the tree ... an empty tensor is returned.
3492 ///
3493 /// !! This routine is crying out for an optimization to
3494 /// manage the number of messages being sent ... presently
3495 /// each parent is fetched 2^(n*d) times where n is the no. of
3496 /// levels between the level of evaluation and the parent.
3497 /// Alternatively, reimplement multiply as a downward tree
3498 /// walk and just pass the parent down. Slightly less
3499 /// parallelism but much less communication.
3500 /// @todo Robert .... help!
3501 void sock_it_to_me(const keyT& key,
3502 const RemoteReference< FutureImpl< std::pair<keyT,coeffT> > >& ref) const;
3503 /// As above, except
3504 /// 3) The coeffs are constructed from the avg of nodes further down the tree
3505 /// @todo Robert .... help!
3506 void sock_it_to_me_too(const keyT& key,
3507 const RemoteReference< FutureImpl< std::pair<keyT,coeffT> > >& ref) const;
3508
3509 /// @todo help!
3511 const keyT& key,
3512 const coordT& plotlo, const coordT& plothi, const std::vector<long>& npt,
3513 bool eval_refine) const;
3514
3515
3516 /// Evaluate a cube/slice of points ... plotlo and plothi are already in simulation coordinates
3517 /// No communications
3518 /// @param[in] plotlo the coordinate of the starting point
3519 /// @param[in] plothi the coordinate of the ending point
3520 /// @param[in] npt the number of points in each dimension
3521 Tensor<T> eval_plot_cube(const coordT& plotlo,
3522 const coordT& plothi,
3523 const std::vector<long>& npt,
3524 const bool eval_refine = false) const;
3525
3526
3527 /// Evaluate function only if point is local returning (true,value); otherwise return (false,0.0)
3528
3529 /// maxlevel is the maximum depth to search down to --- the max local depth can be
3530 /// computed with max_local_depth();
3531 std::pair<bool,T> eval_local_only(const Vector<double,NDIM>& xin, Level maxlevel) ;
3532
3533 /// Allocation-free core of the batched eval_local_only: writes one
3534 /// (local?,value) pair per point, in input order, into results[0..npt).
3535 /// Consecutive points in the same leaf box share that box's descent and
3536 /// coefficient fetch (last-box memoization); each point is evaluated by
3537 /// the same eval_cube on the same tensor as the single-point path, so
3538 /// results are bit-for-bit identical. No communications.
3539 void eval_local_only(const Vector<double,NDIM>* xin, std::size_t npt,
3540 Level maxlevel, std::pair<bool,T>* results);
3541
3542 /// Batched eval_local_only returning a fresh vector (see the pointer
3543 /// core above for semantics).
3544 /// maxlevel is the maximum depth to search down to --- the max local depth can
3545 /// be computed with max_local_depth();
3546 std::vector<std::pair<bool,T>>
3547 eval_local_only(const std::vector<Vector<double,NDIM>>& xin, Level maxlevel) ;
3548
3549
3550 /// Evaluate the function at a point in \em simulation coordinates
3551
3552 /// Only the invoking process will get the result via the
3553 /// remote reference to a future. Active messages may be sent
3554 /// to other nodes.
3555 void eval(const Vector<double,NDIM>& xin,
3556 const keyT& keyin,
3557 const typename Future<T>::remote_refT& ref);
3558
3559 /// Get the depth of the tree at a point in \em simulation coordinates
3560
3561 /// Only the invoking process will get the result via the
3562 /// remote reference to a future. Active messages may be sent
3563 /// to other nodes.
3564 ///
3565 /// This function is a minimally-modified version of eval()
3566 void evaldepthpt(const Vector<double,NDIM>& xin,
3567 const keyT& keyin,
3568 const typename Future<Level>::remote_refT& ref);
3569
3570 /// Get the rank of leaf box of the tree at a point in \em simulation coordinates
3571
3572 /// Only the invoking process will get the result via the
3573 /// remote reference to a future. Active messages may be sent
3574 /// to other nodes.
3575 ///
3576 /// This function is a minimally-modified version of eval()
3577 void evalR(const Vector<double,NDIM>& xin,
3578 const keyT& keyin,
3579 const typename Future<long>::remote_refT& ref);
3580
3581
3582 /// Computes norm of low/high-order polyn. coeffs for autorefinement test
3583
3584 /// t is a k^d tensor. In order to screen the autorefinement
3585 /// during multiplication compute the norms of
3586 /// ... lo ... the block of t for all polynomials of order < k/2
3587 /// ... hi ... the block of t for all polynomials of order >= k/2
3588 ///
3589 /// k=5 0,1,2,3,4 --> 0,1,2 ... 3,4
3590 /// k=6 0,1,2,3,4,5 --> 0,1,2 ... 3,4,5
3591 ///
3592 /// k=number of wavelets, so k=5 means max order is 4, so max exactly
3593 /// representable squarable polynomial is of order 2.
3594 void static tnorm(const tensorT& t, double* lo, double* hi);
3595
3596 void static tnorm(const GenTensor<T>& t, double* lo, double* hi);
3597
3598 void static tnorm(const SVDTensor<T>& t, double* lo, double* hi, const int particle);
3599
3600 // This invoked if node has not been autorefined
3601 void do_square_inplace(const keyT& key);
3602
3603 // This invoked if node has been autorefined
3604 void do_square_inplace2(const keyT& parent, const keyT& child, const tensorT& parent_coeff);
3605
3606 /// Always returns false (for when autorefine is not wanted)
3607 bool noautorefine(const keyT& key, const tensorT& t) const;
3608
3609 /// Returns true if this block of coeffs needs autorefining
3610 bool autorefine_square_test(const keyT& key, const nodeT& t) const;
3611
3612 /// Pointwise squaring of function with optional global fence
3613
3614 /// If not autorefining, local computation only if not fencing.
3615 /// If autorefining, may result in asynchronous communication.
3616 void square_inplace(bool fence);
3617 void abs_inplace(bool fence);
3618 void abs_square_inplace(bool fence);
3619
3620 /// is this the same as trickle_down() ?
3621 void sum_down_spawn(const keyT& key, const coeffT& s);
3622
3623 /// After 1d push operator must sum coeffs down the tree to restore correct scaling function coefficients
3624 void sum_down(bool fence);
3625
3626 /// perform this multiplication: h(1,2) = f(1,2) * g(1)
3627 template<size_t LDIM>
3629
3630 static bool randomize() {return false;}
3634
3635 implT* h; ///< the result function h(1,2) = f(1,2) * g(1)
3638 int particle; ///< if g is g(1) or g(2)
3639
3640 multiply_op() : h(), f(), g(), particle(1) {}
3641
3642 multiply_op(implT* h1, const ctT& f1, const ctL& g1, const int particle1)
3643 : h(h1), f(f1), g(g1), particle(particle1) {};
3644
3645 /// return true if this will be a leaf node
3646
3647 /// use generalization of tnorm for a GenTensor
3648 bool screen(const coeffT& fcoeff, const coeffT& gcoeff, const keyT& key) const {
3650 MADNESS_ASSERT(fcoeff.is_svd_tensor());
3653
3654 double glo=0.0, ghi=0.0, flo=0.0, fhi=0.0;
3655 g.get_impl()->tnorm(gcoeff.get_tensor(), &glo, &ghi);
3656 g.get_impl()->tnorm(fcoeff.get_svdtensor(),&flo,&fhi,particle);
3657
3658 double total_hi=glo*fhi + ghi*flo + fhi*ghi;
3659 return (total_hi<h->truncate_tol(h->get_thresh(),key));
3660
3661 }
3662
3663 /// apply this on a FunctionNode of f and g of Key key
3664
3665 /// @param[in] key key for FunctionNode in f and g, (g: broken into particles)
3666 /// @return <this node is a leaf, coefficients of this node>
3667 std::pair<bool,coeffT> operator()(const Key<NDIM>& key) const {
3668
3669 // bool is_leaf=(not fdatum.second.has_children());
3670 // if (not is_leaf) return std::pair<bool,coeffT> (is_leaf,coeffT());
3671
3672 // break key into particles (these are the child keys, with f/gdatum come the parent keys)
3673 Key<LDIM> key1,key2;
3674 key.break_apart(key1,key2);
3675 const Key<LDIM> gkey= (particle==1) ? key1 : key2;
3676
3677 // get coefficients of the actual FunctionNode
3678 coeffT coeff1=f.get_impl()->parent_to_child(f.coeff(),f.key(),key);
3679 coeff1.normalize();
3680 const coeffT coeff2=g.get_impl()->parent_to_child(g.coeff(),g.key(),gkey);
3681
3682 // multiplication is done in TT_2D
3683 coeffT coeff1_2D=coeff1.convert(TensorArgs(h->get_thresh(),TT_2D));
3684 coeff1_2D.normalize();
3685
3686 bool is_leaf=screen(coeff1_2D,coeff2,key);
3687 if (key.level()<2) is_leaf=false;
3688
3689 coeffT hcoeff;
3690 if (is_leaf) {
3691
3692 // convert coefficients to values
3693 coeffT hvalues=f.get_impl()->coeffs2values(key,coeff1_2D);
3694 coeffT gvalues=g.get_impl()->coeffs2values(gkey,coeff2);
3695
3696 // perform multiplication
3697 coeffT result_val=h->multiply(hvalues,gvalues,particle-1);
3698
3699 hcoeff=h->values2coeffs(key,result_val);
3700
3701 // conversion on coeffs, not on values, because it implies truncation!
3702 if (not hcoeff.is_of_tensortype(h->get_tensor_type()))
3703 hcoeff=hcoeff.convert(h->get_tensor_args());
3704 }
3705
3706 return std::pair<bool,coeffT> (is_leaf,hcoeff);
3707 }
3708
3709 this_type make_child(const keyT& child) const {
3710
3711 // break key into particles
3712 Key<LDIM> key1, key2;
3713 child.break_apart(key1,key2);
3714 const Key<LDIM> gkey= (particle==1) ? key1 : key2;
3715
3716 return this_type(h,f.make_child(child),g.make_child(gkey),particle);
3717 }
3718
3720 Future<ctT> f1=f.activate();
3722 return h->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
3723 &this_type::forward_ctor),h,f1,g1,particle);
3724 }
3725
3726 this_type forward_ctor(implT* h1, const ctT& f1, const ctL& g1, const int particle) {
3727 return this_type(h1,f1,g1,particle);
3728 }
3729
3730 template <typename Archive> void serialize(const Archive& ar) {
3731 ar & h & f & g & particle;
3732 }
3733 };
3734
3735
3736 /// add two functions f and g: result=alpha * f + beta * g
3737 struct add_op {
3738
3741
3742 bool randomize() const {return false;}
3743
3744 /// tracking coeffs of first and second addend
3746 /// prefactor for f, g
3747 double alpha, beta;
3748
3749 add_op() = default;
3750 add_op(const ctT& f, const ctT& g, const double alpha, const double beta)
3751 : f(f), g(g), alpha(alpha), beta(beta){}
3752
3753 /// if we are at the bottom of the trees, return the sum of the coeffs
3754 std::pair<bool,coeffT> operator()(const keyT& key) const {
3755
3756 bool is_leaf=(f.is_leaf() and g.is_leaf());
3757 if (not is_leaf) return std::pair<bool,coeffT> (is_leaf,coeffT());
3758
3759 coeffT fcoeff=f.get_impl()->parent_to_child(f.coeff(),f.key(),key);
3760 coeffT gcoeff=g.get_impl()->parent_to_child(g.coeff(),g.key(),key);
3761 coeffT hcoeff=copy(fcoeff);
3762 hcoeff.gaxpy(alpha,gcoeff,beta);
3763 hcoeff.reduce_rank(f.get_impl()->get_tensor_args().thresh);
3764 return std::pair<bool,coeffT> (is_leaf,hcoeff);
3765 }
3766
3767 this_type make_child(const keyT& child) const {
3768 return this_type(f.make_child(child),g.make_child(child),alpha,beta);
3769 }
3770
3771 /// retrieve the coefficients (parent coeffs might be remote)
3773 Future<ctT> f1=f.activate();
3774 Future<ctT> g1=g.activate();
3775 return f.get_impl()->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
3777 }
3778
3779 /// taskq-compatible ctor
3780 this_type forward_ctor(const ctT& f1, const ctT& g1, const double alpha, const double beta) {
3781 return this_type(f1,g1,alpha,beta);
3782 }
3783
3784 template <typename Archive> void serialize(const Archive& ar) {
3785 ar & f & g & alpha & beta;
3786 }
3787
3788 };
3789
3790 /// multiply f (a pair function of NDIM) with an orbital g (LDIM=NDIM/2)
3791
3792 /// as in (with h(1,2)=*this) : h(1,2) = g(1) * f(1,2)
3793 /// use tnorm as a measure to determine if f (=*this) must be refined
3794 /// @param[in] f the NDIM function f=f(1,2)
3795 /// @param[in] g the LDIM function g(1) (or g(2))
3796 /// @param[in] particle 1 or 2, as in g(1) or g(2)
3797 template<size_t LDIM>
3798 void multiply(const implT* f, const FunctionImpl<T,LDIM>* g, const int particle) {
3799
3802
3803 typedef multiply_op<LDIM> coeff_opT;
3804 coeff_opT coeff_op(this,ff,gg,particle);
3805
3806 typedef insert_op<T,NDIM> apply_opT;
3807 apply_opT apply_op(this);
3808
3809 keyT key0=f->cdata.key0;
3810 if (world.rank() == coeffs.owner(key0)) {
3812 woT::task(p, &implT:: template forward_traverse<coeff_opT,apply_opT>, coeff_op, apply_op, key0);
3813 }
3814
3816 }
3817
3818 /// Hartree product of two LDIM functions to yield a NDIM = 2*LDIM function
3819 template<size_t LDIM, typename leaf_opT>
3820 struct hartree_op {
3821 bool randomize() const {return false;}
3822
3825
3826 implT* result; ///< where to construct the pair function
3827 ctL p1, p2; ///< tracking coeffs of the two lo-dim functions
3828 leaf_opT leaf_op; ///< determine if a given node will be a leaf node
3829
3830 // ctor
3832 hartree_op(implT* result, const ctL& p11, const ctL& p22, const leaf_opT& leaf_op)
3833 : result(result), p1(p11), p2(p22), leaf_op(leaf_op) {
3834 MADNESS_ASSERT(LDIM+LDIM==NDIM);
3835 }
3836
3837 std::pair<bool,coeffT> operator()(const Key<NDIM>& key) const {
3838
3839 // break key into particles (these are the child keys, with datum1/2 come the parent keys)
3840 Key<LDIM> key1,key2;
3841 key.break_apart(key1,key2);
3842
3843 // this returns the appropriate NS coeffs for key1 and key2 resp.
3844 const coeffT fcoeff=p1.coeff(key1);
3845 const coeffT gcoeff=p2.coeff(key2);
3846 bool is_leaf=leaf_op(key,fcoeff.full_tensor(),gcoeff.full_tensor());
3847 if (not is_leaf) return std::pair<bool,coeffT> (is_leaf,coeffT());
3848
3849 // extract the sum coeffs from the NS coeffs
3850 const coeffT s1=fcoeff(p1.get_impl()->cdata.s0);
3851 const coeffT s2=gcoeff(p2.get_impl()->cdata.s0);
3852
3853 // new coeffs are simply the hartree/kronecker/outer product --
3854 coeffT coeff=outer(s1,s2,result->get_tensor_args());
3855 // no post-determination
3856 // is_leaf=leaf_op(key,coeff);
3857 return std::pair<bool,coeffT>(is_leaf,coeff);
3858 }
3859
3860 this_type make_child(const keyT& child) const {
3861
3862 // break key into particles
3863 Key<LDIM> key1, key2;
3864 child.break_apart(key1,key2);
3865
3866 return this_type(result,p1.make_child(key1),p2.make_child(key2),leaf_op);
3867 }
3868
3870 Future<ctL> p11=p1.activate();
3871 Future<ctL> p22=p2.activate();
3872 return result->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
3873 &this_type::forward_ctor),result,p11,p22,leaf_op);
3874 }
3875
3876 this_type forward_ctor(implT* result1, const ctL& p11, const ctL& p22, const leaf_opT& leaf_op) {
3877 return this_type(result1,p11,p22,leaf_op);
3878 }
3879
3880 template <typename Archive> void serialize(const Archive& ar) {
3881 ar & result & p1 & p2 & leaf_op;
3882 }
3883 };
3884
3885 /// traverse a non-existing tree
3886
3887 /// part II: activate coeff_op, i.e. retrieve all the necessary remote boxes (communication)
3888 /// @param[in] coeff_op operator making the coefficients that needs activation
3889 /// @param[in] apply_op just passing thru
3890 /// @param[in] key the key we are working on
3891 template<typename coeff_opT, typename apply_opT>
3892 void forward_traverse(const coeff_opT& coeff_op, const apply_opT& apply_op, const keyT& key) const {
3894 Future<coeff_opT> active_coeff=coeff_op.activate();
3895 woT::task(world.rank(), &implT:: template traverse_tree<coeff_opT,apply_opT>, active_coeff, apply_op, key);
3896 }
3897
3898
3899 /// traverse a non-existing tree
3900
3901 /// part I: make the coefficients, process them and continue the recursion if necessary
3902 /// @param[in] coeff_op operator making the coefficients and determining them being leaves
3903 /// @param[in] apply_op operator processing the coefficients
3904 /// @param[in] key the key we are currently working on
3905 template<typename coeff_opT, typename apply_opT>
3906 void traverse_tree(const coeff_opT& coeff_op, const apply_opT& apply_op, const keyT& key) const {
3908
3909 typedef typename std::pair<bool,coeffT> argT;
3910 const argT arg=coeff_op(key);
3911 apply_op.operator()(key,arg.second,arg.first);
3912
3913 const bool has_children=(not arg.first);
3914 if (has_children) {
3915 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
3916 const keyT& child=kit.key();
3917 coeff_opT child_op=coeff_op.make_child(child);
3918 // spawn activation where child is local
3919 ProcessID p=coeffs.owner(child);
3920
3921 void (implT::*ft)(const coeff_opT&, const apply_opT&, const keyT&) const = &implT::forward_traverse<coeff_opT,apply_opT>;
3922
3923 woT::task(p, ft, child_op, apply_op, child);
3924 }
3925 }
3926 }
3927
3928
3929 /// given two functions of LDIM, perform the Hartree/Kronecker/outer product
3930
3931 /// |Phi(1,2)> = |phi(1)> x |phi(2)>
3932 /// @param[in] p1 FunctionImpl of particle 1
3933 /// @param[in] p2 FunctionImpl of particle 2
3934 /// @param[in] leaf_op operator determining of a given box will be a leaf
3935 template<std::size_t LDIM, typename leaf_opT>
3936 void hartree_product(const std::vector<std::shared_ptr<FunctionImpl<T,LDIM>>> p1,
3937 const std::vector<std::shared_ptr<FunctionImpl<T,LDIM>>> p2,
3938 const leaf_opT& leaf_op, bool fence) {
3939 MADNESS_CHECK_THROW(p1.size()==p2.size(),"hartree_product: p1 and p2 must have the same size");
3940 for (auto& p : p1) MADNESS_CHECK(p->is_nonstandard() or p->is_nonstandard_with_leaves());
3941 for (auto& p : p2) MADNESS_CHECK(p->is_nonstandard() or p->is_nonstandard_with_leaves());
3942
3943 const keyT key0=cdata.key0;
3944
3945 for (std::size_t i=0; i<p1.size(); ++i) {
3946 if (world.rank() == this->get_coeffs().owner(key0)) {
3947
3948 // prepare the CoeffTracker
3949 CoeffTracker<T,LDIM> iap1(p1[i].get());
3950 CoeffTracker<T,LDIM> iap2(p2[i].get());
3951
3952 // the operator making the coefficients
3953 typedef hartree_op<LDIM,leaf_opT> coeff_opT;
3954 coeff_opT coeff_op(this,iap1,iap2,leaf_op);
3955
3956 // this operator simply inserts the coeffs into this' tree
3957// typedef insert_op<T,NDIM> apply_opT;
3958 typedef accumulate_op<T,NDIM> apply_opT;
3959 apply_opT apply_op(this);
3960
3961 woT::task(world.rank(), &implT:: template forward_traverse<coeff_opT,apply_opT>,
3962 coeff_op, apply_op, cdata.key0);
3963
3964 }
3965 }
3966
3968 if (fence) world.gop.fence();
3969 }
3970
3971
3972 template <typename opT, typename R>
3973 void
3975 const opT* op = pop.ptr;
3976 const Level n = key.level();
3977 const double cnorm = c.normf();
3978 const double tol = truncate_tol(thresh, key)*0.1; // ??? why this value????
3979
3981 const Translation lold = lnew[axis];
3982 const Translation maxs = Translation(1)<<n;
3983
3984 int nsmall = 0; // Counts neglected blocks to terminate s loop
3985 for (Translation s=0; s<maxs; ++s) {
3986 int maxdir = s ? 1 : -1;
3987 for (int direction=-1; direction<=maxdir; direction+=2) {
3988 lnew[axis] = lold + direction*s;
3989 if (lnew[axis] >= 0 && lnew[axis] < maxs) { // NON-ZERO BOUNDARY CONDITIONS IGNORED HERE !!!!!!!!!!!!!!!!!!!!
3990 const Tensor<typename opT::opT>& r = op->rnlij(n, s*direction, true);
3991 double Rnorm = r.normf();
3992
3993 if (Rnorm == 0.0) {
3994 return; // Hard zero means finished!
3995 }
3996
3997 if (s <= 1 || r.normf()*cnorm > tol) { // Always do kernel and neighbor
3998 nsmall = 0;
3999 tensorT result = transform_dir(c,r,axis);
4000
4001 if (result.normf() > tol*0.3) {
4002 Key<NDIM> dest(n,lnew);
4003 coeffs.task(dest, &nodeT::accumulate2, result, coeffs, dest, TaskAttributes::hipri());
4004 }
4005 }
4006 else {
4007 ++nsmall;
4008 }
4009 }
4010 else {
4011 ++nsmall;
4012 }
4013 }
4014 if (nsmall >= 4) {
4015 // If have two negligble blocks in
4016 // succession in each direction interpret
4017 // this as the operator being zero beyond
4018 break;
4019 }
4020 }
4021 }
4022
4023 template <typename opT, typename R>
4024 void
4025 apply_1d_realspace_push(const opT& op, const FunctionImpl<R,NDIM>* f, int axis, bool fence) {
4026 MADNESS_ASSERT(!f->is_compressed());
4027
4028 typedef typename FunctionImpl<R,NDIM>::dcT::const_iterator fiterT;
4029 typedef FunctionNode<R,NDIM> fnodeT;
4030 fiterT end = f->coeffs.end();
4031 ProcessID me = world.rank();
4032 for (fiterT it=f->coeffs.begin(); it!=end; ++it) {
4033 const fnodeT& node = it->second;
4034 if (node.has_coeff()) {
4035 const keyT& key = it->first;
4036 const Tensor<R>& c = node.coeff().full_tensor_copy();
4037 woT::task(me, &implT:: template apply_1d_realspace_push_op<opT,R>,
4039 }
4040 }
4041 if (fence) world.gop.fence();
4042 }
4043
4045 const implT* f,
4046 const keyT& key,
4047 const std::pair<keyT,coeffT>& left,
4048 const std::pair<keyT,coeffT>& center,
4049 const std::pair<keyT,coeffT>& right);
4050
4051 void do_diff1(const DerivativeBase<T,NDIM>* D,
4052 const implT* f,
4053 const keyT& key,
4054 const std::pair<keyT,coeffT>& left,
4055 const std::pair<keyT,coeffT>& center,
4056 const std::pair<keyT,coeffT>& right);
4057
4058 // Called by result function to differentiate f
4059 void diff(const DerivativeBase<T,NDIM>* D, const implT* f, bool fence);
4060
4061 /// Returns key of general neighbor enforcing BC
4062
4063 /// Out of volume keys are mapped to enforce the BC as follows.
4064 /// * Periodic BC map back into the volume and return the correct key
4065 /// * non-periodic BC - returns invalid() to indicate out of volume
4066 keyT neighbor(const keyT& key, const keyT& disp, const array_of_bools<NDIM>& is_periodic) const;
4067
4068 /// Returns key of general neighbor that resides in-volume
4069
4070 /// Out of volume keys are mapped to invalid()
4071 keyT neighbor_in_volume(const keyT& key, const keyT& disp) const;
4072
4073 /// find_me. Called by diff_bdry to get coefficients of boundary function
4074 Future< std::pair<keyT,coeffT> > find_me(const keyT& key) const;
4075
4076 /// return the a std::pair<key, node>, which MUST exist
4077 std::pair<Key<NDIM>,ShallowNode<T,NDIM> > find_datum(keyT key) const;
4078
4079 /// multiply the ket with a one-electron potential rr(1,2)= f(1,2)*g(1)
4080
4081 /// @param[in] val_ket function values of f(1,2)
4082 /// @param[in] val_pot function values of g(1)
4083 /// @param[in] particle if 0 then g(1), if 1 then g(2)
4084 /// @return the resulting function values
4085 coeffT multiply(const coeffT& val_ket, const coeffT& val_pot, int particle) const;
4086
4087
4088 /// given several coefficient tensors, assemble a result tensor
4089
4090 /// the result looks like: (v(1,2) + v(1) + v(2)) |ket(1,2)>
4091 /// or (v(1,2) + v(1) + v(2)) |p(1) p(2)>
4092 /// i.e. coefficients for the ket and coefficients for the two particles are
4093 /// mutually exclusive. All potential terms are optional, just pass in empty coeffs.
4094 /// @param[in] key the key of the FunctionNode to which these coeffs belong
4095 /// @param[in] coeff_ket coefficients of the ket
4096 /// @param[in] vpotential1 function values of the potential for particle 1
4097 /// @param[in] vpotential2 function values of the potential for particle 2
4098 /// @param[in] veri function values for the 2-particle potential
4099 coeffT assemble_coefficients(const keyT& key, const coeffT& coeff_ket,
4100 const coeffT& vpotential1, const coeffT& vpotential2,
4101 const tensorT& veri) const;
4102
4103
4104
4105 template<std::size_t LDIM>
4109 double error=0.0;
4110 double lo=0.0, hi=0.0, lo1=0.0, hi1=0.0, lo2=0.0, hi2=0.0;
4111
4113 pointwise_multiplier(const Key<NDIM> key, const coeffT& clhs) : coeff_lhs(clhs) {
4115 val_lhs=fcf.coeffs2values(key,coeff_lhs);
4116 error=0.0;
4118 if (coeff_lhs.is_svd_tensor()) {
4121 }
4122 }
4123
4124 /// multiply values of rhs and lhs, result on rhs, rhs and lhs are of the same dimensions
4125 tensorT operator()(const Key<NDIM> key, const tensorT& coeff_rhs) {
4126
4127 MADNESS_ASSERT(coeff_rhs.dim(0)==coeff_lhs.dim(0));
4129
4130 // the tnorm estimate is not tight enough to be efficient, better use oversampling
4131 bool use_tnorm=false;
4132 if (use_tnorm) {
4133 double rlo, rhi;
4134 implT::tnorm(coeff_rhs,&rlo,&rhi);
4135 error = hi*rlo + rhi*lo + rhi*hi;
4136 tensorT val_rhs=fcf.coeffs2values(key, coeff_rhs);
4137 val_rhs.emul(val_lhs.full_tensor());
4138 return fcf.values2coeffs(key,val_rhs);
4139 } else { // use quadrature of order k+1
4140
4141 auto& cdata=FunctionCommonData<T,NDIM>::get(coeff_rhs.dim(0)); // npt=k+1
4142 auto& cdata_npt=FunctionCommonData<T,NDIM>::get(coeff_rhs.dim(0)+oversampling); // npt=k+1
4143 FunctionCommonFunctionality<T,NDIM> fcf_hi_npt(cdata_npt);
4144
4145 // coeffs2values for rhs: k -> npt=k+1
4146 tensorT coeff1(cdata_npt.vk);
4147 coeff1(cdata.s0)=coeff_rhs; // s0 is smaller than vk!
4148 tensorT val_rhs_k1=fcf_hi_npt.coeffs2values(key,coeff1);
4149
4150 // coeffs2values for lhs: k -> npt=k+1
4151 tensorT coeff_lhs_k1(cdata_npt.vk);
4152 coeff_lhs_k1(cdata.s0)=std::as_const(coeff_lhs).full_tensor();
4153 tensorT val_lhs_k1=fcf_hi_npt.coeffs2values(key,coeff_lhs_k1);
4154
4155 // multiply
4156 val_lhs_k1.emul(val_rhs_k1);
4157
4158 // values2coeffs: npt = k+1-> k
4159 tensorT result1=fcf_hi_npt.values2coeffs(key,val_lhs_k1);
4160
4161 // extract coeffs up to k
4162 tensorT result=copy(result1(cdata.s0));
4163 result1(cdata.s0)=0.0;
4164 error=result1.normf();
4165 return result;
4166 }
4167 }
4168
4169 /// multiply values of rhs and lhs, result on rhs, rhs and lhs are of differnet dimensions
4170 coeffT operator()(const Key<NDIM> key, const tensorT& coeff_rhs, const int particle) {
4171 Key<LDIM> key1, key2;
4172 key.break_apart(key1,key2);
4173 const long k=coeff_rhs.dim(0);
4175 auto& cdata_lowdim=FunctionCommonData<T,LDIM>::get(k);
4176 FunctionCommonFunctionality<T,LDIM> fcf_lo(cdata_lowdim);
4180
4181
4182 // make hi-dim values from lo-dim coeff_rhs on npt grid points
4183 tensorT ones=tensorT(fcf_lo_npt.cdata.vk);
4184 ones=1.0;
4185
4186 tensorT coeff_rhs_npt1(fcf_lo_npt.cdata.vk);
4187 coeff_rhs_npt1(fcf_lo.cdata.s0)=coeff_rhs;
4188 tensorT val_rhs_npt1=fcf_lo_npt.coeffs2values(key1,coeff_rhs_npt1);
4189
4190 TensorArgs targs(-1.0,TT_2D);
4191 coeffT val_rhs;
4192 if (particle==1) val_rhs=outer(val_rhs_npt1,ones,targs);
4193 if (particle==2) val_rhs=outer(ones,val_rhs_npt1,targs);
4194
4195 // make values from hi-dim coeff_lhs on npt grid points
4196 coeffT coeff_lhs_k1(fcf_hi_npt.cdata.vk,coeff_lhs.tensor_type());
4197 coeff_lhs_k1(fcf_hi.cdata.s0)+=coeff_lhs;
4198 coeffT val_lhs_npt=fcf_hi_npt.coeffs2values(key,coeff_lhs_k1);
4199
4200 // multiply
4201 val_lhs_npt.emul(val_rhs);
4202
4203 // values2coeffs: npt = k+1-> k
4204 coeffT result1=fcf_hi_npt.values2coeffs(key,val_lhs_npt);
4205
4206 // extract coeffs up to k
4207 coeffT result=copy(result1(cdata.s0));
4208 result1(cdata.s0)=0.0;
4209 error=result1.normf();
4210 return result;
4211 }
4212
4213 template <typename Archive> void serialize(const Archive& ar) {
4214 ar & error & lo & lo1 & lo2 & hi & hi1& hi2 & val_lhs & coeff_lhs;
4215 }
4216
4217
4218 };
4219
4220 /// given a ket and the 1- and 2-electron potentials, construct the function V phi
4221
4222 /// small memory footstep version of Vphi_op: use the NS form to have information
4223 /// about parent and children to determine if a box is a leaf. This will require
4224 /// compression of the constituent functions, which will lead to more memory usage
4225 /// there, but will avoid oversampling of the result function.
4226 template<typename opT, size_t LDIM>
4227 struct Vphi_op_NS {
4228
4229 bool randomize() const {return true;}
4230
4234
4235 implT* result; ///< where to construct Vphi, no need to track parents
4236 opT leaf_op; ///< deciding if a given FunctionNode will be a leaf node
4237 ctT iaket; ///< the ket of a pair function (exclusive with p1, p2)
4238 ctL iap1, iap2; ///< the particles 1 and 2 (exclusive with ket)
4239 ctL iav1, iav2; ///< potentials for particles 1 and 2
4240 const implT* eri; ///< 2-particle potential, must be on-demand
4241
4242 bool have_ket() const {return iaket.get_impl();}
4243 bool have_v1() const {return iav1.get_impl();}
4244 bool have_v2() const {return iav2.get_impl();}
4245 bool have_eri() const {return eri;}
4246
4247 void accumulate_into_result(const Key<NDIM>& key, const coeffT& coeff) const {
4249 }
4250
4251 // ctor
4253 Vphi_op_NS(implT* result, const opT& leaf_op, const ctT& iaket,
4254 const ctL& iap1, const ctL& iap2, const ctL& iav1, const ctL& iav2,
4255 const implT* eri)
4257 , iav1(iav1), iav2(iav2), eri(eri) {
4258
4259 // 2-particle potential must be on-demand
4261 }
4262
4263 /// make and insert the coefficients into result's tree
4264 std::pair<bool,coeffT> operator()(const Key<NDIM>& key) const {
4265
4267 if(leaf_op.do_pre_screening()){
4268 // this means that we only construct the boxes which are leaf boxes from the other function in the leaf_op
4269 if(leaf_op.pre_screening(key)){
4270 // construct sum_coefficients, insert them and leave
4271 auto [sum_coeff, error]=make_sum_coeffs(key);
4272 accumulate_into_result(key,sum_coeff);
4273 return std::pair<bool,coeffT> (true,coeffT());
4274 }else{
4275 return continue_recursion(std::vector<bool>(1<<NDIM,false),tensorT(),key);
4276 }
4277 }
4278
4279 // this means that the function has to be completely constructed and not mirrored by another function
4280
4281 // if the initial level is not reached then this must not be a leaf box
4282 size_t il = result->get_initial_level();
4284 if(key.level()<int(il)){
4285 return continue_recursion(std::vector<bool>(1<<NDIM,false),tensorT(),key);
4286 }
4287 // if further refinement is needed (because we are at a special box, special point)
4288 // and the special_level is not reached then this must not be a leaf box
4289 if(key.level()<result->get_special_level() and leaf_op.special_refinement_needed(key)){
4290 return continue_recursion(std::vector<bool>(1<<NDIM,false),tensorT(),key);
4291 }
4292
4293 auto [sum_coeff,error]=make_sum_coeffs(key);
4294
4295 // coeffs are leaf (for whatever reason), insert into tree and stop recursion
4296 if(leaf_op.post_screening(key,sum_coeff)){
4297 accumulate_into_result(key,sum_coeff);
4298 return std::pair<bool,coeffT> (true,coeffT());
4299 }
4300
4301 // coeffs are accurate, insert into tree and stop recursion
4302 if(error<result->truncate_tol(result->get_thresh(),key)){
4303 accumulate_into_result(key,sum_coeff);
4304 return std::pair<bool,coeffT> (true,coeffT());
4305 }
4306
4307 // coeffs are inaccurate, continue recursion
4308 std::vector<bool> child_is_leaf(1<<NDIM,false);
4309 return continue_recursion(child_is_leaf,tensorT(),key);
4310 }
4311
4312
4313 /// loop over all children and either insert their sum coeffs or continue the recursion
4314
4315 /// @param[in] child_is_leaf for each child: is it a leaf?
4316 /// @param[in] coeffs coefficient tensor with 2^N sum coeffs (=unfiltered NS coeffs)
4317 /// @param[in] key the key for the NS coeffs (=parent key of the children)
4318 /// @return to avoid recursion outside this return: std::pair<is_leaf,coeff> = true,coeffT()
4319 std::pair<bool,coeffT> continue_recursion(const std::vector<bool> child_is_leaf,
4320 const tensorT& coeffs, const keyT& key) const {
4321 std::size_t i=0;
4322 for (KeyChildIterator<NDIM> kit(key); kit; ++kit, ++i) {
4323 keyT child=kit.key();
4324 bool is_leaf=child_is_leaf[i];
4325
4326 if (is_leaf) {
4327 // insert the sum coeffs
4329 iop(child,coeffT(copy(coeffs(result->child_patch(child))),result->get_tensor_args()),is_leaf);
4330 } else {
4331 this_type child_op=this->make_child(child);
4332 noop<T,NDIM> no;
4333 // spawn activation where child is local
4334 ProcessID p=result->get_coeffs().owner(child);
4335
4336 void (implT::*ft)(const Vphi_op_NS<opT,LDIM>&, const noop<T,NDIM>&, const keyT&) const = &implT:: template forward_traverse< Vphi_op_NS<opT,LDIM>, noop<T,NDIM> >;
4337 result->task(p, ft, child_op, no, child);
4338 }
4339 }
4340 // return e sum coeffs; also return always is_leaf=true:
4341 // the recursion is continued within this struct, not outside in traverse_tree!
4342 return std::pair<bool,coeffT> (true,coeffT());
4343 }
4344
4345 tensorT eri_coeffs(const keyT& key) const {
4348 if (eri->get_functor()->provides_coeff()) {
4349 return eri->get_functor()->coeff(key).full_tensor();
4350 } else {
4351 tensorT val_eri(eri->cdata.vk);
4352 eri->fcube(key,*(eri->get_functor()),eri->cdata.quad_x,val_eri);
4353 return eri->values2coeffs(key,val_eri);
4354 }
4355 }
4356
4357 /// the error is computed from the d coefficients of the constituent functions
4358
4359 /// the result is h_n = P_n(f g), computed as h_n \approx Pn(f_n g_n)
4360 /// its error is therefore
4361 /// h_n = (f g)_n = ((Pn(f) + Qn(f)) (Pn(g) + Qn(g))
4362 /// = Pn(fn gn) + Qn(fn gn) + Pn(f) Qn(g) + Qn(f) Pn(g) + Qn(f) Pn(g)
4363 /// the first term is what we compute, the second term is estimated by tnorm (in another function),
4364 /// the third to last terms are estimated in this function by e.g.: Qn(f)Pn(g) < ||Qn(f)|| ||Pn(g)||
4366 const tensorT& ceri) const {
4367 double error = 0.0;
4368 Key<LDIM> key1, key2;
4369 key.break_apart(key1,key2);
4370
4371 PROFILE_BLOCK(compute_error);
4372 double dnorm_ket, snorm_ket;
4373 if (have_ket()) {
4374 snorm_ket=iaket.coeff(key).normf();
4375 dnorm_ket=iaket.dnorm(key);
4376 } else {
4377 double s1=iap1.coeff(key1).normf();
4378 double s2=iap2.coeff(key2).normf();
4379 double d1=iap1.dnorm(key1);
4380 double d2=iap2.dnorm(key2);
4381 snorm_ket=s1*s2;
4382 dnorm_ket=s1*d2 + s2*d1 + d1*d2;
4383 }
4384
4385 if (have_v1()) {
4386 double snorm=iav1.coeff(key1).normf();
4387 double dnorm=iav1.dnorm(key1);
4388 error+=snorm*dnorm_ket + dnorm*snorm_ket + dnorm*dnorm_ket;
4389 }
4390 if (have_v2()) {
4391 double snorm=iav2.coeff(key2).normf();
4392 double dnorm=iav2.dnorm(key2);
4393 error+=snorm*dnorm_ket + dnorm*snorm_ket + dnorm*dnorm_ket;
4394 }
4395 if (have_eri()) {
4396 tensorT s_coeffs=ceri(result->cdata.s0);
4397 double snorm=s_coeffs.normf();
4398 tensorT d=copy(ceri);
4399 d(result->cdata.s0)=0.0;
4400 double dnorm=d.normf();
4401 error+=snorm*dnorm_ket + dnorm*snorm_ket + dnorm*dnorm_ket;
4402 }
4403
4404 bool no_potential=not ((have_v1() or have_v2() or have_eri()));
4405 if (no_potential) {
4406 error=dnorm_ket;
4407 }
4408 return error;
4409 }
4410
4411 /// make the sum coeffs for key
4412 std::pair<coeffT,double> make_sum_coeffs(const keyT& key) const {
4414 // break key into particles
4415 Key<LDIM> key1, key2;
4416 key.break_apart(key1,key2);
4417
4418 // bool printme=(int(key.translation()[0])==int(std::pow(key.level(),2)/2)) and
4419 // (int(key.translation()[1])==int(std::pow(key.level(),2)/2)) and
4420 // (int(key.translation()[2])==int(std::pow(key.level(),2)/2));
4421
4422// printme=false;
4423
4424 // get/make all coefficients
4425 const coeffT coeff_ket = (iaket.get_impl()) ? iaket.coeff(key)
4426 : outer(iap1.coeff(key1),iap2.coeff(key2),result->get_tensor_args());
4427 const coeffT cpot1 = (have_v1()) ? iav1.coeff(key1) : coeffT();
4428 const coeffT cpot2 = (have_v2()) ? iav2.coeff(key2) : coeffT();
4429 const tensorT ceri = (have_eri()) ? eri_coeffs(key) : tensorT();
4430
4431 // compute first part of the total error
4432 double refine_error=compute_error_from_inaccurate_refinement(key,ceri);
4433 double error=refine_error;
4434
4435 // prepare the multiplication
4436 pointwise_multiplier<LDIM> pm(key,coeff_ket);
4437
4438 // perform the multiplication, compute tnorm part of the total error
4439 coeffT cresult(result->cdata.vk,result->get_tensor_args());
4440 if (have_v1()) {
4441 cresult+=pm(key,cpot1.get_tensor(),1);
4442 error+=pm.error;
4443 }
4444 if (have_v2()) {
4445 cresult+=pm(key,cpot2.get_tensor(),2);
4446 error+=pm.error;
4447 }
4448
4449 if (have_eri()) {
4450 tensorT result1=cresult.full_tensor_copy();
4451 result1+=pm(key,copy(ceri(result->cdata.s0)));
4452 cresult=coeffT(result1,result->get_tensor_args());
4453 error+=pm.error;
4454 } else {
4456 }
4457 if ((not have_v1()) and (not have_v2()) and (not have_eri())) {
4458 cresult=coeff_ket;
4459 }
4460
4461 return std::make_pair(cresult,error);
4462 }
4463
4464 this_type make_child(const keyT& child) const {
4465
4466 // break key into particles
4467 Key<LDIM> key1, key2;
4468 child.break_apart(key1,key2);
4469
4470 return this_type(result,leaf_op,iaket.make_child(child),
4471 iap1.make_child(key1),iap2.make_child(key2),
4472 iav1.make_child(key1),iav2.make_child(key2),eri);
4473 }
4474
4476 Future<ctT> iaket1=iaket.activate();
4477 Future<ctL> iap11=iap1.activate();
4478 Future<ctL> iap21=iap2.activate();
4479 Future<ctL> iav11=iav1.activate();
4480 Future<ctL> iav21=iav2.activate();
4481 return result->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
4482 &this_type::forward_ctor),result,leaf_op,
4483 iaket1,iap11,iap21,iav11,iav21,eri);
4484 }
4485
4486 this_type forward_ctor(implT* result1, const opT& leaf_op, const ctT& iaket1,
4487 const ctL& iap11, const ctL& iap21, const ctL& iav11, const ctL& iav21,
4488 const implT* eri1) {
4489 return this_type(result1,leaf_op,iaket1,iap11,iap21,iav11,iav21,eri1);
4490 }
4491
4492 /// serialize this (needed for use in recursive_op)
4493 template <typename Archive> void serialize(const Archive& ar) {
4494 ar & iaket & eri & result & leaf_op & iap1 & iap2 & iav1 & iav2;
4495 }
4496 };
4497
4498 /// assemble the function V*phi using V and phi given from the functor
4499
4500 /// this function must have been constructed using the CompositeFunctorInterface.
4501 /// The interface provides one- and two-electron potentials, and the ket, which are
4502 /// assembled to give V*phi.
4503 /// @param[in] leaf_op operator to decide if a given node is a leaf node
4504 /// @param[in] fence global fence
4505 template<typename opT>
4506 void make_Vphi(const opT& leaf_op, const bool fence=true) {
4507
4508 constexpr size_t LDIM=NDIM/2;
4509 MADNESS_CHECK_THROW(NDIM==LDIM*2,"make_Vphi only works for even dimensions");
4510
4511
4512 // keep the functor available, but remove it from the result
4513 // result will return false upon is_on_demand(), which is necessary for the
4514 // CoeffTracker to track the parent coeffs correctly for error_leaf_op
4515 std::shared_ptr< FunctionFunctorInterface<T,NDIM> > func2(this->get_functor());
4516 this->unset_functor();
4517
4519 dynamic_cast<CompositeFunctorInterface<T,NDIM,LDIM>* >(&(*func2));
4521
4522 // make sure everything is in place if no fence is requested
4523 if (fence) func->make_redundant(true); // no-op if already redundant
4524 MADNESS_CHECK_THROW(func->check_redundant(),"make_Vphi requires redundant functions");
4525
4526 // loop over all functions in the functor (either ket or particles)
4527 for (auto& ket : func->impl_ket_vector) {
4528 FunctionImpl<T,NDIM>* eri=func->impl_eri.get();
4529 FunctionImpl<T,LDIM>* v1=func->impl_m1.get();
4530 FunctionImpl<T,LDIM>* v2=func->impl_m2.get();
4531 FunctionImpl<T,LDIM>* p1=nullptr;
4532 FunctionImpl<T,LDIM>* p2=nullptr;
4533 make_Vphi_only(leaf_op,ket.get(),v1,v2,p1,p2,eri,false);
4534 }
4535
4536 for (std::size_t i=0; i<func->impl_p1_vector.size(); ++i) {
4537 FunctionImpl<T,NDIM>* ket=nullptr;
4538 FunctionImpl<T,NDIM>* eri=func->impl_eri.get();
4539 FunctionImpl<T,LDIM>* v1=func->impl_m1.get();
4540 FunctionImpl<T,LDIM>* v2=func->impl_m2.get();
4541 FunctionImpl<T,LDIM>* p1=func->impl_p1_vector[i].get();
4542 FunctionImpl<T,LDIM>* p2=func->impl_p2_vector[i].get();
4543 make_Vphi_only(leaf_op,ket,v1,v2,p1,p2,eri,false);
4544 }
4545
4546 // some post-processing:
4547 // - FunctionNode::accumulate() uses buffer -> add the buffer contents to the actual coefficients
4548 // - the operation constructs sum coefficients on all scales -> sum down to get a well-defined tree-state
4549 if (fence) {
4550 world.gop.fence();
4552 sum_down(true);
4554 }
4555
4556
4557 }
4558
4559 /// assemble the function V*phi using V and phi given from the functor
4560
4561 /// this function must have been constructed using the CompositeFunctorInterface.
4562 /// The interface provides one- and two-electron potentials, and the ket, which are
4563 /// assembled to give V*phi.
4564 /// @param[in] leaf_op operator to decide if a given node is a leaf node
4565 /// @param[in] fence global fence
4566 template<typename opT, std::size_t LDIM>
4571 const bool fence=true) {
4572
4573 // prepare the CoeffTracker
4574 CoeffTracker<T,NDIM> iaket(ket);
4575 CoeffTracker<T,LDIM> iap1(p1);
4576 CoeffTracker<T,LDIM> iap2(p2);
4577 CoeffTracker<T,LDIM> iav1(v1);
4578 CoeffTracker<T,LDIM> iav2(v2);
4579
4580 // the operator making the coefficients
4581 typedef Vphi_op_NS<opT,LDIM> coeff_opT;
4582 coeff_opT coeff_op(this,leaf_op,iaket,iap1,iap2,iav1,iav2,eri);
4583
4584 // this operator simply inserts the coeffs into this' tree
4585 typedef noop<T,NDIM> apply_opT;
4586 apply_opT apply_op;
4587
4588 if (world.rank() == coeffs.owner(cdata.key0)) {
4589 woT::task(world.rank(), &implT:: template forward_traverse<coeff_opT,apply_opT>,
4590 coeff_op, apply_op, cdata.key0);
4591 }
4592
4594 if (fence) world.gop.fence();
4595
4596 }
4597
4598 /// Permute the dimensions of f according to map, result on this
4599 void mapdim(const implT& f, const std::vector<long>& map, bool fence);
4600
4601 /// mirror the dimensions of f according to map, result on this
4602 void mirror(const implT& f, const std::vector<long>& mirror, bool fence);
4603
4604 /// map and mirror the translation index and the coefficients, result on this
4605
4606 /// first map the dimensions, the mirror!
4607 /// this = mirror(map(f))
4608 void map_and_mirror(const implT& f, const std::vector<long>& map,
4609 const std::vector<long>& mirror, bool fence);
4610
4611 /// take the average of two functions, similar to: this=0.5*(this+rhs)
4612
4613 /// works in either basis and also in nonstandard form
4614 void average(const implT& rhs);
4615
4616 /// change the tensor type of the coefficients in the FunctionNode
4617
4618 /// @param[in] targs target tensor arguments (threshold and full/low rank)
4619 void change_tensor_type1(const TensorArgs& targs, bool fence);
4620
4621 /// reduce the rank of the coefficients tensors
4622
4623 /// @param[in] targs target tensor arguments (threshold and full/low rank)
4624 void reduce_rank(const double thresh, bool fence);
4625
4626
4627 /// remove all nodes with level higher than n
4628 void chop_at_level(const int n, const bool fence=true);
4629
4630 /// compute norm of s and d coefficients for all nodes
4631 void compute_snorm_and_dnorm(bool fence=true);
4632
4633 /// compute the norm of the wavelet coefficients
4636
4640
4641 bool operator()(typename rangeT::iterator& it) const {
4642 auto& node=it->second;
4643 node.recompute_snorm_and_dnorm(cdata);
4644 return true;
4645 }
4646 };
4647
4648
4649 T eval_cube(Level n, coordT& x, const tensorT& c) const;
4650
4651 /// Transform sum coefficients at level n to sums+differences at level n-1
4652
4653 /// Given scaling function coefficients s[n][l][i] and s[n][l+1][i]
4654 /// return the scaling function and wavelet coefficients at the
4655 /// coarser level. I.e., decompose Vn using Vn = Vn-1 + Wn-1.
4656 /// \code
4657 /// s_i = sum(j) h0_ij*s0_j + h1_ij*s1_j
4658 /// d_i = sum(j) g0_ij*s0_j + g1_ij*s1_j
4659 // \endcode
4660 /// Returns a new tensor and has no side effects. Works for any
4661 /// number of dimensions.
4662 ///
4663 /// No communication involved.
4664 tensorT filter(const tensorT& s) const;
4665
4666 coeffT filter(const coeffT& s) const;
4667
4668 /// Transform sums+differences at level n to sum coefficients at level n+1
4669
4670 /// Given scaling function and wavelet coefficients (s and d)
4671 /// returns the scaling function coefficients at the next finer
4672 /// level. I.e., reconstruct Vn using Vn = Vn-1 + Wn-1.
4673 /// \code
4674 /// s0 = sum(j) h0_ji*s_j + g0_ji*d_j
4675 /// s1 = sum(j) h1_ji*s_j + g1_ji*d_j
4676 /// \endcode
4677 /// Returns a new tensor and has no side effects
4678 ///
4679 /// If (sonly) ... then ss is only the scaling function coeff (and
4680 /// assume the d are zero). Works for any number of dimensions.
4681 ///
4682 /// No communication involved.
4683 tensorT unfilter(const tensorT& s) const;
4684
4685 coeffT unfilter(const coeffT& s) const;
4686
4687 /// downsample the sum coefficients of level n+1 to sum coeffs on level n
4688
4689 /// specialization of the filter method, will yield only the sum coefficients
4690 /// @param[in] key key of level n
4691 /// @param[in] v vector of sum coefficients of level n+1
4692 /// @return sum coefficients on level n in full tensor format
4693 tensorT downsample(const keyT& key, const std::vector< Future<coeffT > >& v) const;
4694
4695 /// upsample the sum coefficients of level 1 to sum coeffs on level n+1
4696
4697 /// specialization of the unfilter method, will transform only the sum coefficients
4698 /// @param[in] key key of level n+1
4699 /// @param[in] coeff sum coefficients of level n (does NOT belong to key!!)
4700 /// @return sum coefficients on level n+1
4701 coeffT upsample(const keyT& key, const coeffT& coeff) const;
4702
4703 /// Projects old function into new basis (only in reconstructed form)
4704 void project(const implT& old, bool fence);
4705
4707 bool operator()(const implT* f, const keyT& key, const nodeT& t) const {
4708 return true;
4709 }
4710 template <typename Archive> void serialize(Archive& ar) {}
4711 };
4712
4713 template <typename opT>
4714 void refine_op(const opT& op, const keyT& key) {
4715 // Must allow for someone already having autorefined the coeffs
4716 // and we get a write accessor just in case they are already executing
4717 typename dcT::accessor acc;
4718 const auto found = coeffs.find(acc,key);
4719 MADNESS_CHECK(found);
4720 nodeT& node = acc->second;
4721 if (node.has_coeff() && key.level() < max_refine_level && op(this, key, node)) {
4722 coeffT d(cdata.v2k,targs);
4723 d(cdata.s0) += copy(node.coeff());
4724 d = unfilter(d);
4725 node.clear_coeff();
4726 node.set_has_children(true);
4727 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
4728 const keyT& child = kit.key();
4729 coeffT ss = copy(d(child_patch(child)));
4731 // coeffs.replace(child,nodeT(ss,-1.0,false).node_to_low_rank());
4732 coeffs.replace(child,nodeT(ss,-1.0,false));
4733 // Note value -1.0 for norm tree to indicate result of refinement
4734 }
4735 }
4736 }
4737
4738 template <typename opT>
4739 void refine_spawn(const opT& op, const keyT& key) {
4740 nodeT& node = coeffs.find(key).get()->second;
4741 if (node.has_children()) {
4742 for (KeyChildIterator<NDIM> kit(key); kit; ++kit)
4743 woT::task(coeffs.owner(kit.key()), &implT:: template refine_spawn<opT>, op, kit.key(), TaskAttributes::hipri());
4744 }
4745 else {
4746 woT::task(coeffs.owner(key), &implT:: template refine_op<opT>, op, key);
4747 }
4748 }
4749
4750 // Refine in real space according to local user-defined criterion
4751 template <typename opT>
4752 void refine(const opT& op, bool fence) {
4753 if (world.rank() == coeffs.owner(cdata.key0))
4754 woT::task(coeffs.owner(cdata.key0), &implT:: template refine_spawn<opT>, op, cdata.key0, TaskAttributes::hipri());
4755 if (fence)
4756 world.gop.fence();
4757 }
4758
4759 bool exists_and_has_children(const keyT& key) const;
4760
4761 bool exists_and_is_leaf(const keyT& key) const;
4762
4763
4764 void broaden_op(const keyT& key, const std::vector< Future <bool> >& v);
4765
4766 // For each local node sets value of norm tree, snorm and dnorm to 0.0
4767 void zero_norm_tree();
4768
4769 // Broaden tree
4770 void broaden(const array_of_bools<NDIM>& is_periodic, bool fence);
4771
4772 /// sum all the contributions from all scales after applying an operator in mod-NS form
4773 void trickle_down(bool fence);
4774
4775 /// sum all the contributions from all scales after applying an operator in mod-NS form
4776
4777 /// cf reconstruct_op
4778 void trickle_down_op(const keyT& key, const coeffT& s);
4779
4780 /// reconstruct this tree -- respects fence
4781 void reconstruct(bool fence);
4782
4783 void change_tree_state(const TreeState finalstate, bool fence=true);
4784
4785 // Invoked on node where key is local
4786 // void reconstruct_op(const keyT& key, const tensorT& s);
4787 void reconstruct_op(const keyT& key, const coeffT& s, const bool accumulate_NS=true);
4788
4789 /// compress the wave function
4790
4791 /// after application there will be sum coefficients at the root level,
4792 /// and difference coefficients at all other levels; furthermore:
4793 /// @param[in] nonstandard keep sum coeffs at all other levels, except leaves
4794 /// @param[in] keepleaves keep sum coeffs (but no diff coeffs) at leaves
4795 /// @param[in] redundant keep only sum coeffs at all levels, discard difference coeffs
4796// void compress(bool nonstandard, bool keepleaves, bool redundant, bool fence);
4797 void compress(const TreeState newstate, bool fence);
4798
4799 /// s coefficients plus the (snorm_tree, dnorm_tree) pair propagated up by compress
4800 typedef std::pair<coeffT, std::pair<double,double> > compressT;
4801
4802 /// Invoked on node where key is local
4803 Future<compressT> compress_spawn(const keyT& key, bool nonstandard, bool keepleaves,
4804 bool redundant1);
4805
4806 private:
4807 /// convert this to redundant, i.e. have sum coefficients on all levels
4808 void make_redundant(const bool fence);
4809 public:
4810
4811 /// convert this from redundant to standard reconstructed form
4812 void undo_redundant(const bool fence);
4813
4814 void remove_internal_coefficients(const bool fence);
4815 void remove_leaf_coefficients(const bool fence);
4816
4817
4818 /// compute for each FunctionNode the norm of the function inside that node
4819 void norm_tree(bool fence);
4820
4821 double norm_tree_op(const keyT& key, const std::vector< Future<double> >& v);
4822
4824
4825 /// truncate using a tree in reconstructed form
4826
4827 /// must be invoked where key is local
4828 Future<coeffT> truncate_reconstructed_spawn(const keyT& key, const double tol);
4829
4830 /// given the sum coefficients of all children, truncate or not
4831
4832 /// @return new sum coefficients (empty if internal, not empty, if new leaf); might delete its children
4833 coeffT truncate_reconstructed_op(const keyT& key, const std::vector< Future<coeffT > >& v, const double tol);
4834
4835 /// calculate the wavelet coefficients using the sum coefficients of all child nodes
4836
4837 /// also propagates norm_tree and dnorm_tree for all nodes
4838 /// @param[in] key this's key
4839 /// @param[in] v sum coefficients and propagated norms of the child nodes
4840 /// @param[in] nonstandard keep the sum coefficients with the wavelet coefficients
4841 /// @return the sum coefficients and propagated norms
4842 compressT compress_op(const keyT& key, const std::vector< Future<compressT> >& v, bool nonstandard);
4843
4844
4845 /// similar to compress_op, but insert only the sum coefficients in the tree
4846
4847 /// also propagates norm_tree and dnorm_tree for all nodes
4848 /// @param[in] key this's key
4849 /// @param[in] v sum coefficients and propagated norms of the child nodes
4850 /// @return the sum coefficients and propagated norms
4851 compressT make_redundant_op(const keyT& key,const std::vector< Future<compressT> >& v);
4852
4853 /// Changes non-standard compressed form to standard compressed form
4854 void standard(bool fence);
4855
4856 /// Changes non-standard compressed form to standard compressed form
4859
4860 // threshold for rank reduction / SVD truncation
4862
4863 // constructor takes target precision
4864 do_standard() = default;
4866
4867 //
4868 bool operator()(typename rangeT::iterator& it) const {
4869
4870 const keyT& key = it->first;
4871 nodeT& node = it->second;
4872 if (key.level()> 0 && node.has_coeff()) {
4873 if (node.has_children()) {
4874 // Zero out scaling coeffs
4875 MADNESS_ASSERT(node.coeff().dim(0)==2*impl->get_k());
4876 node.coeff()(impl->cdata.s0)=0.0;
4877 node.reduceRank(impl->targs.thresh);
4878 } else {
4879 // Deleting both scaling and wavelet coeffs
4880 node.clear_coeff();
4881 }
4882 }
4883 return true;
4884 }
4885 template <typename Archive> void serialize(const Archive& ar) {
4886 MADNESS_EXCEPTION("no serialization of do_standard",1);
4887 }
4888 };
4889
4890
4891 /// laziness
4892 template<size_t OPDIM>
4893 struct do_op_args {
4896 double tol, fac, cnorm;
4897
4898 do_op_args() = default;
4899 do_op_args(const Key<OPDIM>& key, const Key<OPDIM>& d, const keyT& dest, double tol, double fac, double cnorm)
4900 : key(key), d(d), dest(dest), tol(tol), fac(fac), cnorm(cnorm) {}
4901 template <class Archive>
4902 void serialize(Archive& ar) {
4903 ar & archive::wrap_opaque(this,1);
4904 }
4905 };
4906
4907 /// for fine-grain parallelism: call the apply method of an operator in a separate task
4908
4909 /// @param[in] op the operator working on our function
4910 /// @param[in] c full rank tensor holding the NS coefficients
4911 /// @param[in] args laziness holding norm of the coefficients, displacement, destination, ..
4912 template <typename opT, typename R, size_t OPDIM>
4913 void do_apply_kernel(const opT* op, const Tensor<R>& c, const do_op_args<OPDIM>& args) {
4914
4915 tensorT result = op->apply(args.key, args.d, c, args.tol/args.fac/args.cnorm);
4916
4917 // Screen here to reduce communication cost of negligible data
4918 // and also to ensure we don't needlessly widen the tree when
4919 // applying the operator
4920 if (result.normf()> 0.3*args.tol/args.fac) {
4922 //woT::task(world.rank(),&implT::accumulate_timer,time,TaskAttributes::hipri());
4923 // UGLY BUT ADDED THE OPTIMIZATION BACK IN HERE EXPLICITLY/
4924 if (args.dest == world.rank()) {
4925 coeffs.send(args.dest, &nodeT::accumulate, result, coeffs, args.dest);
4926 }
4927 else {
4929 }
4930 }
4931 }
4932
4933 /// same as do_apply_kernel, but use full rank tensors as input and low rank tensors as output
4934
4935 /// @param[in] op the operator working on our function
4936 /// @param[in] c full rank tensor holding the NS coefficients
4937 /// @param[in] args laziness holding norm of the coefficients, displacement, destination, ..
4938 /// @param[in] apply_targs TensorArgs with tightened threshold for accumulation
4939 /// @return nothing, but accumulate the result tensor into the destination node
4940 template <typename opT, typename R, size_t OPDIM>
4941 double do_apply_kernel2(const opT* op, const Tensor<R>& c, const do_op_args<OPDIM>& args,
4942 const TensorArgs& apply_targs) {
4943
4944 tensorT result_full = op->apply(args.key, args.d, c, args.tol/args.fac/args.cnorm);
4945 const double norm=result_full.normf();
4946
4947 // Screen here to reduce communication cost of negligible data
4948 // and also to ensure we don't needlessly widen the tree when
4949 // applying the operator
4950 // OPTIMIZATION NEEDED HERE ... CHANGING THIS TO TASK NOT SEND REMOVED
4951 // BUILTIN OPTIMIZATION TO SHORTCIRCUIT MSG IF DATA IS LOCAL
4952 if (norm > 0.3*args.tol/args.fac) {
4953
4954 small++;
4955 //double cpu0=cpu_time();
4956 coeffT result=coeffT(result_full,apply_targs);
4957 MADNESS_ASSERT(result.is_full_tensor() or result.is_svd_tensor());
4958 //double cpu1=cpu_time();
4959 //timer_lr_result.accumulate(cpu1-cpu0);
4960
4961 coeffs.task(args.dest, &nodeT::accumulate, result, coeffs, args.dest, apply_targs,
4963
4964 //woT::task(world.rank(),&implT::accumulate_timer,time,TaskAttributes::hipri());
4965 }
4966 return norm;
4967 }
4968
4969
4970
4971 /// same as do_apply_kernel2, but use low rank tensors as input and low rank tensors as output
4972
4973 /// @param[in] op the operator working on our function
4974 /// @param[in] coeff full rank tensor holding the NS coefficients
4975 /// @param[in] args laziness holding norm of the coefficients, displacement, destination, ..
4976 /// @param[in] apply_targs TensorArgs with tightened threshold for accumulation
4977 /// @return nothing, but accumulate the result tensor into the destination node
4978 template <typename opT, typename R, size_t OPDIM>
4979 double do_apply_kernel3(const opT* op, const GenTensor<R>& coeff, const do_op_args<OPDIM>& args,
4980 const TensorArgs& apply_targs) {
4981
4982 coeffT result;
4983 if (2*OPDIM==NDIM) result= op->apply2_lowdim(args.key, args.d, coeff,
4984 args.tol/args.fac/args.cnorm, args.tol/args.fac);
4985 if (OPDIM==NDIM) result = op->apply2(args.key, args.d, coeff,
4986 args.tol/args.fac/args.cnorm, args.tol/args.fac);
4987
4988 const double result_norm=result.svd_normf();
4989
4990 if (result_norm> 0.3*args.tol/args.fac) {
4991 small++;
4992
4993 double cpu0=cpu_time();
4994 if (not result.is_of_tensortype(targs.tt)) result=result.convert(targs);
4995 double cpu1=cpu_time();
4996 timer_lr_result.accumulate(cpu1-cpu0);
4997
4998 // accumulate also expects result in SVD form
4999 coeffs.task(args.dest, &nodeT::accumulate, result, coeffs, args.dest, apply_targs,
5001// woT::task(world.rank(),&implT::accumulate_timer,time,TaskAttributes::hipri());
5002
5003 }
5004 return result_norm;
5005
5006 }
5007
5008 // volume of n-dimensional sphere of radius R
5009 double vol_nsphere(int n, double R) {
5010 return std::pow(madness::constants::pi,n*0.5)*std::pow(R,n)/std::tgamma(1+0.5*n);
5011 }
5012
5013
5014 /// apply an operator on the coeffs c (at node key)
5015
5016 /// the result is accumulated inplace to this's tree at various FunctionNodes
5017 /// @param[in] op the operator to act on the source function
5018 /// @param[in] key key of the source FunctionNode of f which is processed
5019 /// @param[in] c coeffs of the FunctionNode of f which is processed
5020 template <typename opT, typename R>
5021 void do_apply(const opT* op, const keyT& key, const Tensor<R>& c) {
5023
5024 // working assumption here WAS that the operator is
5025 // isotropic and monotonically decreasing with distance
5026 // ... however, now we are using derivative Gaussian
5027 // expansions (and also non-cubic boxes) isotropic is
5028 // violated. While not strictly monotonically decreasing,
5029 // the derivative gaussian is still such that once it
5030 // becomes negligible we are in the asymptotic region.
5031
5032 typedef typename opT::keyT opkeyT;
5033 constexpr auto opdim = opT::opdim;
5034 const opkeyT source = op->get_source_key(key);
5035
5036 // Tuning here is based on observation that with
5037 // sufficiently high-order wavelet relative to the
5038 // precision, that only nearest neighbor boxes contribute,
5039 // whereas for low-order wavelets more neighbors will
5040 // contribute. Sufficiently high is picked as
5041 // k>=2-log10(eps) which is our empirical rule for
5042 // efficiency/accuracy and code instrumentation has
5043 // previously indicated that (in 3D) just unit
5044 // displacements are invoked. The error decays as R^-(k+1),
5045 // and the number of boxes increases as R^d.
5046 //
5047 // Fac is the expected number of contributions to a given
5048 // box, so the error permitted per contribution will be
5049 // tol/fac
5050
5051 // radius of shell (nearest neighbor is diameter of 3 boxes, so radius=1.5)
5052 double radius = 1.5 + 0.33 * std::max(0.0, 2 - std::log10(thresh) -
5053 k); // 0.33 was 0.5
5054 //double radius = 2.5;
5055 double fac = vol_nsphere(NDIM, radius);
5056 // previously fac=10.0 selected empirically constrained by qmprop
5057
5058 double cnorm = c.normf();
5059
5060 // BC handling:
5061 // - if operator is lattice-summed then treat this as nonperiodic (i.e. tell neighbor() to stay in simulation cell)
5062 // - if operator is NOT lattice-summed then obey BC (i.e. tell neighbor() to go outside the simulation cell along periodic dimensions)
5063 // - BUT user can force operator to treat its arguments as non-periodic (`op.set_domain_periodicity({true,true,true})`) so ... which dimensions of this function are treated as periodic by op?
5064 const array_of_bools<NDIM> func_is_treated_by_op_as_periodic =
5065 (op->particle() == 1)
5066 ? array_of_bools<NDIM>{false}.or_front(
5067 op->func_domain_is_periodic())
5068 : array_of_bools<NDIM>{false}.or_back(
5069 op->func_domain_is_periodic());
5070
5071 const auto default_real_distance_squared = [&](const auto &displacement)
5072 -> double {
5073 return displacement.real_distsq_bc(op->lattice_summed(), FunctionDefaults<NDIM>::get_cell_width());
5074 };
5075 const auto default_lattice_distance_squared = [&](const auto &displacement)
5076 -> std::uint64_t {
5077 return displacement.distsq_bc(op->lattice_summed());
5078 };
5079 const auto default_skip_predicate = [&](const auto &displacement)
5080 -> bool {
5081 return false;
5082 };
5083 const auto for_each = [&](const auto &displacements,
5084 const auto &real_distance_squared,
5085 const auto &lattice_distance_squared,
5086 const auto &skip_predicate) -> std::optional<double> {
5087
5088 // used to screen estimated and actual contributions
5089 //const double tol = truncate_tol(thresh, key);
5090 //const double tol = 0.1*truncate_tol(thresh, key);
5091 const double tol = truncate_tol(thresh, key);
5092
5093 // assume isotropic decaying kernel, screen in shell-wise fashion by
5094 // monitoring the decay of magnitude of contribution norms with the
5095 // distance ... as soon as we find a shell of displacements at least
5096 // one of each in simulation domain (see neighbor()) and
5097 // all in-domain shells produce negligible contributions, stop.
5098 // a displacement is negligible if ||op|| * ||c|| > tol / fac
5099 // where fac takes into account
5100 int nvalid = 1; // Counts #valid at each distance
5101 int nused = 1; // Counts #used at each distance
5102 std::optional<double> real_last_distsq;
5103 std::optional<std::uint64_t> lattice_last_distsq;
5104
5105 // displacements to the kernel range boundary are typically same magnitude (modulo variation)
5106 // estimate the norm of the resulting contributions and skip all if one is too small
5107 if constexpr (std::is_same_v<std::decay_t<decltype(displacements)>,BoxSurfaceDisplacementRange<opdim>>) {
5108 const auto &probing_displacement =
5109 displacements.probing_displacement();
5110 const double opnorm =
5111 op->norm(key.level(), probing_displacement, source);
5112 if (cnorm * opnorm <= tol / fac) {
5113 return {};
5114 }
5115 }
5116
5117 for (const auto& displacement: displacements) {
5118 if (skip_predicate(displacement)) continue;
5119
5120 keyT d;
5121 Key<NDIM - opdim> nullkey(key.level());
5122 MADNESS_ASSERT(op->particle() == 1 || op->particle() == 2);
5123 if (op->particle() == 1)
5124 d = displacement.merge_with(nullkey);
5125 else
5126 d = nullkey.merge_with(displacement);
5127
5128 // Screen out shells. We assume shells are grouped into shells so that the operator decays with shell index.
5129 // Shells are indexed by least distance from box to the central box.
5130 // Cells touching so much as a corner of the central box are further grouped by their lattice distance.
5131 // N.B. lattice-summed decaying kernel is periodic (i.e. does decay w.r.t. r), so loop over shells of displacements sorted by distances modulated by periodicity (Key::distsq_bc)
5132 const auto real_distsq = real_distance_squared(displacement);
5133 const std::uint64_t lattice_distsq = real_distsq ? 0 : lattice_distance_squared(displacement);
5134 if (!real_last_distsq.has_value() ||
5135 !nearlyEqual(real_distsq, *real_last_distsq) || (nearlyEqual(*real_last_distsq, 0) && lattice_distsq != *lattice_last_distsq)) { // Moved to next shell of neighbors
5136 if (nvalid > 0 && nused == 0 && (real_distsq > 0 || lattice_distsq > 1)) {
5137 // Have at least done the input box and all first
5138 // nearest neighbors, and none of the last set
5139 // of neighbors made significant contributions. Thus,
5140 // assuming monotonic decrease, we are done.
5141 break;
5142 }
5143 nused = 0;
5144 nvalid = 0;
5145 real_last_distsq = real_distsq;
5146 // After real_last_distsq > 0, we stop caring about keeping lattice_last_distsq up-to-date.
5147 lattice_last_distsq = real_distsq ? std::optional<std::uint64_t>{} : lattice_distsq;
5148 }
5149
5150 keyT dest = neighbor(key, d, func_is_treated_by_op_as_periodic);
5151 if (dest.is_valid()) {
5152 nvalid++;
5153 const double opnorm = op->norm(key.level(), displacement, source);
5154
5155 if (cnorm * opnorm > tol / fac) {
5156 tensorT result =
5157 op->apply(source, displacement, c, tol / fac / cnorm);
5158 if (result.normf() > 0.3 * tol / fac) {
5159 if (coeffs.is_local(dest))
5160 coeffs.send(dest, &nodeT::accumulate2, result, coeffs,
5161 dest);
5162 else
5163 coeffs.task(dest, &nodeT::accumulate2, result, coeffs,
5164 dest);
5165 nused++;
5166 }
5167 }
5168 }
5169 }
5170
5171 return real_last_distsq;
5172 };
5173
5174 // process "standard" displacements, screening assumes monotonic decay of the kernel
5175 // list of displacements sorted in order of increasing distance
5176 // N.B. if op is lattice-summed use periodic displacements, else use
5177 // non-periodic even if op treats any modes of this as periodic
5178 const std::vector<opkeyT> &disp = op->get_disp(key.level());
5179 const auto max_distsq_reached = for_each(disp, default_real_distance_squared, default_lattice_distance_squared, default_skip_predicate);
5180
5181 // for range-restricted kernels displacements to the boundary of the kernel range also need to be included
5182 // N.B. hard range restriction will result in slow decay of operator matrix elements for the displacements
5183 // to the range boundary, should use soft restriction or sacrifice precision
5184 if (op->range_restricted() && key.level() >= 1) {
5185
5186 std::array<std::optional<std::int64_t>, opdim> box_radius;
5187 std::array<std::optional<std::int64_t>, opdim> surface_thickness;
5188 auto &range = op->get_range();
5189 for (int d = 0; d != opdim; ++d) {
5190 if (range[d]) {
5191 box_radius[d] = range[d].N();
5192 surface_thickness[d] = range[d].finite_soft() ? 1 : 0;
5193 }
5194 }
5195
5197 // skip surface displacements that take us outside of the domain and/or were included in regular displacements
5198 // N.B. for lattice-summed axes the "filter" also maps the displacement back into the simulation cell
5199 if (max_distsq_reached)
5200 validator = BoxSurfaceDisplacementValidator<opdim>(/* is_infinite_domain= */ op->func_domain_is_periodic(), /* is_lattice_summed= */ op->lattice_summed(), range, default_real_distance_squared, *max_distsq_reached);
5201
5202 // Least N such that being N boxes away from origin_ guarantees you're outside of the short-range region.
5203 std::optional<Translation> probe_offset_radius;
5204 if (max_distsq_reached) {
5205 // default_real_distance_squared measures cell_width*(|l|-1) per axis (see Key::real_distsq_bc);
5206 // invert it. The offset axis is not known here, so use the widest one, which yields the
5207 // smallest radius and hence the most conservative probe.
5208 const auto &cell_width = FunctionDefaults<NDIM>::get_cell_width();
5209 const std::size_t d0 = (op->particle() == 1) ? 0 : NDIM - opdim;
5210 double widest = 0.;
5211 for (std::size_t d = d0; d != d0 + opdim; ++d) widest = std::max(widest, cell_width(d));
5212 const Translation reach = 1 + static_cast<Translation>(std::sqrt(*max_distsq_reached) / widest);
5213 probe_offset_radius = std::min<Translation>(reach, Displacements<opdim>::bmax_default()) + 1;
5214 } else // no validator => no treatment of short-range point. let surface handle everything
5215 probe_offset_radius = 0;
5216
5217 // this range iterates over the entire surface layer(s), and provides a probing displacement that can be used to screen out the entire box
5218 auto opkey = op->particle() == 1 ? key.template extract_front<opdim>() : key.template extract_back<opdim>();
5220 range_boundary_face_displacements(opkey, box_radius,
5221 surface_thickness,
5222 op->lattice_summed(),
5223 validator,
5224 probe_offset_radius);
5225 for_each(
5226 range_boundary_face_displacements,
5227 // surface displacements are not screened, all are included
5228 [](const auto &displacement) -> double { return 0; },
5229 [](const auto &displacement) -> std::uint64_t { return 0; },
5230 default_skip_predicate);
5231 }
5232 }
5233
5234
5235 /// apply an operator on f to return this
5236 template <typename opT, typename R>
5237 void apply(opT& op, const FunctionImpl<R,NDIM>& f, bool fence) {
5239 MADNESS_ASSERT(!op.modified());
5240 for (const auto& [key, node]: f.coeffs) {
5241 if (node.has_coeff()) {
5242 if (node.coeff().dim(0) != k /* i.e. not a leaf */ || op.doleaves) {
5244// woT::task(p, &implT:: template do_apply<opT,R>, &op, key, node.coeff()); //.full_tensor_copy() ????? why copy ????
5245 woT::task(p, &implT:: template do_apply<opT,R>, &op, key, node.coeff().reconstruct_tensor());
5246 }
5247 }
5248 }
5249 if (fence)
5250 world.gop.fence();
5251
5253// this->compressed=true;
5254// this->nonstandard=true;
5255// this->redundant=false;
5256
5257 }
5258
5259
5260
5261 /// apply an operator on the coeffs c (at node key)
5262
5263 /// invoked by result; the result is accumulated inplace to this's tree at various FunctionNodes
5264 /// @param[in] op the operator to act on the source function
5265 /// @param[in] key key of the source FunctionNode of f which is processed (see "source")
5266 /// @param[in] coeff coeffs of FunctionNode being processed
5267 /// @param[in] do_kernel true: do the 0-disp only; false: do everything but the kernel
5268 /// @return max norm, and will modify or include new nodes in this' tree
5269 template <typename opT, typename R>
5270 double do_apply_directed_screening(const opT* op, const keyT& key, const coeffT& coeff,
5271 const bool& do_kernel) {
5273 // insert timer here
5274 typedef typename opT::keyT opkeyT;
5275
5276 // screening: contains all displacement keys that had small result norms
5277 std::list<opkeyT> blacklist;
5278
5279 constexpr auto opdim=opT::opdim;
5280 Key<NDIM-opdim> nullkey(key.level());
5281
5282 // source is that part of key that corresponds to those dimensions being processed
5283 const opkeyT source=op->get_source_key(key);
5284
5285 const double tol = truncate_tol(thresh, key);
5286
5287 // fac is the root of the number of contributing neighbors (1st shell)
5288 double fac=std::pow(3,NDIM*0.5);
5289 double cnorm = coeff.normf();
5290
5291 // for accumulation: keep slightly tighter TensorArgs
5292 TensorArgs apply_targs(targs);
5293 apply_targs.thresh=tol/fac*0.03;
5294
5295 double maxnorm=0.0;
5296
5297 // for the kernel it may be more efficient to do the convolution in full rank
5298 tensorT coeff_full;
5299 // for partial application (exchange operator) it's more efficient to
5300 // do SVD tensors instead of tensortrains, because addition in apply
5301 // can be done in full form for the specific particle
5302 coeffT coeff_SVD=coeff.convert(TensorArgs(-1.0,TT_2D));
5303#ifdef HAVE_GENTENSOR
5304 coeff_SVD.get_svdtensor().orthonormalize(tol*GenTensor<T>::fac_reduce());
5305#endif
5306
5307 // list of displacements sorted in order of increasing distance
5308 // N.B. if op is lattice-summed gives periodic displacements, else uses
5309 // non-periodic even if op treats any modes of this as periodic
5310 const std::vector<opkeyT>& disp = Displacements<opdim>().get_disp(key.level(), op->lattice_summed());
5311
5312 for (const auto& d: disp) {
5313 const int shell=d.distsq_bc(op->lattice_summed());
5314 if (do_kernel and (shell>0)) break;
5315 if ((not do_kernel) and (shell==0)) continue;
5316
5317 keyT disp1;
5318 if (op->particle()==1) disp1=d.merge_with(nullkey);
5319 else if (op->particle()==2) disp1=nullkey.merge_with(d);
5320 else {
5321 MADNESS_EXCEPTION("confused particle in operator??",1);
5322 }
5323
5324 keyT dest = neighbor_in_volume(key, disp1);
5325
5326 if (not dest.is_valid()) continue;
5327
5328 // directed screening
5329 // working assumption here is that the operator is isotropic and
5330 // monotonically decreasing with distance
5331 bool screened=false;
5332 typename std::list<opkeyT>::const_iterator it2;
5333 for (it2=blacklist.begin(); it2!=blacklist.end(); it2++) {
5334 if (d.is_farther_out_than(*it2)) {
5335 screened=true;
5336 break;
5337 }
5338 }
5339 if (not screened) {
5340
5341 double opnorm = op->norm(key.level(), d, source);
5342 double norm=0.0;
5343
5344 if (cnorm*opnorm> tol/fac) {
5345
5346 double cost_ratio=op->estimate_costs(source, d, coeff_SVD, tol/fac/cnorm, tol/fac);
5347 // cost_ratio=1.5; // force low rank
5348 // cost_ratio=0.5; // force full rank
5349
5350 if (cost_ratio>0.0) {
5351
5352 do_op_args<opdim> args(source, d, dest, tol, fac, cnorm);
5353 norm=0.0;
5354 if (cost_ratio<1.0) {
5355 if (not coeff_full.has_data()) coeff_full=coeff.full_tensor_copy();
5356 norm=do_apply_kernel2(op, coeff_full,args,apply_targs);
5357 } else {
5358 if (2*opdim==NDIM) { // apply operator on one particle only
5359 norm=do_apply_kernel3(op,coeff_SVD,args,apply_targs);
5360 } else {
5361 norm=do_apply_kernel3(op,coeff,args,apply_targs);
5362 }
5363 }
5364 maxnorm=std::max(norm,maxnorm);
5365 }
5366
5367 } else if (shell >= 12) {
5368 break; // Assumes monotonic decay beyond nearest neighbor
5369 }
5370 if (norm<0.3*tol/fac) blacklist.push_back(d);
5371 }
5372 }
5373 return maxnorm;
5374 }
5375
5376
5377 /// similar to apply, but for low rank coeffs
5378 template <typename opT, typename R>
5379 void apply_source_driven(opT& op, const FunctionImpl<R,NDIM>& f, bool fence) {
5381
5382 MADNESS_ASSERT(not op.modified());
5383 // looping through all the coefficients of the source f
5384 typename dcT::const_iterator end = f.get_coeffs().end();
5385 for (typename dcT::const_iterator it=f.get_coeffs().begin(); it!=end; ++it) {
5386
5387 const keyT& key = it->first;
5388 const coeffT& coeff = it->second.coeff();
5389
5390 if (coeff.has_data() and (coeff.rank()!=0)) {
5392 woT::task(p, &implT:: template do_apply_directed_screening<opT,R>, &op, key, coeff, true);
5393 woT::task(p, &implT:: template do_apply_directed_screening<opT,R>, &op, key, coeff, false);
5394 }
5395 }
5396 if (fence) world.gop.fence();
5398 }
5399
5400 /// after apply we need to do some cleanup;
5401
5402 /// forces fence
5403 double finalize_apply();
5404
5405 /// after summing up we need to do some cleanup;
5406
5407 /// forces fence
5408 void finalize_sum();
5409
5410 /// traverse a non-existing tree, make its coeffs and apply an operator
5411
5412 /// invoked by result
5413 /// here we use the fact that the hi-dim NS coefficients on all scales are exactly
5414 /// the outer product of the underlying low-dim functions (also in NS form),
5415 /// so we don't need to construct the full hi-dim tree and then turn it into NS form.
5416 /// @param[in] apply_op the operator acting on the NS tree
5417 /// @param[in] fimpl the funcimpl of the function of particle 1
5418 /// @param[in] gimpl the funcimpl of the function of particle 2
5419 template<typename opT, std::size_t LDIM>
5420 void recursive_apply(opT& apply_op, const FunctionImpl<T,LDIM>* fimpl,
5421 const FunctionImpl<T,LDIM>* gimpl, const bool fence) {
5422
5423 //print("IN RECUR2");
5424 const keyT& key0=cdata.key0;
5425
5426 if (world.rank() == coeffs.owner(key0)) {
5427
5428 CoeffTracker<T,LDIM> ff(fimpl);
5429 CoeffTracker<T,LDIM> gg(gimpl);
5430
5431 typedef recursive_apply_op<opT,LDIM> coeff_opT;
5432 coeff_opT coeff_op(this,ff,gg,&apply_op);
5433
5434 typedef noop<T,NDIM> apply_opT;
5435 apply_opT apply_op;
5436
5438 woT::task(p, &implT:: template forward_traverse<coeff_opT,apply_opT>, coeff_op, apply_op, key0);
5439
5440 }
5441 if (fence) world.gop.fence();
5443 }
5444
5445 /// recursive part of recursive_apply
5446 template<typename opT, std::size_t LDIM>
5448 bool randomize() const {return true;}
5449
5451
5456
5457 // ctor
5461 const opT* apply_op) : result(result), iaf(iaf), iag(iag), apply_op(apply_op)
5462 {
5463 MADNESS_ASSERT(LDIM+LDIM==NDIM);
5464 }
5466 iag(other.iag), apply_op(other.apply_op) {}
5467
5468
5469 /// make the NS-coefficients and send off the application of the operator
5470
5471 /// @return a Future<bool,coeffT>(is_leaf,coeffT())
5472 std::pair<bool,coeffT> operator()(const Key<NDIM>& key) const {
5473
5474 // World& world=result->world;
5475 // break key into particles (these are the child keys, with datum1/2 come the parent keys)
5476 Key<LDIM> key1,key2;
5477 key.break_apart(key1,key2);
5478
5479 // the lo-dim functions should be in full tensor form
5480 const tensorT fcoeff=iaf.coeff(key1).full_tensor();
5481 const tensorT gcoeff=iag.coeff(key2).full_tensor();
5482
5483 // would this be a leaf node? If so, then its sum coeffs have already been
5484 // processed by the parent node's wavelet coeffs. Therefore we won't
5485 // process it any more.
5487 bool is_leaf=leaf_op(key,fcoeff,gcoeff);
5488
5489 if (not is_leaf) {
5490 // new coeffs are simply the hartree/kronecker/outer product --
5491 const std::vector<Slice>& s0=iaf.get_impl()->cdata.s0;
5492 const coeffT coeff = (apply_op->modified())
5493 ? outer(copy(fcoeff(s0)),copy(gcoeff(s0)),result->targs)
5494 : outer(fcoeff,gcoeff,result->targs);
5495
5496 // now send off the application
5497 tensorT coeff_full;
5499 double norm0=result->do_apply_directed_screening<opT,T>(apply_op, key, coeff, true);
5500
5501 result->task(p,&implT:: template do_apply_directed_screening<opT,T>,
5502 apply_op,key,coeff,false);
5503
5504 return finalize(norm0,key,coeff);
5505
5506 } else {
5507 return std::pair<bool,coeffT> (is_leaf,coeffT());
5508 }
5509 }
5510
5511 /// sole purpose is to wait for the kernel norm, wrap it and send it back to caller
5512 std::pair<bool,coeffT> finalize(const double kernel_norm, const keyT& key,
5513 const coeffT& coeff) const {
5514 const double thresh=result->get_thresh()*0.1;
5515 bool is_leaf=(kernel_norm<result->truncate_tol(thresh,key));
5516 if (key.level()<2) is_leaf=false;
5517 return std::pair<bool,coeffT> (is_leaf,coeff);
5518 }
5519
5520
5521 this_type make_child(const keyT& child) const {
5522
5523 // break key into particles
5524 Key<LDIM> key1, key2;
5525 child.break_apart(key1,key2);
5526
5527 return this_type(result,iaf.make_child(key1),iag.make_child(key2),apply_op);
5528 }
5529
5533 return result->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
5534 &this_type::forward_ctor),result,f1,g1,apply_op);
5535 }
5536
5538 const opT* apply_op1) {
5539 return this_type(r,f1,g1,apply_op1);
5540 }
5541
5542 template <typename Archive> void serialize(const Archive& ar) {
5543 ar & result & iaf & iag & apply_op;
5544 }
5545 };
5546
5547 /// traverse an existing tree and apply an operator
5548
5549 /// invoked by result
5550 /// @param[in] apply_op the operator acting on the NS tree
5551 /// @param[in] fimpl the funcimpl of the source function
5552 /// @param[in] rimpl a dummy function for recursive_op to insert data
5553 template<typename opT>
5554 void recursive_apply(opT& apply_op, const implT* fimpl, implT* rimpl, const bool fence) {
5555
5556 print("IN RECUR1");
5557
5558 const keyT& key0=cdata.key0;
5559
5560 if (world.rank() == coeffs.owner(key0)) {
5561
5562 typedef recursive_apply_op2<opT> coeff_opT;
5563 coeff_opT coeff_op(this,fimpl,&apply_op);
5564
5565 typedef noop<T,NDIM> apply_opT;
5566 apply_opT apply_op;
5567
5568 woT::task(world.rank(), &implT:: template forward_traverse<coeff_opT,apply_opT>,
5569 coeff_op, apply_op, cdata.key0);
5570
5571 }
5572 if (fence) world.gop.fence();
5574 }
5575
5576 /// recursive part of recursive_apply
5577 template<typename opT>
5579 bool randomize() const {return true;}
5580
5583 typedef std::pair<bool,coeffT> argT;
5584
5585 mutable implT* result;
5586 ctT iaf; /// need this for randomization
5587 const opT* apply_op;
5588
5589 // ctor
5593
5595 iaf(other.iaf), apply_op(other.apply_op) {}
5596
5597
5598 /// send off the application of the operator
5599
5600 /// the first (core) neighbor (ie. the box itself) is processed
5601 /// immediately, all other ones are shoved into the taskq
5602 /// @return a pair<bool,coeffT>(is_leaf,coeffT())
5603 argT operator()(const Key<NDIM>& key) const {
5604
5605 const coeffT& coeff=iaf.coeff();
5606
5607 if (coeff.has_data()) {
5608
5609 // now send off the application for all neighbor boxes
5611 result->task(p,&implT:: template do_apply_directed_screening<opT,T>,
5612 apply_op, key, coeff, false);
5613
5614 // process the core box
5615 double norm0=result->do_apply_directed_screening<opT,T>(apply_op,key,coeff,true);
5616
5617 if (iaf.is_leaf()) return argT(true,coeff);
5618 return finalize(norm0,key,coeff,result);
5619
5620 } else {
5621 const bool is_leaf=true;
5622 return argT(is_leaf,coeffT());
5623 }
5624 }
5625
5626 /// sole purpose is to wait for the kernel norm, wrap it and send it back to caller
5627 argT finalize(const double kernel_norm, const keyT& key,
5628 const coeffT& coeff, const implT* r) const {
5629 const double thresh=r->get_thresh()*0.1;
5630 bool is_leaf=(kernel_norm<r->truncate_tol(thresh,key));
5631 if (key.level()<2) is_leaf=false;
5632 return argT(is_leaf,coeff);
5633 }
5634
5635
5636 this_type make_child(const keyT& child) const {
5637 return this_type(result,iaf.make_child(child),apply_op);
5638 }
5639
5640 /// retrieve the coefficients (parent coeffs might be remote)
5642 Future<ctT> f1=iaf.activate();
5643
5644// Future<ctL> g1=g.activate();
5645// return h->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
5646// &this_type::forward_ctor),h,f1,g1,particle);
5647
5648 return result->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
5649 &this_type::forward_ctor),result,f1,apply_op);
5650 }
5651
5652 /// taskq-compatible ctor
5653 this_type forward_ctor(implT* result1, const ctT& iaf1, const opT* apply_op1) {
5654 return this_type(result1,iaf1,apply_op1);
5655 }
5656
5657 template <typename Archive> void serialize(const Archive& ar) {
5658 ar & result & iaf & apply_op;
5659 }
5660 };
5661
5662 /// Returns the square of the error norm in the box labeled by key
5663
5664 /// Assumed to be invoked locally but it would be easy to eliminate
5665 /// this assumption
5666 template <typename opT>
5667 double err_box(const keyT& key, const nodeT& node, const opT& func,
5668 int npt, const Tensor<double>& qx, const Tensor<double>& quad_phit,
5669 const Tensor<double>& quad_phiw) const {
5670
5671 std::vector<long> vq(NDIM);
5672 for (std::size_t i=0; i<NDIM; ++i)
5673 vq[i] = npt;
5674 tensorT fval(vq,false), work(vq,false), result(vq,false);
5675
5676 // Compute the "exact" function in this volume at npt points
5677 // where npt is usually this->npt+1.
5678 fcube(key, func, qx, fval);
5679
5680 // Transform into the scaling function basis of order npt
5681 double scale = pow(0.5,0.5*NDIM*key.level())*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
5682 fval = fast_transform(fval,quad_phiw,result,work).scale(scale);
5683
5684 // Subtract to get the error ... the original coeffs are in the order k
5685 // basis but we just computed the coeffs in the order npt(=k+1) basis
5686 // so we can either use slices or an iterator macro.
5687 const tensorT coeff = node.coeff().full_tensor();
5688 ITERATOR(coeff,fval(IND)-=coeff(IND););
5689 // flo note: we do want to keep a full tensor here!
5690
5691 // Compute the norm of what remains
5692 double err = fval.normf();
5693 return err*err;
5694 }
5695
5696 template <typename opT>
5698 const implT* impl;
5699 const opT* func;
5700 int npt;
5704 public:
5705 do_err_box() = default;
5706
5710
5713
5714 double operator()(typename dcT::const_iterator& it) const {
5715 const keyT& key = it->first;
5716 const nodeT& node = it->second;
5717 if (node.has_coeff())
5718 return impl->err_box(key, node, *func, npt, qx, quad_phit, quad_phiw);
5719 else
5720 return 0.0;
5721 }
5722
5723 double operator()(double a, double b) const {
5724 return a+b;
5725 }
5726
5727 template <typename Archive>
5728 void serialize(const Archive& ar) {
5729 MADNESS_EXCEPTION("not yet", 1);
5730 }
5731 };
5732
5733 /// Returns the sum of squares of errors from local info ... no comms
5734 template <typename opT>
5735 double errsq_local(const opT& func) const {
5737 // Make quadrature rule of higher order
5738 const int npt = cdata.npt + 1;
5739 Tensor<double> qx, qw, quad_phi, quad_phiw, quad_phit;
5740 FunctionCommonData<T,NDIM>::_init_quadrature(k+1, npt, qx, qw, quad_phi, quad_phiw, quad_phit);
5741
5744 return world.taskq.reduce< double,rangeT,do_err_box<opT> >(range,
5745 do_err_box<opT>(this, &func, npt, qx, quad_phit, quad_phiw));
5746 }
5747
5748 /// Returns \c int(f(x),x) in local volume
5749 T trace_local() const;
5750
5752 double operator()(typename dcT::const_iterator& it) const {
5753 const nodeT& node = it->second;
5754 if (node.has_coeff()) {
5755 double norm = node.coeff().normf();
5756 return norm*norm;
5757 }
5758 else {
5759 return 0.0;
5760 }
5761 }
5762
5763 double operator()(double a, double b) const {
5764 return (a+b);
5765 }
5766
5767 template <typename Archive> void serialize(const Archive& ar) {
5768 MADNESS_EXCEPTION("NOT IMPLEMENTED", 1);
5769 }
5770 };
5771
5772
5773 /// Returns the square of the local norm ... no comms
5774 double norm2sq_local() const;
5775
5776 /// compute the inner product of this range with other
5777 template<typename R>
5781 typedef TENSOR_RESULT_TYPE(T,R) resultT;
5782
5785 resultT operator()(typename dcT::const_iterator& it) const {
5786
5787 TENSOR_RESULT_TYPE(T,R) sum=0.0;
5788 const keyT& key=it->first;
5789 const nodeT& fnode = it->second;
5790 if (fnode.has_coeff()) {
5791 if (other->coeffs.probe(it->first)) {
5792 const FunctionNode<R,NDIM>& gnode = other->coeffs.find(key).get()->second;
5793 if (gnode.has_coeff()) {
5794 if (gnode.coeff().dim(0) != fnode.coeff().dim(0)) {
5795 madness::print("INNER", it->first, gnode.coeff().dim(0),fnode.coeff().dim(0));
5796 MADNESS_EXCEPTION("functions have different k or compress/reconstruct error", 0);
5797 }
5798 if (leaves_only) {
5799 if (gnode.is_leaf() or fnode.is_leaf()) {
5800 sum += fnode.coeff().trace_conj(gnode.coeff());
5801 }
5802 } else {
5803 sum += fnode.coeff().trace_conj(gnode.coeff());
5804 }
5805 }
5806 }
5807 }
5808 return sum;
5809 }
5810
5811 resultT operator()(resultT a, resultT b) const {
5812 return (a+b);
5813 }
5814
5815 template <typename Archive> void serialize(const Archive& ar) {
5816 MADNESS_EXCEPTION("NOT IMPLEMENTED", 1);
5817 }
5818 };
5819
5820 /// Returns the inner product ASSUMING same distribution
5821
5822 /// handles compressed and redundant form
5823 template <typename R>
5827 typedef TENSOR_RESULT_TYPE(T,R) resultT;
5828
5829 // make sure the states of the trees are consistent
5832 return world.taskq.reduce<resultT,rangeT,do_inner_local<R> >
5834 }
5835
5836
5837 /// compute the inner product of this range with other
5838 template<typename R>
5842 bool leaves_only=true;
5843 typedef TENSOR_RESULT_TYPE(T,R) resultT;
5844
5848 resultT operator()(typename dcT::const_iterator& it) const {
5849
5850 constexpr std::size_t LDIM=std::max(NDIM/2,std::size_t(1));
5851
5852 const keyT& key=it->first;
5853 const nodeT& fnode = it->second;
5854 if (not fnode.has_coeff()) return resultT(0.0); // probably internal nodes
5855
5856 // assuming all boxes (esp the low-dim ones) are local, i.e. the functions are replicated
5857 auto find_valid_parent = [](auto& key, auto& impl, auto&& find_valid_parent) {
5858 MADNESS_CHECK(impl->get_coeffs().owner(key)==impl->world.rank()); // make sure everything is local!
5859 if (impl->get_coeffs().probe(key)) return key;
5860 auto parentkey=key.parent();
5861 return find_valid_parent(parentkey, impl, find_valid_parent);
5862 };
5863
5864 // returns coefficients, empty if no functor present
5865 auto get_coeff = [&find_valid_parent](const auto& key, const auto& v_impl) {
5866 if ((v_impl.size()>0) and v_impl.front().get()) {
5867 auto impl=v_impl.front();
5868
5869// bool have_impl=impl.get();
5870// if (have_impl) {
5871 auto parentkey = find_valid_parent(key, impl, find_valid_parent);
5872 MADNESS_CHECK(impl->get_coeffs().probe(parentkey));
5873 typename decltype(impl->coeffs)::accessor acc;
5874 impl->get_coeffs().find(acc,parentkey);
5875 auto parentcoeff=acc->second.coeff();
5876 auto coeff=impl->parent_to_child(parentcoeff, parentkey, key);
5877 return coeff;
5878 } else {
5879 // get type of vector elements
5880 typedef typename std::decay_t<decltype(v_impl)>::value_type::element_type::typeT S;
5881// typedef typename std::decay_t<decltype(v_impl)>::value_type S;
5882 return GenTensor<S>();
5883// return GenTensor<typename std::decay_t<decltype(*impl)>::typeT>();
5884 }
5885 };
5886
5887 auto make_vector = [](auto& arg) {
5888 return std::vector<std::decay_t<decltype(arg)>>(1,arg);
5889 };
5890
5891
5892 Key<LDIM> key1,key2;
5893 key.break_apart(key1,key2);
5894
5895 auto func=dynamic_cast<CompositeFunctorInterface<R,NDIM,LDIM>* >(ket->functor.get());
5897
5898 MADNESS_CHECK_THROW(func->impl_ket_vector.size()==0 or func->impl_ket_vector.size()==1,
5899 "only one ket function supported in inner_on_demand");
5900 MADNESS_CHECK_THROW(func->impl_p1_vector.size()==0 or func->impl_p1_vector.size()==1,
5901 "only one p1 function supported in inner_on_demand");
5902 MADNESS_CHECK_THROW(func->impl_p2_vector.size()==0 or func->impl_p2_vector.size()==1,
5903 "only one p2 function supported in inner_on_demand");
5904 auto coeff_bra=fnode.coeff();
5905 auto coeff_ket=get_coeff(key,func->impl_ket_vector);
5906 auto coeff_v1=get_coeff(key1,make_vector(func->impl_m1));
5907 auto coeff_v2=get_coeff(key2,make_vector(func->impl_m2));
5908 auto coeff_p1=get_coeff(key1,func->impl_p1_vector);
5909 auto coeff_p2=get_coeff(key2,func->impl_p2_vector);
5910
5911 // construct |ket(1,2)> or |p(1)p(2)> or |p(1)p(2) ket(1,2)>
5912 double error=0.0;
5913 if (coeff_ket.has_data() and coeff_p1.has_data()) {
5914 pointwise_multiplier<LDIM> pm(key,coeff_ket);
5915 coeff_ket=pm(key,outer(coeff_p1,coeff_p2,TensorArgs(TT_FULL,-1.0)).full_tensor());
5916 error+=pm.error;
5917 } else if (coeff_ket.has_data() or coeff_p1.has_data()) {
5918 coeff_ket = (coeff_ket.has_data()) ? coeff_ket : outer(coeff_p1,coeff_p2);
5919 } else { // not ket and no p1p2
5920 MADNESS_EXCEPTION("confused ket/p1p2 in do_inner_local_on_demand",1);
5921 }
5922
5923 // construct (v(1) + v(2)) |ket(1,2)>
5924 coeffT v1v2ket;
5925 if (coeff_v1.has_data()) {
5926 pointwise_multiplier<LDIM> pm(key,coeff_ket);
5927 v1v2ket = pm(key,coeff_v1.full_tensor(), 1);
5928 error+=pm.error;
5929 v1v2ket+= pm(key,coeff_v2.full_tensor(), 2);
5930 error+=pm.error;
5931 } else {
5932 v1v2ket = coeff_ket;
5933 }
5934
5935 resultT result;
5936 if (func->impl_eri) { // project bra*ket onto eri, avoid multiplication with eri
5937 MADNESS_CHECK(func->impl_eri->get_functor()->provides_coeff());
5938 coeffT coeff_eri=func->impl_eri->get_functor()->coeff(key).full_tensor();
5939 pointwise_multiplier<LDIM> pm(key,v1v2ket);
5940 tensorT braket=pm(key,coeff_bra.full_tensor_copy().conj());
5941 error+=pm.error;
5942 if (error>1.e-3) print("error in key",key,error);
5943 result=coeff_eri.full_tensor().trace(braket);
5944
5945 } else { // no eri, project ket onto bra
5946 result=coeff_bra.full_tensor_copy().trace_conj(v1v2ket.full_tensor_copy());
5947 }
5948 return result;
5949 }
5950
5951 resultT operator()(resultT a, resultT b) const {
5952 return (a+b);
5953 }
5954
5955 template <typename Archive> void serialize(const Archive& ar) {
5956 MADNESS_EXCEPTION("NOT IMPLEMENTED", 1);
5957 }
5958 };
5959
5960 /// Returns the inner product of this with function g constructed on-the-fly
5961
5962 /// the leaf boxes of this' MRA tree defines the inner product
5963 template <typename R>
5964 TENSOR_RESULT_TYPE(T,R) inner_local_on_demand(const FunctionImpl<R,NDIM>& gimpl) const {
5967
5971 do_inner_local_on_demand<R>(this, &gimpl));
5972 }
5973
5974 /// compute the inner product of this range with other
5975 template<typename R>
5979 typedef TENSOR_RESULT_TYPE(T,R) resultT;
5980
5983 resultT operator()(typename dcT::const_iterator& it) const {
5984
5985 TENSOR_RESULT_TYPE(T,R) sum=0.0;
5986 const keyT& key=it->first;
5987 const nodeT& fnode = it->second;
5988 if (fnode.has_coeff()) {
5989 if (other->coeffs.probe(it->first)) {
5990 const FunctionNode<R,NDIM>& gnode = other->coeffs.find(key).get()->second;
5991 if (gnode.has_coeff()) {
5992 if (gnode.coeff().dim(0) != fnode.coeff().dim(0)) {
5993 madness::print("DOT", it->first, gnode.coeff().dim(0),fnode.coeff().dim(0));
5994 MADNESS_EXCEPTION("functions have different k or compress/reconstruct error", 0);
5995 }
5996 if (leaves_only) {
5997 if (gnode.is_leaf() or fnode.is_leaf()) {
5998 sum += fnode.coeff().full_tensor().trace(gnode.coeff().full_tensor());
5999 }
6000 } else {
6001 sum += fnode.coeff().full_tensor().trace(gnode.coeff().full_tensor());
6002 }
6003 }
6004 }
6005 }
6006 return sum;
6007 }
6008
6009 resultT operator()(resultT a, resultT b) const {
6010 return (a+b);
6011 }
6012
6013 template <typename Archive> void serialize(const Archive& ar) {
6014 MADNESS_EXCEPTION("NOT IMPLEMENTED", 1);
6015 }
6016 };
6017
6018 /// Returns the dot product ASSUMING same distribution
6019
6020 /// handles compressed and redundant form
6021 template <typename R>
6025 typedef TENSOR_RESULT_TYPE(T,R) resultT;
6026
6027 // make sure the states of the trees are consistent
6029 bool leaves_only=(this->is_redundant());
6030 return world.taskq.reduce<resultT,rangeT,do_dot_local<R> >
6032 }
6033
6034 /// Type of the entry in the map returned by make_key_vec_map
6035 typedef std::vector< std::pair<int,const coeffT*> > mapvecT;
6036
6037 /// Type of the map returned by make_key_vec_map
6039
6040 /// Adds keys to union of local keys with specified index
6041 void add_keys_to_map(mapT* map, int index) const {
6042 typename dcT::const_iterator end = coeffs.end();
6043 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
6044 typename mapT::accessor acc;
6045 const keyT& key = it->first;
6046 const FunctionNode<T,NDIM>& node = it->second;
6047 if (node.has_coeff()) {
6048 [[maybe_unused]] auto inserted = map->insert(acc,key);
6049 acc->second.push_back(std::make_pair(index,&(node.coeff())));
6050 }
6051 }
6052 }
6053
6054 /// Returns map of union of local keys to vector of indexes of functions containing that key
6055
6056 /// Local concurrency and synchronization only; no communication
6057 static
6058 mapT
6059 make_key_vec_map(const std::vector<const FunctionImpl<T,NDIM>*>& v) {
6060 mapT map(100000);
6061 // This loop must be parallelized
6062 for (unsigned int i=0; i<v.size(); i++) {
6063 //v[i]->add_keys_to_map(&map,i);
6064 v[i]->world.taskq.add(*(v[i]), &FunctionImpl<T,NDIM>::add_keys_to_map, &map, int(i));
6065 }
6066 if (v.size()) v[0]->world.taskq.fence();
6067 return map;
6068 }
6069
6070#if 0
6071// Original
6072 template <typename R>
6073 static void do_inner_localX(const typename mapT::iterator lstart,
6074 const typename mapT::iterator lend,
6075 typename FunctionImpl<R,NDIM>::mapT* rmap_ptr,
6076 const bool sym,
6077 Tensor< TENSOR_RESULT_TYPE(T,R) >* result_ptr,
6078 Mutex* mutex) {
6079 Tensor< TENSOR_RESULT_TYPE(T,R) >& result = *result_ptr;
6080 Tensor< TENSOR_RESULT_TYPE(T,R) > r(result.dim(0),result.dim(1));
6081 for (typename mapT::iterator lit=lstart; lit!=lend; ++lit) {
6082 const keyT& key = lit->first;
6083 typename FunctionImpl<R,NDIM>::mapT::iterator rit=rmap_ptr->find(key);
6084 if (rit != rmap_ptr->end()) {
6085 const mapvecT& leftv = lit->second;
6086 const typename FunctionImpl<R,NDIM>::mapvecT& rightv =rit->second;
6087 const int nleft = leftv.size();
6088 const int nright= rightv.size();
6089
6090 for (int iv=0; iv<nleft; iv++) {
6091 const int i = leftv[iv].first;
6092 const GenTensor<T>* iptr = leftv[iv].second;
6093
6094 for (int jv=0; jv<nright; jv++) {
6095 const int j = rightv[jv].first;
6096 const GenTensor<R>* jptr = rightv[jv].second;
6097
6098 if (!sym || (sym && i<=j))
6099 r(i,j) += iptr->trace_conj(*jptr);
6100 }
6101 }
6102 }
6103 }
6104 mutex->lock();
6105 result += r;
6106 mutex->unlock();
6107 }
6108#else
6109 template <typename R>
6110 static void do_inner_localX(const typename mapT::iterator lstart,
6111 const typename mapT::iterator lend,
6112 typename FunctionImpl<R,NDIM>::mapT* rmap_ptr,
6113 const bool sym,
6114 Tensor< TENSOR_RESULT_TYPE(T,R) >* result_ptr,
6115 Mutex* mutex) {
6116 Tensor< TENSOR_RESULT_TYPE(T,R) >& result = *result_ptr;
6117 //Tensor< TENSOR_RESULT_TYPE(T,R) > r(result.dim(0),result.dim(1));
6118 for (typename mapT::iterator lit=lstart; lit!=lend; ++lit) {
6119 const keyT& key = lit->first;
6120 typename FunctionImpl<R,NDIM>::mapT::iterator rit=rmap_ptr->find(key);
6121 if (rit != rmap_ptr->end()) {
6122 const mapvecT& leftv = lit->second;
6123 const typename FunctionImpl<R,NDIM>::mapvecT& rightv =rit->second;
6124 const size_t nleft = leftv.size();
6125 const size_t nright= rightv.size();
6126
6127 unsigned int size = leftv[0].second->size();
6128 Tensor<T> Left(nleft, size);
6129 Tensor<R> Right(nright, size);
6130 Tensor< TENSOR_RESULT_TYPE(T,R)> r(nleft, nright);
6131 for(unsigned int iv = 0; iv < nleft; ++iv) Left(iv,_) = (*(leftv[iv].second)).full_tensor();
6132 for(unsigned int jv = 0; jv < nright; ++jv) Right(jv,_) = (*(rightv[jv].second)).full_tensor();
6133 // call mxmT from mxm.h in tensor
6134 if(TensorTypeData<T>::iscomplex) Left = Left.conj(); // Should handle complex case and leave real case alone
6135 mxmT(nleft, nright, size, r.ptr(), Left.ptr(), Right.ptr());
6136 mutex->lock();
6137 for(unsigned int iv = 0; iv < nleft; ++iv) {
6138 const int i = leftv[iv].first;
6139 for(unsigned int jv = 0; jv < nright; ++jv) {
6140 const int j = rightv[jv].first;
6141 if (!sym || (sym && i<=j)) result(i,j) += r(iv,jv);
6142 }
6143 }
6144 mutex->unlock();
6145 }
6146 }
6147 }
6148#endif
6149
6150#if 0
6151// Original
6152 template <typename R, typename = std::enable_if_t<std::is_floating_point_v<R>>>
6153 static void do_dot_localX(const typename mapT::iterator lstart,
6154 const typename mapT::iterator lend,
6155 typename FunctionImpl<R, NDIM>::mapT* rmap_ptr,
6156 const bool sym,
6157 Tensor<TENSOR_RESULT_TYPE(T, R)>* result_ptr,
6158 Mutex* mutex) {
6159 if (TensorTypeData<T>::iscomplex) MADNESS_EXCEPTION("no complex trace in LowRankTensor, sorry", 1);
6160 Tensor<TENSOR_RESULT_TYPE(T, R)>& result = *result_ptr;
6161 Tensor<TENSOR_RESULT_TYPE(T, R)> r(result.dim(0), result.dim(1));
6162 for (typename mapT::iterator lit = lstart; lit != lend; ++lit) {
6163 const keyT& key = lit->first;
6164 typename FunctionImpl<R, NDIM>::mapT::iterator rit = rmap_ptr->find(key);
6165 if (rit != rmap_ptr->end()) {
6166 const mapvecT& leftv = lit->second;
6167 const typename FunctionImpl<R, NDIM>::mapvecT& rightv = rit->second;
6168 const int nleft = leftv.size();
6169 const int nright = rightv.size();
6170
6171 for (int iv = 0; iv < nleft; iv++) {
6172 const int i = leftv[iv].first;
6173 const GenTensor<T>* iptr = leftv[iv].second;
6174
6175 for (int jv = 0; jv < nright; jv++) {
6176 const int j = rightv[jv].first;
6177 const GenTensor<R>* jptr = rightv[jv].second;
6178
6179 if (!sym || (sym && i <= j))
6180 r(i, j) += iptr->trace_conj(*jptr);
6181 }
6182 }
6183 }
6184 }
6185 mutex->lock();
6186 result += r;
6187 mutex->unlock();
6188 }
6189#else
6190 template <typename R>
6191 static void do_dot_localX(const typename mapT::iterator lstart,
6192 const typename mapT::iterator lend,
6193 typename FunctionImpl<R, NDIM>::mapT* rmap_ptr,
6194 const bool sym,
6195 Tensor<TENSOR_RESULT_TYPE(T, R)>* result_ptr,
6196 Mutex* mutex) {
6197 Tensor<TENSOR_RESULT_TYPE(T, R)>& result = *result_ptr;
6198 // Tensor<TENSOR_RESULT_TYPE(T, R)> r(result.dim(0), result.dim(1));
6199 for (typename mapT::iterator lit = lstart; lit != lend; ++lit) {
6200 const keyT& key = lit->first;
6201 typename FunctionImpl<R, NDIM>::mapT::iterator rit = rmap_ptr->find(key);
6202 if (rit != rmap_ptr->end()) {
6203 const mapvecT& leftv = lit->second;
6204 const typename FunctionImpl<R, NDIM>::mapvecT& rightv = rit->second;
6205 const size_t nleft = leftv.size();
6206 const size_t nright= rightv.size();
6207
6208 unsigned int size = leftv[0].second->size();
6209 Tensor<T> Left(nleft, size);
6210 Tensor<R> Right(nright, size);
6211 Tensor< TENSOR_RESULT_TYPE(T, R)> r(nleft, nright);
6212 for(unsigned int iv = 0; iv < nleft; ++iv) Left(iv, _) = (*(leftv[iv].second)).full_tensor();
6213 for(unsigned int jv = 0; jv < nright; ++jv) Right(jv, _) = (*(rightv[jv].second)).full_tensor();
6214 // call mxmT from mxm.h in tensor
6215 mxmT(nleft, nright, size, r.ptr(), Left.ptr(), Right.ptr());
6216 mutex->lock();
6217 for(unsigned int iv = 0; iv < nleft; ++iv) {
6218 const int i = leftv[iv].first;
6219 for(unsigned int jv = 0; jv < nright; ++jv) {
6220 const int j = rightv[jv].first;
6221 if (!sym || (sym && i <= j)) result(i, j) += r(iv, jv);
6222 }
6223 }
6224 mutex->unlock();
6225 }
6226 }
6227 }
6228#endif
6229
6230 template <typename Real>
6231 static std::enable_if_t<std::is_floating_point_v<Real>, Real> conj(const Real x) {
6232 return x;
6233 }
6234
6235 template <typename Real>
6236 static std::complex<Real> conj(const std::complex<Real>& x) {
6237 return std::conj(x);
6238 }
6239
6240 template <typename R>
6241 static Tensor< TENSOR_RESULT_TYPE(T,R) >
6242 inner_local(const std::vector<const FunctionImpl<T,NDIM>*>& left,
6243 const std::vector<const FunctionImpl<R,NDIM>*>& right,
6244 bool sym) {
6245
6246 // This is basically a sparse matrix^T * matrix product
6247 // Rij = sum(k) Aki * Bkj
6248 // where i and j index functions and k index the wavelet coeffs
6249 // eventually the goal is this structure (don't have jtile yet)
6250 //
6251 // do in parallel tiles of k (tensors of coeffs)
6252 // do tiles of j
6253 // do i
6254 // do j in jtile
6255 // do k in ktile
6256 // Rij += Aki*Bkj
6257
6258 mapT lmap = make_key_vec_map(left);
6259 typename FunctionImpl<R,NDIM>::mapT rmap;
6260 auto* rmap_ptr = (typename FunctionImpl<R,NDIM>::mapT*)(&lmap);
6261 if ((std::vector<const FunctionImpl<R,NDIM>*>*)(&left) != &right) {
6263 rmap_ptr = &rmap;
6264 }
6265
6266 size_t chunk = (lmap.size()-1)/(3*4*5)+1;
6267
6268 Tensor< TENSOR_RESULT_TYPE(T,R) > r(left.size(), right.size());
6269 Mutex mutex;
6270
6271 typename mapT::iterator lstart=lmap.begin();
6272 while (lstart != lmap.end()) {
6273 typename mapT::iterator lend = lstart;
6274 advance(lend,chunk);
6275 left[0]->world.taskq.add(&FunctionImpl<T,NDIM>::do_inner_localX<R>, lstart, lend, rmap_ptr, sym, &r, &mutex);
6276 lstart = lend;
6277 }
6278 left[0]->world.taskq.fence();
6279
6280 if (sym) {
6281 for (long i=0; i<r.dim(0); i++) {
6282 for (long j=0; j<i; j++) {
6283 TENSOR_RESULT_TYPE(T,R) sum = r(i,j)+conj(r(j,i));
6284 r(i,j) = sum;
6285 r(j,i) = conj(sum);
6286 }
6287 }
6288 }
6289 return r;
6290 }
6291
6292 template <typename R>
6293 static Tensor<TENSOR_RESULT_TYPE(T, R)>
6294 dot_local(const std::vector<const FunctionImpl<T, NDIM>*>& left,
6295 const std::vector<const FunctionImpl<R, NDIM>*>& right,
6296 bool sym) {
6297
6298 // This is basically a sparse matrix * matrix product
6299 // Rij = sum(k) Aik * Bkj
6300 // where i and j index functions and k index the wavelet coeffs
6301 // eventually the goal is this structure (don't have jtile yet)
6302 //
6303 // do in parallel tiles of k (tensors of coeffs)
6304 // do tiles of j
6305 // do i
6306 // do j in jtile
6307 // do k in ktile
6308 // Rij += Aik*Bkj
6309
6310 mapT lmap = make_key_vec_map(left);
6311 typename FunctionImpl<R, NDIM>::mapT rmap;
6312 auto* rmap_ptr = (typename FunctionImpl<R, NDIM>::mapT*)(&lmap);
6313 if ((std::vector<const FunctionImpl<R, NDIM>*>*)(&left) != &right) {
6315 rmap_ptr = &rmap;
6316 }
6317
6318 size_t chunk = (lmap.size() - 1) / (3 * 4 * 5) + 1;
6319
6320 Tensor<TENSOR_RESULT_TYPE(T, R)> r(left.size(), right.size());
6321 Mutex mutex;
6322
6323 typename mapT::iterator lstart=lmap.begin();
6324 while (lstart != lmap.end()) {
6325 typename mapT::iterator lend = lstart;
6326 advance(lend, chunk);
6327 left[0]->world.taskq.add(&FunctionImpl<T, NDIM>::do_dot_localX<R>, lstart, lend, rmap_ptr, sym, &r, &mutex);
6328 lstart = lend;
6329 }
6330 left[0]->world.taskq.fence();
6331
6332 // sym is for hermiticity
6333 if (sym) {
6334 for (long i = 0; i < r.dim(0); i++) {
6335 for (long j = 0; j < i; j++) {
6336 TENSOR_RESULT_TYPE(T, R) sum = r(i, j) + conj(r(j, i));
6337 r(i, j) = sum;
6338 r(j, i) = conj(sum);
6339 }
6340 }
6341 }
6342 return r;
6343 }
6344
6345 template <typename R>
6347 {
6348 static_assert(!std::is_same<R, int>::value &&
6349 std::is_same<R, int>::value,
6350 "Compilation failed because you wanted to know the type; see below:");
6351 }
6352
6353 /// invoked by result
6354
6355 /// contract 2 functions f(x,z) = \int g(x,y) * h(y,z) dy
6356 /// @tparam CDIM: the dimension of the contraction variable (y)
6357 /// @tparam NDIM: the dimension of the result (x,z)
6358 /// @tparam LDIM: the dimension of g(x,y)
6359 /// @tparam KDIM: the dimension of h(y,z)
6360 template<typename Q, std::size_t LDIM, typename R, std::size_t KDIM,
6361 std::size_t CDIM = (KDIM + LDIM - NDIM) / 2>
6363 const std::array<int, CDIM> v1, const std::array<int, CDIM> v2) {
6364
6365 typedef std::multimap<Key<NDIM>, std::list<Key<CDIM>>> contractionmapT;
6366 //double wall_get_lists=0.0;
6367 //double wall_recur=0.0;
6368 //double wall_contract=0.0;
6371
6372 // auto print_map = [](const auto& map) {
6373 // for (const auto& kv : map) print(kv.first,"--",kv.second);
6374 // };
6375 // logical constness, not bitwise constness
6376 FunctionImpl<Q,LDIM>& g_nc=const_cast<FunctionImpl<Q,LDIM>&>(g);
6377 FunctionImpl<R,KDIM>& h_nc=const_cast<FunctionImpl<R,KDIM>&>(h);
6378
6379 std::list<contractionmapT> all_contraction_maps;
6380 for (std::size_t n=0; n<nmax; ++n) {
6381
6382 // list of nodes with d coefficients (and their parents)
6383 //double wall0 = wall_time();
6384 auto [g_ijlist, g_jlist] = g.get_contraction_node_lists(n, v1);
6385 auto [h_ijlist, h_jlist] = h.get_contraction_node_lists(n, v2);
6386 if ((g_ijlist.size() == 0) and (h_ijlist.size() == 0)) break;
6387 //double wall1 = wall_time();
6388 //wall_get_lists += (wall1 - wall0);
6389 //wall0 = wall1;
6390// print("g_jlist");
6391// for (const auto& kv : g_jlist) print(kv.first,kv.second);
6392// print("h_jlist");
6393// for (const auto& kv : h_jlist) print(kv.first,kv.second);
6394
6395 // next lines will insert s nodes into g and h -> possible race condition!
6396 bool this_first = true; // are the remaining indices of g before those of g: f(x,z) = g(x,y) h(y,z)
6397 // CDIM, NDIM, KDIM
6398 contractionmapT contraction_map = g_nc.recur_down_for_contraction_map(
6399 g_nc.key0(), g_nc.get_coeffs().find(g_nc.key0()).get()->second, v1, v2,
6400 h_ijlist, h_jlist, this_first, thresh);
6401
6402 this_first = false;
6403 // CDIM, NDIM, LDIM
6404 auto hnode0=h_nc.get_coeffs().find(h_nc.key0()).get()->second;
6405 contractionmapT contraction_map1 = h_nc.recur_down_for_contraction_map(
6406 h_nc.key0(), hnode0, v2, v1,
6407 g_ijlist, g_jlist, this_first, thresh);
6408
6409 // will contain duplicate entries
6410 contraction_map.merge(contraction_map1);
6411 // turn multimap into a map of list
6412 auto it = contraction_map.begin();
6413 while (it != contraction_map.end()) {
6414 auto it_end = contraction_map.upper_bound(it->first);
6415 auto it2 = it;
6416 it2++;
6417 while (it2 != it_end) {
6418 it->second.splice(it->second.end(), it2->second);
6419 it2 = contraction_map.erase(it2);
6420 }
6421 it = it_end;
6422 }
6423// print("thresh ",thresh);
6424// print("contraction list size",contraction_map.size());
6425
6426 // remove all double entries
6427 for (auto& elem: contraction_map) {
6428 elem.second.sort();
6429 elem.second.unique();
6430 }
6431 //wall1 = wall_time();
6432 //wall_recur += (wall1 - wall0);
6433// if (n==2) {
6434// print("contraction map for n=", n);
6435// print_map(contraction_map);
6436// }
6437 all_contraction_maps.push_back(contraction_map);
6438
6439 long mapsize=contraction_map.size();
6440 if (mapsize==0) break;
6441 }
6442
6443
6444 // finally do the contraction
6445 for (const auto& contraction_map : all_contraction_maps) {
6446 for (const auto& key_list : contraction_map) {
6447 const Key<NDIM>& key=key_list.first;
6448 const std::list<Key<CDIM>>& list=key_list.second;
6449 woT::task(coeffs.owner(key), &implT:: template partial_inner_contract<Q,LDIM,R,KDIM>,
6450 &g,&h,v1,v2,key,list);
6451 }
6452 }
6453 }
6454
6455 /// for contraction two functions f(x,z) = \int g(x,y) h(y,z) dy
6456
6457 /// find all nodes with d coefficients and return a list of complete keys and of
6458 /// keys holding only the y dimension, also the maximum norm of all d for the j dimension
6459 /// @param[in] n the scale
6460 /// @param[in] v array holding the indices of the integration variable
6461 /// @return ijlist: list of all nodes with d coeffs; jlist: j-part of ij list only
6462 template<std::size_t CDIM>
6463 std::tuple<std::set<Key<NDIM>>, std::map<Key<CDIM>,double>>
6464 get_contraction_node_lists(const std::size_t n, const std::array<int, CDIM>& v) const {
6465
6466 const auto& cdata=get_cdata();
6467 auto has_d_coeffs = [&cdata](const coeffT& coeff) {
6468 if (coeff.has_no_data()) return false;
6469 return (coeff.dim(0)==2*cdata.k);
6470 };
6471
6472 // keys to be contracted in g
6473 std::set<Key<NDIM>> ij_list; // full key
6474 std::map<Key<CDIM>,double> j_list; // only that dimension that will be contracted
6475
6476 for (auto it=get_coeffs().begin(); it!=get_coeffs().end(); ++it) {
6477 const Key<NDIM>& key=it->first;
6478 const FunctionNode<T,NDIM>& node=it->second;
6479 if ((key.level()==int(n)) and (has_d_coeffs(node.coeff()))) {
6480 ij_list.insert(key);
6482 for (std::size_t i=0; i<CDIM; ++i) j_trans[i]=key.translation()[v[i]];
6483 Key<CDIM> jkey(n,j_trans);
6484 const double max_d_norm=j_list[jkey];
6485 j_list.insert_or_assign(jkey,std::max(max_d_norm,node.get_dnorm()));
6486 Key<CDIM> parent_jkey=jkey.parent();
6487 while (j_list.count(parent_jkey)==0) {
6488 j_list.insert({parent_jkey,1.0});
6489 parent_jkey=parent_jkey.parent();
6490 }
6491 }
6492 }
6493 return std::make_tuple(ij_list,j_list);
6494 }
6495
6496 /// make a map of all nodes that will contribute to a partial inner product
6497
6498 /// given the list of d coefficient-holding nodes of the other function:
6499 /// recur down h if snorm * dnorm > tol and key n−jx ∈ other−ij-list. Make s
6500 /// coefficients if necessary. Make list of nodes n − ijk as map(n-ik, list(j)).
6501 ///
6502 /// !! WILL ADD NEW S NODES TO THIS TREE THAT MUST BE REMOVED TO AVOID INCONSISTENT TREE STRUCTURE !!
6503 ///
6504 /// @param[in] key for recursion
6505 /// @param[in] node corresponds to key
6506 /// @param[in] v_this this' dimension that are contracted
6507 /// @param[in] v_other other's dimension that are contracted
6508 /// @param[in] ij_other_list list of nodes of the other function that will be contracted (and their parents)
6509 /// @param[in] j_other_list list of column nodes of the other function that will be contracted (and their parents)
6510 /// @param[in] max_d_norm max d coeff norm of the nodes in j_list
6511 /// @param[in] this_first are the remaining coeffs of this functions first or last in the result function
6512 /// @param[in] thresh threshold for including nodes in the contraction: snorm*dnorm > thresh
6513 /// @tparam CDIM dimension to be contracted
6514 /// @tparam ODIM dimensions of the other function
6515 /// @tparam FDIM dimensions of the final function
6516 template<std::size_t CDIM, std::size_t ODIM, std::size_t FDIM=NDIM+ODIM-2*CDIM>
6517 std::multimap<Key<FDIM>, std::list<Key<CDIM>>> recur_down_for_contraction_map(
6518 const keyT& key, const nodeT& node,
6519 const std::array<int,CDIM>& v_this,
6520 const std::array<int,CDIM>& v_other,
6521 const std::set<Key<ODIM>>& ij_other_list,
6522 const std::map<Key<CDIM>,double>& j_other_list,
6523 bool this_first, const double thresh) {
6524
6525 std::multimap<Key<FDIM>, std::list<Key<CDIM>>> contraction_map;
6526
6527 // fast return if the other function has no d coeffs
6528 if (j_other_list.empty()) return contraction_map;
6529
6530 // continue recursion if this node may be contracted with the j column
6531 // extract relevant node translations from this node
6532 const auto j_this_key=key.extract_key(v_this);
6533
6534// print("\nkey, j_this_key", key, j_this_key);
6535 const double max_d_norm=j_other_list.find(j_this_key)->second;
6536 const bool sd_norm_product_large = node.get_snorm() * max_d_norm > truncate_tol(thresh,key);
6537// print("sd_product_norm",node.get_snorm() * max_d_norm, thresh);
6538
6539 // end recursion if we have reached the final scale n
6540 // with which nodes from other will this node be contracted?
6541 bool final_scale=key.level()==ij_other_list.begin()->level();
6542 if (final_scale and sd_norm_product_large) {
6543 for (auto& other_key : ij_other_list) {
6544 const auto j_other_key=other_key.extract_key(v_other);
6545 if (j_this_key != j_other_key) continue;
6546 auto i_key=key.extract_complement_key(v_this);
6547 auto k_key=other_key.extract_complement_key(v_other);
6548// print("key, ij_other_key",key,other_key);
6549// print("i, k, j key",i_key, k_key, j_this_key);
6550 Key<FDIM> ik_key=(this_first) ? i_key.merge_with(k_key) : k_key.merge_with(i_key);
6551// print("ik_key",ik_key);
6552// MADNESS_CHECK(contraction_map.count(ik_key)==0);
6553 contraction_map.insert(std::make_pair(ik_key,std::list<Key<CDIM>>{j_this_key}));
6554 }
6555 return contraction_map;
6556 }
6557
6558 bool continue_recursion = (j_other_list.count(j_this_key)==1);
6559 if (not continue_recursion) return contraction_map;
6560
6561
6562 // continue recursion if norms are large
6563 continue_recursion = (node.has_children() or sd_norm_product_large);
6564
6565 if (continue_recursion) {
6566 // in case we need to compute children's coefficients: unfilter only once
6567 bool compute_child_s_coeffs=true;
6568 coeffT d = node.coeff();
6569// print("continuing recursion from key",key);
6570
6571 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
6572 keyT child=kit.key();
6573 typename dcT::accessor acc;
6574
6575 // make child's s coeffs if it doesn't exist or if is has no s coeffs
6576 bool childnode_exists=get_coeffs().find(acc,child);
6577 bool need_s_coeffs= childnode_exists ? (acc->second.get_snorm()<=0.0) : true;
6578
6579 coeffT child_s_coeffs;
6580 if (need_s_coeffs) {
6581 if (compute_child_s_coeffs) {
6582 if (d.dim(0)==cdata.vk[0]) { // s coeffs only in this node
6583 coeffT d1(cdata.v2k,get_tensor_args());
6584 d1(cdata.s0)+=d;
6585 d=d1;
6586 }
6587 d = unfilter(d);
6588 compute_child_s_coeffs=false;
6589 }
6590 child_s_coeffs=copy(d(child_patch(child)));
6591 child_s_coeffs.reduce_rank(thresh);
6592 }
6593
6594 if (not childnode_exists) {
6595 get_coeffs().replace(child,nodeT(child_s_coeffs,false));
6596 get_coeffs().find(acc,child);
6597 } else if (childnode_exists and need_s_coeffs) {
6598 acc->second.coeff()=child_s_coeffs;
6599 }
6600 bool exists= get_coeffs().find(acc,child);
6601 MADNESS_CHECK(exists);
6602 nodeT& childnode = acc->second;
6603 if (need_s_coeffs) childnode.recompute_snorm_and_dnorm(get_cdata());
6604// print("recurring down to",child);
6605 contraction_map.merge(recur_down_for_contraction_map(child,childnode, v_this, v_other,
6606 ij_other_list, j_other_list, this_first, thresh));
6607// print("contraction_map.size()",contraction_map.size());
6608 }
6609
6610 }
6611
6612 return contraction_map;
6613 }
6614
6615
6616 /// tensor contraction part of partial_inner
6617
6618 /// @param[in] g rhs of the inner product
6619 /// @param[in] h lhs of the inner product
6620 /// @param[in] v1 dimensions of g to be contracted
6621 /// @param[in] v2 dimensions of h to be contracted
6622 /// @param[in] key key of result's (this) FunctionNode
6623 /// @param[in] j_key_list list of contraction index-j keys contributing to this' node
6624 template<typename Q, std::size_t LDIM, typename R, std::size_t KDIM,
6625 std::size_t CDIM = (KDIM + LDIM - NDIM) / 2>
6627 const std::array<int, CDIM> v1, const std::array<int, CDIM> v2,
6628 const Key<NDIM>& key, const std::list<Key<CDIM>>& j_key_list) {
6629
6630 Key<LDIM - CDIM> i_key;
6631 Key<KDIM - CDIM> k_key;
6632 key.break_apart(i_key, k_key);
6633
6634 coeffT result_coeff(get_cdata().v2k, get_tensor_type());
6635 for (const auto& j_key: j_key_list) {
6636
6637 auto v_complement = [](const auto& v, const auto& vc) {
6638 constexpr std::size_t VDIM = std::tuple_size<std::decay_t<decltype(v)>>::value;
6639 constexpr std::size_t VCDIM = std::tuple_size<std::decay_t<decltype(vc)>>::value;
6640 std::array<int, VCDIM> result;
6641 for (std::size_t i = 0; i < VCDIM; i++) result[i] = (v.back() + i + 1) % (VDIM + VCDIM);
6642 return result;
6643 };
6644 auto make_ij_key = [&v_complement](const auto i_key, const auto j_key, const auto& v) {
6645 constexpr std::size_t IDIM = std::decay_t<decltype(i_key)>::static_size;
6646 constexpr std::size_t JDIM = std::decay_t<decltype(j_key)>::static_size;
6647 static_assert(JDIM == std::tuple_size<std::decay_t<decltype(v)>>::value);
6648
6650 for (std::size_t i = 0; i < v.size(); ++i) l[v[i]] = j_key.translation()[i];
6651 std::array<int, IDIM> vc1;
6652 auto vc = v_complement(v, vc1);
6653 for (std::size_t i = 0; i < vc.size(); ++i) l[vc[i]] = i_key.translation()[i];
6654
6655 return Key<IDIM + JDIM>(i_key.level(), l);
6656 };
6657
6658 Key<LDIM> ij_key = make_ij_key(i_key, j_key, v1);
6659 Key<KDIM> jk_key = make_ij_key(k_key, j_key, v2);
6660
6661 MADNESS_CHECK(g->get_coeffs().probe(ij_key));
6662 MADNESS_CHECK(h->get_coeffs().probe(jk_key));
6663 const coeffT& gcoeff = g->get_coeffs().find(ij_key).get()->second.coeff();
6664 const coeffT& hcoeff = h->get_coeffs().find(jk_key).get()->second.coeff();
6665 coeffT gcoeff1, hcoeff1;
6666 if (gcoeff.dim(0) == g->get_cdata().k) {
6667 gcoeff1 = coeffT(g->get_cdata().v2k, g->get_tensor_args());
6668 gcoeff1(g->get_cdata().s0) += gcoeff;
6669 } else {
6670 gcoeff1 = gcoeff;
6671 }
6672 if (hcoeff.dim(0) == g->get_cdata().k) {
6673 hcoeff1 = coeffT(h->get_cdata().v2k, h->get_tensor_args());
6674 hcoeff1(h->get_cdata().s0) += hcoeff;
6675 } else {
6676 hcoeff1 = hcoeff;
6677 }
6678
6679 // offset: 0 for full tensor, 1 for svd representation with rand being the first dimension (r,d1,d2,d3) -> (r,d1*d2*d3)
6680 auto fuse = [](Tensor<T> tensor, const std::array<int, CDIM>& v, int offset) {
6681 for (std::size_t i = 0; i < CDIM - 1; ++i) {
6682 MADNESS_CHECK((v[i] + 1) == v[i + 1]); // make sure v is contiguous and ascending
6683 tensor = tensor.fusedim(v[0]+offset);
6684 }
6685 return tensor;
6686 };
6687
6688 // use case: partial_projection of 2-electron functions in svd representation f(1) = \int g(2) h(1,2) d2
6689 // c_i = \sum_j a_j b_ij = \sum_jr a_j b_rj b'_rj
6690 // = \sum_jr ( a_j b_rj) b'_rj )
6691 auto contract2 = [](const auto& svdcoeff, const auto& tensor, const int particle) {
6692#if HAVE_GENTENSOR
6693 const int spectator_particle=(particle+1)%2;
6694 Tensor<Q> gtensor = svdcoeff.get_svdtensor().make_vector_with_weights(particle);
6695 gtensor=gtensor.reshape(svdcoeff.rank(),gtensor.size()/svdcoeff.rank());
6696 MADNESS_CHECK(gtensor.ndim()==2);
6697 Tensor<Q> gtensor_other = svdcoeff.get_svdtensor().ref_vector(spectator_particle);
6698 Tensor<T> tmp1=inner(gtensor,tensor.flat(),1,0); // tmp1(r) = sum_j a'_(r,j) b(j)
6699 MADNESS_CHECK(tmp1.ndim()==1);
6700 Tensor<T> tmp2=inner(gtensor_other,tmp1,0,0); // tmp2(i) = sum_r a_(r,i) tmp1(r)
6701 return tmp2;
6702#else
6703 MADNESS_EXCEPTION("no partial_inner using svd without GenTensor",1);
6704 return Tensor<T>();
6705#endif
6706 };
6707
6708 if (gcoeff.is_full_tensor() and hcoeff.is_full_tensor() and result_coeff.is_full_tensor()) {
6709 // merge multiple contraction dimensions into one
6710 int offset = 0;
6711 Tensor<Q> gtensor = fuse(gcoeff1.full_tensor(), v1, offset);
6712 Tensor<R> htensor = fuse(hcoeff1.full_tensor(), v2, offset);
6713 result_coeff.full_tensor() += inner(gtensor, htensor, v1[0], v2[0]);
6714 if (key.level() > 0) {
6715 gtensor = copy(gcoeff1.full_tensor()(g->get_cdata().s0));
6716 htensor = copy(hcoeff1.full_tensor()(h->get_cdata().s0));
6717 gtensor = fuse(gtensor, v1, offset);
6718 htensor = fuse(htensor, v2, offset);
6719 result_coeff.full_tensor()(get_cdata().s0) -= inner(gtensor, htensor, v1[0], v2[0]);
6720 }
6721 }
6722
6723
6724 // use case: 2-electron functions in svd representation f(1,3) = \int g(1,2) h(2,3) d2
6725 // c_ik = \sum_j a_ij b_jk = \sum_jrr' a_ri a'_rj b_r'j b_r'k
6726 // = \sum_jrr' ( a_ri (a'_rj b_r'j) ) b_r'k
6727 // = \sum_jrr' c_r'i b_r'k
6728 else if (gcoeff.is_svd_tensor() and hcoeff.is_svd_tensor() and result_coeff.is_svd_tensor()) {
6729 MADNESS_CHECK(v1[0]==0 or v1[CDIM-1]==LDIM-1);
6730 MADNESS_CHECK(v2[0]==0 or v2[CDIM-1]==KDIM-1);
6731 int gparticle= v1[0]==0 ? 0 : 1; // which particle to integrate over
6732 int hparticle= v2[0]==0 ? 0 : 1; // which particle to integrate over
6733 // merge multiple contraction dimensions into one
6734 Tensor<Q> gtensor = gcoeff1.get_svdtensor().flat_vector_with_weights(gparticle);
6735 Tensor<Q> gtensor_other = gcoeff1.get_svdtensor().flat_vector((gparticle+1)%2);
6736 Tensor<R> htensor = hcoeff1.get_svdtensor().flat_vector_with_weights(hparticle);
6737 Tensor<R> htensor_other = hcoeff1.get_svdtensor().flat_vector((hparticle+1)%2);
6738 Tensor<T> tmp1=inner(gtensor,htensor,1,1); // tmp1(r,r') = sum_j b(r,j) a(r',j)
6739 Tensor<T> tmp2=inner(tmp1,gtensor_other,0,0); // tmp2(r',i) = sum_r tmp1(r,r') a(r,i)
6741 MADNESS_CHECK(tmp2.dim(0)==htensor_other.dim(0));
6742 w=1.0;
6743 coeffT result_tmp(get_cdata().v2k, get_tensor_type());
6744 result_tmp.get_svdtensor().set_vectors_and_weights(w,tmp2,htensor_other);
6745 if (key.level() > 0) {
6746 GenTensor<Q> gcoeff2 = copy(gcoeff1(g->get_cdata().s0));
6747 GenTensor<R> hcoeff2 = copy(hcoeff1(h->get_cdata().s0));
6748 Tensor<Q> gtensor = gcoeff2.get_svdtensor().flat_vector_with_weights(gparticle);
6749 Tensor<Q> gtensor_other = gcoeff2.get_svdtensor().flat_vector((gparticle+1)%2);
6750 Tensor<R> htensor = hcoeff2.get_svdtensor().flat_vector_with_weights(hparticle);
6751 Tensor<R> htensor_other = hcoeff2.get_svdtensor().flat_vector((hparticle+1)%2);
6752 Tensor<T> tmp1=inner(gtensor,htensor,1,1); // tmp1(r,r') = sum_j b(r,j) a(r',j)
6753 Tensor<T> tmp2=inner(tmp1,gtensor_other,0,0); // tmp2(r',i) = sum_r tmp1(r,r') a(r,i)
6755 MADNESS_CHECK(tmp2.dim(0)==htensor_other.dim(0));
6756 w=1.0;
6757 coeffT result_coeff1(get_cdata().vk, get_tensor_type());
6758 result_coeff1.get_svdtensor().set_vectors_and_weights(w,tmp2,htensor_other);
6759 result_tmp(get_cdata().s0)-=result_coeff1;
6760 }
6761 result_coeff+=result_tmp;
6762 }
6763
6764 // use case: partial_projection of 2-electron functions in svd representation f(1) = \int g(2) h(1,2) d2
6765 // c_i = \sum_j a_j b_ij = \sum_jr a_j b_rj b'_rj
6766 // = \sum_jr ( a_j b_rj) b'_rj )
6767 else if (gcoeff.is_full_tensor() and hcoeff.is_svd_tensor() and result_coeff.is_full_tensor()) {
6768 MADNESS_CHECK(v1[0]==0 and v1[CDIM-1]==LDIM-1);
6769 MADNESS_CHECK(v2[0]==0 or v2[CDIM-1]==KDIM-1);
6770 MADNESS_CHECK(LDIM==CDIM);
6771 int hparticle= v2[0]==0 ? 0 : 1; // which particle to integrate over
6772
6773 Tensor<T> r=contract2(hcoeff1,gcoeff1.full_tensor(),hparticle);
6774 if (key.level()>0) r(get_cdata().s0)-=contract2(copy(hcoeff1(h->get_cdata().s0)),copy(gcoeff.full_tensor()(g->get_cdata().s0)),hparticle);
6775 result_coeff.full_tensor()+=r;
6776 }
6777 // use case: partial_projection of 2-electron functions in svd representation f(1) = \int g(1,2) h(2) d2
6778 // c_i = \sum_j a_ij b_j = \sum_jr a_ri a'_rj b_j
6779 // = \sum_jr ( a_ri (a'_rj b_j) )
6780 else if (gcoeff.is_svd_tensor() and hcoeff.is_full_tensor() and result_coeff.is_full_tensor()) {
6781 MADNESS_CHECK(v1[0]==0 or v1[CDIM-1]==LDIM-1);
6782 MADNESS_CHECK(v2[0]==0 and v2[CDIM-1]==KDIM-1);
6783 MADNESS_CHECK(KDIM==CDIM);
6784 int gparticle= v1[0]==0 ? 0 : 1; // which particle to integrate over
6785
6786 Tensor<T> r=contract2(gcoeff1,hcoeff1.full_tensor(),gparticle);
6787 if (key.level()>0) r(get_cdata().s0)-=contract2(copy(gcoeff1(g->get_cdata().s0)),copy(hcoeff.full_tensor()(h->get_cdata().s0)),gparticle);
6788 result_coeff.full_tensor()+=r;
6789
6790 } else {
6791 MADNESS_EXCEPTION("unknown case in partial_inner_contract",1);
6792 }
6793 }
6794
6795 MADNESS_CHECK(result_coeff.is_assigned());
6796 result_coeff.reduce_rank(get_thresh());
6797
6798 if (coeffs.is_local(key))
6799 coeffs.send(key, &nodeT::accumulate, result_coeff, coeffs, key, get_tensor_args());
6800 else
6802 }
6803
6804 /// Return the inner product with an external function on a specified function node.
6805
6806 /// @param[in] key Key of the function node to compute the inner product on. (the domain of integration)
6807 /// @param[in] c Tensor of coefficients for the function at the function node given by key
6808 /// @param[in] f Reference to FunctionFunctorInterface. This is the externally provided function
6809 /// @return Returns the inner product over the domain of a single function node, no guarantee of accuracy.
6810 T inner_ext_node(keyT key, tensorT c, const std::shared_ptr< FunctionFunctorInterface<T,NDIM> > f) const {
6811 tensorT fvals = tensorT(this->cdata.vk);
6812 // Compute the value of the external function at the quadrature points.
6813 fcube(key, *(f), cdata.quad_x, fvals);
6814 // Convert quadrature point values to scaling coefficients.
6815 tensorT fc = tensorT(values2coeffs(key, fvals));
6816 // Return the inner product of the two functions' scaling coefficients.
6817 return c.trace_conj(fc);
6818 }
6819
6820 /// Call inner_ext_node recursively until convergence.
6821 /// @param[in] key Key of the function node on which to compute inner product (the domain of integration)
6822 /// @param[in] c coeffs for the function at the node given by key
6823 /// @param[in] f Reference to FunctionFunctorInterface. This is the externally provided function
6824 /// @param[in] leaf_refine boolean switch to turn on/off refinement past leaf nodes
6825 /// @param[in] old_inner the inner product on the parent function node
6826 /// @return Returns the inner product over the domain of a single function, checks for convergence.
6827 T inner_ext_recursive(keyT key, tensorT c, const std::shared_ptr< FunctionFunctorInterface<T,NDIM> > f, const bool leaf_refine, T old_inner=T(0)) const {
6828 int i = 0;
6829 tensorT c_child, inner_child;
6830 T new_inner, result = 0.0;
6831
6832 c_child = tensorT(cdata.v2k); // tensor of child coeffs
6833 inner_child = Tensor<double>(pow(2, NDIM)); // child inner products
6834
6835 // If old_inner is default value, assume this is the first call
6836 // and compute inner product on this node.
6837 if (old_inner == T(0)) {
6838 old_inner = inner_ext_node(key, c, f);
6839 }
6840
6841 if (coeffs.find(key).get()->second.has_children()) {
6842 // Since the key has children and we know the func is redundant,
6843 // Iterate over all children of this compute node, computing
6844 // the inner product on each child node. new_inner will store
6845 // the sum of these, yielding a more accurate inner product.
6846 for (KeyChildIterator<NDIM> it(key); it; ++it, ++i) {
6847 const keyT& child = it.key();
6848 tensorT cc = coeffs.find(child).get()->second.coeff().full_tensor_copy();
6849 inner_child(i) = inner_ext_node(child, cc, f);
6850 }
6851 new_inner = inner_child.sum();
6852 } else if (leaf_refine) {
6853 // We need the scaling coefficients of the numerical function
6854 // at each of the children nodes. We can't use project because
6855 // there is no guarantee that the numerical function will have
6856 // a functor. Instead, since we know we are at or below the
6857 // leaf nodes, the wavelet coefficients are zero (to within the
6858 // truncate tolerance). Thus, we can use unfilter() to
6859 // get the scaling coefficients at the next level.
6860 tensorT d = tensorT(cdata.v2k);
6861 d = T(0);
6862 d(cdata.s0) = copy(c);
6863 c_child = unfilter(d);
6864
6865 // Iterate over all children of this compute node, computing
6866 // the inner product on each child node. new_inner will store
6867 // the sum of these, yielding a more accurate inner product.
6868 for (KeyChildIterator<NDIM> it(key); it; ++it, ++i) {
6869 const keyT& child = it.key();
6870 tensorT cc = tensorT(c_child(child_patch(child)));
6871 inner_child(i) = inner_ext_node(child, cc, f);
6872 }
6873 new_inner = inner_child.sum();
6874 } else {
6875 // If we get to here, we are at the leaf nodes and the user has
6876 // specified that they do not want refinement past leaf nodes.
6877 new_inner = old_inner;
6878 }
6879
6880 // Check for convergence. If converged...yay, we're done. If not,
6881 // call inner_ext_node_recursive on each child node and accumulate
6882 // the inner product in result.
6883 // if (std::abs(new_inner - old_inner) <= truncate_tol(thresh, key)) {
6884 if (std::abs(new_inner - old_inner) <= thresh) {
6885 result = new_inner;
6886 } else {
6887 i = 0;
6888 for (KeyChildIterator<NDIM> it(key); it; ++it, ++i) {
6889 const keyT& child = it.key();
6890 tensorT cc = tensorT(c_child(child_patch(child)));
6891 result += inner_ext_recursive(child, cc, f, leaf_refine, inner_child(i));
6892 }
6893 }
6894
6895 return result;
6896 }
6897
6899 const std::shared_ptr< FunctionFunctorInterface<T, NDIM> > fref;
6900 const implT * impl;
6901 const bool leaf_refine;
6902 const bool do_leaves; ///< start with leaf nodes instead of initial_level
6903
6905 const implT * impl, const bool leaf_refine, const bool do_leaves)
6906 : fref(f), impl(impl), leaf_refine(leaf_refine), do_leaves(do_leaves) {};
6907
6908 T operator()(typename dcT::const_iterator& it) const {
6909 if (do_leaves and it->second.is_leaf()) {
6910 tensorT cc = it->second.coeff().full_tensor();
6911 return impl->inner_adaptive_recursive(it->first, cc, fref, leaf_refine, T(0));
6912 } else if ((not do_leaves) and (it->first.level() == impl->initial_level)) {
6913 tensorT cc = it->second.coeff().full_tensor();
6914 return impl->inner_ext_recursive(it->first, cc, fref, leaf_refine, T(0));
6915 } else {
6916 return 0.0;
6917 }
6918 }
6919
6920 T operator()(T a, T b) const {
6921 return (a + b);
6922 }
6923
6924 template <typename Archive> void serialize(const Archive& ar) {
6925 MADNESS_EXCEPTION("NOT IMPLEMENTED", 1);
6926 }
6927 };
6928
6929 /// Return the local part of inner product with external function ... no communication.
6930 /// @param[in] f Reference to FunctionFunctorInterface. This is the externally provided function
6931 /// @param[in] leaf_refine boolean switch to turn on/off refinement past leaf nodes
6932 /// @return Returns local part of the inner product, i.e. over the domain of all function nodes on this compute node.
6933 T inner_ext_local(const std::shared_ptr< FunctionFunctorInterface<T,NDIM> > f, const bool leaf_refine) const {
6935
6937 do_inner_ext_local_ffi(f, this, leaf_refine, false));
6938 }
6939
6940 /// Return the local part of inner product with external function ... no communication.
6941 /// @param[in] f Reference to FunctionFunctorInterface. This is the externally provided function
6942 /// @param[in] leaf_refine boolean switch to turn on/off refinement past leaf nodes
6943 /// @return Returns local part of the inner product, i.e. over the domain of all function nodes on this compute node.
6944 T inner_adaptive_local(const std::shared_ptr< FunctionFunctorInterface<T,NDIM> > f, const bool leaf_refine) const {
6946
6948 do_inner_ext_local_ffi(f, this, leaf_refine, true));
6949 }
6950
6951 /// Call inner_ext_node recursively until convergence.
6952 /// @param[in] key Key of the function node on which to compute inner product (the domain of integration)
6953 /// @param[in] c coeffs for the function at the node given by key
6954 /// @param[in] f Reference to FunctionFunctorInterface. This is the externally provided function
6955 /// @param[in] leaf_refine boolean switch to turn on/off refinement past leaf nodes
6956 /// @param[in] old_inner the inner product on the parent function node
6957 /// @return Returns the inner product over the domain of a single function, checks for convergence.
6959 const std::shared_ptr< FunctionFunctorInterface<T,NDIM> > f,
6960 const bool leaf_refine, T old_inner=T(0)) const {
6961
6962 // the inner product in the current node
6963 old_inner = inner_ext_node(key, c, f);
6964 T result=0.0;
6965
6966 // the inner product in the child nodes
6967
6968 // compute the sum coefficients of the MRA function
6969 tensorT d = tensorT(cdata.v2k);
6970 d = T(0);
6971 d(cdata.s0) = copy(c);
6972 tensorT c_child = unfilter(d);
6973
6974 // compute the inner product in the child nodes
6975 T new_inner=0.0; // child inner products
6976 for (KeyChildIterator<NDIM> it(key); it; ++it) {
6977 const keyT& child = it.key();
6978 tensorT cc = tensorT(c_child(child_patch(child)));
6979 new_inner+= inner_ext_node(child, cc, f);
6980 }
6981
6982 // continue recursion if needed
6983 const double tol=truncate_tol(thresh,key);
6984 if (leaf_refine and (std::abs(new_inner - old_inner) > tol)) {
6985 for (KeyChildIterator<NDIM> it(key); it; ++it) {
6986 const keyT& child = it.key();
6987 tensorT cc = tensorT(c_child(child_patch(child)));
6988 result += inner_adaptive_recursive(child, cc, f, leaf_refine, T(0));
6989 }
6990 } else {
6991 result = new_inner;
6992 }
6993 return result;
6994
6995 }
6996
6997
6998 /// Return the gaxpy product with an external function on a specified
6999 /// function node.
7000 /// @param[in] key Key of the function node on which to compute gaxpy
7001 /// @param[in] lc Tensor of coefficients for the function at the
7002 /// function node given by key
7003 /// @param[in] f Pointer to function of type T that takes coordT
7004 /// arguments. This is the externally provided function and
7005 /// the right argument of gaxpy.
7006 /// @param[in] alpha prefactor of c Tensor for gaxpy
7007 /// @param[in] beta prefactor of fcoeffs for gaxpy
7008 /// @return Returns coefficient tensor of the gaxpy product at specified
7009 /// key, no guarantee of accuracy.
7010 template <typename L>
7011 tensorT gaxpy_ext_node(keyT key, Tensor<L> lc, T (*f)(const coordT&), T alpha, T beta) const {
7012 // Compute the value of external function at the quadrature points.
7013 tensorT fvals = madness::fcube(key, f, cdata.quad_x);
7014 // Convert quadrature point values to scaling coefficients.
7015 tensorT fcoeffs = values2coeffs(key, fvals);
7016 // Return the inner product of the two functions' scaling coeffs.
7017 tensorT c2 = copy(lc);
7018 c2.gaxpy(alpha, fcoeffs, beta);
7019 return c2;
7020 }
7021
7022 /// Return out of place gaxpy using recursive descent.
7023 /// @param[in] key Key of the function node on which to compute gaxpy
7024 /// @param[in] left FunctionImpl, left argument of gaxpy
7025 /// @param[in] lcin coefficients of left at this node
7026 /// @param[in] c coefficients of gaxpy product at this node
7027 /// @param[in] f pointer to function of type T that takes coordT
7028 /// arguments. This is the externally provided function and
7029 /// the right argument of gaxpy.
7030 /// @param[in] alpha prefactor of left argument for gaxpy
7031 /// @param[in] beta prefactor of right argument for gaxpy
7032 /// @param[in] tol convergence tolerance...when the norm of the gaxpy's
7033 /// difference coefficients is less than tol, we are done.
7034 template <typename L>
7035 void gaxpy_ext_recursive(const keyT& key, const FunctionImpl<L,NDIM>* left,
7036 Tensor<L> lcin, tensorT c, T (*f)(const coordT&),
7037 T alpha, T beta, double tol, bool below_leaf) {
7038 typedef typename FunctionImpl<L,NDIM>::dcT::const_iterator literT;
7039
7040 // If we haven't yet reached the leaf level, check whether the
7041 // current key is a leaf node of left. If so, set below_leaf to true
7042 // and continue. If not, make this a parent, recur down, return.
7043 if (not below_leaf) {
7044 bool left_leaf = left->coeffs.find(key).get()->second.is_leaf();
7045 if (left_leaf) {
7046 below_leaf = true;
7047 } else {
7048 this->coeffs.replace(key, nodeT(coeffT(), true));
7049 for (KeyChildIterator<NDIM> it(key); it; ++it) {
7050 const keyT& child = it.key();
7051 woT::task(left->coeffs.owner(child), &implT:: template gaxpy_ext_recursive<L>,
7052 child, left, Tensor<L>(), tensorT(), f, alpha, beta, tol, below_leaf);
7053 }
7054 return;
7055 }
7056 }
7057
7058 // Compute left's coefficients if not provided
7059 Tensor<L> lc = lcin;
7060 if (lc.size() == 0) {
7061 literT it = left->coeffs.find(key).get();
7062 MADNESS_ASSERT(it != left->coeffs.end());
7063 if (it->second.has_coeff())
7064 lc = it->second.coeff().reconstruct_tensor();
7065 }
7066
7067 // Compute this node's coefficients if not provided in function call
7068 if (c.size() == 0) {
7069 c = gaxpy_ext_node(key, lc, f, alpha, beta);
7070 }
7071
7072 // We need the scaling coefficients of the numerical function at
7073 // each of the children nodes. We can't use project because there
7074 // is no guarantee that the numerical function will have a functor.
7075 // Instead, since we know we are at or below the leaf nodes, the
7076 // wavelet coefficients are zero (to within the truncate tolerance).
7077 // Thus, we can use unfilter() to get the scaling coefficients at
7078 // the next level.
7079 Tensor<L> lc_child = Tensor<L>(cdata.v2k); // left's child coeffs
7080 Tensor<L> ld = Tensor<L>(cdata.v2k);
7081 ld = L(0);
7082 ld(cdata.s0) = copy(lc);
7083 lc_child = unfilter(ld);
7084
7085 // Iterate over children of this node,
7086 // storing the gaxpy coeffs in c_child
7087 tensorT c_child = tensorT(cdata.v2k); // tensor of child coeffs
7088 for (KeyChildIterator<NDIM> it(key); it; ++it) {
7089 const keyT& child = it.key();
7090 tensorT lcoeff = tensorT(lc_child(child_patch(child)));
7091 c_child(child_patch(child)) = gaxpy_ext_node(child, lcoeff, f, alpha, beta);
7092 }
7093
7094 // Compute the difference coefficients to test for convergence.
7095 tensorT d = tensorT(cdata.v2k);
7096 d = filter(c_child);
7097 // Filter returns both s and d coefficients, so set scaling
7098 // coefficient part of d to 0 so that we take only the
7099 // norm of the difference coefficients.
7100 d(cdata.s0) = T(0);
7101 double dnorm = d.normf();
7102
7103 // Small d.normf means we've reached a good level of resolution
7104 // Store the coefficients and return.
7105 if (dnorm <= truncate_tol(tol,key)) {
7106 this->coeffs.replace(key, nodeT(coeffT(c,targs), false));
7107 } else {
7108 // Otherwise, make this a parent node and recur down
7109 this->coeffs.replace(key, nodeT(coeffT(), true)); // Interior node
7110
7111 for (KeyChildIterator<NDIM> it(key); it; ++it) {
7112 const keyT& child = it.key();
7113 tensorT child_coeff = tensorT(c_child(child_patch(child)));
7114 tensorT left_coeff = tensorT(lc_child(child_patch(child)));
7115 woT::task(left->coeffs.owner(child), &implT:: template gaxpy_ext_recursive<L>,
7116 child, left, left_coeff, child_coeff, f, alpha, beta, tol, below_leaf);
7117 }
7118 }
7119 }
7120
7121 template <typename L>
7122 void gaxpy_ext(const FunctionImpl<L,NDIM>* left, T (*f)(const coordT&), T alpha, T beta, double tol, bool fence) {
7123 if (world.rank() == coeffs.owner(cdata.key0))
7124 gaxpy_ext_recursive<L> (cdata.key0, left, Tensor<L>(), tensorT(), f, alpha, beta, tol, false);
7125 if (fence)
7126 world.gop.fence();
7127 }
7128
7129 /// project the low-dim function g on the hi-dim function f: result(x) = <this(x,y) | g(y)>
7130
7131 /// invoked by the hi-dim function, a function of NDIM+LDIM
7132
7133 /// Upon return, result matches this, with contributions on all scales
7134 /// @param[in] result lo-dim function of NDIM-LDIM \todo Should this be param[out]?
7135 /// @param[in] gimpl lo-dim function of LDIM
7136 /// @param[in] dim over which dimensions to be integrated: 0..LDIM or LDIM..LDIM+NDIM-1
7137 template<size_t LDIM>
7139 const int dim, const bool fence) {
7140
7141 const keyT& key0=cdata.key0;
7142
7143 if (world.rank() == coeffs.owner(key0)) {
7144
7145 // coeff_op will accumulate the result
7146 typedef project_out_op<LDIM> coeff_opT;
7147 coeff_opT coeff_op(this,result,CoeffTracker<T,LDIM>(gimpl),dim);
7148
7149 // don't do anything on this -- coeff_op will accumulate into result
7150 typedef noop<T,NDIM> apply_opT;
7151 apply_opT apply_op;
7152
7153 woT::task(world.rank(), &implT:: template forward_traverse<coeff_opT,apply_opT>,
7154 coeff_op, apply_op, cdata.key0);
7155
7156 }
7157 if (fence) world.gop.fence();
7158
7159 }
7160
7161
7162 /// project the low-dim function g on the hi-dim function f: result(x) = <f(x,y) | g(y)>
7163 template<size_t LDIM>
7165 bool randomize() const {return false;}
7166
7169 typedef FunctionImpl<T,NDIM-LDIM> implL1;
7170 typedef std::pair<bool,coeffT> argT;
7171
7172 const implT* fimpl; ///< the hi dim function f
7173 mutable implL1* result; ///< the low dim result function
7174 ctL iag; ///< the low dim function g
7175 int dim; ///< 0: project 0..LDIM-1, 1: project LDIM..NDIM-1
7176
7177 // ctor
7178 project_out_op() = default;
7179 project_out_op(const implT* fimpl, implL1* result, const ctL& iag, const int dim)
7180 : fimpl(fimpl), result(result), iag(iag), dim(dim) {}
7182 : fimpl(other.fimpl), result(other.result), iag(other.iag), dim(other.dim) {}
7183
7184
7185 /// do the actual contraction
7187
7188 Key<LDIM> key1,key2,dest;
7189 key.break_apart(key1,key2);
7190
7191 // make the right coefficients
7192 coeffT gcoeff;
7193 if (dim==0) {
7194 gcoeff=iag.get_impl()->parent_to_child(iag.coeff(),iag.key(),key1);
7195 dest=key2;
7196 }
7197 if (dim==1) {
7198 gcoeff=iag.get_impl()->parent_to_child(iag.coeff(),iag.key(),key2);
7199 dest=key1;
7200 }
7201
7202 MADNESS_ASSERT(fimpl->get_coeffs().probe(key)); // must be local!
7203 const nodeT& fnode=fimpl->get_coeffs().find(key).get()->second;
7204 const coeffT& fcoeff=fnode.coeff();
7205
7206 // fast return if possible
7207 if (fcoeff.has_no_data() or gcoeff.has_no_data())
7208 return Future<argT> (argT(fnode.is_leaf(),coeffT()));;
7209
7210 MADNESS_CHECK(gcoeff.is_full_tensor());
7211 tensorT final(result->cdata.vk);
7212 const int k=fcoeff.dim(0);
7213 const int k_ldim=std::pow(k,LDIM);
7214 std::vector<long> shape(LDIM, k);
7215
7216 if (fcoeff.is_full_tensor()) {
7217 // result_i = \sum_j g_j f_ji
7218 const tensorT gtensor = gcoeff.full_tensor().reshape(k_ldim);
7219 const tensorT ftensor = fcoeff.full_tensor().reshape(k_ldim,k_ldim);
7220 final=inner(gtensor,ftensor,0,dim).reshape(shape);
7221
7222 } else if (fcoeff.is_svd_tensor()) {
7223 if (fcoeff.rank()>0) {
7224
7225 // result_i = \sum_jr g_j a_rj w_r b_ri
7226 const int otherdim = (dim + 1) % 2;
7227 const tensorT gtensor = gcoeff.full_tensor().flat();
7228 const tensorT atensor = fcoeff.get_svdtensor().flat_vector(dim); // a_rj
7229 const tensorT btensor = fcoeff.get_svdtensor().flat_vector(otherdim);
7230 const tensorT gatensor = inner(gtensor, atensor, 0, 1); // ga_r
7231 tensorT weights = copy(fcoeff.get_svdtensor().weights_);
7232 weights.emul(gatensor); // ga_r * w_r
7233 // sum over all ranks of b, include new weights:
7234 // result_i = \sum_r ga_r * w_r * b_ri
7235 for (int r = 0; r < fcoeff.rank(); ++r) final += weights(r) * btensor(r, _);
7236 final = final.reshape(shape);
7237 }
7238
7239 } else {
7240 MADNESS_EXCEPTION("unsupported tensor type in project_out_op",1);
7241 }
7242
7243 // accumulate the result
7244 result->coeffs.task(dest, &FunctionNode<T,LDIM>::accumulate2, final, result->coeffs, dest, TaskAttributes::hipri());
7245
7246 return Future<argT> (argT(fnode.is_leaf(),coeffT()));
7247 }
7248
7249 this_type make_child(const keyT& child) const {
7250 Key<LDIM> key1,key2;
7251 child.break_apart(key1,key2);
7252 const Key<LDIM> gkey = (dim==0) ? key1 : key2;
7253
7254 return this_type(fimpl,result,iag.make_child(gkey),dim);
7255 }
7256
7257 /// retrieve the coefficients (parent coeffs might be remote)
7260 return result->world.taskq.add(detail::wrap_mem_fn(*const_cast<this_type *> (this),
7261 &this_type::forward_ctor),fimpl,result,g1,dim);
7262 }
7263
7264 /// taskq-compatible ctor
7265 this_type forward_ctor(const implT* fimpl1, implL1* result1, const ctL& iag1, const int dim1) {
7266 return this_type(fimpl1,result1,iag1,dim1);
7267 }
7268
7269 template <typename Archive> void serialize(const Archive& ar) {
7270 ar & result & iag & fimpl & dim;
7271 }
7272
7273 };
7274
7275
7276 /// project the low-dim function g on the hi-dim function f: this(x) = <f(x,y) | g(y)>
7277
7278 /// invoked by result, a function of NDIM
7279
7280 /// @param[in] f hi-dim function of LDIM+NDIM
7281 /// @param[in] g lo-dim function of LDIM
7282 /// @param[in] dim over which dimensions to be integrated: 0..LDIM or LDIM..LDIM+NDIM-1
7283 template<size_t LDIM>
7284 void project_out2(const FunctionImpl<T,LDIM+NDIM>* f, const FunctionImpl<T,LDIM>* g, const int dim) {
7285
7286 typedef std::pair< keyT,coeffT > pairT;
7287 typedef typename FunctionImpl<T,NDIM+LDIM>::dcT::const_iterator fiterator;
7288
7289 // loop over all nodes of hi-dim f, compute the inner products with all
7290 // appropriate nodes of g, and accumulate in result
7291 fiterator end = f->get_coeffs().end();
7292 for (fiterator it=f->get_coeffs().begin(); it!=end; ++it) {
7293 const Key<LDIM+NDIM> key=it->first;
7294 const FunctionNode<T,LDIM+NDIM> fnode=it->second;
7295 const coeffT& fcoeff=fnode.coeff();
7296
7297 if (fnode.is_leaf() and fcoeff.has_data()) {
7298
7299 // break key into particle: over key1 will be summed, over key2 will be
7300 // accumulated, or vice versa, depending on dim
7301 if (dim==0) {
7302 Key<NDIM> key1;
7303 Key<LDIM> key2;
7304 key.break_apart(key1,key2);
7305
7306 Future<pairT> result;
7307 // sock_it_to_me(key1, result.remote_ref(world));
7308 g->task(coeffs.owner(key1), &implT::sock_it_to_me, key1, result.remote_ref(world), TaskAttributes::hipri());
7309 woT::task(world.rank(),&implT:: template do_project_out<LDIM>,fcoeff,result,key1,key2,dim);
7310
7311 } else if (dim==1) {
7312 Key<LDIM> key1;
7313 Key<NDIM> key2;
7314 key.break_apart(key1,key2);
7315
7316 Future<pairT> result;
7317 // sock_it_to_me(key2, result.remote_ref(world));
7318 g->task(coeffs.owner(key2), &implT::sock_it_to_me, key2, result.remote_ref(world), TaskAttributes::hipri());
7319 woT::task(world.rank(),&implT:: template do_project_out<LDIM>,fcoeff,result,key2,key1,dim);
7320
7321 } else {
7322 MADNESS_EXCEPTION("confused dim in project_out",1);
7323 }
7324 }
7325 }
7327// this->compressed=false;
7328// this->nonstandard=false;
7329// this->redundant=true;
7330 }
7331
7332
7333 /// compute the inner product of two nodes of only some dimensions and accumulate on result
7334
7335 /// invoked by result
7336 /// @param[in] fcoeff coefficients of high dimension LDIM+NDIM
7337 /// @param[in] gpair key and coeffs of low dimension LDIM (possibly a parent node)
7338 /// @param[in] gkey key of actual low dim node (possibly the same as gpair.first, iff gnode exists)
7339 /// @param[in] dest destination node for the result
7340 /// @param[in] dim which dimensions should be contracted: 0..LDIM-1 or LDIM..NDIM+LDIM-1
7341 template<size_t LDIM>
7342 void do_project_out(const coeffT& fcoeff, const std::pair<keyT,coeffT> gpair, const keyT& gkey,
7343 const Key<NDIM>& dest, const int dim) const {
7344
7345 const coeffT gcoeff=parent_to_child(gpair.second,gpair.first,gkey);
7346
7347 // fast return if possible
7348 if (fcoeff.has_no_data() or gcoeff.has_no_data()) return;
7349
7350 // let's specialize for the time being on SVD tensors for f and full tensors of half dim for g
7352 MADNESS_ASSERT(fcoeff.tensor_type()==TT_2D);
7353 const tensorT gtensor=gcoeff.full_tensor();
7354 tensorT result(cdata.vk);
7355
7356 const int otherdim=(dim+1)%2;
7357 const int k=fcoeff.dim(0);
7358 std::vector<Slice> s(fcoeff.config().dim_per_vector()+1,_);
7359
7360 // do the actual contraction
7361 for (int r=0; r<fcoeff.rank(); ++r) {
7362 s[0]=Slice(r,r);
7363 const tensorT contracted_tensor=fcoeff.config().ref_vector(dim)(s).reshape(k,k,k);
7364 const tensorT other_tensor=fcoeff.config().ref_vector(otherdim)(s).reshape(k,k,k);
7365 const double ovlp= gtensor.trace_conj(contracted_tensor);
7366 const double fac=ovlp * fcoeff.config().weights(r);
7367 result+=fac*other_tensor;
7368 }
7369
7370 // accumulate the result
7371 coeffs.task(dest, &nodeT::accumulate2, result, coeffs, dest, TaskAttributes::hipri());
7372 }
7373
7374
7375
7376
7377 /// Returns the maximum local depth of the tree ... no communications.
7378 std::size_t max_local_depth() const;
7379
7380
7381 /// Returns the maximum depth of the tree ... collective ... global sum/broadcast
7382 std::size_t max_depth() const;
7383
7384 /// Returns the max number of nodes on a processor
7385 std::size_t max_nodes() const;
7386
7387 /// Returns the min number of nodes on a processor
7388 std::size_t min_nodes() const;
7389
7390 /// Returns the size of the tree structure of the function ... collective global sum
7391 std::size_t tree_size() const;
7392
7393 /// Returns the number of coefficients in the function for each rank
7394 std::size_t size_local() const;
7395
7396 /// Returns the number of coefficients in the function ... collective global sum
7397 std::size_t size() const;
7398
7399 /// Returns the number of coefficients in the function for this MPI rank
7400 std::size_t nCoeff_local() const;
7401
7402 /// Returns the number of coefficients in the function ... collective global sum
7403 std::size_t nCoeff() const;
7404
7405 /// Returns the number of coefficients in the function ... collective global sum
7406 std::size_t real_size() const;
7407
7408 /// print tree size and size
7409 void print_size(const std::string name) const;
7410
7411 /// print the number of configurations per node
7412 void print_stats() const;
7413
7414 /// In-place scale by a constant
7415 void scale_inplace(const T q, bool fence);
7416
7417 /// Out-of-place scale by a constant
7418 template <typename Q, typename F>
7419 void scale_oop(const Q q, const FunctionImpl<F,NDIM>& f, bool fence) {
7420 typedef typename FunctionImpl<F,NDIM>::nodeT fnodeT;
7421 typedef typename FunctionImpl<F,NDIM>::dcT fdcT;
7422 typename fdcT::const_iterator end = f.coeffs.end();
7423 for (typename fdcT::const_iterator it=f.coeffs.begin(); it!=end; ++it) {
7424 const keyT& key = it->first;
7425 const fnodeT& node = it->second;
7426
7427 if (node.has_coeff()) {
7428 coeffs.replace(key,nodeT(node.coeff()*q,node.has_children()));
7429 }
7430 else {
7431 coeffs.replace(key,nodeT(coeffT(),node.has_children()));
7432 }
7433 }
7434 if (fence)
7435 world.gop.fence();
7436 }
7437
7438 /// Hash a pointer to \c FunctionImpl
7439
7440 /// \param[in] impl pointer to a FunctionImpl
7441 /// \return The hash.
7442 inline friend hashT hash_value(const FunctionImpl<T,NDIM>* pimpl) {
7443 hashT seed = hash_value(pimpl->id().get_world_id());
7444 detail::combine_hash(seed, hash_value(pimpl->id().get_obj_id()));
7445 return seed;
7446 }
7447
7448 /// Hash a shared_ptr to \c FunctionImpl
7449
7450 /// \param[in] impl pointer to a FunctionImpl
7451 /// \return The hash.
7452 inline friend hashT hash_value(const std::shared_ptr<FunctionImpl<T,NDIM>> impl) {
7453 return hash_value(impl.get());
7454 }
7455 };
7456
7457 namespace archive {
7458 template <class Archive, class T, std::size_t NDIM>
7459 struct ArchiveLoadImpl<Archive,const FunctionImpl<T,NDIM>*> {
7460 static void load(const Archive& ar, const FunctionImpl<T,NDIM>*& ptr) {
7461 bool exists=false;
7462 ar & exists;
7463 if (exists) {
7464 uniqueidT id;
7465 ar & id;
7466 World* world = World::world_from_id(id.get_world_id());
7467 MADNESS_ASSERT(world);
7468 auto ptr_opt = world->ptr_from_id< WorldObject< FunctionImpl<T,NDIM> > >(id);
7469 if (!ptr_opt)
7470 MADNESS_EXCEPTION("FunctionImpl: remote operation attempting to use a locally uninitialized object",0);
7471 ptr = static_cast< const FunctionImpl<T,NDIM>*>(*ptr_opt);
7472 if (!ptr)
7473 MADNESS_EXCEPTION("FunctionImpl: remote operation attempting to use an unregistered object",0);
7474 } else {
7475 ptr=nullptr;
7476 }
7477 }
7478 };
7479
7480 template <class Archive, class T, std::size_t NDIM>
7481 struct ArchiveStoreImpl<Archive,const FunctionImpl<T,NDIM>*> {
7482 static void store(const Archive& ar, const FunctionImpl<T,NDIM>*const& ptr) {
7483 bool exists=(ptr) ? true : false;
7484 ar & exists;
7485 if (exists) ar & ptr->id();
7486 }
7487 };
7488
7489 template <class Archive, class T, std::size_t NDIM>
7490 struct ArchiveLoadImpl<Archive, FunctionImpl<T,NDIM>*> {
7491 static void load(const Archive& ar, FunctionImpl<T,NDIM>*& ptr) {
7492 bool exists=false;
7493 ar & exists;
7494 if (exists) {
7495 uniqueidT id;
7496 ar & id;
7497 World* world = World::world_from_id(id.get_world_id());
7498 MADNESS_ASSERT(world);
7499 auto ptr_opt = world->ptr_from_id< WorldObject< FunctionImpl<T,NDIM> > >(id);
7500 if (!ptr_opt)
7501 MADNESS_EXCEPTION("FunctionImpl: remote operation attempting to use a locally uninitialized object",0);
7502 ptr = static_cast< FunctionImpl<T,NDIM>*>(*ptr_opt);
7503 if (!ptr) {
7504 auto ids=world->get_object_ids();
7505 print(world->get_world_ids());
7506 MADNESS_EXCEPTION("FunctionImpl: remote operation attempting to use an unregistered object",0);
7507 }
7508 } else {
7509 ptr=nullptr;
7510 }
7511 }
7512 };
7513
7514 template <class Archive, class T, std::size_t NDIM>
7515 struct ArchiveStoreImpl<Archive, FunctionImpl<T,NDIM>*> {
7516 static void store(const Archive& ar, FunctionImpl<T,NDIM>*const& ptr) {
7517 bool exists=(ptr) ? true : false;
7518 ar & exists;
7519 if (exists) ar & ptr->id();
7520 // ar & ptr->id();
7521 }
7522 };
7523
7524 template <class Archive, class T, std::size_t NDIM>
7525 struct ArchiveLoadImpl<Archive, std::shared_ptr<const FunctionImpl<T,NDIM> > > {
7526 static void load(const Archive& ar, std::shared_ptr<const FunctionImpl<T,NDIM> >& ptr) {
7527 const FunctionImpl<T,NDIM>* f = nullptr;
7529 ptr.reset(f, [] (const FunctionImpl<T,NDIM> *p_) -> void {});
7530 }
7531 };
7532
7533 template <class Archive, class T, std::size_t NDIM>
7534 struct ArchiveStoreImpl<Archive, std::shared_ptr<const FunctionImpl<T,NDIM> > > {
7535 static void store(const Archive& ar, const std::shared_ptr<const FunctionImpl<T,NDIM> >& ptr) {
7537 }
7538 };
7539
7540 template <class Archive, class T, std::size_t NDIM>
7541 struct ArchiveLoadImpl<Archive, std::shared_ptr<FunctionImpl<T,NDIM> > > {
7542 static void load(const Archive& ar, std::shared_ptr<FunctionImpl<T,NDIM> >& ptr) {
7543 FunctionImpl<T,NDIM>* f = nullptr;
7545 ptr.reset(f, [] (FunctionImpl<T,NDIM> *p_) -> void {});
7546 }
7547 };
7548
7549 template <class Archive, class T, std::size_t NDIM>
7550 struct ArchiveStoreImpl<Archive, std::shared_ptr<FunctionImpl<T,NDIM> > > {
7551 static void store(const Archive& ar, const std::shared_ptr<FunctionImpl<T,NDIM> >& ptr) {
7553 }
7554 };
7555 }
7556
7557}
7558
7559#endif // MADNESS_MRA_FUNCIMPL_H__INCLUDED
double w(double t, double eps)
Definition DKops.h:22
double q(double t)
Definition DKops.h:18
This header should include pretty much everything needed for the parallel runtime.
An integer with atomic set, get, read+increment, read+decrement, and decrement+test operations.
Definition atomicint.h:126
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
Definition displacements.h:333
std::function< bool(Level, const PointPattern &, std::optional< Displacement > &)> Validator
Definition displacements.h:341
Definition displacements.h:892
a class to track where relevant (parent) coeffs are
Definition funcimpl.h:814
const keyT & key() const
const reference to the key
Definition funcimpl.h:864
CoeffTracker(const CoeffTracker &other, const datumT &datum)
ctor with a pair<keyT,nodeT>
Definition funcimpl.h:844
const LeafStatus & is_leaf() const
const reference to is_leaf flag
Definition funcimpl.h:888
const implT * impl
the funcimpl that has the coeffs
Definition funcimpl.h:823
CoeffTracker & operator=(const CoeffTracker &other)=default
LeafStatus
Definition funcimpl.h:820
@ yes
Definition funcimpl.h:820
@ no
Definition funcimpl.h:820
@ unknown
Definition funcimpl.h:820
CoeffTracker(const CoeffTracker &other)
copy ctor
Definition funcimpl.h:852
double dnorm(const keyT &key) const
return the s and dnorm belonging to the passed-in key
Definition funcimpl.h:881
coeffT coeff_
the coefficients belonging to key
Definition funcimpl.h:829
const implT * get_impl() const
const reference to impl
Definition funcimpl.h:858
const coeffT & coeff() const
const reference to the coeffs
Definition funcimpl.h:861
keyT key_
the current key, which must exists in impl
Definition funcimpl.h:825
double dnorm_
norm of d coefficients corresponding to key
Definition funcimpl.h:831
CoeffTracker(const implT *impl)
the initial ctor making the root key
Definition funcimpl.h:839
void serialize(const Archive &ar)
serialization
Definition funcimpl.h:940
Future< CoeffTracker > activate() const
find the coefficients
Definition funcimpl.h:917
CoeffTracker()
default ctor
Definition funcimpl.h:836
GenTensor< T > coeffT
Definition funcimpl.h:818
CoeffTracker make_child(const keyT &child) const
make a child of this, ignoring the coeffs
Definition funcimpl.h:891
FunctionImpl< T, NDIM > implT
Definition funcimpl.h:816
std::pair< Key< NDIM >, ShallowNode< T, NDIM > > datumT
Definition funcimpl.h:819
CoeffTracker forward_ctor(const CoeffTracker &other, const datumT &datum) const
taskq-compatible forwarding to the ctor
Definition funcimpl.h:934
LeafStatus is_leaf_
flag if key is a leaf node
Definition funcimpl.h:827
coeffT coeff(const keyT &key) const
return the coefficients belonging to the passed-in key
Definition funcimpl.h:872
Key< NDIM > keyT
Definition funcimpl.h:817
CompositeFunctorInterface implements a wrapper of holding several functions and functors.
Definition function_interface.h:172
Definition worldhashmap.h:396
Tri-diagonal operator traversing tree primarily for derivative operator.
Definition derivative.h:73
Holds displacements for applying operators to avoid replicating for all operators.
Definition displacements.h:66
const std::vector< Key< NDIM > > & get_disp(Level n, const array_of_bools< NDIM > &kernel_lattice_sum_axes)
Definition displacements.h:237
FunctionCommonData holds all Function data common for given k.
Definition function_common_data.h:52
Tensor< double > quad_phit
transpose of quad_phi
Definition function_common_data.h:102
Tensor< double > quad_phiw
quad_phiw(i,j) = at x[i] value of w[i]*phi[j]
Definition function_common_data.h:103
std::vector< long > vk
(k,...) used to initialize Tensors
Definition function_common_data.h:93
std::vector< Slice > s0
s[0] in each dimension to get scaling coeff
Definition function_common_data.h:91
static const FunctionCommonData< T, NDIM > & get(int k)
Definition function_common_data.h:111
static void _init_quadrature(int k, int npt, Tensor< double > &quad_x, Tensor< double > &quad_w, Tensor< double > &quad_phi, Tensor< double > &quad_phiw, Tensor< double > &quad_phit)
Initialize the quadrature information.
Definition mraimpl.h:91
collect common functionality does not need to be member function of funcimpl
Definition function_common_data.h:135
const FunctionCommonData< T, NDIM > & cdata
Definition function_common_data.h:138
GenTensor< T > coeffs2values(const Key< NDIM > &key, const GenTensor< T > &coeff) const
Definition function_common_data.h:142
Tensor< T > values2coeffs(const Key< NDIM > &key, const Tensor< T > &values) const
Definition function_common_data.h:155
FunctionDefaults holds default paramaters as static class members.
Definition funcdefaults.h:100
static const double & get_thresh()
Returns the default threshold.
Definition funcdefaults.h:177
static int get_max_refine_level()
Gets the default maximum adaptive refinement level.
Definition funcdefaults.h:214
static const Tensor< double > & get_cell_width()
Returns the width of each user cell dimension.
Definition funcdefaults.h:379
static bool get_apply_randomize()
Gets the random load balancing for integral operators flag.
Definition funcdefaults.h:288
static const Tensor< double > & get_cell()
Gets the user cell for the simulation.
Definition funcdefaults.h:346
FunctionFactory implements the named-parameter idiom for Function.
Definition function_factory.h:86
bool _refine
Definition function_factory.h:99
bool _empty
Definition function_factory.h:100
bool _fence
Definition function_factory.h:103
Abstract base class interface required for functors used as input to Functions.
Definition function_interface.h:68
Definition funcimpl.h:5697
double operator()(double a, double b) const
Definition funcimpl.h:5723
const opT * func
Definition funcimpl.h:5699
Tensor< double > qx
Definition funcimpl.h:5701
double operator()(typename dcT::const_iterator &it) const
Definition funcimpl.h:5714
void serialize(const Archive &ar)
Definition funcimpl.h:5728
do_err_box(const implT *impl, const opT *func, int npt, const Tensor< double > &qx, const Tensor< double > &quad_phit, const Tensor< double > &quad_phiw)
Definition funcimpl.h:5707
int npt
Definition funcimpl.h:5700
Tensor< double > quad_phiw
Definition funcimpl.h:5703
const implT * impl
Definition funcimpl.h:5698
Tensor< double > quad_phit
Definition funcimpl.h:5702
do_err_box(const do_err_box &e)
Definition funcimpl.h:5711
FunctionImpl holds all Function state to facilitate shallow copy semantics.
Definition funcimpl.h:970
std::tuple< std::set< Key< NDIM > >, std::map< Key< CDIM >, double > > get_contraction_node_lists(const std::size_t n, const std::array< int, CDIM > &v) const
for contraction two functions f(x,z) = \int g(x,y) h(y,z) dy
Definition funcimpl.h:6464
void copy_coeffs(const FunctionImpl< Q, NDIM > &other, bool fence)
Copy coeffs from other into self.
Definition funcimpl.h:1228
bool is_nonstandard() const
Definition mraimpl.h:273
void insert_serialized_coeffs(std::vector< unsigned char > &v)
insert coeffs from vector archive into this
Definition funcimpl.h:1284
T eval_cube(Level n, coordT &x, const tensorT &c) const
Definition mraimpl.h:2054
void partial_inner_contract(const FunctionImpl< Q, LDIM > *g, const FunctionImpl< R, KDIM > *h, const std::array< int, CDIM > v1, const std::array< int, CDIM > v2, const Key< NDIM > &key, const std::list< Key< CDIM > > &j_key_list)
tensor contraction part of partial_inner
Definition funcimpl.h:6626
AtomicInt large
Definition funcimpl.h:1085
Timer timer_target_driven
Definition funcimpl.h:1083
void binaryXX(const FunctionImpl< L, NDIM > *left, const FunctionImpl< R, NDIM > *right, const opT &op, bool fence)
Definition funcimpl.h:3395
void do_apply(const opT *op, const keyT &key, const Tensor< R > &c)
apply an operator on the coeffs c (at node key)
Definition funcimpl.h:5021
void do_print_tree_graphviz(const keyT &key, std::ostream &os, Level maxlevel) const
Functor for the do_print_tree method (using GraphViz)
Definition mraimpl.h:2808
void add_keys_to_map(mapT *map, int index) const
Adds keys to union of local keys with specified index.
Definition funcimpl.h:6041
void change_tensor_type1(const TensorArgs &targs, bool fence)
change the tensor type of the coefficients in the FunctionNode
Definition mraimpl.h:1113
void gaxpy_ext_recursive(const keyT &key, const FunctionImpl< L, NDIM > *left, Tensor< L > lcin, tensorT c, T(*f)(const coordT &), T alpha, T beta, double tol, bool below_leaf)
Definition funcimpl.h:7035
int initial_level
Initial level for refinement.
Definition funcimpl.h:999
int max_refine_level
Do not refine below this level.
Definition funcimpl.h:1003
double do_apply_kernel3(const opT *op, const GenTensor< R > &coeff, const do_op_args< OPDIM > &args, const TensorArgs &apply_targs)
same as do_apply_kernel2, but use low rank tensors as input and low rank tensors as output
Definition funcimpl.h:4979
void hartree_product(const std::vector< std::shared_ptr< FunctionImpl< T, LDIM > > > p1, const std::vector< std::shared_ptr< FunctionImpl< T, LDIM > > > p2, const leaf_opT &leaf_op, bool fence)
given two functions of LDIM, perform the Hartree/Kronecker/outer product
Definition funcimpl.h:3936
void traverse_tree(const coeff_opT &coeff_op, const apply_opT &apply_op, const keyT &key) const
traverse a non-existing tree
Definition funcimpl.h:3906
void do_square_inplace(const keyT &key)
int special_level
Minimium level for refinement on special points.
Definition funcimpl.h:1000
void do_apply_kernel(const opT *op, const Tensor< R > &c, const do_op_args< OPDIM > &args)
for fine-grain parallelism: call the apply method of an operator in a separate task
Definition funcimpl.h:4913
compressT compress_op(const keyT &key, const std::vector< Future< compressT > > &v, bool nonstandard)
calculate the wavelet coefficients using the sum coefficients of all child nodes
Definition mraimpl.h:1688
double errsq_local(const opT &func) const
Returns the sum of squares of errors from local info ... no comms.
Definition funcimpl.h:5735
WorldContainer< keyT, nodeT > dcT
Type of container holding the coefficients.
Definition funcimpl.h:982
void evaldepthpt(const Vector< double, NDIM > &xin, const keyT &keyin, const typename Future< Level >::remote_refT &ref)
Get the depth of the tree at a point in simulation coordinates.
Definition mraimpl.h:3080
void scale_inplace(const T q, bool fence)
In-place scale by a constant.
Definition mraimpl.h:3251
void gaxpy_oop_reconstructed(const double alpha, const implT &f, const double beta, const implT &g, const bool fence)
perform: this= alpha*f + beta*g, invoked by result
Definition mraimpl.h:223
void unary_op_coeff_inplace(const opT &op, bool fence)
Definition funcimpl.h:2213
World & world
Definition funcimpl.h:989
void apply_1d_realspace_push_op(const archive::archive_ptr< const opT > &pop, int axis, const keyT &key, const Tensor< R > &c)
Definition funcimpl.h:3974
bool is_redundant() const
Returns true if the function is redundant.
Definition mraimpl.h:262
FunctionNode< T, NDIM > nodeT
Type of node.
Definition funcimpl.h:980
std::size_t nCoeff_local() const
Returns the number of coefficients in the function for this MPI rank.
Definition mraimpl.h:1951
void print_size(const std::string name) const
print tree size and size
Definition mraimpl.h:1970
FunctionImpl(const FunctionImpl< T, NDIM > &p)
void print_info() const
Prints summary of data distribution.
Definition mraimpl.h:833
void abs_inplace(bool fence)
Definition mraimpl.h:3263
void binaryXXa(const keyT &key, const FunctionImpl< L, NDIM > *left, const Tensor< L > &lcin, const FunctionImpl< R, NDIM > *right, const Tensor< R > &rcin, const opT &op)
Definition funcimpl.h:3264
void print_timer() const
Definition mraimpl.h:357
void evalR(const Vector< double, NDIM > &xin, const keyT &keyin, const typename Future< long >::remote_refT &ref)
Get the rank of leaf box of the tree at a point in simulation coordinates.
Definition mraimpl.h:3122
const FunctionCommonData< T, NDIM > & cdata
Definition funcimpl.h:1009
void do_print_grid(const std::string filename, const std::vector< keyT > &keys) const
print the grid in xyz format
Definition mraimpl.h:584
void mulXXa(const keyT &key, const FunctionImpl< L, NDIM > *left, const Tensor< L > &lcin, const FunctionImpl< R, NDIM > *right, const Tensor< R > &rcin, double tol)
Definition funcimpl.h:3178
int get_truncate_mode() const
Definition funcimpl.h:1850
const std::vector< Vector< double, NDIM > > & get_special_points() const
Definition funcimpl.h:994
Future< compressT > compress_spawn(const keyT &key, bool nonstandard, bool keepleaves, bool redundant1)
Invoked on node where key is local.
Definition mraimpl.h:3404
std::size_t nCoeff() const
Returns the number of coefficients in the function ... collective global sum.
Definition mraimpl.h:1961
double vol_nsphere(int n, double R)
Definition funcimpl.h:5009
keyT neighbor_in_volume(const keyT &key, const keyT &disp) const
Returns key of general neighbor that resides in-volume.
Definition mraimpl.h:3376
void compress(const TreeState newstate, bool fence)
compress the wave function
Definition mraimpl.h:1521
void do_dirac_convolution(FunctionImpl< T, LDIM > *f, bool fence) const
Definition funcimpl.h:2296
Future< bool > truncate_spawn(const keyT &key, double tol)
Returns true if after truncation this node has coefficients.
Definition mraimpl.h:2653
void print_type_in_compilation_error(R &&)
Definition funcimpl.h:6346
Future< double > norm_tree_spawn(const keyT &key)
Definition mraimpl.h:1591
std::vector< keyT > local_leaf_keys() const
return the keys of the local leaf boxes
Definition mraimpl.h:558
MADNESS_ASSERT(this->is_redundant()==g.is_redundant())
void do_print_tree(const keyT &key, std::ostream &os, Level maxlevel) const
Functor for the do_print_tree method.
Definition mraimpl.h:2726
void vtransform(const std::vector< std::shared_ptr< FunctionImpl< R, NDIM > > > &vright, const Tensor< Q > &c, const std::vector< std::shared_ptr< FunctionImpl< T, NDIM > > > &vleft, double tol, bool fence)
Definition funcimpl.h:3008
void unset_functor()
Definition mraimpl.h:312
void refine_spawn(const opT &op, const keyT &key)
Definition funcimpl.h:4739
void apply_1d_realspace_push(const opT &op, const FunctionImpl< R, NDIM > *f, int axis, bool fence)
Definition funcimpl.h:4025
void set_truncate_mode(int mode)
Definition funcimpl.h:1851
void do_print_plane(const std::string filename, std::vector< Tensor< double > > plotinfo, const int xaxis, const int yaxis, const coordT el2)
print the MRA structure
Definition mraimpl.h:499
std::pair< Key< NDIM >, ShallowNode< T, NDIM > > find_datum(keyT key) const
return the a std::pair<key, node>, which MUST exist
Definition mraimpl.h:979
void set_functor(const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > functor1)
Definition mraimpl.h:293
std::enable_if< NDIM==FDIM >::type read_grid2(const std::string gridfile, std::shared_ptr< FunctionFunctorInterface< double, NDIM > > vnuc_functor)
read data from a grid
Definition funcimpl.h:1744
bool verify_tree_state_local() const
check that the tree state and the coeffs are consistent
Definition mraimpl.h:169
const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > & get_pmap() const
Definition mraimpl.h:207
Tensor< Q > fcube_for_mul(const keyT &child, const keyT &parent, const Tensor< Q > &coeff) const
Compute the function values for multiplication.
Definition funcimpl.h:2060
Timer timer_filter
Definition funcimpl.h:1081
void sock_it_to_me(const keyT &key, const RemoteReference< FutureImpl< std::pair< keyT, coeffT > > > &ref) const
Walk up the tree returning pair(key,node) for first node with coefficients.
Definition mraimpl.h:2866
void recursive_apply(opT &apply_op, const implT *fimpl, implT *rimpl, const bool fence)
traverse an existing tree and apply an operator
Definition funcimpl.h:5554
double get_thresh() const
Definition mraimpl.h:328
void trickle_down(bool fence)
sum all the contributions from all scales after applying an operator in mod-NS form
Definition mraimpl.h:1368
bool autorefine
If true, autorefine where appropriate.
Definition funcimpl.h:1005
bool halo_enabled() const
Is a neighbor halo staged on this function?
Definition funcimpl.h:1032
void set_autorefine(bool value)
Definition mraimpl.h:337
tensorT filter(const tensorT &s) const
Transform sum coefficients at level n to sums+differences at level n-1.
Definition mraimpl.h:1166
void chop_at_level(const int n, const bool fence=true)
remove all nodes with level higher than n
Definition mraimpl.h:1129
void unaryXXvalues(const FunctionImpl< Q, NDIM > *func, const opT &op, bool fence)
Definition funcimpl.h:3422
void partial_inner(const FunctionImpl< Q, LDIM > &g, const FunctionImpl< R, KDIM > &h, const std::array< int, CDIM > v1, const std::array< int, CDIM > v2)
invoked by result
Definition funcimpl.h:6362
TreeState tree_state
Definition funcimpl.h:1012
void print_tree_json(std::ostream &os=std::cout, Level maxlevel=10000) const
Definition mraimpl.h:2746
coeffT parent_to_child_NS(const keyT &child, const keyT &parent, const coeffT &coeff) const
Directly project parent NS coeffs to child NS coeffs.
Definition mraimpl.h:707
void copy_coeffs_different_world(const FunctionImpl< Q, NDIM > &other)
Copy coefficients from other funcimpl with possibly different world and on a different node.
Definition funcimpl.h:1238
void mapdim(const implT &f, const std::vector< long > &map, bool fence)
Permute the dimensions of f according to map, result on this.
Definition mraimpl.h:1071
bool is_compressed() const
Returns true if the function is compressed.
Definition mraimpl.h:250
void receive_halo(const std::vector< std::pair< keyT, coeffT > > &buf) const
Insert pushed neighbor nodes into the halo; runs as a task, concurrently with other pushes.
Definition funcimpl.h:1052
Vector< double, NDIM > coordT
Type of vector holding coordinates.
Definition funcimpl.h:984
void apply(opT &op, const FunctionImpl< R, NDIM > &f, bool fence)
apply an operator on f to return this
Definition funcimpl.h:5237
Tensor< T > tensorT
Type of tensor for anything but to hold coeffs.
Definition funcimpl.h:977
void mirror(const implT &f, const std::vector< long > &mirror, bool fence)
mirror the dimensions of f according to map, result on this
Definition mraimpl.h:1080
T inner_adaptive_recursive(keyT key, const tensorT &c, const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > f, const bool leaf_refine, T old_inner=T(0)) const
Definition funcimpl.h:6958
void store(Archive &ar)
Definition funcimpl.h:1416
void do_binary_op(const keyT &key, const Tensor< L > &left, const std::pair< keyT, Tensor< R > > &arg, const opT &op)
Functor for the binary_op method.
Definition funcimpl.h:2162
void gaxpy_ext(const FunctionImpl< L, NDIM > *left, T(*f)(const coordT &), T alpha, T beta, double tol, bool fence)
Definition funcimpl.h:7122
void accumulate_trees(FunctionImpl< Q, NDIM > &result, const R alpha, const bool fence=true) const
merge the trees of this and other, while multiplying them with the alpha or beta, resp
Definition funcimpl.h:1337
void print_stats() const
print the number of configurations per node
Definition mraimpl.h:1998
void broaden(const array_of_bools< NDIM > &is_periodic, bool fence)
Definition mraimpl.h:1317
coeffT truncate_reconstructed_op(const keyT &key, const std::vector< Future< coeffT > > &v, const double tol)
given the sum coefficients of all children, truncate or not
Definition mraimpl.h:1638
void refine_op(const opT &op, const keyT &key)
Definition funcimpl.h:4714
static Tensor< TENSOR_RESULT_TYPE(T, R) > inner_local(const std::vector< const FunctionImpl< T, NDIM > * > &left, const std::vector< const FunctionImpl< R, NDIM > * > &right, bool sym)
Definition funcimpl.h:6242
void fcube(const keyT &key, const FunctionFunctorInterface< T, NDIM > &f, const Tensor< double > &qx, tensorT &fval) const
Evaluate function at quadrature points in the specified box.
Definition mraimpl.h:2488
Timer timer_change_tensor_type
Definition funcimpl.h:1079
void forward_do_diff1(const DerivativeBase< T, NDIM > *D, const implT *f, const keyT &key, const std::pair< keyT, coeffT > &left, const std::pair< keyT, coeffT > &center, const std::pair< keyT, coeffT > &right)
Definition mraimpl.h:932
std::vector< Slice > child_patch(const keyT &child) const
Returns patch referring to coeffs of child in parent box.
Definition mraimpl.h:696
void print_tree_graphviz(std::ostream &os=std::cout, Level maxlevel=10000) const
Definition mraimpl.h:2799
void set_tree_state(const TreeState &state)
Definition funcimpl.h:1447
std::size_t min_nodes() const
Returns the min number of nodes on a processor.
Definition mraimpl.h:1902
void copy_coeffs_same_world(const FunctionImpl< Q, NDIM > &other, bool fence)
Copy coeffs from other into self.
Definition funcimpl.h:1291
std::shared_ptr< FunctionFunctorInterface< T, NDIM > > functor
Definition funcimpl.h:1011
Timer timer_compress_svd
Definition funcimpl.h:1082
Tensor< TENSOR_RESULT_TYPE(T, R)> mul(const Tensor< T > &c1, const Tensor< R > &c2, const int npt, const keyT &key) const
multiply the values of two coefficient tensors using a custom number of grid points
Definition funcimpl.h:2135
void make_redundant(const bool fence)
convert this to redundant, i.e. have sum coefficients on all levels
Definition mraimpl.h:1549
void load(Archive &ar)
Definition funcimpl.h:1398
std::size_t max_nodes() const
Returns the max number of nodes on a processor.
Definition mraimpl.h:1893
T inner_ext_local(const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > f, const bool leaf_refine) const
Definition funcimpl.h:6933
coeffT upsample(const keyT &key, const coeffT &coeff) const
upsample the sum coefficients of level 1 to sum coeffs on level n+1
Definition mraimpl.h:1245
TensorArgs targs
type of tensor to be used in the FunctionNodes
Definition funcimpl.h:1007
void flo_unary_op_node_inplace(const opT &op, bool fence)
Definition funcimpl.h:2325
std::size_t size_local() const
Returns the number of coefficients in the function for each rank.
Definition mraimpl.h:1920
GenTensor< Q > values2coeffs(const keyT &key, const GenTensor< Q > &values) const
Definition funcimpl.h:2039
void plot_cube_kernel(archive::archive_ptr< Tensor< T > > ptr, const keyT &key, const coordT &plotlo, const coordT &plothi, const std::vector< long > &npt, bool eval_refine) const
Definition mraimpl.h:3470
T trace_local() const
Returns int(f(x),x) in local volume.
Definition mraimpl.h:3305
void print_grid(const std::string filename) const
Definition mraimpl.h:542
void replicate_on_hosts(bool fence=true)
Definition funcimpl.h:1207
bool get_autorefine() const
Definition mraimpl.h:334
int k
Wavelet order.
Definition funcimpl.h:997
void vtransform_doit(const std::shared_ptr< FunctionImpl< R, NDIM > > &right, const Tensor< Q > &c, const std::vector< std::shared_ptr< FunctionImpl< T, NDIM > > > &vleft, double tol)
Definition funcimpl.h:2857
MADNESS_CHECK(this->is_reconstructed())
void phi_for_mul(Level np, Translation lp, Level nc, Translation lc, Tensor< double > &phi) const
Compute the Legendre scaling functions for multiplication.
Definition mraimpl.h:3273
Future< std::pair< keyT, coeffT > > find_me(const keyT &key) const
find_me. Called by diff_bdry to get coefficients of boundary function
Definition mraimpl.h:3391
TensorType get_tensor_type() const
Definition mraimpl.h:319
void do_project_out(const coeffT &fcoeff, const std::pair< keyT, coeffT > gpair, const keyT &gkey, const Key< NDIM > &dest, const int dim) const
compute the inner product of two nodes of only some dimensions and accumulate on result
Definition funcimpl.h:7342
void remove_leaf_coefficients(const bool fence)
Definition mraimpl.h:1543
void insert_zero_down_to_initial_level(const keyT &key)
Initialize nodes to zero function at initial_level of refinement.
Definition mraimpl.h:2622
void do_diff1(const DerivativeBase< T, NDIM > *D, const implT *f, const keyT &key, const std::pair< keyT, coeffT > &left, const std::pair< keyT, coeffT > &center, const std::pair< keyT, coeffT > &right)
Definition mraimpl.h:943
typedef TENSOR_RESULT_TYPE(T, R) resultT
void unary_op_node_inplace(const opT &op, bool fence)
Definition funcimpl.h:2234
T inner_adaptive_local(const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > f, const bool leaf_refine) const
Definition funcimpl.h:6944
void do_print_tree_json(const keyT &key, std::multimap< Level, std::tuple< tranT, std::string > > &data, Level maxlevel) const
Functor for the do_print_tree_json method.
Definition mraimpl.h:2777
std::multimap< Key< FDIM >, std::list< Key< CDIM > > > recur_down_for_contraction_map(const keyT &key, const nodeT &node, const std::array< int, CDIM > &v_this, const std::array< int, CDIM > &v_other, const std::set< Key< ODIM > > &ij_other_list, const std::map< Key< CDIM >, double > &j_other_list, bool this_first, const double thresh)
make a map of all nodes that will contribute to a partial inner product
Definition funcimpl.h:6517
std::shared_ptr< FunctionImpl< T, NDIM > > pimplT
pointer to this class
Definition funcimpl.h:976
TENSOR_RESULT_TYPE(T, R) dot_local(const FunctionImpl< R
Returns the dot product ASSUMING same distribution.
void finalize_sum()
after summing up we need to do some cleanup;
Definition mraimpl.h:1850
std::enable_if< NDIM==FDIM >::type read_grid(const std::string keyfile, const std::string gridfile, std::shared_ptr< FunctionFunctorInterface< double, NDIM > > vnuc_functor)
read data from a grid
Definition funcimpl.h:1637
dcT coeffs
The coefficients.
Definition funcimpl.h:1014
bool exists_and_is_leaf(const keyT &key) const
Definition mraimpl.h:1289
static std::complex< Real > conj(const std::complex< Real > &x)
Definition funcimpl.h:6236
void make_Vphi(const opT &leaf_op, const bool fence=true)
assemble the function V*phi using V and phi given from the functor
Definition funcimpl.h:4506
void unaryXX(const FunctionImpl< Q, NDIM > *func, const opT &op, bool fence)
Definition funcimpl.h:3409
std::vector< std::pair< int, const coeffT * > > mapvecT
Type of the entry in the map returned by make_key_vec_map.
Definition funcimpl.h:6035
void project_out(FunctionImpl< T, NDIM-LDIM > *result, const FunctionImpl< T, LDIM > *gimpl, const int dim, const bool fence)
project the low-dim function g on the hi-dim function f: result(x) = <this(x,y) | g(y)>
Definition funcimpl.h:7138
void verify_tree() const
Verify tree is properly constructed ... global synchronization involved.
Definition mraimpl.h:111
void do_square_inplace2(const keyT &parent, const keyT &child, const tensorT &parent_coeff)
void gaxpy_inplace_reconstructed(const T &alpha, const FunctionImpl< Q, NDIM > &g, const R &beta, const bool fence)
Definition funcimpl.h:1305
void undo_replicate(bool fence=true)
Definition funcimpl.h:1212
void set_tensor_args(const TensorArgs &t)
Definition mraimpl.h:325
GenTensor< Q > fcube_for_mul(const keyT &child, const keyT &parent, const GenTensor< Q > &coeff) const
Compute the function values for multiplication.
Definition funcimpl.h:2088
Range< typename dcT::const_iterator > rangeT
Definition funcimpl.h:5826
std::size_t real_size() const
Returns the number of coefficients in the function ... collective global sum.
Definition mraimpl.h:1938
bool exists_and_has_children(const keyT &key) const
Definition mraimpl.h:1284
void sum_down_spawn(const keyT &key, const coeffT &s)
is this the same as trickle_down() ?
Definition mraimpl.h:876
void multi_to_multi_op_values(const opT &op, const std::vector< implT * > &vin, std::vector< implT * > &vout, const bool fence=true)
Inplace operate on many functions (impl's) with an operator within a certain box.
Definition funcimpl.h:2979
long box_interior[1000]
Definition funcimpl.h:3454
std::atomic< ConcurrentHashMap< keyT, coeffT > * > neighbor_halo_
Neighbor coefficients pushed here by whoever owns them; null until something stages.
Definition funcimpl.h:1025
keyT neighbor(const keyT &key, const keyT &disp, const array_of_bools< NDIM > &is_periodic) const
Returns key of general neighbor enforcing BC.
Definition mraimpl.h:3361
GenTensor< Q > NS_fcube_for_mul(const keyT &child, const keyT &parent, const GenTensor< Q > &coeff, const bool s_only) const
Compute the function values for multiplication.
Definition funcimpl.h:1958
rangeT range(coeffs.begin(), coeffs.end())
void norm_tree(bool fence)
compute for each FunctionNode the norm of the function inside that node
Definition mraimpl.h:1568
void gaxpy_inplace(const T &alpha, const FunctionImpl< Q, NDIM > &other, const R &beta, bool fence)
Inplace general bilinear operation.
Definition funcimpl.h:1385
const Tensor< double > cell
the size of the root cell in each dimension, unchangeable
Definition funcimpl.h:1002
bool has_leaves() const
Definition mraimpl.h:288
bool verify_parents_and_children() const
check that parents and children are consistent
Definition mraimpl.h:119
void apply_source_driven(opT &op, const FunctionImpl< R, NDIM > &f, bool fence)
similar to apply, but for low rank coeffs
Definition funcimpl.h:5379
std::size_t halo_size() const
How many neighbor nodes are staged on this rank; zero if no halo.
Definition funcimpl.h:1044
void distribute(std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > newmap) const
Definition funcimpl.h:1219
int get_special_level() const
Definition funcimpl.h:993
void reconstruct_op(const keyT &key, const coeffT &s, const bool accumulate_NS=true)
Definition mraimpl.h:2121
tensorT gaxpy_ext_node(keyT key, Tensor< L > lc, T(*f)(const coordT &), T alpha, T beta) const
Definition funcimpl.h:7011
const coeffT parent_to_child(const coeffT &s, const keyT &parent, const keyT &child) const
Directly project parent coeffs to child coeffs.
Definition mraimpl.h:3288
WorldObject< FunctionImpl< T, NDIM > > woT
Base class world object type.
Definition funcimpl.h:972
void undo_redundant(const bool fence)
convert this from redundant to standard reconstructed form
Definition mraimpl.h:1559
GenTensor< T > coeffT
Type of tensor used to hold coeffs.
Definition funcimpl.h:981
const keyT & key0() const
Returns cdata.key0.
Definition mraimpl.h:394
double finalize_apply()
after apply we need to do some cleanup;
Definition mraimpl.h:1807
bool leaves_only
Definition funcimpl.h:5831
friend hashT hash_value(const FunctionImpl< T, NDIM > *pimpl)
Hash a pointer to FunctionImpl.
Definition funcimpl.h:7442
const dcT & get_coeffs() const
Definition mraimpl.h:343
FunctionImpl(World &world, const FunctionImpl< Q, NDIM > &other, const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > &pmap, bool dozero)
Copy constructor.
Definition funcimpl.h:1168
compressT make_redundant_op(const keyT &key, const std::vector< Future< compressT > > &v)
similar to compress_op, but insert only the sum coefficients in the tree
Definition mraimpl.h:1752
T inner_ext_node(keyT key, tensorT c, const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > f) const
Return the inner product with an external function on a specified function node.
Definition funcimpl.h:6810
double norm2sq_local() const
Returns the square of the local norm ... no comms.
Definition mraimpl.h:1859
const FunctionCommonData< T, NDIM > & get_cdata() const
Definition mraimpl.h:349
void sum_down(bool fence)
After 1d push operator must sum coeffs down the tree to restore correct scaling function coefficients...
Definition mraimpl.h:922
T inner_ext_recursive(keyT key, tensorT c, const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > f, const bool leaf_refine, T old_inner=T(0)) const
Definition funcimpl.h:6827
bool noautorefine(const keyT &key, const tensorT &t) const
Always returns false (for when autorefine is not wanted)
Definition mraimpl.h:859
double truncate_tol(double tol, const keyT &key) const
Returns the truncation threshold according to truncate_method.
Definition mraimpl.h:649
void flo_unary_op_node_inplace(const opT &op, bool fence) const
Definition funcimpl.h:2335
bool autorefine_square_test(const keyT &key, const nodeT &t) const
Returns true if this block of coeffs needs autorefining.
Definition mraimpl.h:865
void erase(const Level &max_level)
truncate tree at a certain level
Definition mraimpl.h:739
void mulXX(const FunctionImpl< L, NDIM > *left, const FunctionImpl< R, NDIM > *right, double tol, bool fence)
Definition funcimpl.h:3381
std::pair< coeffT, std::pair< double, double > > compressT
s coefficients plus the (snorm_tree, dnorm_tree) pair propagated up by compress
Definition funcimpl.h:4800
void reconstruct(bool fence)
reconstruct this tree – respects fence
Definition mraimpl.h:1489
void multiply(const implT *f, const FunctionImpl< T, LDIM > *g, const int particle)
multiply f (a pair function of NDIM) with an orbital g (LDIM=NDIM/2)
Definition funcimpl.h:3798
coeffT assemble_coefficients(const keyT &key, const coeffT &coeff_ket, const coeffT &vpotential1, const coeffT &vpotential2, const tensorT &veri) const
given several coefficient tensors, assemble a result tensor
Definition mraimpl.h:1027
static void tnorm(const tensorT &t, double *lo, double *hi)
Computes norm of low/high-order polyn. coeffs for autorefinement test.
Definition mraimpl.h:3165
std::pair< bool, T > eval_local_only(const Vector< double, NDIM > &xin, Level maxlevel)
Evaluate function only if point is local returning (true,value); otherwise return (false,...
Definition mraimpl.h:2960
bool halo_probe(const keyT &key, coeffT &out) const
Look up a staged neighbor; on a hit copy its coefficients, which are empty for an interior node.
Definition funcimpl.h:1070
std::size_t max_depth() const
Returns the maximum depth of the tree ... collective ... global sum/broadcast.
Definition mraimpl.h:1885
std::size_t size() const
Returns the number of coefficients in the function ... collective global sum.
Definition mraimpl.h:1930
void reduce_rank(const double thresh, bool fence)
reduce the rank of the coefficients tensors
Definition mraimpl.h:1121
TreeState get_tree_state() const
Definition funcimpl.h:1451
void merge_trees(const T alpha, const FunctionImpl< Q, NDIM > &other, const R beta, const bool fence=true)
merge the trees of this and other, while multiplying them with the alpha or beta, resp
Definition funcimpl.h:1325
const Tensor< double > & get_cell() const
return the simulation cell
Definition funcimpl.h:1470
void halo_clear() const
Discard the neighbor halo, freeing the staged coefficients.
Definition funcimpl.h:1039
std::shared_ptr< FunctionFunctorInterface< T, NDIM > > get_functor()
Definition mraimpl.h:300
double do_apply_directed_screening(const opT *op, const keyT &key, const coeffT &coeff, const bool &do_kernel)
apply an operator on the coeffs c (at node key)
Definition funcimpl.h:5270
tensorT unfilter(const tensorT &s) const
Transform sums+differences at level n to sum coefficients at level n+1.
Definition mraimpl.h:1195
int get_initial_level() const
getter
Definition funcimpl.h:992
Tensor< T > eval_plot_cube(const coordT &plotlo, const coordT &plothi, const std::vector< long > &npt, const bool eval_refine=false) const
Definition mraimpl.h:3562
virtual ~FunctionImpl()
Definition funcimpl.h:1199
Vector< Translation, NDIM > tranT
Type of array holding translation.
Definition funcimpl.h:978
void change_tree_state(const TreeState finalstate, bool fence=true)
change the tree state of this function, might or might not respect fence!
Definition mraimpl.h:1421
Future< coeffT > truncate_reconstructed_spawn(const keyT &key, const double tol)
truncate using a tree in reconstructed form
Definition mraimpl.h:1614
GenTensor< Q > coeffs2values(const keyT &key, const GenTensor< Q > &coeff) const
Definition funcimpl.h:1906
FunctionImpl(const FunctionFactory< T, NDIM > &factory)
Initialize function impl from data in factory.
Definition funcimpl.h:1088
void map_and_mirror(const implT &f, const std::vector< long > &map, const std::vector< long > &mirror, bool fence)
map and mirror the translation index and the coefficients, result on this
Definition mraimpl.h:1090
Timer timer_lr_result
Definition funcimpl.h:1080
void gaxpy(T alpha, const FunctionImpl< L, NDIM > &left, T beta, const FunctionImpl< R, NDIM > &right, bool fence)
Invoked by result to perform result += alpha*left+beta*right in wavelet basis.
Definition funcimpl.h:2185
void truncate(double tol, bool fence)
Truncate according to the threshold with optional global fence.
Definition mraimpl.h:378
void do_mul(const keyT &key, const Tensor< L > &left, const std::pair< keyT, Tensor< R > > &arg)
Functor for the mul method.
Definition funcimpl.h:2110
void copy_remote_coeffs_from_pid(const ProcessID pid, const FunctionImpl< Q, NDIM > &other)
Definition funcimpl.h:1264
void project_out2(const FunctionImpl< T, LDIM+NDIM > *f, const FunctionImpl< T, LDIM > *g, const int dim)
project the low-dim function g on the hi-dim function f: this(x) = <f(x,y) | g(y)>
Definition funcimpl.h:7284
double do_apply_kernel2(const opT *op, const Tensor< R > &c, const do_op_args< OPDIM > &args, const TensorArgs &apply_targs)
same as do_apply_kernel, but use full rank tensors as input and low rank tensors as output
Definition funcimpl.h:4941
static Tensor< TENSOR_RESULT_TYPE(T, R)> dot_local(const std::vector< const FunctionImpl< T, NDIM > * > &left, const std::vector< const FunctionImpl< R, NDIM > * > &right, bool sym)
Definition funcimpl.h:6294
Tensor< Q > coeffs2values(const keyT &key, const Tensor< Q > &coeff) const
Definition funcimpl.h:2032
Tensor< Q > values2coeffs(const keyT &key, const Tensor< Q > &values) const
Definition funcimpl.h:2046
void multi_to_multi_op_values_doit(const keyT &key, const opT &op, const std::vector< implT * > &vin, std::vector< implT * > &vout)
Inplace operate on many functions (impl's) with an operator within a certain box.
Definition funcimpl.h:2956
bool is_reconstructed() const
Returns true if the function is compressed.
Definition mraimpl.h:256
void replicate(bool fence=true)
Definition funcimpl.h:1203
double norm_tree_op(const keyT &key, const std::vector< Future< double > > &v)
Definition mraimpl.h:1576
void reset_timer()
Definition mraimpl.h:366
void refine_to_common_level(const std::vector< FunctionImpl< T, NDIM > * > &v, const std::vector< tensorT > &c, const keyT key)
Refine multiple functions down to the same finest level.
Definition mraimpl.h:769
int get_k() const
Definition mraimpl.h:340
void dirac_convolution_op(const keyT &key, const nodeT &node, FunctionImpl< T, LDIM > *f) const
The operator.
Definition funcimpl.h:2251
FunctionImpl< T, NDIM > implT
Type of this class (implementation)
Definition funcimpl.h:975
void eval(const Vector< double, NDIM > &xin, const keyT &keyin, const typename Future< T >::remote_refT &ref)
Evaluate the function at a point in simulation coordinates.
Definition mraimpl.h:2916
bool truncate_op(const keyT &key, double tol, const std::vector< Future< bool > > &v)
Definition mraimpl.h:2689
void zero_norm_tree()
Definition mraimpl.h:1306
std::size_t max_local_depth() const
Returns the maximum local depth of the tree ... no communications.
Definition mraimpl.h:1871
tensorT project(const keyT &key) const
Definition mraimpl.h:2834
double thresh
Screening threshold.
Definition funcimpl.h:998
double check_symmetry_local() const
Returns some asymmetry measure ... no comms.
Definition mraimpl.h:755
Future< double > get_norm_tree_recursive(const keyT &key) const
Definition mraimpl.h:2855
bool is_redundant_after_merge() const
Returns true if the function is redundant_after_merge.
Definition mraimpl.h:268
void mulXXvec(const FunctionImpl< L, NDIM > *left, const std::vector< const FunctionImpl< R, NDIM > * > &vright, const std::vector< FunctionImpl< T, NDIM > * > &vresult, double tol, bool fence)
Definition funcimpl.h:3438
Key< NDIM > keyT
Type of key.
Definition funcimpl.h:979
friend hashT hash_value(const std::shared_ptr< FunctionImpl< T, NDIM > > impl)
Hash a shared_ptr to FunctionImpl.
Definition funcimpl.h:7452
std::vector< Vector< double, NDIM > > special_points
special points for further refinement (needed for composite functions or multiplication)
Definition funcimpl.h:1001
bool truncate_on_project
If true projection inserts at level n-1 not n.
Definition funcimpl.h:1006
AtomicInt small
Definition funcimpl.h:1084
static void do_dot_localX(const typename mapT::iterator lstart, const typename mapT::iterator lend, typename FunctionImpl< R, NDIM >::mapT *rmap_ptr, const bool sym, Tensor< TENSOR_RESULT_TYPE(T, R)> *result_ptr, Mutex *mutex)
Definition funcimpl.h:6191
bool is_on_demand() const
Definition mraimpl.h:283
double err_box(const keyT &key, const nodeT &node, const opT &func, int npt, const Tensor< double > &qx, const Tensor< double > &quad_phit, const Tensor< double > &quad_phiw) const
Returns the square of the error norm in the box labeled by key.
Definition funcimpl.h:5667
void accumulate_timer(const double time) const
Definition mraimpl.h:352
void trickle_down_op(const keyT &key, const coeffT &s)
sum all the contributions from all scales after applying an operator in mod-NS form
Definition mraimpl.h:1379
static void do_inner_localX(const typename mapT::iterator lstart, const typename mapT::iterator lend, typename FunctionImpl< R, NDIM >::mapT *rmap_ptr, const bool sym, Tensor< TENSOR_RESULT_TYPE(T, R) > *result_ptr, Mutex *mutex)
Definition funcimpl.h:6110
void mulXXveca(const keyT &key, const FunctionImpl< L, NDIM > *left, const Tensor< L > &lcin, const std::vector< const FunctionImpl< R, NDIM > * > vrightin, const std::vector< Tensor< R > > &vrcin, const std::vector< FunctionImpl< T, NDIM > * > vresultin, double tol)
Definition funcimpl.h:3043
void set_thresh(double value)
Definition mraimpl.h:331
Tensor< double > print_plane_local(const int xaxis, const int yaxis, const coordT &el2)
collect the data for a plot of the MRA structure locally on each node
Definition mraimpl.h:423
void sock_it_to_me_too(const keyT &key, const RemoteReference< FutureImpl< std::pair< keyT, coeffT > > > &ref) const
Definition mraimpl.h:2894
void broaden_op(const keyT &key, const std::vector< Future< bool > > &v)
Definition mraimpl.h:1295
void print_plane(const std::string filename, const int xaxis, const int yaxis, const coordT &el2)
Print a plane ("xy", "xz", or "yz") containing the point x to file.
Definition mraimpl.h:403
void print_tree(std::ostream &os=std::cout, Level maxlevel=10000) const
Definition mraimpl.h:2717
void project_refine_op(const keyT &key, bool do_refine, const std::vector< Vector< double, NDIM > > &specialpts)
Definition mraimpl.h:2500
void scale_oop(const Q q, const FunctionImpl< F, NDIM > &f, bool fence)
Out-of-place scale by a constant.
Definition funcimpl.h:7419
T typeT
Definition funcimpl.h:974
std::size_t tree_size() const
Returns the size of the tree structure of the function ... collective global sum.
Definition mraimpl.h:1911
ConcurrentHashMap< keyT, mapvecT > mapT
Type of the map returned by make_key_vec_map.
Definition funcimpl.h:6038
void add_scalar_inplace(T t, bool fence)
Adds a constant to the function. Local operation, optional fence.
Definition mraimpl.h:2581
void forward_traverse(const coeff_opT &coeff_op, const apply_opT &apply_op, const keyT &key) const
traverse a non-existing tree
Definition funcimpl.h:3892
tensorT downsample(const keyT &key, const std::vector< Future< coeffT > > &v) const
downsample the sum coefficients of level n+1 to sum coeffs on level n
Definition mraimpl.h:1215
void abs_square_inplace(bool fence)
Definition mraimpl.h:3268
FunctionImpl(const FunctionImpl< Q, NDIM > &other, const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > &pmap, bool dozero)
Copy constructor.
Definition funcimpl.h:1154
void refine(const opT &op, bool fence)
Definition funcimpl.h:4752
static mapT make_key_vec_map(const std::vector< const FunctionImpl< T, NDIM > * > &v)
Returns map of union of local keys to vector of indexes of functions containing that key.
Definition funcimpl.h:6059
void put_in_box(ProcessID from, long nl, long ni) const
Definition mraimpl.h:824
void unary_op_value_inplace(const opT &op, bool fence)
Definition funcimpl.h:3023
std::pair< const keyT, nodeT > datumT
Type of entry in container.
Definition funcimpl.h:983
Timer timer_accumulate
Definition funcimpl.h:1078
TensorArgs get_tensor_args() const
Definition mraimpl.h:322
void unaryXXa(const keyT &key, const FunctionImpl< Q, NDIM > *func, const opT &op)
Definition funcimpl.h:3356
void make_Vphi_only(const opT &leaf_op, FunctionImpl< T, NDIM > *ket, FunctionImpl< T, LDIM > *v1, FunctionImpl< T, LDIM > *v2, FunctionImpl< T, LDIM > *p1, FunctionImpl< T, LDIM > *p2, FunctionImpl< T, NDIM > *eri, const bool fence=true)
assemble the function V*phi using V and phi given from the functor
Definition funcimpl.h:4567
void average(const implT &rhs)
take the average of two functions, similar to: this=0.5*(this+rhs)
Definition mraimpl.h:1102
void recursive_apply(opT &apply_op, const FunctionImpl< T, LDIM > *fimpl, const FunctionImpl< T, LDIM > *gimpl, const bool fence)
traverse a non-existing tree, make its coeffs and apply an operator
Definition funcimpl.h:5420
void diff(const DerivativeBase< T, NDIM > *D, const implT *f, bool fence)
Definition mraimpl.h:955
void square_inplace(bool fence)
Pointwise squaring of function with optional global fence.
Definition mraimpl.h:3257
void remove_internal_coefficients(const bool fence)
Definition mraimpl.h:1538
void compute_snorm_and_dnorm(bool fence=true)
compute norm of s and d coefficients for all nodes
Definition mraimpl.h:1145
std::vector< unsigned char > serialize_remote_coeffs()
invoked by copy_remote_coeffs_from_pid to serialize local coeffs
Definition funcimpl.h:1276
long box_leaf[1000]
Definition funcimpl.h:3453
void standard(bool fence)
Changes non-standard compressed form to standard compressed form.
Definition mraimpl.h:1794
void multiop_values_doit(const keyT &key, const opT &op, const std::vector< implT * > &v)
Definition funcimpl.h:2914
bool is_nonstandard_with_leaves() const
Definition mraimpl.h:278
GenTensor< Q > values2NScoeffs(const keyT &key, const GenTensor< Q > &values) const
convert function values of the a child generation directly to NS coeffs
Definition funcimpl.h:2007
int truncate_mode
0=default=(|d|<thresh), 1=(|d|<thresh/2^n), 2=(|d|<thresh/4^n);
Definition funcimpl.h:1004
void multiop_values(const opT &op, const std::vector< implT * > &v)
Definition funcimpl.h:2931
GenTensor< Q > NScoeffs2values(const keyT &key, const GenTensor< Q > &coeff, const bool s_only) const
convert S or NS coeffs to values on a 2k grid of the children
Definition funcimpl.h:1922
static std::enable_if_t< std::is_floating_point_v< Real >, Real > conj(const Real x)
Definition funcimpl.h:6231
FunctionNode holds the coefficients, etc., at each node of the 2^NDIM-tree.
Definition funcimpl.h:136
FunctionNode< Q, NDIM > convert() const
Copy with possible type conversion of coefficients, copying all other state.
Definition funcimpl.h:204
GenTensor< T > coeffT
Definition funcimpl.h:138
bool has_coeff() const
Returns true if there are coefficients in this node.
Definition funcimpl.h:210
void recompute_snorm_and_dnorm(const FunctionCommonData< T, NDIM > &cdata)
Definition funcimpl.h:355
FunctionNode(const coeffT &coeff, bool has_children=false)
Constructor from given coefficients with optional children.
Definition funcimpl.h:166
FunctionNode()
Default constructor makes node without coeff or children.
Definition funcimpl.h:156
void serialize(Archive &ar)
Definition funcimpl.h:478
double _dnorm_tree
norm of the difference coefficients summed up the tree
Definition funcimpl.h:147
void consolidate_buffer(const TensorArgs &args)
Definition funcimpl.h:464
double get_dnorm() const
return the precomputed norm of the (virtual) d coefficients
Definition funcimpl.h:336
size_t size() const
Returns the number of coefficients in this node.
Definition funcimpl.h:252
void set_has_children_recursive(const typename FunctionNode< T, NDIM >::dcT &c, const Key< NDIM > &key)
Sets has_children attribute to true recurring up to ensure connected.
Definition funcimpl.h:269
FunctionNode< T, NDIM > & operator=(const FunctionNode< T, NDIM > &other)
Definition funcimpl.h:186
FunctionNode(const coeffT &coeff, double norm_tree, double dnorm_tree, double snorm, double dnorm, bool has_children)
Definition funcimpl.h:176
double snorm
norm of the s coefficients
Definition funcimpl.h:151
void clear_coeff()
Clears the coefficients (has_coeff() will subsequently return false)
Definition funcimpl.h:305
Tensor< T > tensorT
Definition funcimpl.h:139
coeffT buffer
The coefficients, if any.
Definition funcimpl.h:149
T trace_conj(const FunctionNode< T, NDIM > &rhs) const
Definition funcimpl.h:473
void scale(Q a)
Scale the coefficients of this node.
Definition funcimpl.h:311
bool is_leaf() const
Returns true if this does not have children.
Definition funcimpl.h:223
void set_has_children(bool flag)
Sets has_children attribute to value of flag.
Definition funcimpl.h:264
void accumulate(const coeffT &t, const typename FunctionNode< T, NDIM >::dcT &c, const Key< NDIM > &key, const TensorArgs &args)
Accumulate inplace and if necessary connect node to parent.
Definition funcimpl.h:436
double get_norm_tree() const
Gets the value of norm_tree.
Definition funcimpl.h:326
bool _has_children
True if there are children.
Definition funcimpl.h:148
void set_snorm(const double sn)
set the precomputed norm of the (virtual) s coefficients
Definition funcimpl.h:341
coeffT _coeffs
The coefficients, if any.
Definition funcimpl.h:145
void accumulate2(const tensorT &t, const typename FunctionNode< T, NDIM >::dcT &c, const Key< NDIM > &key)
Accumulate inplace and if necessary connect node to parent.
Definition funcimpl.h:403
void reduceRank(const double &eps)
reduces the rank of the coefficients (if applicable)
Definition funcimpl.h:259
WorldContainer< Key< NDIM >, FunctionNode< T, NDIM > > dcT
Definition funcimpl.h:154
void gaxpy_inplace(const T &alpha, const FunctionNode< Q, NDIM > &other, const R &beta)
General bi-linear operation — this = this*alpha + other*beta.
Definition funcimpl.h:385
double get_dnorm_tree() const
Gets the value of dnorm_tree.
Definition funcimpl.h:331
double _norm_tree
After norm_tree will contain norm of sum coefficients summed up tree.
Definition funcimpl.h:146
void set_is_leaf(bool flag)
Sets has_children attribute to value of !flag.
Definition funcimpl.h:290
void print_json(std::ostream &s) const
Definition funcimpl.h:487
double get_snorm() const
get the precomputed norm of the (virtual) s coefficients
Definition funcimpl.h:351
void set_dnorm_tree(double dnorm_tree)
Sets the value of dnorm_tree.
Definition funcimpl.h:321
const coeffT & coeff() const
Returns a const reference to the tensor containing the coeffs.
Definition funcimpl.h:247
FunctionNode(const coeffT &coeff, double norm_tree, bool has_children)
Definition funcimpl.h:171
bool has_children() const
Returns true if this node has children.
Definition funcimpl.h:217
void set_coeff(const coeffT &coeffs)
Takes a shallow copy of the coeff — same as this->coeff()=coeff.
Definition funcimpl.h:295
void set_dnorm(const double dn)
set the precomputed norm of the (virtual) d coefficients
Definition funcimpl.h:346
double dnorm
norm of the d coefficients, also defined if there are no d coefficients
Definition funcimpl.h:150
bool is_invalid() const
Returns true if this node is invalid (no coeffs and no children)
Definition funcimpl.h:229
FunctionNode(const FunctionNode< T, NDIM > &other)
Definition funcimpl.h:180
coeffT & coeff()
Returns a non-const reference to the tensor containing the coeffs.
Definition funcimpl.h:237
void set_norm_tree(double norm_tree)
Sets the value of norm_tree.
Definition funcimpl.h:316
Implements the functionality of futures.
Definition future.h:75
A future is a possibly yet unevaluated value.
Definition future.h:370
remote_refT remote_ref(World &world) const
Returns a structure used to pass references to another process.
Definition future.h:672
RemoteReference< FutureImpl< T > > remote_refT
Definition future.h:395
Definition lowranktensor.h:59
bool is_of_tensortype(const TensorType &tt) const
Definition gentensor.h:225
GenTensor convert(const TensorArgs &) const
Definition gentensor.h:198
long dim(const int i) const
return the number of entries in dimension i
Definition lowranktensor.h:391
Tensor< T > full_tensor_copy() const
Definition gentensor.h:206
long ndim() const
Definition lowranktensor.h:386
constexpr bool is_full_tensor() const
Definition gentensor.h:224
void add_SVD(const GenTensor< T > &rhs, const double &)
Definition gentensor.h:235
const Tensor< T > & get_tensor() const
Definition gentensor.h:203
void reduce_rank(const double &)
Definition gentensor.h:217
bool has_no_data() const
Definition gentensor.h:211
void normalize()
Definition gentensor.h:218
GenTensor< T > & emul(const GenTensor< T > &other)
Inplace multiply by corresponding elements of argument Tensor.
Definition lowranktensor.h:637
float_scalar_type normf() const
Definition lowranktensor.h:406
double svd_normf() const
Definition gentensor.h:213
SRConf< T > config() const
Definition gentensor.h:237
long rank() const
Definition gentensor.h:212
const Tensor< T > & full_tensor() const
Definition gentensor.h:200
long size() const
Definition lowranktensor.h:488
SVDTensor< T > & get_svdtensor()
Definition gentensor.h:228
TensorType tensor_type() const
Definition gentensor.h:221
bool has_data() const
Definition gentensor.h:210
Tensor< T > reconstruct_tensor() const
Definition gentensor.h:199
GenTensor & gaxpy(const T alpha, const GenTensor &other, const T beta)
Definition lowranktensor.h:586
bool is_assigned() const
Definition gentensor.h:209
IsSupported< TensorTypeData< Q >, GenTensor< T > & >::type scale(Q fac)
Inplace multiplication by scalar of supported type (legacy name)
Definition lowranktensor.h:426
constexpr bool is_svd_tensor() const
Definition gentensor.h:222
Definition worldhashmap.h:330
Iterates in lexical order thru all children of a key.
Definition key.h:548
Key is the index for a node of the 2^NDIM-tree.
Definition key.h:70
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:487
Level level() const
Definition key.h:169
bool is_valid() const
Checks if a key is valid.
Definition key.h:124
hashT hash() const
Definition key.h:158
Key< NDIM-VDIM > extract_complement_key(const std::array< int, VDIM > &v) const
extract a new key with the Translations complementary to the ones indicated in the v array
Definition key.h:473
Key< VDIM > extract_key(const std::array< int, VDIM > &v) const
extract a new key with the Translations indicated in the v array
Definition key.h:465
Key parent(int generation=1) const
Returns the key of the parent.
Definition key.h:290
const Vector< Translation, NDIM > & translation() const
Definition key.h:174
void break_apart(Key< LDIM > &key1, Key< KDIM > &key2) const
break key into two low-dimensional keys
Definition key.h:424
A pmap that locates children on odd levels with their even level parents.
Definition funcimpl.h:105
LevelPmap(World &world)
Definition funcimpl.h:111
const int nproc
Definition funcimpl.h:107
LevelPmap()
Definition funcimpl.h:109
ProcessID owner(const keyT &key) const
Find the owner of a given key.
Definition funcimpl.h:114
Definition funcimpl.h:77
Mutex using pthread mutex operations.
Definition worldmutex.h:131
void unlock() const
Free a mutex owned by this thread.
Definition worldmutex.h:165
void lock() const
Acquire the mutex waiting if necessary.
Definition worldmutex.h:155
Range, vaguely a la Intel TBB, to encapsulate a random-access, STL-like start and end iterator with c...
Definition range.h:64
Simple structure used to manage references/pointers to remote instances.
Definition worldref.h:395
Definition SVDTensor.h:42
A simple process map.
Definition funcimpl.h:86
SimplePmap(World &world)
Definition funcimpl.h:92
const int nproc
Definition funcimpl.h:88
const ProcessID me
Definition funcimpl.h:89
ProcessID owner(const keyT &key) const
Maps key to processor.
Definition funcimpl.h:95
A slice defines a sub-range or patch of a dimension.
Definition slice.h:103
static TaskAttributes hipri()
Definition thread.h:456
Traits class to specify support of numeric types.
Definition type_data.h:56
A tensor is a multidimensional array.
Definition tensor.h:318
float_scalar_type normf() const
Returns the Frobenius norm of the tensor.
Definition tensor.h:1727
Tensor< T > & gaxpy(T alpha, const Tensor< T > &other, T beta)
Inplace generalized saxpy ... this = this*alpha + other*beta.
Definition tensor.h:1806
T sum() const
Returns the sum of all elements of the tensor.
Definition tensor.h:1663
Tensor< T > reshape(int ndimnew, const long *d)
Returns new view/tensor reshaping size/number of dimensions to conforming tensor.
Definition tensor.h:1385
T * ptr()
Returns a pointer to the internal data.
Definition tensor.h:1841
Tensor< T > mapdim(const std::vector< long > &map)
Returns new view/tensor permuting the dimensions.
Definition tensor.h:1625
IsSupported< TensorTypeData< Q >, Tensor< T > & >::type scale(Q x)
Inplace multiplication by scalar of supported type (legacy name)
Definition tensor.h:687
Tensor< T > & emul(const Tensor< T > &t)
Inplace multiply by corresponding elements of argument Tensor.
Definition tensor.h:1800
bool has_data() const
Definition tensor.h:1903
Tensor< T > fusedim(long i)
Returns new view/tensor fusing contiguous dimensions i and i+1.
Definition tensor.h:1588
Tensor< T > flat()
Returns new view/tensor rehshaping to flat (1-d) tensor.
Definition tensor.h:1556
Tensor< T > & conj()
Inplace complex conjugate.
Definition tensor.h:717
Definition function_common_data.h:169
void accumulate(const double time) const
accumulate timer
Definition function_common_data.h:183
A simple, fixed dimension vector.
Definition vector.h:64
Makes a distributed container with specified attributes.
Definition worlddc.h:1231
void process_pending()
Process pending messages.
Definition worlddc.h:1574
bool find(accessor &acc, const keyT &key)
Write access to LOCAL value by key. Returns true if found, false otherwise (always false for remote).
Definition worlddc.h:1395
bool probe(const keyT &key) const
Returns true if local data is immediately available (no communication)
Definition worlddc.h:1432
iterator begin()
Returns an iterator to the beginning of the local data (no communication)
Definition worlddc.h:1478
bool is_replicated() const
Definition worlddc.h:1331
ProcessID owner(const keyT &key) const
Returns processor that logically owns key (no communication)
Definition worlddc.h:1442
implT::const_iterator const_iterator
Definition worlddc.h:1239
void replicate(bool fence=true)
replicates this WorldContainer on all ProcessIDs
Definition worlddc.h:1353
void erase(const keyT &key)
Erases entry from container (non-blocking comm if remote)
Definition worlddc.h:1513
void replace(const pairT &datum)
Inserts/replaces key+value pair (non-blocking communication if key not local)
Definition worlddc.h:1382
iterator end()
Returns an iterator past the end of the local data (no communication)
Definition worlddc.h:1492
const std::shared_ptr< WorldDCPmapInterface< keyT > > & get_pmap() const
Returns shared pointer to the process mapping.
Definition worlddc.h:1550
bool insert(accessor &acc, const keyT &key)
Write access to LOCAL value by key. Returns true if inserted, false if already exists (throws if remo...
Definition worlddc.h:1409
bool is_distributed() const
Definition worlddc.h:1327
implT::iterator iterator
Definition worlddc.h:1238
std::size_t size() const
Returns the number of local entries (no communication)
Definition worlddc.h:1543
Future< REMFUTURE(MEMFUN_RETURNT(memfunT))> task(const keyT &key, memfunT memfun, const TaskAttributes &attr=TaskAttributes())
Adds task "resultT memfun()" in process owning item (non-blocking comm if remote)
Definition worlddc.h:1834
bool is_local(const keyT &key) const
Returns true if the key maps to the local processor (no communication)
Definition worlddc.h:1449
bool is_host_replicated() const
Definition worlddc.h:1335
Future< MEMFUN_RETURNT(memfunT)> send(const keyT &key, memfunT memfun)
Sends message "resultT memfun()" to item (non-blocking comm if remote)
Definition worlddc.h:1591
void replicate_on_hosts(bool fence=true)
replicates this WorldContainer on all hosts (one PID per host)
Definition worlddc.h:1359
implT::accessor accessor
Definition worlddc.h:1240
Interface to be provided by any process map.
Definition worlddc.h:125
void fence(bool debug=false)
Synchronizes all processes in communicator AND globally ensures no pending AM or tasks.
Definition worldgop.cc:176
Implements most parts of a globally addressable object (via unique ID).
Definition world_object.h:491
void process_pending()
To be called from derived constructor to process pending messages.
Definition world_object.h:787
ProcessID me
Rank of self.
Definition world_object.h:514
detail::task_result_type< memfnT >::futureT send(ProcessID dest, memfnT memfn) const
Definition world_object.h:858
detail::task_result_type< memfnT >::futureT task(ProcessID dest, memfnT memfn, const TaskAttributes &attr=TaskAttributes()) const
Sends task to derived class method returnT (this->*memfn)().
Definition world_object.h:1132
Future< bool > for_each(const rangeT &range, const opT &op)
Apply op(item) on all items in range.
Definition world_task_queue.h:572
void add(TaskInterface *t)
Add a new local task, taking ownership of the pointer.
Definition world_task_queue.h:466
Future< resultT > reduce(const rangeT &range, const opT &op)
Reduce op(item) for all items in range using op(sum,op(item)).
Definition world_task_queue.h:527
A parallel world class.
Definition world.h:134
static World * world_from_id(std::uint64_t id)
Convert a World ID to a World pointer.
Definition world.h:516
WorldTaskQueue & taskq
Task queue.
Definition world.h:215
std::vector< uniqueidT > get_object_ids() const
Returns a vector of all unique IDs in this World.
Definition world.h:492
ProcessID rank() const
Returns the process rank in this World (same as MPI_Comm_rank()).
Definition world.h:344
static std::vector< unsigned long > get_world_ids()
return a vector containing all world ids
Definition world.h:500
ProcessID size() const
Returns the number of processes in this World (same as MPI_Comm_size()).
Definition world.h:354
unsigned long id() const
Definition world.h:324
WorldGopInterface & gop
Global operations.
Definition world.h:216
std::optional< T * > ptr_from_id(uniqueidT id) const
Look up a local pointer from a world-wide unique ID.
Definition world.h:440
ProcessID random_proc()
Returns a random process number; that is, an integer in [0,world.size()).
Definition world.h:615
Wraps an archive around an STL vector for input.
Definition vector_archive.h:101
Wraps an archive around an STL vector for output.
Definition vector_archive.h:55
Wrapper for an opaque pointer for serialization purposes.
Definition archive.h:851
syntactic sugar for std::array<bool, N>
Definition array_of_bools.h:19
Class for unique global IDs.
Definition uniqueid.h:53
unsigned long get_obj_id() const
Access the object ID.
Definition uniqueid.h:97
unsigned long get_world_id() const
Access the World ID.
Definition uniqueid.h:90
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
static double lo
Definition dirac-hatom.cc:23
@ upper
Definition dirac-hatom.cc:15
Provides FunctionDefaults and utilities for coordinate transformation.
archive_array< unsigned char > wrap_opaque(const T *, unsigned int)
Factory function to wrap a pointer to contiguous data as an opaque (uchar) archive_array.
Definition archive.h:926
Tensor< typename Tensor< T >::scalar_type > arg(const Tensor< T > &t)
Return a new tensor holding the argument of each element of t (complex types only)
Definition tensor.h:2643
Tensor< TENSOR_RESULT_TYPE(T, Q) > & fast_transform(const Tensor< T > &t, const Tensor< Q > &c, Tensor< TENSOR_RESULT_TYPE(T, Q) > &result, Tensor< TENSOR_RESULT_TYPE(T, Q) > &workspace)
Restricted but heavily optimized form of transform()
Definition tensor.h:2460
const double beta
Definition gygi_soltion.cc:62
static const double v
Definition hatom_sf_dirac.cc:20
Provides IndexIterator.
Tensor< double > op(const Tensor< double > &x)
Definition kain.cc:508
Multidimension Key for MRA tree and associated iterators.
static double pow(const double *a, const double *b)
Definition lda.h:74
#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
Header to declare stuff which has not yet found a home.
constexpr double pi
Mathematical constant .
Definition constants.h:48
MemFuncWrapper< objT *, memfnT, typename result_of< memfnT >::type > wrap_mem_fn(objT &obj, memfnT memfn)
Create a member function wrapper (MemFuncWrapper) from an object and a member function pointer.
Definition mem_func_wrapper.h:251
void combine_hash(hashT &seed, hashT hash)
Internal use only.
Definition worldhash.h:248
Namespace for all elements and tools of MADNESS.
Definition DFParameters.h:13
std::ostream & operator<<(std::ostream &os, const particle< PDIM > &p)
Definition lowrankfunction.h:401
static const char * filename
Definition legendre.cc:96
static const std::vector< Slice > ___
Entire dimension.
Definition slice.h:124
static double cpu_time()
Returns the cpu time in seconds relative to an arbitrary origin.
Definition timers.h:128
GenTensor< TENSOR_RESULT_TYPE(R, Q)> general_transform(const GenTensor< R > &t, const Tensor< Q > c[])
Definition gentensor.h:274
bool nearlyEqual(double a, double b, double epsilon=1e-9)
Definition numerics.cc:11
void finalize()
Call this once at the very end of your main program instead of MPI_Finalize().
Definition world.cc:246
void norm_tree(World &world, const std::vector< Function< T, NDIM > > &v, bool fence=true)
Makes the norm tree for all functions in a vector.
Definition vmra.h:1306
std::vector< Function< TENSOR_RESULT_TYPE(T, R), NDIM > > transform(World &world, const std::vector< Function< T, NDIM > > &v, const Tensor< R > &c, bool fence=true)
Transforms a vector of functions according to new[i] = sum[j] old[j]*c[j,i].
Definition vmra.h:758
TreeState
Definition funcdefaults.h:59
@ nonstandard_after_apply
s and d coeffs, state after operator application
Definition funcdefaults.h:64
@ redundant_after_merge
s coeffs everywhere, must be summed up to yield the result
Definition funcdefaults.h:66
@ reconstructed
s coeffs at the leaves only
Definition funcdefaults.h:60
@ nonstandard
s and d coeffs in internal nodes
Definition funcdefaults.h:62
@ redundant
s coeffs everywhere
Definition funcdefaults.h:65
static Tensor< double > weights[max_npt+1]
Definition legendre.cc:99
int64_t Translation
Definition key.h:58
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:533
static const Slice _(0,-1, 1)
std::shared_ptr< FunctionFunctorInterface< double, 3 > > func(new opT(g))
int Level
Definition key.h:59
std::enable_if< std::is_base_of< ProjectorBase, projT >::value, OuterProjector< projT, projQ > >::type outer(const projT &p0, const projQ &p1)
Definition projector.h:457
static constexpr double NORM_TREE_UNCOMPUTED
Definition funcimpl.h:127
int RandomValue< int >()
Random int.
Definition ran.cc:250
bool has_data(const PropertyResults &p)
Definition Results.h:413
static constexpr double MUL_SCREENING_SAFETY
Definition funcimpl.h:132
static double pop(std::vector< double > &v)
Definition SCF.cc:117
void print(const T &t, const Ts &... ts)
Print items to std::cout (items separated by spaces) and terminate with a new line.
Definition print.h:227
Tensor< T > fcube(const Key< NDIM > &, T(*f)(const Vector< double, NDIM > &), const Tensor< double > &)
Definition mraimpl.h:2175
TensorType
low rank representations of tensors (see gentensor.h)
Definition gentensor.h:120
@ TT_2D
Definition gentensor.h:120
@ TT_FULL
Definition gentensor.h:120
NDIM & f
Definition mra.h:2620
void error(const char *msg)
Definition world.cc:147
NDIM const Function< R, NDIM > & g
Definition mra.h:2620
std::size_t hashT
The hash value type.
Definition worldhash.h:145
void change_tensor_type(GenTensor< T > &, const TensorArgs &targs)
change representation to targ.tt
Definition gentensor.h:284
static const int kmax
Definition twoscale.cc:52
GenTensor< TENSOR_RESULT_TYPE(R, Q)> transform_dir(const GenTensor< R > &t, const Tensor< Q > &c, const int axis)
Definition lowranktensor.h:1106
Function< T, CCPairFunction< T, NDIM >::LDIM > inner(const CCPairFunction< T, NDIM > &c, const Function< T, CCPairFunction< T, NDIM >::LDIM > &f, const std::tuple< int, int, int > v1, const std::tuple< int, int, int > v2)
Definition ccpairfunction.h:993
void scale(World &world, std::vector< Function< T, NDIM > > &v, const std::vector< Q > &factors, bool fence=true)
Scales inplace a vector of functions by distinct values.
Definition vmra.h:874
std::string name(const FuncType &type, const int ex=-1)
Definition ccpairfunction.h:28
void mxmT(long dimi, long dimj, long dimk, T *MADNESS_RESTRICT c, const T *a, const T *b)
Matrix += Matrix * matrix transpose ... MKL interface version.
Definition mxm.h:225
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:2185
static const int MAXK
The maximum wavelet order presently supported.
Definition funcdefaults.h:54
Definition mraimpl.h:51
static long abs(long a)
Definition tensor.h:219
const double cc
Definition navstokes_cosines.cc:107
static const double b
Definition nonlinschro.cc:119
static const double d
Definition nonlinschro.cc:121
static const double a
Definition nonlinschro.cc:118
Defines simple templates for printing to std::cout "a la Python".
double Q(double a)
Definition relops.cc:20
static const double c
Definition relops.cc:10
static const double L
Definition rk.cc:46
static const double thresh
Definition rk.cc:45
Definition test_ar.cc:204
Definition test_dc.cc:47
Key parent() const
Definition test_tree.cc:68
hashT hash() const
Definition test_dc.cc:54
Definition test_ccpairfunction.cc:22
given a ket and the 1- and 2-electron potentials, construct the function V phi
Definition funcimpl.h:4227
implT * result
where to construct Vphi, no need to track parents
Definition funcimpl.h:4235
bool have_v2() const
Definition funcimpl.h:4244
ctL iav1
Definition funcimpl.h:4239
Vphi_op_NS(implT *result, const opT &leaf_op, const ctT &iaket, const ctL &iap1, const ctL &iap2, const ctL &iav1, const ctL &iav2, const implT *eri)
Definition funcimpl.h:4253
ctL iap1
Definition funcimpl.h:4238
bool have_v1() const
Definition funcimpl.h:4243
std::pair< bool, coeffT > continue_recursion(const std::vector< bool > child_is_leaf, const tensorT &coeffs, const keyT &key) const
loop over all children and either insert their sum coeffs or continue the recursion
Definition funcimpl.h:4319
opT leaf_op
deciding if a given FunctionNode will be a leaf node
Definition funcimpl.h:4236
std::pair< coeffT, double > make_sum_coeffs(const keyT &key) const
make the sum coeffs for key
Definition funcimpl.h:4412
CoeffTracker< T, NDIM > ctT
Definition funcimpl.h:4232
ctL iap2
the particles 1 and 2 (exclusive with ket)
Definition funcimpl.h:4238
bool have_ket() const
Definition funcimpl.h:4242
const implT * eri
2-particle potential, must be on-demand
Definition funcimpl.h:4240
CoeffTracker< T, LDIM > ctL
Definition funcimpl.h:4233
std::pair< bool, coeffT > operator()(const Key< NDIM > &key) const
make and insert the coefficients into result's tree
Definition funcimpl.h:4264
void serialize(const Archive &ar)
serialize this (needed for use in recursive_op)
Definition funcimpl.h:4493
Vphi_op_NS< opT, LDIM > this_type
Definition funcimpl.h:4231
ctT iaket
the ket of a pair function (exclusive with p1, p2)
Definition funcimpl.h:4237
double compute_error_from_inaccurate_refinement(const keyT &key, const tensorT &ceri) const
the error is computed from the d coefficients of the constituent functions
Definition funcimpl.h:4365
void accumulate_into_result(const Key< NDIM > &key, const coeffT &coeff) const
Definition funcimpl.h:4247
this_type make_child(const keyT &child) const
Definition funcimpl.h:4464
tensorT eri_coeffs(const keyT &key) const
Definition funcimpl.h:4345
ctL iav2
potentials for particles 1 and 2
Definition funcimpl.h:4239
bool have_eri() const
Definition funcimpl.h:4245
this_type forward_ctor(implT *result1, const opT &leaf_op, const ctT &iaket1, const ctL &iap11, const ctL &iap21, const ctL &iav11, const ctL &iav21, const implT *eri1)
Definition funcimpl.h:4486
Vphi_op_NS()
Definition funcimpl.h:4252
Future< this_type > activate() const
Definition funcimpl.h:4475
bool randomize() const
Definition funcimpl.h:4229
add two functions f and g: result=alpha * f + beta * g
Definition funcimpl.h:3737
bool randomize() const
Definition funcimpl.h:3742
Future< this_type > activate() const
retrieve the coefficients (parent coeffs might be remote)
Definition funcimpl.h:3772
add_op(const ctT &f, const ctT &g, const double alpha, const double beta)
Definition funcimpl.h:3750
ctT f
tracking coeffs of first and second addend
Definition funcimpl.h:3745
double alpha
prefactor for f, g
Definition funcimpl.h:3747
add_op this_type
Definition funcimpl.h:3740
CoeffTracker< T, NDIM > ctT
Definition funcimpl.h:3739
void serialize(const Archive &ar)
Definition funcimpl.h:3784
ctT g
Definition funcimpl.h:3745
std::pair< bool, coeffT > operator()(const keyT &key) const
if we are at the bottom of the trees, return the sum of the coeffs
Definition funcimpl.h:3754
double beta
Definition funcimpl.h:3747
this_type make_child(const keyT &child) const
Definition funcimpl.h:3767
this_type forward_ctor(const ctT &f1, const ctT &g1, const double alpha, const double beta)
taskq-compatible ctor
Definition funcimpl.h:3780
opT op
Definition funcimpl.h:3326
opT::resultT resultT
Definition funcimpl.h:3324
Tensor< resultT > operator()(const Key< NDIM > &key, const Tensor< Q > &t) const
Definition funcimpl.h:3333
coeff_value_adaptor(const FunctionImpl< Q, NDIM > *impl_func, const opT &op)
Definition funcimpl.h:3329
const FunctionImpl< Q, NDIM > * impl_func
Definition funcimpl.h:3325
void serialize(Archive &ar)
Definition funcimpl.h:3342
merge the coefficent boxes of this into result's tree
Definition funcimpl.h:2539
Range< typename dcT::const_iterator > rangeT
Definition funcimpl.h:2540
void serialize(const Archive &ar)
Definition funcimpl.h:2557
FunctionImpl< Q, NDIM > * result
Definition funcimpl.h:2541
do_accumulate_trees(FunctionImpl< Q, NDIM > &result, const T alpha)
Definition funcimpl.h:2544
T alpha
Definition funcimpl.h:2542
bool operator()(typename rangeT::iterator &it) const
return the norm of the difference of this node and its "mirror" node
Definition funcimpl.h:2548
"put" this on g
Definition funcimpl.h:2750
Range< typename dcT::const_iterator > rangeT
Definition funcimpl.h:2751
void serialize(const Archive &ar)
Definition funcimpl.h:2779
implT * g
Definition funcimpl.h:2753
do_average()
Definition funcimpl.h:2755
bool operator()(typename rangeT::iterator &it) const
iterator it points to this
Definition funcimpl.h:2759
do_average(implT &g)
Definition funcimpl.h:2756
change representation of nodes' coeffs to low rank, optional fence
Definition funcimpl.h:2783
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2784
void serialize(const Archive &ar)
Definition funcimpl.h:2807
TensorArgs targs
Definition funcimpl.h:2787
do_change_tensor_type(const TensorArgs &targs, implT &g)
Definition funcimpl.h:2793
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2796
implT * f
Definition funcimpl.h:2788
check symmetry wrt particle exchange
Definition funcimpl.h:2456
Range< typename dcT::const_iterator > rangeT
Definition funcimpl.h:2457
double operator()(typename rangeT::iterator &it) const
return the norm of the difference of this node and its "mirror" node
Definition funcimpl.h:2463
do_check_symmetry_local()
Definition funcimpl.h:2459
void serialize(const Archive &ar)
Definition funcimpl.h:2526
double operator()(double a, double b) const
Definition funcimpl.h:2522
do_check_symmetry_local(const implT &f)
Definition funcimpl.h:2460
const implT * f
Definition funcimpl.h:2458
compute the norm of the wavelet coefficients
Definition funcimpl.h:4634
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:4635
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:4641
do_compute_snorm_and_dnorm(const FunctionCommonData< T, NDIM > &cdata)
Definition funcimpl.h:4638
const FunctionCommonData< T, NDIM > & cdata
Definition funcimpl.h:4637
TensorArgs targs
Definition funcimpl.h:2814
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2819
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2811
do_consolidate_buffer(const TensorArgs &targs)
Definition funcimpl.h:2818
void serialize(const Archive &ar)
Definition funcimpl.h:2823
double operator()(double val) const
Definition funcimpl.h:1575
double limit
Definition funcimpl.h:1570
do_convert_to_color(const double limit, const bool log)
Definition funcimpl.h:1574
bool log
Definition funcimpl.h:1571
static double lower()
Definition funcimpl.h:1572
compute the inner product of this range with other
Definition funcimpl.h:5976
do_dot_local(const FunctionImpl< R, NDIM > *other, const bool leaves_only)
Definition funcimpl.h:5981
bool leaves_only
Definition funcimpl.h:5978
typedef TENSOR_RESULT_TYPE(T, R) resultT
resultT operator()(resultT a, resultT b) const
Definition funcimpl.h:6009
const FunctionImpl< R, NDIM > * other
Definition funcimpl.h:5977
void serialize(const Archive &ar)
Definition funcimpl.h:6013
resultT operator()(typename dcT::const_iterator &it) const
Definition funcimpl.h:5983
functor for the gaxpy_inplace method
Definition funcimpl.h:1357
FunctionImpl< T, NDIM > * f
prefactor for current function impl
Definition funcimpl.h:1359
do_gaxpy_inplace(FunctionImpl< T, NDIM > *f, T alpha, R beta)
Definition funcimpl.h:1363
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:1364
R beta
prefactor for other function impl
Definition funcimpl.h:1361
void serialize(Archive &ar)
Definition funcimpl.h:1372
Range< typename FunctionImpl< Q, NDIM >::dcT::const_iterator > rangeT
Definition funcimpl.h:1358
T alpha
the current function impl
Definition funcimpl.h:1360
const bool do_leaves
start with leaf nodes instead of initial_level
Definition funcimpl.h:6902
T operator()(T a, T b) const
Definition funcimpl.h:6920
do_inner_ext_local_ffi(const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > f, const implT *impl, const bool leaf_refine, const bool do_leaves)
Definition funcimpl.h:6904
void serialize(const Archive &ar)
Definition funcimpl.h:6924
const bool leaf_refine
Definition funcimpl.h:6901
const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > fref
Definition funcimpl.h:6899
T operator()(typename dcT::const_iterator &it) const
Definition funcimpl.h:6908
const implT * impl
Definition funcimpl.h:6900
compute the inner product of this range with other
Definition funcimpl.h:5839
const FunctionImpl< T, NDIM > * bra
Definition funcimpl.h:5840
void serialize(const Archive &ar)
Definition funcimpl.h:5955
const FunctionImpl< R, NDIM > * ket
Definition funcimpl.h:5841
bool leaves_only
Definition funcimpl.h:5842
do_inner_local_on_demand(const FunctionImpl< T, NDIM > *bra, const FunctionImpl< R, NDIM > *ket, const bool leaves_only=true)
Definition funcimpl.h:5845
resultT operator()(resultT a, resultT b) const
Definition funcimpl.h:5951
resultT operator()(typename dcT::const_iterator &it) const
Definition funcimpl.h:5848
compute the inner product of this range with other
Definition funcimpl.h:5778
resultT operator()(resultT a, resultT b) const
Definition funcimpl.h:5811
bool leaves_only
Definition funcimpl.h:5780
void serialize(const Archive &ar)
Definition funcimpl.h:5815
do_inner_local(const FunctionImpl< R, NDIM > *other, const bool leaves_only)
Definition funcimpl.h:5783
const FunctionImpl< R, NDIM > * other
Definition funcimpl.h:5779
resultT operator()(typename dcT::const_iterator &it) const
Definition funcimpl.h:5785
typedef TENSOR_RESULT_TYPE(T, R) resultT
keep only the sum coefficients in each node
Definition funcimpl.h:2410
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2411
do_keep_sum_coeffs(implT *impl)
constructor need impl for cdata
Definition funcimpl.h:2415
implT * impl
Definition funcimpl.h:2412
void serialize(const Archive &ar)
Definition funcimpl.h:2424
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2417
mirror dimensions of this, write result on f
Definition funcimpl.h:2684
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2694
implT * f
Definition funcimpl.h:2688
std::vector< long > mirror
Definition funcimpl.h:2687
void serialize(const Archive &ar)
Definition funcimpl.h:2741
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2685
std::vector< long > map
Definition funcimpl.h:2687
do_map_and_mirror(const std::vector< long > map, const std::vector< long > mirror, implT &f)
Definition funcimpl.h:2691
map this on f
Definition funcimpl.h:2604
do_mapdim(const std::vector< long > map, implT &f)
Definition funcimpl.h:2611
void serialize(const Archive &ar)
Definition funcimpl.h:2627
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2605
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2613
std::vector< long > map
Definition funcimpl.h:2607
do_mapdim()
Definition funcimpl.h:2610
implT * f
Definition funcimpl.h:2608
merge the coefficient boxes of this into other's tree
Definition funcimpl.h:2568
bool operator()(typename rangeT::iterator &it) const
return the norm of the difference of this node and its "mirror" node
Definition funcimpl.h:2578
Range< typename dcT::const_iterator > rangeT
Definition funcimpl.h:2569
FunctionImpl< Q, NDIM > * other
Definition funcimpl.h:2570
do_merge_trees(const T alpha, const R beta, FunctionImpl< Q, NDIM > &other)
Definition funcimpl.h:2574
T alpha
Definition funcimpl.h:2571
do_merge_trees()
Definition funcimpl.h:2573
R beta
Definition funcimpl.h:2572
void serialize(const Archive &ar)
Definition funcimpl.h:2597
mirror dimensions of this, write result on f
Definition funcimpl.h:2634
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2643
implT * f
Definition funcimpl.h:2638
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2635
do_mirror()
Definition funcimpl.h:2640
do_mirror(const std::vector< long > mirror, implT &f)
Definition funcimpl.h:2641
void serialize(const Archive &ar)
Definition funcimpl.h:2677
std::vector< long > mirror
Definition funcimpl.h:2637
Definition funcimpl.h:5751
double operator()(typename dcT::const_iterator &it) const
Definition funcimpl.h:5752
void serialize(const Archive &ar)
Definition funcimpl.h:5767
double operator()(double a, double b) const
Definition funcimpl.h:5763
laziness
Definition funcimpl.h:4893
void serialize(Archive &ar)
Definition funcimpl.h:4902
Key< OPDIM > d
Definition funcimpl.h:4894
Key< OPDIM > key
Definition funcimpl.h:4894
keyT dest
Definition funcimpl.h:4895
double fac
Definition funcimpl.h:4896
do_op_args(const Key< OPDIM > &key, const Key< OPDIM > &d, const keyT &dest, double tol, double fac, double cnorm)
Definition funcimpl.h:4899
double cnorm
Definition funcimpl.h:4896
double tol
Definition funcimpl.h:4896
reduce the rank of the nodes, optional fence
Definition funcimpl.h:2430
do_reduce_rank(const TensorArgs &targs)
Definition funcimpl.h:2438
TensorArgs args
Definition funcimpl.h:2434
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2444
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2431
do_reduce_rank(const double &thresh)
Definition funcimpl.h:2439
void serialize(const Archive &ar)
Definition funcimpl.h:2450
Changes non-standard compressed form to standard compressed form.
Definition funcimpl.h:4857
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:4868
do_standard(implT *impl)
Definition funcimpl.h:4865
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:4858
void serialize(const Archive &ar)
Definition funcimpl.h:4885
implT * impl
Definition funcimpl.h:4861
given an NS tree resulting from a convolution, truncate leafs if appropriate
Definition funcimpl.h:2351
void serialize(const Archive &ar)
Definition funcimpl.h:2371
const implT * f
Definition funcimpl.h:2353
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2357
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2352
do_truncate_NS_leafs(const implT *f)
Definition funcimpl.h:2355
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2830
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2834
implT * impl
Definition funcimpl.h:2831
void serialize(const Archive &ar)
Definition funcimpl.h:2852
do_unary_op_value_inplace(implT *impl, const opT &op)
Definition funcimpl.h:2833
Hartree product of two LDIM functions to yield a NDIM = 2*LDIM function.
Definition funcimpl.h:3820
this_type forward_ctor(implT *result1, const ctL &p11, const ctL &p22, const leaf_opT &leaf_op)
Definition funcimpl.h:3876
bool randomize() const
Definition funcimpl.h:3821
void serialize(const Archive &ar)
Definition funcimpl.h:3880
hartree_op(implT *result, const ctL &p11, const ctL &p22, const leaf_opT &leaf_op)
Definition funcimpl.h:3832
CoeffTracker< T, LDIM > ctL
Definition funcimpl.h:3824
ctL p2
tracking coeffs of the two lo-dim functions
Definition funcimpl.h:3827
leaf_opT leaf_op
determine if a given node will be a leaf node
Definition funcimpl.h:3828
hartree_op()
Definition funcimpl.h:3831
implT * result
where to construct the pair function
Definition funcimpl.h:3826
hartree_op< LDIM, leaf_opT > this_type
Definition funcimpl.h:3823
std::pair< bool, coeffT > operator()(const Key< NDIM > &key) const
Definition funcimpl.h:3837
ctL p1
Definition funcimpl.h:3827
this_type make_child(const keyT &child) const
Definition funcimpl.h:3860
Future< this_type > activate() const
Definition funcimpl.h:3869
perform this multiplication: h(1,2) = f(1,2) * g(1)
Definition funcimpl.h:3628
multiply_op()
Definition funcimpl.h:3640
ctL g
Definition funcimpl.h:3637
Future< this_type > activate() const
Definition funcimpl.h:3719
CoeffTracker< T, LDIM > ctL
Definition funcimpl.h:3632
implT * h
the result function h(1,2) = f(1,2) * g(1)
Definition funcimpl.h:3635
CoeffTracker< T, NDIM > ctT
Definition funcimpl.h:3631
std::pair< bool, coeffT > operator()(const Key< NDIM > &key) const
apply this on a FunctionNode of f and g of Key key
Definition funcimpl.h:3667
this_type forward_ctor(implT *h1, const ctT &f1, const ctL &g1, const int particle)
Definition funcimpl.h:3726
static bool randomize()
Definition funcimpl.h:3630
int particle
if g is g(1) or g(2)
Definition funcimpl.h:3638
ctT f
Definition funcimpl.h:3636
multiply_op< LDIM > this_type
Definition funcimpl.h:3633
multiply_op(implT *h1, const ctT &f1, const ctL &g1, const int particle1)
Definition funcimpl.h:3642
bool screen(const coeffT &fcoeff, const coeffT &gcoeff, const keyT &key) const
return true if this will be a leaf node
Definition funcimpl.h:3648
this_type make_child(const keyT &child) const
Definition funcimpl.h:3709
void serialize(const Archive &ar)
Definition funcimpl.h:3730
coeffT val_lhs
Definition funcimpl.h:4107
double lo
Definition funcimpl.h:4110
double lo1
Definition funcimpl.h:4110
long oversampling
Definition funcimpl.h:4108
double error
Definition funcimpl.h:4109
tensorT operator()(const Key< NDIM > key, const tensorT &coeff_rhs)
multiply values of rhs and lhs, result on rhs, rhs and lhs are of the same dimensions
Definition funcimpl.h:4125
coeffT coeff_lhs
Definition funcimpl.h:4107
void serialize(const Archive &ar)
Definition funcimpl.h:4213
double lo2
Definition funcimpl.h:4110
double hi1
Definition funcimpl.h:4110
pointwise_multiplier(const Key< NDIM > key, const coeffT &clhs)
Definition funcimpl.h:4113
coeffT operator()(const Key< NDIM > key, const tensorT &coeff_rhs, const int particle)
multiply values of rhs and lhs, result on rhs, rhs and lhs are of differnet dimensions
Definition funcimpl.h:4170
double hi2
Definition funcimpl.h:4110
double hi
Definition funcimpl.h:4110
project the low-dim function g on the hi-dim function f: result(x) = <f(x,y) | g(y)>
Definition funcimpl.h:7164
project_out_op(const implT *fimpl, implL1 *result, const ctL &iag, const int dim)
Definition funcimpl.h:7179
ctL iag
the low dim function g
Definition funcimpl.h:7174
FunctionImpl< T, NDIM-LDIM > implL1
Definition funcimpl.h:7169
Future< this_type > activate() const
retrieve the coefficients (parent coeffs might be remote)
Definition funcimpl.h:7258
std::pair< bool, coeffT > argT
Definition funcimpl.h:7170
const implT * fimpl
the hi dim function f
Definition funcimpl.h:7172
this_type forward_ctor(const implT *fimpl1, implL1 *result1, const ctL &iag1, const int dim1)
taskq-compatible ctor
Definition funcimpl.h:7265
this_type make_child(const keyT &child) const
Definition funcimpl.h:7249
project_out_op< LDIM > this_type
Definition funcimpl.h:7167
implL1 * result
the low dim result function
Definition funcimpl.h:7173
Future< argT > operator()(const Key< NDIM > &key) const
do the actual contraction
Definition funcimpl.h:7186
void serialize(const Archive &ar)
Definition funcimpl.h:7269
project_out_op(const project_out_op &other)
Definition funcimpl.h:7181
int dim
0: project 0..LDIM-1, 1: project LDIM..NDIM-1
Definition funcimpl.h:7175
bool randomize() const
Definition funcimpl.h:7165
CoeffTracker< T, LDIM > ctL
Definition funcimpl.h:7168
recursive part of recursive_apply
Definition funcimpl.h:5578
ctT iaf
Definition funcimpl.h:5586
recursive_apply_op2< opT > this_type
Definition funcimpl.h:5581
Future< this_type > activate() const
retrieve the coefficients (parent coeffs might be remote)
Definition funcimpl.h:5641
const opT * apply_op
need this for randomization
Definition funcimpl.h:5587
bool randomize() const
Definition funcimpl.h:5579
recursive_apply_op2(const recursive_apply_op2 &other)
Definition funcimpl.h:5594
void serialize(const Archive &ar)
Definition funcimpl.h:5657
argT finalize(const double kernel_norm, const keyT &key, const coeffT &coeff, const implT *r) const
sole purpose is to wait for the kernel norm, wrap it and send it back to caller
Definition funcimpl.h:5627
this_type make_child(const keyT &child) const
Definition funcimpl.h:5636
recursive_apply_op2(implT *result, const ctT &iaf, const opT *apply_op)
Definition funcimpl.h:5591
std::pair< bool, coeffT > argT
Definition funcimpl.h:5583
implT * result
Definition funcimpl.h:5585
CoeffTracker< T, NDIM > ctT
Definition funcimpl.h:5582
argT operator()(const Key< NDIM > &key) const
send off the application of the operator
Definition funcimpl.h:5603
this_type forward_ctor(implT *result1, const ctT &iaf1, const opT *apply_op1)
taskq-compatible ctor
Definition funcimpl.h:5653
recursive part of recursive_apply
Definition funcimpl.h:5447
std::pair< bool, coeffT > operator()(const Key< NDIM > &key) const
make the NS-coefficients and send off the application of the operator
Definition funcimpl.h:5472
this_type forward_ctor(implT *r, const CoeffTracker< T, LDIM > &f1, const CoeffTracker< T, LDIM > &g1, const opT *apply_op1)
Definition funcimpl.h:5537
opT * apply_op
Definition funcimpl.h:5455
recursive_apply_op(const recursive_apply_op &other)
Definition funcimpl.h:5465
recursive_apply_op< opT, LDIM > this_type
Definition funcimpl.h:5450
Future< this_type > activate() const
Definition funcimpl.h:5530
bool randomize() const
Definition funcimpl.h:5448
implT * result
Definition funcimpl.h:5452
CoeffTracker< T, LDIM > iaf
Definition funcimpl.h:5453
void serialize(const Archive &ar)
Definition funcimpl.h:5542
std::pair< bool, coeffT > finalize(const double kernel_norm, const keyT &key, const coeffT &coeff) const
sole purpose is to wait for the kernel norm, wrap it and send it back to caller
Definition funcimpl.h:5512
recursive_apply_op(implT *result, const CoeffTracker< T, LDIM > &iaf, const CoeffTracker< T, LDIM > &iag, const opT *apply_op)
Definition funcimpl.h:5459
this_type make_child(const keyT &child) const
Definition funcimpl.h:5521
CoeffTracker< T, LDIM > iag
Definition funcimpl.h:5454
remove all coefficients of internal nodes
Definition funcimpl.h:2376
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2377
remove_internal_coeffs()=default
constructor need impl for cdata
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2382
void serialize(const Archive &ar)
Definition funcimpl.h:2388
remove all coefficients of leaf nodes
Definition funcimpl.h:2393
bool operator()(typename rangeT::iterator &it) const
Definition funcimpl.h:2399
remove_leaf_coeffs()=default
constructor need impl for cdata
void serialize(const Archive &ar)
Definition funcimpl.h:2404
Range< typename dcT::iterator > rangeT
Definition funcimpl.h:2394
Definition funcimpl.h:4706
void serialize(Archive &ar)
Definition funcimpl.h:4710
bool operator()(const implT *f, const keyT &key, const nodeT &t) const
Definition funcimpl.h:4707
shallow-copy, pared-down version of FunctionNode, for special purpose only
Definition funcimpl.h:772
coeffT & coeff()
Definition funcimpl.h:786
GenTensor< T > coeffT
Definition funcimpl.h:773
bool is_leaf() const
Definition funcimpl.h:788
void serialize(Archive &ar)
Definition funcimpl.h:790
ShallowNode(const ShallowNode< T, NDIM > &node)
Definition funcimpl.h:781
ShallowNode(const FunctionNode< T, NDIM > &node)
Definition funcimpl.h:778
bool has_children() const
Definition funcimpl.h:787
ShallowNode()
Definition funcimpl.h:777
bool _has_children
Definition funcimpl.h:775
double dnorm
Definition funcimpl.h:776
const coeffT & coeff() const
Definition funcimpl.h:785
coeffT _coeffs
Definition funcimpl.h:774
TensorArgs holds the arguments for creating a LowRankTensor.
Definition gentensor.h:134
double thresh
Definition gentensor.h:135
TensorType tt
Definition gentensor.h:136
const uniqueidT & id() const
Returns the globally unique object ID.
Definition world_object.h:424
inserts/accumulates coefficients into impl's tree
Definition funcimpl.h:739
FunctionImpl< T, NDIM > * impl
Definition funcimpl.h:743
FunctionNode< T, NDIM > nodeT
Definition funcimpl.h:741
accumulate_op(const accumulate_op &other)=default
void operator()(const Key< NDIM > &key, const coeffT &coeff, const bool &is_leaf) const
Definition funcimpl.h:747
void serialize(Archive &ar)
Definition funcimpl.h:751
GenTensor< T > coeffT
Definition funcimpl.h:740
accumulate_op(FunctionImpl< T, NDIM > *f)
Definition funcimpl.h:745
static void load(const Archive &ar, FunctionImpl< T, NDIM > *&ptr)
Definition funcimpl.h:7491
static void load(const Archive &ar, const FunctionImpl< T, NDIM > *&ptr)
Definition funcimpl.h:7460
static void load(const Archive &ar, std::shared_ptr< FunctionImpl< T, NDIM > > &ptr)
Definition funcimpl.h:7542
static void load(const Archive &ar, std::shared_ptr< const FunctionImpl< T, NDIM > > &ptr)
Definition funcimpl.h:7526
Default load of an object via serialize(ar, t).
Definition archive.h:667
static void load(const A &ar, const U &t)
Load an object.
Definition archive.h:679
static void store(const Archive &ar, FunctionImpl< T, NDIM > *const &ptr)
Definition funcimpl.h:7516
static void store(const Archive &ar, const FunctionImpl< T, NDIM > *const &ptr)
Definition funcimpl.h:7482
static void store(const Archive &ar, const std::shared_ptr< FunctionImpl< T, NDIM > > &ptr)
Definition funcimpl.h:7551
static void store(const Archive &ar, const std::shared_ptr< const FunctionImpl< T, NDIM > > &ptr)
Definition funcimpl.h:7535
Default store of an object via serialize(ar, t).
Definition archive.h:612
static std::enable_if_t< is_output_archive_v< A > &&!std::is_function< U >::value &&(has_member_serialize_v< U, A >||has_nonmember_serialize_v< U, A >||has_freestanding_serialize_v< U, A >||has_freestanding_default_serialize_v< U, A >), void > store(const A &ar, const U &t)
Definition archive.h:622
Definition funcimpl.h:633
void serialize(Archive &ar)
Definition funcimpl.h:697
const opT * op
Definition funcimpl.h:640
hartree_convolute_leaf_op(const implT *f, const implL *g, const opT *op)
Definition funcimpl.h:644
bool operator()(const Key< NDIM > &key) const
no pre-determination
Definition funcimpl.h:648
bool operator()(const Key< NDIM > &key, const Tensor< T > &fcoeff, const Tensor< T > &gcoeff) const
post-determination: true if f is a leaf and the result is well-represented
Definition funcimpl.h:661
const implL * g
Definition funcimpl.h:639
const FunctionImpl< T, NDIM > * f
Definition funcimpl.h:638
FunctionImpl< T, LDIM > implL
Definition funcimpl.h:636
bool do_error_leaf_op() const
Definition funcimpl.h:641
FunctionImpl< T, NDIM > implT
Definition funcimpl.h:635
bool operator()(const Key< NDIM > &key, const GenTensor< T > &coeff) const
no post-determination
Definition funcimpl.h:651
returns true if the result of a hartree_product is a leaf node (compute norm & error)
Definition funcimpl.h:523
bool do_error_leaf_op() const
Definition funcimpl.h:528
const FunctionImpl< T, NDIM > * f
Definition funcimpl.h:526
hartree_leaf_op(const implT *f, const long &k)
Definition funcimpl.h:531
long k
Definition funcimpl.h:527
void serialize(Archive &ar)
Definition funcimpl.h:579
bool operator()(const Key< NDIM > &key, const GenTensor< T > &coeff) const
no post-determination
Definition funcimpl.h:537
bool operator()(const Key< NDIM > &key, const Tensor< T > &fcoeff, const Tensor< T > &gcoeff) const
post-determination: true if f is a leaf and the result is well-represented
Definition funcimpl.h:547
bool operator()(const Key< NDIM > &key) const
no pre-determination
Definition funcimpl.h:534
FunctionImpl< T, NDIM > implT
Definition funcimpl.h:525
insert/replaces the coefficients into the function
Definition funcimpl.h:715
insert_op()
Definition funcimpl.h:722
implT * impl
Definition funcimpl.h:721
void operator()(const keyT &key, const coeffT &coeff, const bool &is_leaf) const
Definition funcimpl.h:725
FunctionNode< T, NDIM > nodeT
Definition funcimpl.h:719
Key< NDIM > keyT
Definition funcimpl.h:717
insert_op(const insert_op &other)
Definition funcimpl.h:724
FunctionImpl< T, NDIM > implT
Definition funcimpl.h:716
GenTensor< T > coeffT
Definition funcimpl.h:718
insert_op(implT *f)
Definition funcimpl.h:723
void serialize(Archive &ar)
Definition funcimpl.h:729
Definition mra.h:112
Definition funcimpl.h:703
bool operator()(const Key< NDIM > &key, const GenTensor< T > &fcoeff, const GenTensor< T > &gcoeff) const
Definition funcimpl.h:705
void serialize(Archive &ar)
Definition funcimpl.h:709
void operator()(const Key< NDIM > &key, const GenTensor< T > &coeff, const bool &is_leaf) const
Definition funcimpl.h:704
Definition funcimpl.h:587
bool operator()(const Key< NDIM > &key, const double &cnorm) const
post-determination: return true if operator and coefficient norms are small
Definition funcimpl.h:608
void serialize(Archive &ar)
Definition funcimpl.h:623
const implT * f
the source or result function, needed for truncate_tol
Definition funcimpl.h:591
op_leaf_op(const opT *op, const implT *f)
Definition funcimpl.h:595
FunctionImpl< T, NDIM > implT
Definition funcimpl.h:588
const opT * op
the convolution operator
Definition funcimpl.h:590
bool do_error_leaf_op() const
Definition funcimpl.h:592
bool operator()(const Key< NDIM > &key) const
pre-determination: we can't know if this will be a leaf node before we got the final coeffs
Definition funcimpl.h:598
bool operator()(const Key< NDIM > &key, const GenTensor< T > &coeff) const
post-determination: return true if operator and coefficient norms are small
Definition funcimpl.h:601
Definition lowrankfunction.h:336
Definition funcimpl.h:759
void serialize(Archive &ar)
Definition funcimpl.h:766
bool operator()(const Key< NDIM > &key, const T &t, const R &r) const
Definition funcimpl.h:765
bool operator()(const Key< NDIM > &key, const T &t) const
Definition funcimpl.h:762
int np
Definition tdse1d.cc:165
static const double s0
Definition tdse4.cc:83
Defines and implements most of Tensor.
#define ITERATOR(t, exp)
Definition tensor_macros.h:249
#define IND
Definition tensor_macros.h:204
#define TERNARY_OPTIMIZED_ITERATOR(X, x, Y, y, Z, z, exp)
Definition tensor_macros.h:719
AtomicInt sum
Definition test_atomicint.cc:46
double norm(const T i1)
Definition test_cloud.cc:85
int task(int i)
Definition test_runtime.cpp:4
void e()
Definition test_sig.cc:75
static double g1(const Vector< double, D > &r)
Definition test_state_archive_hdf5.cpp:34
static const double alpha
Definition testcosine.cc:10
const double offset
Definition testfuns.cc:143
constexpr std::size_t NDIM
Definition testgconv.cc:54
double h(const coord_1d &r)
Definition testgconv.cc:175
std::size_t axis
Definition testpdiff.cc:59
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
#define PROFILE_BLOCK(name)
Definition worldprofile.h:208
int ProcessID
Used to clearly identify process number/rank.
Definition worldtypes.h:43