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