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