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