MADNESS 0.10.1
mraimpl.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_MRAIMPL_H__INCLUDED
33#define MADNESS_MRA_MRAIMPL_H__INCLUDED
34
35#ifndef MPRAIMPLX
36#error "mraimpl.h should ONLY be included in one of the mraX.cc files (x=1..6)"
37#endif
38
40#include <memory>
41#include <math.h>
42#include <cmath>
43#include <iomanip>
44#include <sstream>
49
52
53namespace std {
54 template <typename T>
55 bool isnan(const std::complex<T>& v) {
56 MADNESS_PRAGMA_CLANG(diagnostic push)
57 MADNESS_PRAGMA_CLANG(diagnostic ignored "-Wtautological-constant-compare")
58 return ::std::isnan(v.real()) || ::std::isnan(v.imag());
59 MADNESS_PRAGMA_CLANG(diagnostic pop)
60 }
61}
62
63/// \file mra/mraimpl.h
64/// \brief Declaration and initialization of static data, some implementation, some instantiation
65
66namespace madness {
67 // Definition and initialization of FunctionDefaults static members
68 // It cannot be an instance of FunctionFactory since we want to
69 // set the defaults independent of the data type.
70
71 template <typename T, std::size_t NDIM>
73 if (! two_scale_hg(k, &hg)) throw "failed to get twoscale coefficients";
74 hgT = copy(transpose(hg));
75
76 Slice sk(0,k-1), sk2(k,-1);
77 hgsonly = copy(hg(Slice(0,k-1),_));
78
79 h0 = copy(hg(sk,sk));
80 h1 = copy(hg(sk,sk2));
81 g0 = copy(hg(sk2,sk));
82 g1 = copy(hg(sk2,sk2));
83
84 h0T = copy(transpose(hg(sk,sk)));
85 h1T = copy(transpose(hg(sk,sk2)));
86 g0T = copy(transpose(hg(sk2,sk)));
87 g1T = copy(transpose(hg(sk2,sk2)));
88
89 }
90
91 template <typename T, std::size_t NDIM>
95 quad_x = Tensor<double>(npt); // point
96 quad_w = Tensor<double>(npt); // wheight
99
100 gauss_legendre(npt,0.0,1.0,quad_x.ptr(),quad_w.ptr());
101 for (int mu=0; mu<npt; ++mu) {
102 double phi[200];
104 for (int j=0; j<k; ++j) {
105 quad_phi(mu,j) = phi[j];
106 quad_phiw(mu,j) = quad_w(mu)*phi[j];
107 }
108 }
110 }
111
112 template <typename T, std::size_t NDIM>
115 world.gop.fence(); // Make sure nothing is going on
116 MADNESS_CHECK_THROW(verify_tree_state_local(),"inconsistent coefficients in tree node");
117 MADNESS_CHECK_THROW(verify_parents_and_children(),"missing parents or children");
118 }
119
120 template <typename T, std::size_t NDIM>
122
123 // Ensure that parents and children exist appropriately
124 for (const auto& [key, node] : coeffs) {
125
126 if (key.level() > 0) {
127 const keyT parent = key.parent();
128 typename dcT::const_iterator pit = coeffs.find(parent).get();
129 if (pit == coeffs.end()) {
130 print(world.rank(), "FunctionImpl: verify: MISSING PARENT",key,parent);
131 std::cout.flush();
132 return false;
133 MADNESS_EXCEPTION("FunctionImpl: verify: MISSING PARENT", 0);
134 }
135 const nodeT& pnode = pit->second;
136 if (!pnode.has_children()) {
137 print(world.rank(), "FunctionImpl: verify: PARENT THINKS IT HAS NO CHILDREN",key,parent);
138 return false;
139 std::cout.flush();
140 MADNESS_EXCEPTION("FunctionImpl: verify: PARENT THINKS IT HAS NO CHILDREN", 0);
141 }
142 }
143
144 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
145 typename dcT::const_iterator cit = coeffs.find(kit.key()).get();
146 if (cit == coeffs.end()) {
147 if (node.has_children()) {
148 print(world.rank(), "FunctionImpl: verify: MISSING CHILD",key,kit.key());
149 return false;
150 std::cout.flush();
151 MADNESS_EXCEPTION("FunctionImpl: verify: MISSING CHILD", 0);
152 }
153 }
154 else {
155 if (! node.has_children()) {
156 print(world.rank(), "FunctionImpl: verify: UNEXPECTED CHILD",key,kit.key());
157 return false;
158 std::cout.flush();
159 MADNESS_EXCEPTION("FunctionImpl: verify: UNEXPECTED CHILD", 0);
160 }
161 }
162 }
163 }
164 world.gop.fence();
165 return true;
166 }
167
168
169
170 template<typename T, std::size_t NDIM>
172
173 const TreeState state=get_tree_state();
174 const int k=get_k();
175
176 auto check_internal_coeff_size = [&state, &k](const coeffT& c) {
177 if (state==compressed or state==nonstandard or state==nonstandard_with_leaves)
178 return c.dim(0)==2*k;
179 if (state==redundant) return c.dim(0)==k;
180 if (state==reconstructed) return (not c.is_assigned()); // must not be assigned at all
181 if (state==redundant_after_merge or state==nonstandard_after_apply) return true;
182 MADNESS_EXCEPTION("unknown state",1);
183 };
184 auto check_leaf_coeff_size = [&state, &k](const coeffT& c) {
185 // citation from compress_spawn
186 // if (not keepleaves) node.clear_coeff();
187 if (state==reconstructed or state==redundant or state==redundant_after_merge or state==nonstandard_with_leaves)
188 return c.dim(0)==k;
189 if (state==compressed or state==nonstandard) return (not c.is_assigned()); // must not be assigned at all
190 if (state==nonstandard_after_apply) return true;
191 MADNESS_EXCEPTION("unknown state",1);
192 };
193
194 bool good=true;
195 for (const auto& [key, node] : coeffs) {
196 const auto& c=node.coeff();
197 const bool is_internal=node.has_children();
198 const bool is_leaf=not node.has_children();
199 if (is_internal) good=good and check_internal_coeff_size(c);
200 if (is_leaf) good=good and check_leaf_coeff_size(c);
201 if (not good) {
202 print("incorrect size of coefficients for key",key,"state",state,c.dim(0));;
203 }
204 }
205 return good;
206 }
207
208 template <typename T, std::size_t NDIM>
209 const std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > >& FunctionImpl<T,NDIM>::get_pmap() const {
210 return coeffs.get_pmap();
211 }
212
213
214 /// perform: this= alpha*f + beta*g, invoked by result
215
216 /// f and g are reconstructed, so we can save on the compress operation,
217 /// walk down the joint tree, and add leaf coefficients; effectively refines
218 /// to common finest level.
219 /// @param[in] alpha prefactor for f
220 /// @param[in] f first addend
221 /// @param[in] beta prefactor for g
222 /// @param[in] g second addend
223 /// @return nothing, but leaves this's tree reconstructed and as sum of f and g
224 template <typename T, std::size_t NDIM>
226 const double beta, const implT& g, const bool fence) {
227
228 MADNESS_CHECK_THROW(f.is_reconstructed(), "gaxpy_oop_reconstructed: f is not reconstructed");
229 MADNESS_CHECK_THROW(g.is_reconstructed(), "gaxpy_oop_reconstructed: g is not reconstructed");
230
231 ProcessID owner = coeffs.owner(cdata.key0);
232 if (world.rank() == owner) {
233
236
237 typedef add_op coeff_opT;
238 coeff_opT coeff_op(ff,gg,alpha,beta);
239 typedef insert_op<T,NDIM> apply_opT;
240 apply_opT apply_op(this);
241
242 woT::task(world.rank(), &implT:: template forward_traverse<coeff_opT,apply_opT>,
243 coeff_op, apply_op, cdata.key0);
244
245 }
247 if (fence) world.gop.fence();
248 }
249
250 /// Returns true if the function is compressed.
251 template <typename T, std::size_t NDIM>
253 return (tree_state==compressed);
254 }
255
256 /// Returns true if the function is reconstructed.
257 template <typename T, std::size_t NDIM>
261
262 /// Returns true if the function is redundant.
263 template <typename T, std::size_t NDIM>
265 return (tree_state==redundant);
266 }
267
268 /// Returns true if the function is redundant_after_merge.
269 template <typename T, std::size_t NDIM>
273
274 template <typename T, std::size_t NDIM>
278
279 template <typename T, std::size_t NDIM>
283
284 template <typename T, std::size_t NDIM>
286 return tree_state==on_demand;
287 }
288
289 template <typename T, std::size_t NDIM>
293
294 template <typename T, std::size_t NDIM>
298
299 template <typename T, std::size_t NDIM>
303
304 template <typename T, std::size_t NDIM>
307// this->on_demand=true;
308 functor=functor1;
309 }
310
311 template <typename T, std::size_t NDIM>
312 std::shared_ptr<FunctionFunctorInterface<T,NDIM> > FunctionImpl<T,NDIM>::get_functor() {
313 MADNESS_ASSERT(this->functor);
314 return functor;
315 }
316
317 template <typename T, std::size_t NDIM>
318 std::shared_ptr<FunctionFunctorInterface<T,NDIM> > FunctionImpl<T,NDIM>::get_functor() const {
319 MADNESS_ASSERT(this->functor);
320 return functor;
321 }
322
323 template <typename T, std::size_t NDIM>
325// this->on_demand=false;
327 functor.reset();
328 }
329
330 template <typename T, std::size_t NDIM>
332
333 template <typename T, std::size_t NDIM>
335
336 template <typename T, std::size_t NDIM>
338
339 template <typename T, std::size_t NDIM>
341
342 template <typename T, std::size_t NDIM>
344
345 template <typename T, std::size_t NDIM>
347
348 template <typename T, std::size_t NDIM>
350
351 template <typename T, std::size_t NDIM>
352 int FunctionImpl<T,NDIM>::get_k() const {return k;}
353
354 template <typename T, std::size_t NDIM>
356
357 template <typename T, std::size_t NDIM>
359
360 template <typename T, std::size_t NDIM>
362
363 template <typename T, std::size_t NDIM>
364 void FunctionImpl<T,NDIM>::accumulate_timer(const double time) const {
365 timer_accumulate.accumulate(time);
366 }
367
368 template <typename T, std::size_t NDIM>
370 if (world.rank()==0) {
371 timer_accumulate.print("accumulate");
372 timer_target_driven.print("target_driven");
373 timer_lr_result.print("result2low_rank");
374 }
375 }
376
377 template <typename T, std::size_t NDIM>
379 if (world.rank()==0) {
380 timer_accumulate.reset();
381 timer_target_driven.reset();
382 timer_lr_result.reset();
383 }
384 }
385
386 /// Truncate according to the threshold with optional global fence
387
388 /// If thresh<=0 the default value of this->thresh is used
389 template <typename T, std::size_t NDIM>
390 void FunctionImpl<T,NDIM>::truncate(double tol, bool fence) {
391 // Cannot put tol into object since it would make a race condition
392 if (tol <= 0.0)
393 tol = thresh;
394 if (world.rank() == coeffs.owner(cdata.key0)) {
395 if (is_compressed()) {
396 truncate_spawn(cdata.key0,tol);
397 } else {
399 }
400 }
401 if (fence)
402 world.gop.fence();
403 }
404
405 template <typename T, std::size_t NDIM>
407 return cdata.key0;
408 }
409
410 /// Print a plane ("xy", "xz", or "yz") containing the point x to file
411
412 /// works for all dimensions; we walk through the tree, and if a leaf node
413 /// inside the sub-cell touches the plane we print it in pstricks format
414 template <typename T, std::size_t NDIM>
415 void FunctionImpl<T,NDIM>::print_plane(const std::string filename, const int xaxis, const int yaxis, const coordT& el2) {
416
417 // get the local information
418 Tensor<double> localinfo=print_plane_local(xaxis,yaxis,el2);
419
420 // lump all the local information together, and gather on node0
421 std::vector<Tensor<double> > localinfo_vec(1,localinfo);
422 std::vector<Tensor<double> > printinfo=world.gop.concat0(localinfo_vec);
423 world.gop.fence();
424
425 // do the actual print
426 if (world.rank()==0) do_print_plane(filename,printinfo,xaxis,yaxis,el2);
427 }
428
429 /// collect the data for a plot of the MRA structure locally on each node
430
431 /// @param[in] xaxis the x-axis in the plot (can be any axis of the MRA box)
432 /// @param[in] yaxis the y-axis in the plot (can be any axis of the MRA box)
433 /// @param[in] el2
434 template <typename T, std::size_t NDIM>
435 Tensor<double> FunctionImpl<T,NDIM>::print_plane_local(const int xaxis, const int yaxis, const coordT& el2) {
436 coordT x_sim;
437 user_to_sim<NDIM>(el2,x_sim);
438 x_sim[0]+=1.e-10;
439
440 // dimensions are: (# boxes)(hue, x lo left, y lo left, x hi right, y hi right)
441 Tensor<double> plotinfo(coeffs.size(),5);
442 long counter=0;
443
444 // loop over local boxes, if the fit, add the info to the output tensor
445 typename dcT::const_iterator end = coeffs.end();
446 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
447 const keyT& key = it->first;
448 const nodeT& node = it->second;
449
450 // thisKeyContains ignores dim0 and dim1
451 if (key.thisKeyContains(x_sim,xaxis,yaxis) and node.is_leaf() and (node.has_coeff())) {
452
453 Level n=key.level();
455 // get the diametral edges of the node in the plotting plane
456 double scale=std::pow(0.5,double(n));
457 double xloleft = scale*l[xaxis];
458 double yloleft = scale*l[yaxis];
459 double xhiright = scale*(l[xaxis]+1);
460 double yhiright = scale*(l[yaxis]+1);
461
462 // convert back to user coordinates
463 Vector<double,4> user;
468
469
470 // if ((xloleft<-5.0) or (yloleft<-5.0) or (xhiright>5.0) or (yhiright>5.0)) continue;
471 if ((user[0]<-5.0) or (user[1]<-5.0) or (user[2]>5.0) or (user[3]>5.0)) continue;
472
473 // do rank or do error
474 double color=0.0;
475 if (1) {
476
477 const double maxrank=40;
478 do_convert_to_color hue(maxrank,false);
479 color=hue(node.coeff().rank());
480 } else {
481
482 // Make quadrature rule of higher order
483 const int npt = cdata.npt + 1;
484 Tensor<double> qx, qw, quad_phi, quad_phiw, quad_phit;
485 FunctionCommonData<T,NDIM>::_init_quadrature(k+1, npt, qx, qw, quad_phi, quad_phiw, quad_phit);
486 do_err_box< FunctionFunctorInterface<T,NDIM> > op(this, this->get_functor().get(), npt, qx, quad_phit, quad_phiw);
487
488 do_convert_to_color hue(1000.0,true);
489 double error=op(it);
490 error=sqrt(error);//*pow(2,key.level()*6);
491 color=hue(error);
492 }
493
494 plotinfo(counter,0)=color;
495 plotinfo(counter,1)=user[0];
496 plotinfo(counter,2)=user[1];
497 plotinfo(counter,3)=user[2];
498 plotinfo(counter,4)=user[3];
499 ++counter;
500 }
501 }
502
503 // shrink the info
504 if (counter==0) plotinfo=Tensor<double>();
505 else plotinfo=plotinfo(Slice(0,counter-1),Slice(_));
506 return plotinfo;
507 }
508
509 /// print the MRA structure
510 template <typename T, std::size_t NDIM>
511 void FunctionImpl<T,NDIM>::do_print_plane(const std::string filename, std::vector<Tensor<double> > plotinfo,
512 const int xaxis, const int yaxis, const coordT el2) {
513
514 // invoke only on master node
515 MADNESS_ASSERT(world.rank()==0);
516
517 // prepare file
518 FILE * pFile;
519 pFile = fopen(filename.c_str(), "w");
521
522
523 fprintf(pFile,"\\psset{unit=1cm}\n");
524 fprintf(pFile,"\\begin{pspicture}(%4.2f,%4.2f)(%4.2f,%4.2f)\n",
525 // cell(xaxis,0),cell(xaxis,1),cell(yaxis,0),cell(yaxis,1));
526 -5.0,-5.0,5.0,5.0);
527 fprintf(pFile,"\\pslinewidth=0.1pt\n");
528
529 for (std::vector<Tensor<double> >::const_iterator it=plotinfo.begin(); it!=plotinfo.end(); ++it) {
530
531 Tensor<double> localinfo=*it;
532 if (localinfo.has_data()) {
533
534 for (long i=0; i<localinfo.dim(0); ++i) {
535
536 fprintf(pFile,"\\newhsbcolor{mycolor}{%8.4f 1.0 0.7}\n",localinfo(i,0));
537 fprintf(pFile,"\\psframe["//linewidth=0.5pt,"
538 "fillstyle=solid,"
539 "fillcolor=mycolor]"
540 "(%12.8f,%12.8f)(%12.8f,%12.8f)\n",
541 localinfo(i,1),localinfo(i,2),localinfo(i,3),localinfo(i,4));
542 }
543 }
544 }
545
546
547 fprintf(pFile,"\\end{pspicture}\n");
548 fclose(pFile);
549 }
550
551 /// print the grid (the roots of the quadrature of each leaf box)
552 /// of this function in user xyz coordinates
553 template <typename T, std::size_t NDIM>
554 void FunctionImpl<T,NDIM>::print_grid(const std::string filename) const {
555
556 // get the local information
557 std::vector<keyT> local_keys=local_leaf_keys();
558
559 // lump all the local information together, and gather on node0
560 std::vector<keyT> all_keys=world.gop.concat0(local_keys);
561 world.gop.fence();
562
563 // do the actual print
564 if (world.rank()==0) do_print_grid(filename,all_keys);
565
566 }
567
568 /// return the keys of the local leaf boxes
569 template <typename T, std::size_t NDIM>
570 std::vector<typename FunctionImpl<T,NDIM>::keyT> FunctionImpl<T,NDIM>::local_leaf_keys() const {
571
572 // coeffs.size is maximum number of keys (includes internal keys)
573 std::vector<keyT> keys(coeffs.size());
574
575 // loop over local boxes, if they are leaf boxes add their quadrature roots
576 // to the output tensor
577 int i=0;
578 typename dcT::const_iterator end = coeffs.end();
579 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
580 const keyT& key = it->first;
581 const nodeT& node = it->second;
582 if (node.is_leaf()) keys[i++]=key;
583 }
584
585 // shrink the vector to number of leaf keys
586 keys.resize(i);
587 return keys;
588 }
589
590 /// print the grid in xyz format
591
592 /// the quadrature points and the key information will be written to file,
593 /// @param[in] filename where the quadrature points will be written to
594 /// @param[in] keys all leaf keys
595 template <typename T, std::size_t NDIM>
596 void FunctionImpl<T,NDIM>::do_print_grid(const std::string filename, const std::vector<keyT>& keys) const {
597 // invoke only on master node
598 MADNESS_ASSERT(world.rank()==0);
599
600 // the quadrature points in simulation coordinates of the root node
601 const Tensor<double> qx=cdata.quad_x;
602 const size_t npt = qx.dim(0);
603
604 // the number of coordinates (grid point tuples) per box ({x1},{x2},{x3},..,{xNDIM})
605 long npoints=power<NDIM>(npt);
606 // the number of boxes
607 long nboxes=keys.size();
608
609 // prepare file
610 FILE * pFile;
611 pFile = fopen(filename.c_str(), "w");
612
613 fprintf(pFile,"%ld\n",npoints*nboxes);
614 fprintf(pFile,"%ld points per box and %ld boxes \n",npoints,nboxes);
615
616 // loop over all leaf boxes
617 typename std::vector<keyT>::const_iterator key_it=keys.begin();
618 for (key_it=keys.begin(); key_it!=keys.end(); ++key_it) {
619
620 const keyT& key=*key_it;
621 fprintf(pFile,"# key: %8d",key.level());
622 for (size_t d=0; d<NDIM; d++) fprintf(pFile,"%8d",int(key.translation()[d]));
623 fprintf(pFile,"\n");
624
625 // this is borrowed from fcube
626 const Vector<Translation,NDIM>& l = key.translation();
627 const Level n = key.level();
628 const double h = std::pow(0.5,double(n));
629 coordT c; // will hold the point in user coordinates
630
633
634 if (NDIM == 3) {
635 for (size_t i=0; i<npt; ++i) {
636 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
637 for (size_t j=0; j<npt; ++j) {
638 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
639 for (size_t k=0; k<npt; ++k) {
640 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
641 // grid weights
642 // double scale = pow(0.5,0.5*NDIM*key.level())*
643 // sqrt(FunctionDefaults<NDIM>::get_cell_volume());
644 // double w=cdata.quad_phiw[i]*cdata.quad_phiw[j]*cdata.quad_phiw[k];
645
646 fprintf(pFile,"%18.12f %18.12f %18.12f\n",c[0],c[1],c[2]);
647 // fprintf(pFile,"%18.12e %18.12e %18.12e %18.12e\n",c[0],c[1],c[2],w*scale);
648 }
649 }
650 }
651 } else {
652 MADNESS_EXCEPTION("only NDIM=3 in print_grid",0);
653 }
654 }
655 fclose(pFile);
656 }
657
658
659 /// Returns the truncation threshold according to truncate_method
660 ///
661 /// All modes scale tol with the box size h_n = L/2^n at level n (L = cell_min_width).
662 /// The positive modes tighten the threshold at fine levels so that high-frequency
663 /// content is kept accurately — appropriate when the function itself or its
664 /// derivatives must be pointwise accurate. The negative modes loosen the threshold
665 /// at fine levels — appropriate when the function will immediately be passed to a
666 /// smoothing integral operator that suppresses high-frequency content anyway.
667 ///
668 /// Design rationale for each mode:
669 ///
670 /// Mode 0: t_n = tol (uniform, level-independent)
671 /// Simplest choice. No level weighting; each wavelet coefficient is kept
672 /// if it exceeds tol regardless of its scale.
673 ///
674 /// Mode 1: t_n = tol * min(1, L/2^n)
675 /// Designed for first-derivative accuracy. A level-n coefficient of
676 /// magnitude t_n contributes t_n * (2^n/L) to ||∇f||, so this mode
677 /// makes every level contribute at most tol to the gradient error.
678 /// Clamped to tol at coarse levels (L/2^n > 1).
679 ///
680 /// Mode 2: t_n = tol * min(1, (L/2^n)^2)
681 /// Designed for second-derivative (Laplacian) accuracy. Each level
682 /// contributes at most tol to ||∇²f||. Tighter than mode 1 at fine
683 /// levels; same tol at coarse levels.
684 ///
685 /// Mode 3: t_n = tol/2^{NDIM/2} * min(1, L/2^n)
686 /// Like mode 1 but with an extra 1/2^{NDIM/2} prefactor intended to
687 /// account for the growing number of tree nodes in higher dimensions.
688 /// See inline comment below for the (disputed) justification.
689 ///
690 /// Mode 4: t_n = tol * min(1, (L/2^n)^{NDIM/2})
691 /// Rigorous L2 bound for NDIM dimensions: if each node's L2 error is
692 /// at most t_n, then the total L2 error is at most tol when the
693 /// level-n box volume (L/2^n)^NDIM is used to weight the sum.
694 /// Recovers mode 1 for NDIM=2 and mode 2 for NDIM=4.
695 ///
696 /// Mode -1: t_n = tol * max(1, 2^n/L) [dual of mode 1]
697 /// Designed for accuracy after applying a first-order smoothing operator
698 /// S with ||S||_{k} ~ 1/k (e.g. a Poisson-type convolution). If the
699 /// representation error at level n has L2 norm t_n, the error after S is
700 /// ~t_n * (L/2^n). Setting t_n = tol * (2^n/L) ensures ||S(f-f̃)||₂ ≤
701 /// const*tol while allowing much coarser fine-level representation.
702 /// CAUTION: the resulting f̃ is only meaningful as input to such an S;
703 /// derivatives and inner products with non-smooth functions will be wrong.
704 ///
705 /// Mode -2: t_n = tol * max(1, (2^n/L)^2) [dual of mode 2]
706 /// Designed for accuracy after applying the resolvent G = (T-E)^{-1},
707 /// whose Fourier-space symbol is G(k) = 2/(k²+μ²) ~ 2/k² for k >> μ.
708 /// A level-n error of magnitude t_n survives G as ~t_n*(L/2^n)².
709 /// Setting t_n = tol*(2^n/L)² guarantees ||G(f-f̃)||₂ ≤ const*tol
710 /// while aggressively pruning fine levels (factor ~(2^n/L)² looser than
711 /// mode 0 at level n). The coarse-level floor (where max clamps to 1)
712 /// is unchanged — coarse-level errors pass through G at amplitude ~1/|E|
713 /// and are only reduced by tightening tol itself, not by choosing this mode.
714 /// CAUTION: same as mode -1 — use only for intermediates fed into G.
715
716 /// Modes 1, 2 and 3 scale the tolerance by the physical width of the box. The
717 /// width of an anisotropic cell has to be reduced to one number, and that is the
718 /// geometric mean, volume^(1/NDIM) -- not the smallest dimension, which would tie
719 /// the tolerance to the cell's aspect ratio rather than to its resolution.
720 /// Cubic cells are unaffected: there the two agree.
721 template <typename T, std::size_t NDIM>
722 double FunctionImpl<T,NDIM>::truncate_tol(double tol, const keyT& key) const {
723
724 // Caps on the level exponent to prevent threshold from going below
725 // intrinsic numerical noise (positive modes) or growing beyond the
726 // point where further loosening has any practical effect (negative modes).
727 // RJH: original comment — introduced MAXLEVEL to avoid runaway refinement.
728 const int MAXLEVEL1 = 20; // 0.5^20 ~= 1e-6
729 const int MAXLEVEL2 = 10; // 0.25^10 ~= 1e-6
730
731 if (truncate_mode == 0) {
732 return tol;
733 }
734 else if (truncate_mode == 1) {
736 return tol*std::min(1.0,pow(0.5,double(std::min(key.level(),MAXLEVEL1)))*L);
737 }
738 else if (truncate_mode == 2) {
740 return tol*std::min(1.0,pow(0.25,double(std::min(key.level(),MAXLEVEL2)))*L*L);
741 }
742 else if (truncate_mode == 3) {
743 // Like mode 1 but divided by 2^{NDIM/2} to account for the growing number
744 // of tree nodes in higher dimensions. Handwaving argument (FAB): if each
745 // node contributes at most tol, the total error is at most sqrt(#nodes)*tol;
746 // dividing by ~sqrt(siblings per level) = 2^{NDIM/2} absorbs that factor.
747 // Counter-argument (RJH): the total can be as large as #nodes*tol, so the
748 // real fix is an end-to-end error analysis in the application, not this factor.
749 const static double fac=1.0/std::pow(2,NDIM*0.5);
750 tol*=fac;
751
753 return tol*std::min(1.0,pow(0.5,double(std::min(key.level(),MAXLEVEL1)))*L);
754 }
755 else if (truncate_mode == 4) {
756 // Rigorous L2 bound: each box at level n has volume h^NDIM = (L/2^n)^NDIM.
757 // Keeping the L2 error per box below t_n bounds the total L2 error by
758 // tol when t_n = tol * (L/2^n)^{NDIM/2}. This recovers mode 1 for NDIM=2
759 // and mode 2 for NDIM=4; for 6D it gives t_n ~ (L/2^n)^3 (much tighter
760 // at fine levels than modes 1 or 2).
762 int n = std::min(key.level(), MAXLEVEL2);
763 return tol * std::min(1.0, std::pow(std::pow(0.5, n) * L, NDIM * 0.5));
764 }
765 else if (truncate_mode == -1) {
766 // Dual of mode 1: t_n = tol * max(1, 2^n/L).
767 // Loosens the threshold at fine levels by the same factor that mode 1
768 // tightens it. Appropriate when the function is input to a first-order
769 // smoothing convolution S with ||S||_k ~ L/2^n at level n, so that the
770 // post-S error ~t_n*(L/2^n) remains bounded by tol at every level.
772 int n = std::min(key.level(), MAXLEVEL1);
773 return tol * std::max(1.0, std::pow(2.0, n) / L);
774 }
775 else if (truncate_mode == -2) {
776 // Dual of mode 2: t_n = tol * max(1, (2^n/L)^2).
777 // Appropriate when the function is the operand of the resolvent
778 // G = (T-E)^{-1} whose Fourier symbol G(k) ~ 2/(k^2+mu^2). A level-n
779 // wavelet error of magnitude t_n passes through G with amplitude
780 // ~t_n*(L/2^n)^2; this mode sets t_n = tol*(2^n/L)^2 so that
781 // ||G(f-f̃)||_2 <= const*tol regardless of level.
782 // At fine levels the looser threshold dramatically reduces storage:
783 // at level 10 in a 20 a.u. box the factor is (1024/20)^2 ~ 2600.
784 // The coarse-level floor (where max clamps to 1, n <= log2(L) ~ 4-5)
785 // is unchanged — coarse errors in G f are only reducible by tightening tol.
787 int n = std::min(key.level(), MAXLEVEL2);
788 return tol * std::max(1.0, std::pow(std::pow(2.0, n) / L, 2.0));
789 }
790 else {
791 MADNESS_EXCEPTION("truncate_mode invalid",truncate_mode);
792 }
793 }
794
795 /// Returns patch referring to coeffs of child in parent box
796 template <typename T, std::size_t NDIM>
797 std::vector<Slice> FunctionImpl<T,NDIM>::child_patch(const keyT& child) const {
798 std::vector<Slice> s(NDIM);
799 const Vector<Translation,NDIM>& l = child.translation();
800 for (std::size_t i=0; i<NDIM; ++i)
801 s[i] = cdata.s[l[i]&1]; // Lowest bit of translation
802 return s;
803 }
804
805 /// Directly project parent NS coeffs to child NS coeffs
806
807 template <typename T, std::size_t NDIM>
809 const keyT& child, const keyT& parent, const coeffT& coeff) const {
810
811 const implT* f=this;
812 // MADNESS_ASSERT(coeff.tensor_type()==TT_FULL);
813 coeffT result(f->cdata.v2k,coeff.tensor_type());
814
815 // if the node for child is existent in f, and it is an internal node, we
816 // automatically have the NS form; if it is a leaf node, we only have the
817 // sum coeffs, so we take zero difference coeffs
818 if (child==parent) {
819 if (coeff.dim(0)==2*f->get_k()) result=coeff; // internal node
820 else if (coeff.dim(0)==f->get_k()) { // leaf node
821 result(f->cdata.s0)+=coeff;
822 } else {
823 MADNESS_EXCEPTION("confused k in parent_to_child_NS",1);
824 }
825 } else if (child.level()>parent.level()) {
826
827 // parent and coeff should refer to a leaf node with sum coeffs only
828 // b/c tree should be compressed with leaves kept.
829 MADNESS_ASSERT(coeff.dim(0)==f->get_k());
830 const coeffT scoeff=f->parent_to_child(coeff,parent,child);
831 result(f->cdata.s0)+=scoeff;
832 } else {
833 MADNESS_EXCEPTION("confused keys in parent_to_child_NS",1);
834 }
835 return result;
836 }
837
838 /// truncate tree at a certain level
839 template <typename T, std::size_t NDIM>
840 void FunctionImpl<T,NDIM>::erase(const Level& max_level) {
841 this->make_redundant(true);
842
843 typename dcT::iterator end = coeffs.end();
844 for (typename dcT::iterator it= coeffs.begin(); it!=end; ++it) {
845 keyT key=it->first;
846 nodeT& node=it->second;
847 if (key.level()>max_level) coeffs.erase(key);
848 if (key.level()==max_level) node.set_has_children(false);
849 }
850 this->undo_redundant(true);
851 }
852
853
854 /// Returns some asymmetry measure ... no comms
855 template <typename T, std::size_t NDIM>
862
863
864 /// Refine multiple functions down to the same finest level
865
866 /// @param[v] is the vector of functions we are refining.
867 /// @param[key] is the current node.
868 /// @param[c] is the vector of coefficients passed from above.
869 template <typename T, std::size_t NDIM>
871 const std::vector<tensorT>& c,
872 const keyT key) {
873 if (key == cdata.key0 && coeffs.owner(key)!=world.rank()) return;
874
875 // First insert coefficients from above ... also get write accessors here
876 std::unique_ptr<typename dcT::accessor[]> acc(new typename dcT::accessor[v.size()]);
877 for (unsigned int i=0; i<c.size(); i++) {
878 MADNESS_ASSERT(v[i]->coeffs.get_pmap() == coeffs.get_pmap());
879 MADNESS_ASSERT(v[i]->coeffs.owner(key) == world.rank());
880 bool exists = ! v[i]->coeffs.insert(acc[i],key);
881 if (c[i].size()) {
882 MADNESS_CHECK(!exists);
883 acc[i]->second = nodeT(coeffT(c[i],targs),false);
884 }
885 else {
886 MADNESS_ASSERT(exists);
887 }
888 }
889
890 // If everyone has coefficients we are done
891 bool done = true;
892 for (unsigned int i=0; i<v.size(); i++) {
893 done &= acc[i]->second.has_coeff();
894 }
895
896 if (!done) {
897 // Those functions with coefficients need to be refined down
898 std::vector<tensorT> d(v.size());
899 for (unsigned int i=0; i<v.size(); i++) {
900 if (acc[i]->second.has_coeff()) {
901 tensorT s(cdata.v2k);
902 // s(cdata.s0) = acc[i]->second.coeff()(___);
903 s(cdata.s0) = acc[i]->second.coeff().full_tensor();
904 acc[i]->second.clear_coeff();
905 d[i] = unfilter(s);
906 acc[i]->second.set_has_children(true);
907 }
908 }
909
910 // Loop thru children and pass down
911 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
912 const keyT& child = kit.key();
913 std::vector<Slice> cp = child_patch(child);
914 std::vector<tensorT> childc(v.size());
915 for (unsigned int i=0; i<v.size(); i++) {
916 if (d[i].size()) childc[i] = copy(d[i](cp));
917 }
918 woT::task(coeffs.owner(child), &implT::refine_to_common_level, v, childc, child);
919 }
920 }
921 }
922
923 // horrifically non-scalable
924 template <typename T, std::size_t NDIM>
925 void FunctionImpl<T,NDIM>::put_in_box(ProcessID from, long nl, long ni) const {
926 if (world.size()> 1000)
927 throw "NO!";
928 box_leaf[from] = nl;
929 box_interior[from] = ni;
930 }
931
932 /// Prints summary of data distribution
933 template <typename T, std::size_t NDIM>
935 if (world.size() >= 1000)
936 return;
937 for (int i=0; i<world.size(); ++i)
938 box_leaf[i] = box_interior[i] == 0;
939 world.gop.fence();
940 long nleaf=0, ninterior=0;
941 typename dcT::const_iterator end = coeffs.end();
942 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
943 const nodeT& node = it->second;
944 if (node.is_leaf())
945 ++nleaf;
946 else
947 ++ninterior;
948 }
949 this->send(0, &implT::put_in_box, world.rank(), nleaf, ninterior);
950 world.gop.fence();
951 if (world.rank() == 0) {
952 for (int i=0; i<world.size(); ++i) {
953 printf("load: %5d %8ld %8ld\n", i, box_leaf[i], box_interior[i]);
954 }
955 }
956 world.gop.fence();
957 }
958
959 template <typename T, std::size_t NDIM>
960 bool FunctionImpl<T,NDIM>::noautorefine(const keyT& key, const tensorT& t) const {
961 return false;
962 }
963
964 /// Returns true if this block of coeffs needs autorefining
965 template <typename T, std::size_t NDIM>
966 bool FunctionImpl<T,NDIM>::autorefine_square_test(const keyT& key, const nodeT& t) const {
967 double lo, hi;
968 tnorm(t.coeff().full_tensor(), &lo, &hi);
969 double test = 2*lo*hi + hi*hi;
970 //print("autoreftest",key,thresh,truncate_tol(thresh, key),lo,hi,test);
971 return test> truncate_tol(thresh, key);
972 }
973
974
975 /// is this the same as trickle_down() ?
976 template <typename T, std::size_t NDIM>
978 typename dcT::accessor acc;
979 coeffs.insert(acc,key);
980 nodeT& node = acc->second;
981 coeffT& c = node.coeff();
982
983 //print(key,"received",s.normf(),c.normf(),node.has_children());
984
985 if (s.size() > 0) {
986 if (c.size() > 0)
987 c.gaxpy(1.0,s,1.0);
988 else
989 c = s;
990 }
991
992 if (node.has_children()) {
993 coeffT d;
994 if (c.has_data()) {
995 d = coeffT(cdata.v2k,targs);
996 d(cdata.s0) += c;
997 d = unfilter(d);
998 node.clear_coeff();
999 }
1000 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
1001 coeffT ss;
1002 const keyT& child = kit.key();
1003 if (d.size() > 0) ss = copy(d(child_patch(child)));
1004 //print(key,"sending",ss.normf(),"to",child);
1005 woT::task(coeffs.owner(child), &implT::sum_down_spawn, child, ss);
1006 }
1007 }
1008 else {
1009 // Missing coeffs assumed to be zero
1010 if (c.size() <= 0) c = coeffT(cdata.vk,targs);
1011 }
1012 }
1013
1014 /// After 1d push operator must sum coeffs down the tree to restore correct scaling function coefficients
1015
1016 template <typename T, std::size_t NDIM>
1019 if (world.rank() == coeffs.owner(cdata.key0)) sum_down_spawn(cdata.key0, coeffT());
1020 if (fence) world.gop.fence();
1021 }
1022
1023
1024 template <typename T, std::size_t NDIM>
1026 const implT* f,
1027 const keyT& key,
1028 const std::pair<keyT,coeffT>& left,
1029 const std::pair<keyT,coeffT>& center,
1030 const std::pair<keyT,coeffT>& right) {
1031 D->forward_do_diff1(f,this,key,left,center,right);
1032 }
1033
1034
1035 template <typename T, std::size_t NDIM>
1037 const implT* f,
1038 const keyT& key,
1039 const std::pair<keyT,coeffT>& left,
1040 const std::pair<keyT,coeffT>& center,
1041 const std::pair<keyT,coeffT>& right) {
1042 D->do_diff1(f,this,key,left,center,right);
1043 }
1044
1045
1046 // Called by result function to differentiate f
1047 template <typename T, std::size_t NDIM>
1048 void FunctionImpl<T,NDIM>::diff(const DerivativeBase<T,NDIM>* D, const implT* f, bool fence) {
1049 typedef std::pair<keyT,coeffT> argT;
1050 if (D->parallel_submit_) {
1051 D->submit_diff_tasks(f, this); // same tasks, spawned from the pool instead of here
1052 if (fence) world.gop.fence();
1053 return;
1054 }
1055 for (const auto& [key, node]: f->coeffs) {
1056 if (node.has_coeff()) {
1057 Future<argT> left = D->find_neighbor(f, key,-1);
1058 argT center(key,node.coeff());
1059 Future<argT> right = D->find_neighbor(f, key, 1);
1060 world.taskq.add(*this, &implT::do_diff1, D, f, key, left, center, right, TaskAttributes::hipri());
1061 }
1062 else {
1063 coeffs.replace(key,nodeT(coeffT(),true)); // Empty internal node
1064 }
1065 }
1066 if (fence) world.gop.fence();
1067 }
1068
1069
1070 /// return the a std::pair<key, node>, which MUST exist
1071 template <typename T, std::size_t NDIM>
1073 MADNESS_ASSERT(coeffs.probe(key));
1074 ShallowNode<T,NDIM> snode(coeffs.find(key).get()->second);
1075 return std::pair<Key<NDIM>,ShallowNode<T,NDIM> >(key,snode);
1076 }
1077
1078 /// multiply the ket with a one-electron potential rr(1,2)= f(1,2)*g(1)
1079
1080 /// @param[in] val_ket function values of f(1,2)
1081 /// @param[in] val_pot function values of g(1)
1082 /// @param[in] particle if 0 then g(1), if 1 then g(2)
1083 /// @return the resulting function values
1084 template <typename T, std::size_t NDIM>
1086 const coeffT& val_pot, int particle) const {
1087
1089 MADNESS_ASSERT(val_pot.is_full_tensor());
1090 MADNESS_ASSERT(val_ket.is_svd_tensor());
1091
1092 std::vector<long> vkhalf=std::vector<long>(NDIM/2,cdata.vk[0]);
1093 tensorT ones=tensorT(vkhalf);
1094 ones=1.0;
1095
1096 TensorArgs targs(-1.0,val_ket.tensor_type());
1097 coeffT pot12;
1098 if (particle==0) pot12=outer(val_pot.full_tensor(),ones,targs);
1099 else if (particle==1) pot12=outer(ones,val_pot.full_tensor(),targs);
1100
1101 coeffT result=copy(val_ket);
1102 result.emul(pot12);
1103
1104 return result;
1105 }
1106
1107
1108 /// given several coefficient tensors, assemble a result tensor
1109
1110 /// the result looks like: (v(1,2) + v(1) + v(2)) |ket(1,2)>
1111 /// or (v(1,2) + v(1) + v(2)) |p(1) p(2)>
1112 /// i.e. coefficients for the ket and coefficients for the two particles are
1113 /// mutually exclusive. All potential terms are optional, just pass in empty coeffs.
1114 /// @param[in] key the key of the FunctionNode to which these coeffs belong
1115 /// @param[in] cket coefficients of the ket
1116 /// @param[in] vpotential1 function values of the potential for particle 1
1117 /// @param[in] vpotential2 function values of the potential for particle 2
1118 /// @param[in] veri function values for the 2-particle potential
1119 template <typename T, std::size_t NDIM>
1121 const keyT& key, const coeffT& coeff_ket, const coeffT& vpotential1,
1122 const coeffT& vpotential2, const tensorT& veri) const {
1123
1124 // take a shortcut if we are already done
1125 bool ket_only=(not (vpotential1.has_data() or vpotential2.has_data() or veri.has_data()));
1126 if (ket_only) return coeff_ket;
1127
1128 // switch to values instead of coefficients
1129 coeffT val_ket=coeffs2values(key,coeff_ket);
1130
1131 // the result tensor
1132 coeffT val_result=coeffT(val_ket.ndim(),val_ket.dims(),this->get_tensor_args().tt);
1133 coeffT coeff_result;
1134
1135 // potential for particles 1 and 2, must be done in TT_2D
1136 if (vpotential1.has_data() or vpotential2.has_data()) {
1137 val_ket=val_ket.convert(TensorArgs(-1.0,TT_2D));
1138 }
1139 if (vpotential1.has_data()) val_result+=multiply(val_ket,vpotential1,0);
1140 if (vpotential2.has_data()) val_result+=multiply(val_ket,vpotential2,1);
1141
1142 // values for eri: this must be done in full rank...
1143 if (veri.has_data()) {
1144 tensorT val_ket2=val_ket.full_tensor_copy().emul(veri);
1145 if (val_result.has_data()) val_ket2+=val_result.full_tensor();
1146 // values2coeffs expensive (30%), coeffT() (relatively) cheap (8%)
1147 coeff_result=coeffT(values2coeffs(key,val_ket2),this->get_tensor_args());
1148
1149 } else {
1150
1151 // convert back to original tensor type
1152 val_ket=val_ket.convert(get_tensor_args());
1153 MADNESS_ASSERT(val_result.has_data());
1154 coeff_result=values2coeffs(key,val_result);
1155 coeff_result.reduce_rank(this->get_tensor_args().thresh);
1156 }
1157
1158 return coeff_result;
1159
1160 }
1161
1162 /// Permute the dimensions of f according to map, result on this
1163 template <typename T, std::size_t NDIM>
1164 void FunctionImpl<T,NDIM>::mapdim(const implT& f, const std::vector<long>& map, bool fence) {
1165
1167 const_cast<implT*>(&f)->flo_unary_op_node_inplace(do_mapdim(map,*this),fence);
1168
1169 }
1170
1171 /// mirror the dimensions of f according to mirror, result on this
1172 template <typename T, std::size_t NDIM>
1173 void FunctionImpl<T,NDIM>::mirror(const implT& f, const std::vector<long>& mirrormap, bool fence) {
1175 const_cast<implT*>(&f)->flo_unary_op_node_inplace(do_mirror(mirrormap,*this),fence);
1176 }
1177
1178 /// map and mirror the translation index and the coefficients, result on this
1179
1180 /// first map the dimensions, the mirror!
1181 /// this = mirror(map(f))
1182 template <typename T, std::size_t NDIM>
1183 void FunctionImpl<T,NDIM>::map_and_mirror(const implT& f, const std::vector<long>& map,
1184 const std::vector<long>& mirror, bool fence) {
1186 const_cast<implT*>(&f)->flo_unary_op_node_inplace(do_map_and_mirror(map,mirror,*this),fence);
1187 }
1188
1189
1190
1191 /// take the average of two functions, similar to: this=0.5*(this+rhs)
1192
1193 /// works in either basis and also in nonstandard form
1194 template <typename T, std::size_t NDIM>
1196
1197 rhs.flo_unary_op_node_inplace(do_average(*this),true);
1198 this->scale_inplace(0.5,true);
1200 }
1201
1202 /// change the tensor type of the coefficients in the FunctionNode
1203
1204 /// @param[in] targs target tensor arguments (threshold and full/low rank)
1205 template <typename T, std::size_t NDIM>
1209
1210 /// reduce the rank of the coefficients tensors
1211
1212 /// @param[in] targs target tensor arguments (threshold and full/low rank)
1213 template <typename T, std::size_t NDIM>
1214 void FunctionImpl<T,NDIM>::reduce_rank(const double thresh, bool fence) {
1216 }
1217
1218 /// reduce the rank of the coefficients tensors
1219
1220 /// @param[in] targs target tensor arguments (threshold and full/low rank)
1221 template <typename T, std::size_t NDIM>
1222 void FunctionImpl<T,NDIM>::chop_at_level(const int n, bool fence) {
1223 std::list<keyT> to_be_erased;
1224 for (auto it=coeffs.begin(); it!=coeffs.end(); ++it) {
1225 const keyT& key=it->first;
1226 nodeT& node=it->second;
1227 if (key.level()==n) node.set_is_leaf(true);
1228 if (key.level()>n) to_be_erased.push_back(key);
1229 }
1230 for (auto& key : to_be_erased) coeffs.erase(key);
1231 }
1232
1233
1234/// compute norm of s and d coefficients for all nodes
1235
1236 /// @param[in] targs target tensor arguments (threshold and full/low rank)
1237 template <typename T, std::size_t NDIM>
1239 //const auto& data=FunctionCommonData<T,NDIM>::get(get_k());
1242 }
1243
1244
1245/// Transform sum coefficients at level n to sums+differences at level n-1
1246
1247/// Given scaling function coefficients s[n][l][i] and s[n][l+1][i]
1248/// return the scaling function and wavelet coefficients at the
1249/// coarser level. I.e., decompose Vn using Vn = Vn-1 + Wn-1.
1250 /// \code
1251 /// s_i = sum(j) h0_ij*s0_j + h1_ij*s1_j
1252 /// d_i = sum(j) g0_ij*s0_j + g1_ij*s1_j
1253 // \endcode
1254 /// Returns a new tensor and has no side effects. Works for any
1255 /// number of dimensions.
1256 ///
1257 /// No communication involved.
1258 template <typename T, std::size_t NDIM>
1260 tensorT r(cdata.v2k,false);
1261 tensorT w(cdata.v2k,false);
1262 return fast_transform(s,cdata.hgT,r,w);
1263 //return transform(s,cdata.hgT);
1264 }
1265
1266 template <typename T, std::size_t NDIM>
1268 coeffT result=transform(s,cdata.hgT);
1269 return result;
1270 }
1271
1272 /// Transform sums+differences at level n to sum coefficients at level n+1
1273
1274 /// Given scaling function and wavelet coefficients (s and d)
1275 /// returns the scaling function coefficients at the next finer
1276 /// level. I.e., reconstruct Vn using Vn = Vn-1 + Wn-1.
1277 /// \code
1278 /// s0 = sum(j) h0_ji*s_j + g0_ji*d_j
1279 /// s1 = sum(j) h1_ji*s_j + g1_ji*d_j
1280 /// \endcode
1281 /// Returns a new tensor and has no side effects
1282 ///
1283 /// If (sonly) ... then ss is only the scaling function coeff (and
1284 /// assume the d are zero). Works for any number of dimensions.
1285 ///
1286 /// No communication involved.
1287 template <typename T, std::size_t NDIM>
1289 tensorT r(cdata.v2k,false);
1290 tensorT w(cdata.v2k,false);
1291 return fast_transform(s,cdata.hg,r,w);
1292 //return transform(s, cdata.hg);
1293 }
1294
1295 template <typename T, std::size_t NDIM>
1297 return transform(s,cdata.hg);
1298 }
1299
1300 /// downsample the sum coefficients of level n+1 to sum coeffs on level n
1301
1302 /// specialization of the filter method, will yield only the sum coefficients
1303 /// @param[in] key key of level n
1304 /// @param[in] v vector of sum coefficients of level n+1
1305 /// @param[in] args TensorArguments for possible low rank approximations
1306 /// @return sum coefficients on level n in full tensor format
1307 template <typename T, std::size_t NDIM>
1309
1310 tensorT result(cdata.vk);
1311
1312 // the twoscale coefficients: for downsampling use h0/h1; see Alpert Eq (3.34a)
1313 const tensorT h[2] = {cdata.h0T, cdata.h1T};
1314 tensorT matrices[NDIM];
1315
1316 // loop over all child nodes, transform and accumulate
1317 long i=0;
1318 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1319
1320 // get the appropriate twoscale coefficients for each dimension
1321 for (size_t ii=0; ii<NDIM; ++ii) matrices[ii]=h[kit.key().translation()[ii]%2];
1322
1323 // transform and accumulate on the result
1324 result+=general_transform(v[i].get(),matrices).full_tensor();
1325
1326 }
1327 return result;
1328 }
1329
1330 /// upsample the sum coefficients of level 1 to sum coeffs on level n+1
1331
1332 /// specialization of the unfilter method, will transform only the sum coefficients
1333 /// @param[in] key key of level n+1
1334 /// @param[in] coeff sum coefficients of level n (does NOT belong to key!!)
1335 /// @param[in] args TensorArguments for possible low rank approximations
1336 /// @return sum coefficients on level n+1
1337 template <typename T, std::size_t NDIM>
1339
1340 // the twoscale coefficients: for upsampling use h0/h1; see Alpert Eq (3.35a/b)
1341 // note there are no difference coefficients; if you want that use unfilter
1342 const tensorT h[2] = {cdata.h0, cdata.h1};
1343 tensorT matrices[NDIM];
1344
1345 // get the appropriate twoscale coefficients for each dimension
1346 for (size_t ii=0; ii<NDIM; ++ii) matrices[ii]=h[key.translation()[ii]%2];
1347
1348 // transform and accumulate on the result
1349 const coeffT result=general_transform(coeff,matrices);
1350 return result;
1351 }
1352
1353
1354 /// Projects old function into new basis (only in reconstructed form)
1355 template <typename T, std::size_t NDIM>
1356 void FunctionImpl<T,NDIM>::project(const implT& old, bool fence) {
1357 long kmin = std::min(cdata.k,old.cdata.k);
1358 std::vector<Slice> s(NDIM,Slice(0,kmin-1));
1359 typename dcT::const_iterator end = old.coeffs.end();
1360 for (typename dcT::const_iterator it=old.coeffs.begin(); it!=end; ++it) {
1361 const keyT& key = it->first;
1362 const nodeT& node = it->second;
1363 if (node.has_coeff()) {
1364 coeffT c(cdata.vk,targs);
1365 c(s) += node.coeff()(s);
1366 coeffs.replace(key,nodeT(c,false));
1367 }
1368 else {
1369 coeffs.replace(key,nodeT(coeffT(),true));
1370 }
1371 }
1372 if (fence)
1373 world.gop.fence();
1374 }
1375
1376 template <typename T, std::size_t NDIM>
1378 return coeffs.probe(key) && coeffs.find(key).get()->second.has_children();
1379 }
1380
1381 template <typename T, std::size_t NDIM>
1383 return coeffs.probe(key) && (not coeffs.find(key).get()->second.has_children());
1384 }
1385
1386
1387 template <typename T, std::size_t NDIM>
1388 void FunctionImpl<T,NDIM>::broaden_op(const keyT& key, const std::vector< Future <bool> >& v) {
1389 for (unsigned int i=0; i<v.size(); ++i) {
1390 if (v[i]) {
1392 break;
1393 }
1394 }
1395 }
1396
1397 // For each local node sets norm_tree, snorm and dnorm to 0.0, and marks
1398 // dnorm_tree as uncomputed.
1399 template <typename T, std::size_t NDIM>
1401 typename dcT::iterator end = coeffs.end();
1402 for (typename dcT::iterator it=coeffs.begin(); it!=end; ++it) {
1403 it->second.set_norm_tree(0.0);
1404 it->second.set_dnorm_tree(NORM_TREE_UNCOMPUTED);
1405 it->second.set_snorm(0.0);
1406 it->second.set_dnorm(0.0);
1407 }
1408 }
1409
1410 // Broaden tree
1411 template <typename T, std::size_t NDIM>
1412 void FunctionImpl<T,NDIM>::broaden(const array_of_bools<NDIM>& is_periodic, bool fence) {
1413 typename dcT::iterator end = coeffs.end();
1414 for (typename dcT::iterator it=coeffs.begin(); it!=end; ++it) {
1415 const keyT& key = it->first;
1416 typename dcT::accessor acc;
1417 const auto found = coeffs.find(acc,key);
1418 MADNESS_CHECK(found);
1419 nodeT& node = acc->second;
1420 if (node.has_coeff() &&
1421 node.get_norm_tree() != -1.0 &&
1422 node.coeff().normf() >= truncate_tol(thresh,key)) {
1423
1424 node.set_norm_tree(-1.0); // Indicates already broadened or result of broadening/refining
1426 //int ndir = std::pow(3,NDIM);
1427 int ndir = static_cast<int>(std::pow(static_cast<double>(3), static_cast<int>(NDIM)));
1428 std::vector< Future <bool> > v = future_vector_factory<bool>(ndir);
1429 keyT neigh;
1430 int i=0;
1431 for (HighDimIndexIterator it(NDIM,3); it; ++it) {
1433 for (std::size_t d=0; d<NDIM; ++d) {
1434 const int odd = key.translation()[d] & 0x1L; // 1 if odd, 0 if even
1435 l[d] -= 1; // (0,1,2) --> (-1,0,1)
1436 if (l[d] == -1)
1437 l[d] = -1-odd;
1438 else if (l[d] == 1)
1439 l[d] = 2 - odd;
1440 }
1441 keyT neigh = neighbor(key, keyT(key.level(),l), is_periodic);
1442
1443 if (neigh.is_valid()) {
1444 v[i++] = this->task(coeffs.owner(neigh), &implT::exists_and_has_children, neigh);
1445 }
1446 else {
1447 v[i++].set(false);
1448 }
1449 }
1450 woT::task(world.rank(), &implT::broaden_op, key, v);
1451 }
1452 }
1453 // Reset value of norm tree so that can repeat broadening
1454 if (fence) {
1455 world.gop.fence();
1456 zero_norm_tree();
1457 world.gop.fence();
1458 }
1459 }
1460
1461 /// sum all the contributions from all scales after applying an operator in mod-NS form
1462 template <typename T, std::size_t NDIM>
1465 if (world.rank() == coeffs.owner(cdata.key0))
1467 if (fence) world.gop.fence();
1468 }
1469
1470 /// sum all the contributions from all scales after applying an operator in mod-NS form
1471
1472 /// cf reconstruct_op
1473 template <typename T, std::size_t NDIM>
1475 // Note that after application of an integral operator not all
1476 // siblings may be present so it is necessary to check existence
1477 // and if absent insert an empty leaf node.
1478 //
1479 // If summing the result of an integral operator (i.e., from
1480 // non-standard form) there will be significant scaling function
1481 // coefficients at all levels and possibly difference coefficients
1482 // in leaves, hence the tree may refine as a result.
1483 typename dcT::iterator it = coeffs.find(key).get();
1484 if (it == coeffs.end()) {
1485 coeffs.replace(key,nodeT(coeffT(),false));
1486 it = coeffs.find(key).get();
1487 }
1488 nodeT& node = it->second;
1489
1490 // The integral operator will correctly connect interior nodes
1491 // to children but may leave interior nodes without coefficients
1492 // ... but they still need to sum down so just give them zeros
1493 if (node.coeff().has_no_data()) node.coeff()=coeffT(cdata.vk,targs);
1494
1495 // if (node.has_children() || node.has_coeff()) { // Must allow for inconsistent state from transform, etc.
1496 if (node.has_children()) { // Must allow for inconsistent state from transform, etc.
1497 coeffT d = node.coeff();
1498 if (key.level() > 0) d += s; // -- note accumulate for NS summation
1499 node.clear_coeff();
1500 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
1501 const keyT& child = kit.key();
1502 coeffT ss= upsample(child,d);
1503 ss.reduce_rank(thresh);
1504 PROFILE_BLOCK(recon_send);
1505 woT::task(coeffs.owner(child), &implT::trickle_down_op, child, ss);
1506 }
1508 else {
1509 node.coeff()+=s;
1511 }
1513
1514 /// change the tree state of this function, might or might not respect fence!
1515 template <typename T, std::size_t NDIM>
1516 void FunctionImpl<T,NDIM>::change_tree_state(const TreeState finalstate, bool fence) {
1517
1518 TreeState current_state=get_tree_state();
1519 if (current_state==finalstate) return;
1520
1521 // try direct conversion if possible, otherwise change to reconstructed state,
1522 // and then convert to final state
1523
1524 // try direct conversion
1525 if (finalstate==reconstructed) { // this MUST cover all cases
1526 if (current_state==compressed) reconstruct(fence);
1527 else if (current_state==nonstandard) reconstruct(fence);
1528 else if (current_state==nonstandard_after_apply) reconstruct(fence);
1529 else if (current_state==nonstandard_with_leaves) {
1532 }
1533 else if (current_state==redundant) {
1536 }
1537 else if (current_state==redundant_after_merge) {
1538 sum_down(fence);
1540 }
1541 else if (current_state==redundant_after_merge) sum_down(fence);
1542 else MADNESS_EXCEPTION("unknown/unsupported current tree state",1);
1543 set_tree_state(reconstructed);
1544 } else if (finalstate==compressed) { // cases that are not covered will be done in two steps
1545 if (current_state==reconstructed) compress(compressed,fence);
1546 if (current_state==nonstandard) standard(fence);
1547 if (current_state==nonstandard_with_leaves) standard(fence);
1548 } else if (finalstate==nonstandard) { // cases that are not covered will be done in two steps
1549 if (current_state==reconstructed) compress(nonstandard,fence);
1550 if (current_state==nonstandard_with_leaves) {
1553 }
1554 } else if (finalstate==nonstandard_with_leaves) { // cases that are not covered will be done in two steps
1555 if (current_state==reconstructed) compress(nonstandard_with_leaves,fence);
1556 } else if (finalstate==redundant) { // cases that are not covered will be done in two steps
1557 if (current_state==reconstructed) make_redundant(fence);
1558 } else {
1559 MADNESS_EXCEPTION("unknown/unsupported final tree state",1);
1560 }
1561 if (fence && VERIFY_TREE) verify_tree(); // Must be after in case nonstandard
1562
1563 // direct conversion worked, we're good
1564 if (finalstate==get_tree_state()) return;
1565
1567 // go through reconstructed state -- requires fence! The uncovered transitions need the
1568 // reconstructed coefficients before the second pass, so the fence is unavoidable; report a
1569 // broken no-fence promise once, from one rank, rather than per rank per call.
1570 if (not fence and FunctionDefaults<NDIM>::get_debug() and world.rank() == 0) {
1571 static std::atomic<bool> reported(false);
1572 if (not reported.exchange(true))
1573 print("change_tree_state:", current_state, "->", finalstate,
1574 "must reconstruct first and therefore fences, despite fence=false");
1575 }
1577 change_tree_state(finalstate,fence);
1579 }
1581
1583 template <typename T, std::size_t NDIM>
1585
1586 if (is_reconstructed()) return;
1587
1591 } else if (is_compressed() or tree_state==nonstandard_after_apply) {
1592 // Must set true here so that successive calls without fence do the right thing
1593 set_tree_state(reconstructed);
1594 if (world.rank() == coeffs.owner(cdata.key0))
1596 } else if (is_nonstandard()) {
1597 // Must set true here so that successive calls without fence do the right thing
1598 set_tree_state(reconstructed);
1599 if (world.rank() == coeffs.owner(cdata.key0))
1600 woT::task(world.rank(), &implT::reconstruct_op, cdata.key0,coeffT(), false);
1601 } else {
1602 MADNESS_EXCEPTION("cannot reconstruct this tree",1);
1603 }
1604 if (fence) world.gop.fence();
1605
1606 }
1607
1608 /// compress the wave function
1609
1610 /// after application there will be sum coefficients at the root level,
1611 /// and difference coefficients at all other levels; furthermore:
1612 /// @param[in] nonstandard keep sum coeffs at all other levels, except leaves
1613 /// @param[in] keepleaves keep sum coeffs (but no diff coeffs) at leaves
1614 /// @param[in] redundant keep only sum coeffs at all levels, discard difference coeffs
1615 template <typename T, std::size_t NDIM>
1616 void FunctionImpl<T,NDIM>::compress(const TreeState newstate, bool fence) {
1617 MADNESS_CHECK_THROW(is_reconstructed(),"impl::compress wants a reconstructe tree");
1618 // Must set true here so that successive calls without fence do the right thing
1619 set_tree_state(newstate);
1620 bool keepleaves1=(tree_state==nonstandard_with_leaves) or (tree_state==redundant);
1621 bool nonstandard1=(tree_state==nonstandard) or (tree_state==nonstandard_with_leaves);
1622 bool redundant1=(tree_state==redundant);
1623
1624 if (world.rank() == coeffs.owner(cdata.key0)) {
1625
1626 compress_spawn(cdata.key0, nonstandard1, keepleaves1, redundant1);
1627 }
1628 if (fence)
1629 world.gop.fence();
1630 }
1631
1632 template <typename T, std::size_t NDIM>
1634 flo_unary_op_node_inplace(remove_internal_coeffs(),fence);
1635 }
1636
1637 template <typename T, std::size_t NDIM>
1639 flo_unary_op_node_inplace(remove_leaf_coeffs(),fence);
1640 }
1642 /// convert this to redundant, i.e. have sum coefficients on all levels
1643 template <typename T, std::size_t NDIM>
1645
1646 // fast return if possible
1647 if (is_redundant()) return;
1648 MADNESS_CHECK_THROW(is_reconstructed(),"impl::make_redundant() wants a reconstructed tree");
1650 }
1651
1652 /// convert this from redundant to standard reconstructed form
1653 template <typename T, std::size_t NDIM>
1655 MADNESS_CHECK_THROW(is_redundant(),"impl::undo_redundant() wants a redundant tree");
1657 flo_unary_op_node_inplace(remove_internal_coeffs(),fence);
1658 }
1659
1660
1661 /// compute for each FunctionNode the norm of the function inside that node
1662 template <typename T, std::size_t NDIM>
1664 if (world.rank() == coeffs.owner(cdata.key0))
1665 norm_tree_spawn(cdata.key0);
1666 if (fence)
1667 world.gop.fence();
1668 }
1669
1670 template <typename T, std::size_t NDIM>
1671 double FunctionImpl<T,NDIM>::norm_tree_op(const keyT& key, const std::vector< Future<double> >& v) {
1672 //PROFILE_MEMBER_FUNC(FunctionImpl);
1673 double sum = 0.0;
1674 int i=0;
1675 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1676 double value = v[i].get();
1677 sum += value*value;
1678 }
1679 sum = sqrt(sum);
1680 coeffs.task(key, &nodeT::set_norm_tree, sum); // why a task? because send is deprecated to keep comm thread free
1681 //if (key.level() == 0) std::cout << "NORM_TREE_TOP " << sum << "\n";
1682 return sum;
1683 }
1684
1685 template <typename T, std::size_t NDIM>
1687 nodeT& node = coeffs.find(key).get()->second;
1688 if (node.has_children()) {
1689 std::vector< Future<double> > v = future_vector_factory<double>(1<<NDIM);
1690 int i=0;
1691 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1692 v[i] = woT::task(coeffs.owner(kit.key()), &implT::norm_tree_spawn, kit.key());
1693 }
1694 return woT::task(world.rank(),&implT::norm_tree_op, key, v);
1695 }
1696 else {
1697 // return Future<double>(node.coeff().normf());
1698 const double norm=node.coeff().normf();
1699 // invoked locally anyways
1700 node.set_norm_tree(norm);
1701 return Future<double>(norm);
1702 }
1703 }
1705 /// truncate using a tree in reconstructed form
1706
1707 /// must be invoked where key is local
1708 template <typename T, std::size_t NDIM>
1711 nodeT& node = coeffs.find(key).get()->second;
1712
1713 // if this is a leaf node just return the sum coefficients
1714 if (not node.has_children()) return Future<coeffT>(node.coeff());
1715
1716 // if this is an internal node, wait for all the children's sum coefficients
1717 // and use them to determine if the children can be removed
1718 std::vector<Future<coeffT> > v = future_vector_factory<coeffT>(1<<NDIM);
1719 int i=0;
1720 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1721 v[i] = woT::task(coeffs.owner(kit.key()), &implT::truncate_reconstructed_spawn, kit.key(),tol,TaskAttributes::hipri());
1722 }
1723
1724 // will return (possibly empty) sum coefficients
1725 return woT::task(world.rank(),&implT::truncate_reconstructed_op,key,v,tol,TaskAttributes::hipri());
1726
1727 }
1728
1729 /// given the sum coefficients of all children, truncate or not
1730
1731 /// @return new sum coefficients (empty if internal, not empty, if new leaf); might delete its children
1732 template <typename T, std::size_t NDIM>
1733 typename FunctionImpl<T,NDIM>::coeffT FunctionImpl<T,NDIM>::truncate_reconstructed_op(const keyT& key, const std::vector< Future<coeffT > >& v, const double tol) {
1734
1735 MADNESS_ASSERT(coeffs.probe(key));
1736
1737 // the sum coefficients might be empty, which means they come from an internal node
1738 // and we must not truncate; so just return empty coeffs again
1739 for (size_t i=0; i<v.size(); ++i) if (v[i].get().has_no_data()) return coeffT();
1740
1741 // do not truncate below level 1
1742 if (key.level()<2) return coeffT();
1743
1744 // compute the wavelet coefficients from the child nodes
1745 typename dcT::accessor acc;
1746 const auto found = coeffs.find(acc, key);
1747 MADNESS_CHECK(found);
1748 int i=0;
1749 tensorT d(cdata.v2k);
1750 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1751 // d(child_patch(kit.key())) += v[i].get();
1752 d(child_patch(kit.key())) += v[i].get().full_tensor();
1753 }
1754
1755 d = filter(d);
1756 tensorT s=copy(d(cdata.s0));
1757 d(cdata.s0) = 0.0;
1758 const double error=d.normf();
1759
1760 nodeT& node = coeffs.find(key).get()->second;
1761
1762 if (error < truncate_tol(tol,key)) {
1763 node.set_has_children(false);
1764 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
1765 coeffs.erase(kit.key());
1766 }
1767 // "replace" children with new sum coefficients
1768 coeffT ss=coeffT(s,targs);
1769 acc->second.set_coeff(ss);
1770 return ss;
1771 } else {
1772 return coeffT();
1773 }
1774 }
1775
1776 /// calculate the wavelet coefficients using the sum coefficients of all child nodes
1777
1778 /// @param[in] key this's key
1779 /// @param[in] v sum coefficients and propagated norms of the child nodes
1780 /// @param[in] nonstandard keep the sum coefficients with the wavelet coefficients
1781 /// @return the sum coefficients and propagated norms
1782 template <typename T, std::size_t NDIM>
1784 const std::vector< Future<compressT> >& v, bool nonstandard1) {
1785 //PROFILE_MEMBER_FUNC(FunctionImpl);
1786
1787 double cpu0=cpu_time();
1788 // Copy child scaling coeffs into contiguous block
1789 tensorT d(cdata.v2k);
1790 // coeffT d(cdata.v2k,targs);
1791 int i=0;
1792 double norm_tree2=0.0, dnorm_tree2=0.0;
1793 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1794 // d(child_patch(kit.key())) += v[i].get();
1795 d(child_patch(kit.key())) += v[i].get().first.full_tensor();
1796 norm_tree2+=v[i].get().second.first*v[i].get().second.first;
1797 dnorm_tree2+=v[i].get().second.second*v[i].get().second.second;
1798 }
1799
1800 d = filter(d);
1801 double cpu1=cpu_time();
1802 timer_filter.accumulate(cpu1-cpu0);
1803 cpu0=cpu1;
1804
1805 typename dcT::accessor acc;
1806 const auto found = coeffs.find(acc, key);
1807 MADNESS_CHECK(found);
1808 MADNESS_CHECK_THROW(!acc->second.has_coeff(),"compress_op: existing coeffs where there should be none");
1809
1810 // tighter thresh for internal nodes
1811 TensorArgs targs2=targs;
1812 targs2.thresh*=0.1;
1813
1814 // need the deep copy for contiguity; ss shares it rather than taking a
1815 // second one, so this k^NDIM block is the only temporary on the path
1816 const tensorT s0block = copy(d(cdata.s0));
1817 coeffT ss = coeffT(s0block);
1818 double snorm = ss.normf();
1819
1820 // dnorm must mean ||d|| in every tree state. The stored tensor keeps its
1821 // s0 block at the root and everywhere in nonstandard form, so zero s0
1822 // unconditionally to measure and put it back when the stored tensor is
1823 // one that keeps it.
1824 const bool stored_tensor_keeps_s0 = (key.level() == 0) or nonstandard1;
1825 d(cdata.s0) = 0.0;
1826 const double dnorm = d.normf();
1827 if (stored_tensor_keeps_s0) d(cdata.s0) = s0block;
1828
1829 coeffT dd=coeffT(d,targs2);
1830 double norm_tree=sqrt(norm_tree2);
1831 // dnorm_tree accumulates this node's d coefficients and all those below it
1832 double dnorm_tree=sqrt(dnorm_tree2+dnorm*dnorm);
1833
1834 acc->second.set_snorm(snorm);
1835 acc->second.set_dnorm(dnorm);
1836 acc->second.set_norm_tree(norm_tree);
1837 acc->second.set_dnorm_tree(dnorm_tree);
1838
1839 acc->second.set_coeff(dd);
1840 cpu1=cpu_time();
1841 timer_compress_svd.accumulate(cpu1-cpu0);
1842
1843 // return sum coefficients and propagated norms
1844 return std::make_pair(ss,std::make_pair(norm_tree,dnorm_tree));
1845 }
1846
1847 /// similar to compress_op, but insert only the sum coefficients in the tree
1848
1849 /// also sets snorm, dnorm, norm_tree and dnorm_tree for all nodes
1850 /// @param[in] key this's key
1851 /// @param[in] v sum coefficients and propagated norms of the child nodes
1852 /// @return the sum coefficients and propagated norms
1853 template <typename T, std::size_t NDIM>
1856
1857 tensorT d(cdata.v2k);
1858 int i=0;
1859 double norm_tree2=0.0, dnorm_tree2=0.0;
1860 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
1861 d(child_patch(kit.key())) += v[i].get().first.full_tensor();
1862 norm_tree2+=v[i].get().second.first*v[i].get().second.first;
1863 dnorm_tree2+=v[i].get().second.second*v[i].get().second.second;
1864 }
1865 d = filter(d);
1866 double norm_tree=sqrt(norm_tree2);
1867
1868 // tighter thresh for internal nodes
1869 TensorArgs targs2=targs;
1870 targs2.thresh*=0.1;
1871
1872 // need the deep copy for contiguity
1873 coeffT s=coeffT(copy(d(cdata.s0)),targs2);
1874 d(cdata.s0)=0.0;
1875 double dnorm=d.normf();
1876 double snorm=s.normf();
1877
1878 typename dcT::accessor acc;
1879 const auto found = coeffs.find(acc, key);
1880 MADNESS_CHECK(found);
1881
1882 // dnorm_tree accumulates this node's d coefficients and all those below it
1883 double dnorm_tree=sqrt(dnorm_tree2+dnorm*dnorm);
1884
1885 acc->second.set_coeff(s);
1886 acc->second.set_dnorm(dnorm);
1887 acc->second.set_snorm(snorm);
1888 acc->second.set_norm_tree(norm_tree);
1889 acc->second.set_dnorm_tree(dnorm_tree);
1890
1891 // return sum coefficients and propagated norms
1892 return std::make_pair(s,std::make_pair(norm_tree,dnorm_tree));
1893 }
1894
1895 /// Changes non-standard compressed form to standard compressed form
1896 template <typename T, std::size_t NDIM>
1898
1899 if (is_compressed()) return;
1902// make_nonstandard = false;
1903 }
1904
1905
1906 /// after apply we need to do some cleanup;
1907
1908 /// forces fence
1909 template <typename T, std::size_t NDIM>
1911 bool print_timings=false;
1912 bool printme=(world.rank()==0 and print_timings);
1913 TensorArgs tight_args(targs);
1914 tight_args.thresh*=0.01;
1915 double begin=wall_time();
1916 double begin1=wall_time();
1917 flo_unary_op_node_inplace(do_consolidate_buffer(tight_args,true),true);
1918 double end1=wall_time();
1919 if (printme) printf("time in consolidate_buffer %8.4f\n",end1-begin1);
1920
1921
1922 // reduce the rank of the final nodes, leave full tensors unchanged
1923 // flo_unary_op_node_inplace(do_reduce_rank(tight_args.thresh),true);
1924 begin1=wall_time();
1926 end1=wall_time();
1927 if (printme) printf("time in do_reduce_rank %8.4f\n",end1-begin1);
1928
1929 // change TT_FULL to low rank
1930 begin1=wall_time();
1931 flo_unary_op_node_inplace(do_change_tensor_type(targs,*this),true);
1932 end1=wall_time();
1933 if (printme) printf("time in do_change_tensor_type %8.4f\n",end1-begin1);
1934
1935 // truncate leaf nodes to avoid excessive tree refinement
1936 begin1=wall_time();
1937 flo_unary_op_node_inplace(do_truncate_NS_leafs(this,FunctionDefaults<NDIM>::get_thresh()*0.3),true);
1938 end1=wall_time();
1939 if (printme) printf("time in do_truncate_NS_leafs %8.4f\n",end1-begin1);
1941 double end=wall_time();
1942 double elapsed=end-begin;
1944 world.gop.fence();
1945 return elapsed;
1946 }
1948
1949 /// after summing up we need to do some cleanup;
1950
1951 /// forces fence
1952 template <typename T, std::size_t NDIM>
1954 world.gop.fence();
1955 flo_unary_op_node_inplace(do_consolidate_buffer(get_tensor_args(),false), true);
1956 sum_down(true);
1958 }
1959
1960 /// Returns the square of the local norm ... no comms
1961 template <typename T, std::size_t NDIM>
1965 "norm2sq_local() needs a tree that holds its coefficients once");
1967 return world.taskq.reduce<double,rangeT,do_norm2sq_local>(rangeT(coeffs.begin(),coeffs.end()),
1969 }
1970
1971
1972
1973
1974 /// Returns the maximum local depth of the tree ... no communications.
1975 template <typename T, std::size_t NDIM>
1977 std::size_t maxdepth = 0;
1978 typename dcT::const_iterator end = coeffs.end();
1979 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
1980 std::size_t N = (std::size_t) it->first.level();
1981 if (N> maxdepth)
1982 maxdepth = N;
1983 }
1984 return maxdepth;
1985 }
1986
1987
1988 /// Returns the maximum depth of the tree ... collective ... global sum/broadcast
1989 template <typename T, std::size_t NDIM>
1991 std::size_t maxdepth = max_local_depth();
1992 world.gop.max(maxdepth);
1993 return maxdepth;
1994 }
1995
1996 /// Returns the max number of nodes on a processor
1997 template <typename T, std::size_t NDIM>
1999 std::size_t maxsize = 0;
2000 maxsize = coeffs.size();
2001 world.gop.max(maxsize);
2002 return maxsize;
2003 }
2004
2005 /// Returns the min number of nodes on a processor
2006 template <typename T, std::size_t NDIM>
2008 std::size_t minsize = 0;
2009 minsize = coeffs.size();
2010 world.gop.min(minsize);
2011 return minsize;
2012 }
2013
2014 /// Returns the size of the tree structure of the function ... collective global sum
2015 template <typename T, std::size_t NDIM>
2017 std::size_t sum = 0;
2018 sum = coeffs.size();
2019 world.gop.sum(sum);
2020 return sum;
2021 }
2022
2023 /// Returns the number of coefficients in the function for each rank
2024 template <typename T, std::size_t NDIM>
2026 std::size_t sum = 0;
2027 for (const auto& [key,node] : coeffs) {
2028 if (node.has_coeff()) sum+=node.size();
2029 }
2030 return sum;
2031 }
2032
2033 /// Returns the number of coefficients in the function ... collective global sum
2034 template <typename T, std::size_t NDIM>
2035 std::size_t FunctionImpl<T,NDIM>::size() const {
2036 std::size_t sum = size_local();
2037 world.gop.sum(sum);
2038 return sum;
2039 }
2040
2041 /// Returns the number of coefficients in the function ... collective global sum
2042 template <typename T, std::size_t NDIM>
2044 std::size_t sum = coeffs.size() * (sizeof(keyT) + sizeof(nodeT));
2045 typename dcT::const_iterator end = coeffs.end();
2046 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
2047 const nodeT& node = it->second;
2048 if (node.has_coeff()) sum+=node.coeff().real_size();
2049 }
2050 world.gop.sum(sum);
2051 return sum;
2052 }
2053
2054 /// Returns the number of coefficients in the function on this MPI rank
2055 template <typename T, std::size_t NDIM>
2057 std::size_t sum =0;
2058 for (auto& [key,node] : coeffs) {
2059 if (node.has_coeff()) sum+=node.coeff().nCoeff();
2060 }
2061 return sum;
2062 }
2063
2064 /// Returns the number of coefficients in the function ... collective global sum
2065 template <typename T, std::size_t NDIM>
2066 std::size_t FunctionImpl<T,NDIM>::nCoeff() const {
2067 std::size_t sum = nCoeff_local();
2068 world.gop.sum(sum);
2069 return sum;
2070 }
2071
2072
2073 /// print tree size and size
2074 template <typename T, std::size_t NDIM>
2075 void FunctionImpl<T,NDIM>::print_size(const std::string name) const {
2076 const size_t tsize=this->tree_size();
2077// const size_t size=this->size();
2078 const size_t ncoeff=this->nCoeff();
2079 const double wall=wall_time();
2080 const double d=sizeof(T);
2081 const double fac=1024*1024*1024;
2082
2083 // This is a diagnostic and must not mutate the tree, so report the norm
2084 // only in the states where norm2sq_local() is defined (cf.
2085 // has_summable_coefficients()). The tree state is replicated, so all
2086 // ranks take the same branch and the global ops stay collective.
2087 const bool norm_is_meaningful = has_summable_coefficients();
2088 double norm=0.0;
2089 if (norm_is_meaningful) {
2090 double local = norm2sq_local();
2091 this->world.gop.sum(local);
2092 this->world.gop.fence();
2093 norm=sqrt(local);
2094 }
2095
2096 if (this->world.rank()==0) {
2097 std::ostringstream oss;
2098 oss << std::setw(40) << name << " at time "
2099 << std::fixed << std::setprecision(1) << wall
2100 << "s: norm/tree/#coeff/size: ";
2101 if (norm_is_meaningful)
2102 oss << std::setw(7) << std::setprecision(5) << norm;
2103 else
2104 oss << std::setw(7) << "n/a";
2105 oss << " " << tsize
2106 << ", " << std::setw(6) << std::setprecision(3) << double(ncoeff)*1.e-6
2107 << " m, " << std::setw(6) << std::setprecision(3) << double(ncoeff)/fac*d
2108 << " GByte";
2109 print(oss.str());
2110 }
2111 }
2112
2113 /// print the number of configurations per node
2114 template <typename T, std::size_t NDIM>
2116 if (this->targs.tt==TT_FULL) return;
2117 int dim=NDIM/2;
2118 int k0=k;
2119 if (is_compressed()) k0=2*k;
2120 Tensor<long> n(int(std::pow(double(k0),double(dim))+1));
2121 long n_full=0;
2122 long n_large=0;
2123
2124 if (world.rank()==0) print("n.size(),k0,dim",n.size(),k0,dim);
2125 typename dcT::const_iterator end = coeffs.end();
2126 for (typename dcT::const_iterator it=coeffs.begin(); it!=end; ++it) {
2127 const nodeT& node = it->second;
2128 if (node.has_coeff()) {
2129 if (node.coeff().rank()>long(n.size())) {
2130 ++n_large;
2131 } else if (node.coeff().rank()==-1) {
2132 ++n_full;
2133 } else if (node.coeff().rank()<0) {
2134 print("small rank",node.coeff().rank());
2135 } else {
2136 n[node.coeff().rank()]++;
2137 }
2138 }
2139 }
2140
2141 world.gop.sum(n.ptr(), n.size());
2142
2143 if (world.rank()==0) {
2144 print("configurations number of nodes");
2145 print(" full rank ",n_full);
2146 for (unsigned int i=0; i<n.size(); i++) {
2147 print(" ",i," ",n[i]);
2148 }
2149 print(" large rank ",n_large);
2150
2151 // repeat for logarithmic scale: <3, <10, <30, <100, ..
2152 Tensor<long> nlog(6);
2153 nlog=0;
2154 for (unsigned int i=0; i<std::min(3l,n.size()); i++) nlog[0]+=n[i];
2155 for (unsigned int i=3; i<std::min(10l,n.size()); i++) nlog[1]+=n[i];
2156 for (unsigned int i=10; i<std::min(30l,n.size()); i++) nlog[2]+=n[i];
2157 for (unsigned int i=30; i<std::min(100l,n.size()); i++) nlog[3]+=n[i];
2158 for (unsigned int i=100; i<std::min(300l,n.size()); i++) nlog[4]+=n[i];
2159 for (unsigned int i=300; i<std::min(1000l,n.size()); i++) nlog[5]+=n[i];
2160
2161 std::vector<std::string> slog={"3","10","30","100","300","1000"};
2162 for (unsigned int i=0; i<nlog.size(); i++) {
2163 print(" < ",slog[i]," ",nlog[i]);
2164 }
2165 print(" large rank ",n_large);
2166
2167 }
2168 }
2169
2170 template <typename T, std::size_t NDIM>
2173 const int k = cdata.k;
2174 T sum = T(0.0);
2175
2176 // v = sum_{p,q,...} c[p,q,...] phi_p(x0) phi_q(x1) ... is a separable
2177 // contraction; the fastest evaluation depends on the dimension.
2178 //
2179 // NDIM<=2 (deep 1-D radial trees are the hottest eval workload): a
2180 // factored register-resident loop. Partial sums stay in registers, the
2181 // only memory traffic is one streaming read of c, and no per-thread
2182 // scratch is needed (px is <= NDIM*MAXK*8 bytes of stack). Routing the
2183 // tiny (k x 1) contraction through general_fast_transform's dispatch
2184 // and ping-pong scratch measured ~20% slower at NDIM=1.
2185 //
2186 // NDIM>=3: general_fast_transform's staged contraction vectorizes
2187 // (the factored loop's inner reduction cannot under strict FP) and
2188 // measured 4-5x faster at NDIM=6; the phi matrices and scratch are
2189 // thread_local, so this path stays allocation-free after warm-up.
2190 if constexpr (NDIM <= 2) {
2191 MADNESS_ASSERT(k <= MAXK);
2192 double px[NDIM][MAXK];
2193 for (std::size_t i=0; i<NDIM; ++i) legendre_scaling_functions(x[i],k,px[i]);
2194
2195 if constexpr (NDIM == 1) {
2196 const T* cp = c.ptr();
2197 for (int p=0; p<k; ++p) sum += cp[p]*px[0][p];
2198 }
2199 else {
2200 for (int p=0; p<k; ++p) {
2201 const double a = px[0][p];
2202 const T* cq = &c(p,0);
2203 T s2 = T(0);
2204 for (int q=0; q<k; ++q) s2 += cq[q]*px[1][q];
2205 sum += a*s2;
2206 }
2207 }
2208 }
2209 else {
2210 thread_local Tensor<double> phi[NDIM];
2211 thread_local int phi_k = -1;
2212 if (phi_k != k) {
2213 for (std::size_t i=0; i<NDIM; ++i) phi[i] = Tensor<double>(long(k), 1L);
2214 phi_k = k;
2215 }
2216 for (std::size_t i=0; i<NDIM; ++i)
2217 legendre_scaling_functions(x[i], k, phi[i].ptr());
2218
2219 typedef TENSOR_RESULT_TYPE(T,double) evalR;
2220 // ws/res are references bound to the thread_local scratch tensors.
2221 auto [ws, res] = madness::detail::eval_scratch<evalR>(c.size());
2222 general_fast_transform(c, phi, res, ws);
2223 sum = res.ptr()[0];
2224 }
2225 // exp2 replaces pow for the level scaling; 1/sqrt(cell_volume) is cached
2226 // per thread and refreshed only if the cell changes (perf-doc change #2).
2227 thread_local double cached_cell_volume = -1.0;
2228 thread_local double cached_inv_sqrt_cell_vol = 0.0;
2230 if (cell_volume != cached_cell_volume) {
2231 cached_cell_volume = cell_volume;
2232 cached_inv_sqrt_cell_vol = 1.0/std::sqrt(cell_volume);
2233 }
2234 return sum * std::exp2(0.5*NDIM*n) * cached_inv_sqrt_cell_vol;
2235 }
2236
2237 template <typename T, std::size_t NDIM>
2238 void FunctionImpl<T,NDIM>::reconstruct_op(const keyT& key, const coeffT& s, const bool accumulate_NS) {
2239 //PROFILE_MEMBER_FUNC(FunctionImpl);
2240 // Note that after application of an integral operator not all
2241 // siblings may be present so it is necessary to check existence
2242 // and if absent insert an empty leaf node.
2243 //
2244 // If summing the result of an integral operator (i.e., from
2245 // non-standard form) there will be significant scaling function
2246 // coefficients at all levels and possibly difference coefficients
2247 // in leaves, hence the tree may refine as a result.
2248 typename dcT::iterator it = coeffs.find(key).get();
2249 if (it == coeffs.end()) {
2250 coeffs.replace(key,nodeT(coeffT(),false));
2251 it = coeffs.find(key).get();
2252 }
2253 nodeT& node = it->second;
2254
2255 // The integral operator will correctly connect interior nodes
2256 // to children but may leave interior nodes without coefficients
2257 // ... but they still need to sum down so just give them zeros
2258 if (node.has_children() && !node.has_coeff()) {
2259 node.set_coeff(coeffT(cdata.v2k,targs));
2260 }
2261
2262 if (node.has_children() || node.has_coeff()) { // Must allow for inconsistent state from transform, etc.
2263 coeffT d = node.coeff();
2264 if (!d.has_data()) d = coeffT(cdata.v2k,targs);
2265 if (accumulate_NS and (key.level() > 0)) d(cdata.s0) += s; // -- note accumulate for NS summation
2266 if (d.dim(0)==2*get_k()) { // d might be pre-truncated if it's a leaf
2267 d = unfilter(d);
2268 node.clear_coeff();
2269 node.set_has_children(true);
2270 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
2271 const keyT& child = kit.key();
2272 coeffT ss = copy(d(child_patch(child)));
2273 ss.reduce_rank(thresh);
2274 //PROFILE_BLOCK(recon_send); // Too fine grain for routine profiling
2275 woT::task(coeffs.owner(child), &implT::reconstruct_op, child, ss, accumulate_NS);
2276 }
2277 } else {
2278 MADNESS_ASSERT(node.is_leaf());
2279 // node.coeff()+=s;
2280 node.coeff().reduce_rank(targs.thresh);
2281 }
2282 }
2283 else {
2284 coeffT ss=s;
2285 if (s.has_no_data()) ss=coeffT(cdata.vk,targs);
2286 if (key.level()) node.set_coeff(copy(ss));
2287 else node.set_coeff(ss);
2288 }
2289 }
2290
2291 template <typename T, std::size_t NDIM>
2292 Tensor<T> fcube(const Key<NDIM>& key, T (*f)(const Vector<double,NDIM>&), const Tensor<double>& qx) {
2293 // fcube(key,typename FunctionFactory<T,NDIM>::FunctorInterfaceWrapper(f) , qx, fval);
2294 std::vector<long> npt(NDIM,qx.dim(0));
2295 Tensor<T> fval(npt);
2296 fcube(key,ElementaryInterface<T,NDIM>(f) , qx, fval);
2297 return fval;
2298 }
2299
2300 template <typename T, std::size_t NDIM>
2302 // fcube(key,typename FunctionFactory<T,NDIM>::FunctorInterfaceWrapper(f) , qx, fval);
2303 std::vector<long> npt(NDIM,qx.dim(0));
2304 Tensor<T> fval(npt);
2305 fcube(key, f, qx, fval);
2306 return fval;
2307 }
2308
2309 template <typename T, std::size_t NDIM>
2310 // void FunctionImpl<T,NDIM>::fcube(const keyT& key, const FunctionFunctorInterface<T,NDIM>& f, const Tensor<double>& qx, tensorT& fval) const {
2311 void fcube(const Key<NDIM>& key, const FunctionFunctorInterface<T,NDIM>& f, const Tensor<double>& qx, Tensor<T>& fval) {
2312 //~ template <typename T, std::size_t NDIM> template< typename FF>
2313 //~ void FunctionImpl<T,NDIM>::fcube(const keyT& key, const FF& f, const Tensor<double>& qx, tensorT& fval) const {
2315 //PROFILE_MEMBER_FUNC(FunctionImpl);
2316 const Vector<Translation,NDIM>& l = key.translation();
2317 const Level n = key.level();
2318 const double h = std::pow(0.5,double(n));
2319 coordT c; // will hold the point in user coordinates
2320 const int npt = qx.dim(0);
2321
2324
2325 // Do pre-screening of the FunctionFunctorInterface, f, before calculating f(r) at quadrature points
2326 coordT c1, c2;
2327 for (std::size_t i = 0; i < NDIM; i++) {
2328 c1[i] = cell(i,0) + h*cell_width[i]*(l[i] + qx((long)0));
2329 c2[i] = cell(i,0) + h*cell_width[i]*(l[i] + qx(npt-1));
2330 }
2331 if (f.screened(c1, c2)) {
2332 fval(___) = 0.0;
2333 return;
2334 }
2335
2336 Tensor<double> vqx;
2337 bool vectorized = f.supports_vectorized();
2338 if (vectorized) {
2339 T* fvptr = fval.ptr();
2340 if (NDIM == 1) {
2341 double* x1 = new double[npt];
2342 int idx = 0;
2343 for (int i=0; i<npt; ++i, ++idx) {
2344 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2345 x1[idx] = c[0];
2346 }
2347 Vector<double*,1> xvals {x1};
2348 f(xvals, fvptr, npt);
2349 delete [] x1;
2350 }
2351 else if (NDIM == 2) {
2352 double* x1 = new double[npt*npt];
2353 double* x2 = new double[npt*npt];
2354 int idx = 0;
2355 for (int i=0; i<npt; ++i) {
2356 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2357 for (int j=0; j<npt; ++j, ++idx) {
2358 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2359 x1[idx] = c[0];
2360 x2[idx] = c[1];
2361 }
2362 }
2363 Vector<double*,2> xvals {x1, x2};
2364 f(xvals, fvptr, npt*npt);
2365 delete [] x1;
2366 delete [] x2;
2367 }
2368 else if (NDIM == 3) {
2369 double* x1 = new double[npt*npt*npt];
2370 double* x2 = new double[npt*npt*npt];
2371 double* x3 = new double[npt*npt*npt];
2372 int idx = 0;
2373 for (int i=0; i<npt; ++i) {
2374 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2375 for (int j=0; j<npt; ++j) {
2376 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2377 for (int k=0; k<npt; ++k, ++idx) {
2378 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2379 x1[idx] = c[0];
2380 x2[idx] = c[1];
2381 x3[idx] = c[2];
2382 }
2383 }
2384 }
2385 Vector<double*,3> xvals {x1, x2, x3};
2386 f(xvals, fvptr, npt*npt*npt);
2387 delete [] x1;
2388 delete [] x2;
2389 delete [] x3;
2390 }
2391 else if (NDIM == 4) {
2392 double* x1 = new double[npt*npt*npt*npt];
2393 double* x2 = new double[npt*npt*npt*npt];
2394 double* x3 = new double[npt*npt*npt*npt];
2395 double* x4 = new double[npt*npt*npt*npt];
2396 int idx = 0;
2397 for (int i=0; i<npt; ++i) {
2398 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2399 for (int j=0; j<npt; ++j) {
2400 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2401 for (int k=0; k<npt; ++k) {
2402 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2403 for (int m=0; m<npt; ++m, ++idx) {
2404 c[3] = cell(3,0) + h*cell_width[3]*(l[3] + qx(m)); // xx
2405 x1[idx] = c[0];
2406 x2[idx] = c[1];
2407 x3[idx] = c[2];
2408 x4[idx] = c[3];
2409 }
2410 }
2411 }
2412 }
2413 Vector<double*,4> xvals {x1, x2, x3, x4};
2414 f(xvals, fvptr, npt*npt*npt*npt);
2415 delete [] x1;
2416 delete [] x2;
2417 delete [] x3;
2418 delete [] x4;
2419 }
2420 else if (NDIM == 5) {
2421 double* x1 = new double[npt*npt*npt*npt*npt];
2422 double* x2 = new double[npt*npt*npt*npt*npt];
2423 double* x3 = new double[npt*npt*npt*npt*npt];
2424 double* x4 = new double[npt*npt*npt*npt*npt];
2425 double* x5 = new double[npt*npt*npt*npt*npt];
2426 int idx = 0;
2427 for (int i=0; i<npt; ++i) {
2428 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2429 for (int j=0; j<npt; ++j) {
2430 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2431 for (int k=0; k<npt; ++k) {
2432 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2433 for (int m=0; m<npt; ++m) {
2434 c[3] = cell(3,0) + h*cell_width[3]*(l[3] + qx(m)); // xx
2435 for (int n=0; n<npt; ++n, ++idx) {
2436 c[4] = cell(4,0) + h*cell_width[4]*(l[4] + qx(n)); // yy
2437 x1[idx] = c[0];
2438 x2[idx] = c[1];
2439 x3[idx] = c[2];
2440 x4[idx] = c[3];
2441 x5[idx] = c[4];
2442 }
2443 }
2444 }
2445 }
2446 }
2447 Vector<double*,5> xvals {x1, x2, x3, x4, x5};
2448 f(xvals, fvptr, npt*npt*npt*npt*npt);
2449 delete [] x1;
2450 delete [] x2;
2451 delete [] x3;
2452 delete [] x4;
2453 delete [] x5;
2454 }
2455 else if (NDIM == 6) {
2456 double* x1 = new double[npt*npt*npt*npt*npt*npt];
2457 double* x2 = new double[npt*npt*npt*npt*npt*npt];
2458 double* x3 = new double[npt*npt*npt*npt*npt*npt];
2459 double* x4 = new double[npt*npt*npt*npt*npt*npt];
2460 double* x5 = new double[npt*npt*npt*npt*npt*npt];
2461 double* x6 = new double[npt*npt*npt*npt*npt*npt];
2462 int idx = 0;
2463 for (int i=0; i<npt; ++i) {
2464 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2465 for (int j=0; j<npt; ++j) {
2466 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2467 for (int k=0; k<npt; ++k) {
2468 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2469 for (int m=0; m<npt; ++m) {
2470 c[3] = cell(3,0) + h*cell_width[3]*(l[3] + qx(m)); // xx
2471 for (int n=0; n<npt; ++n) {
2472 c[4] = cell(4,0) + h*cell_width[4]*(l[4] + qx(n)); // yy
2473 for (int p=0; p<npt; ++p, ++idx) {
2474 c[5] = cell(5,0) + h*cell_width[5]*(l[5] + qx(p)); // zz
2475 x1[idx] = c[0];
2476 x2[idx] = c[1];
2477 x3[idx] = c[2];
2478 x4[idx] = c[3];
2479 x5[idx] = c[4];
2480 x6[idx] = c[5];
2481 }
2482 }
2483 }
2484 }
2485 }
2486 }
2487 Vector<double*,6> xvals {x1, x2, x3, x4, x5, x6};
2488 f(xvals, fvptr, npt*npt*npt*npt*npt*npt);
2489 delete [] x1;
2490 delete [] x2;
2491 delete [] x3;
2492 delete [] x4;
2493 delete [] x5;
2494 delete [] x6;
2495 }
2496 else {
2497 MADNESS_EXCEPTION("FunctionImpl: fcube: confused about NDIM?",NDIM);
2498 }
2499 }
2500 else {
2501 MADNESS_PRAGMA_CLANG(diagnostic push)
2502 MADNESS_PRAGMA_CLANG(diagnostic ignored "-Wtautological-constant-compare")
2503 auto isnan = [](T v) { return std::isnan(v); };
2504 MADNESS_PRAGMA_CLANG(diagnostic pop)
2505 if (NDIM == 1) {
2506 for (int i=0; i<npt; ++i) {
2507 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2508 fval(i) = f(c);
2509 MADNESS_ASSERT(!isnan(fval(i)));
2510 }
2511 }
2512 else if (NDIM == 2) {
2513 for (int i=0; i<npt; ++i) {
2514 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2515 for (int j=0; j<npt; ++j) {
2516 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2517 fval(i,j) = f(c);
2518 MADNESS_ASSERT(!isnan(fval(i,j)));
2519 }
2520 }
2521 }
2522 else if (NDIM == 3) {
2523 for (int i=0; i<npt; ++i) {
2524 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2525 for (int j=0; j<npt; ++j) {
2526 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2527 for (int k=0; k<npt; ++k) {
2528 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2529 fval(i,j,k) = f(c);
2530 MADNESS_ASSERT(!isnan(fval(i,j,k)));
2531 }
2532 }
2533 }
2534 }
2535 else if (NDIM == 4) {
2536 for (int i=0; i<npt; ++i) {
2537 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2538 for (int j=0; j<npt; ++j) {
2539 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2540 for (int k=0; k<npt; ++k) {
2541 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2542 for (int m=0; m<npt; ++m) {
2543 c[3] = cell(3,0) + h*cell_width[3]*(l[3] + qx(m)); // xx
2544 fval(i,j,k,m) = f(c);
2545 MADNESS_ASSERT(!isnan(fval(i,j,k,m)));
2546 }
2547 }
2548 }
2549 }
2550 }
2551 else if (NDIM == 5) {
2552 for (int i=0; i<npt; ++i) {
2553 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2554 for (int j=0; j<npt; ++j) {
2555 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2556 for (int k=0; k<npt; ++k) {
2557 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2558 for (int m=0; m<npt; ++m) {
2559 c[3] = cell(3,0) + h*cell_width[3]*(l[3] + qx(m)); // xx
2560 for (int n=0; n<npt; ++n) {
2561 c[4] = cell(4,0) + h*cell_width[4]*(l[4] + qx(n)); // yy
2562 fval(i,j,k,m,n) = f(c);
2563 MADNESS_ASSERT(!isnan(fval(i,j,k,m,n)));
2564 }
2565 }
2566 }
2567 }
2568 }
2569 }
2570 else if (NDIM == 6) {
2571 for (int i=0; i<npt; ++i) {
2572 c[0] = cell(0,0) + h*cell_width[0]*(l[0] + qx(i)); // x
2573 for (int j=0; j<npt; ++j) {
2574 c[1] = cell(1,0) + h*cell_width[1]*(l[1] + qx(j)); // y
2575 for (int k=0; k<npt; ++k) {
2576 c[2] = cell(2,0) + h*cell_width[2]*(l[2] + qx(k)); // z
2577 for (int m=0; m<npt; ++m) {
2578 c[3] = cell(3,0) + h*cell_width[3]*(l[3] + qx(m)); // xx
2579 for (int n=0; n<npt; ++n) {
2580 c[4] = cell(4,0) + h*cell_width[4]*(l[4] + qx(n)); // yy
2581 for (int p=0; p<npt; ++p) {
2582 c[5] = cell(5,0) + h*cell_width[5]*(l[5] + qx(p)); // zz
2583 fval(i,j,k,m,n,p) = f(c);
2584 MADNESS_ASSERT(!isnan(fval(i,j,k,m,n,p)));
2585 }
2586 }
2587 }
2588 }
2589 }
2590 }
2591 }
2592 else {
2593 MADNESS_EXCEPTION("FunctionImpl: fcube: confused about NDIM?",NDIM);
2594 }
2595 }
2596 }
2597
2598 template <typename T, std::size_t NDIM>
2599 void FunctionImpl<T,NDIM>::fcube(const keyT& key, T (*f)(const coordT&), const Tensor<double>& qx, tensorT& fval) const {
2600 // fcube(key,typename FunctionFactory<T,NDIM>::FunctorInterfaceWrapper(f) , qx, fval);
2602 }
2603
2604 template <typename T, std::size_t NDIM>
2606 madness::fcube(key,f,qx,fval);
2607 }
2608
2609
2610 /// project the functor into this functionimpl, and "return" a tree in reconstructed,
2611 /// rank-reduced form.
2612
2613 /// @param[in] key current FunctionNode
2614 /// @param[in] do_refine
2615 /// @param[in] specialpts in case these are very spiky functions -- don't undersample
2616 template <typename T, std::size_t NDIM>
2618 bool do_refine,
2619 const std::vector<Vector<double,NDIM> >& specialpts) {
2620 //PROFILE_MEMBER_FUNC(FunctionImpl);
2621 if (do_refine && key.level() < max_refine_level) {
2622
2623 // Restrict special points to this box
2624 std::vector<Vector<double,NDIM> > newspecialpts;
2625 if (key.level() < special_level && specialpts.size() > 0) {
2627 const auto bperiodic = bc.is_periodic();
2628 for (unsigned int i = 0; i < specialpts.size(); ++i) {
2629 coordT simpt;
2630 user_to_sim(specialpts[i], simpt);
2631 Key<NDIM> specialkey = simpt2key(simpt, key.level());
2632 if (specialkey.is_neighbor_of(key,bperiodic)) {
2633 newspecialpts.push_back(specialpts[i]);
2634 }
2635 if (key.is_neighbor_of(simpt, bperiodic)) {
2636 newspecialpts.push_back(specialpts[i]);
2637 }
2638 }
2639 }
2640
2641 // If refining compute scaling function coefficients and
2642 // norm of difference coefficients
2643 tensorT r, s0;
2644 double dnorm = 0.0;
2645 //////////////////////////if (newspecialpts.size() == 0)
2646 {
2647 // Make in r child scaling function coeffs at level n+1
2648 r = tensorT(cdata.v2k);
2649 for (KeyChildIterator<NDIM> it(key); it; ++it) {
2650 const keyT& child = it.key();
2651 r(child_patch(child)) = project(child);
2652 }
2653 // Filter then test difference coeffs at level n
2654 tensorT d = filter(r);
2655 if (truncate_on_project) s0 = copy(d(cdata.s0));
2656 d(cdata.s0) = T(0);
2657 dnorm = d.normf();
2658 }
2659
2660 // If have special points always refine. If don't have special points
2661 // refine if difference norm is big
2662 if (newspecialpts.size() > 0 || dnorm >=truncate_tol(thresh,key.level())) {
2663 coeffs.replace(key,nodeT(coeffT(),true)); // Insert empty node for parent
2664 for (KeyChildIterator<NDIM> it(key); it; ++it) {
2665 const keyT& child = it.key();
2666 ProcessID p;
2668 p = world.random_proc();
2669 }
2670 else {
2671 p = coeffs.owner(child);
2672 }
2673 //PROFILE_BLOCK(proj_refine_send); // Too fine grain for routine profiling
2674 woT::task(p, &implT::project_refine_op, child, do_refine, newspecialpts);
2675 }
2676 }
2677 else {
2678 if (truncate_on_project) {
2680 coeffs.replace(key,nodeT(s,false));
2681 }
2682 else {
2683 coeffs.replace(key,nodeT(coeffT(),true)); // Insert empty node for parent
2684 for (KeyChildIterator<NDIM> it(key); it; ++it) {
2685 const keyT& child = it.key();
2687 coeffs.replace(child,nodeT(s,false));
2688 }
2689 }
2690 }
2691 }
2692 else {
2693 coeffs.replace(key,nodeT(coeffT(project(key),targs),false));
2694 }
2695 }
2696
2697 template <typename T, std::size_t NDIM>
2699 std::vector<long> v0(NDIM,0L);
2700 std::vector<long> v1(NDIM,1L);
2701 std::vector<Slice> s(NDIM,Slice(0,0));
2702 const TensorArgs full_args(-1.0,TT_FULL);
2703 if (is_compressed()) {
2704 if (world.rank() == coeffs.owner(cdata.key0)) {
2705 typename dcT::iterator it = coeffs.find(cdata.key0).get();
2706 MADNESS_ASSERT(it != coeffs.end());
2707 nodeT& node = it->second;
2708 MADNESS_ASSERT(node.has_coeff());
2709 // node.node_to_full_rank();
2710 // node.full_tensor_reference()(v0) += t*sqrt(FunctionDefaults<NDIM>::get_cell_volume());
2711 // node.node_to_low_rank();
2712 change_tensor_type(node.coeff(),full_args);
2715 }
2716 }
2717 else {
2718 for (typename dcT::iterator it=coeffs.begin(); it!=coeffs.end(); ++it) {
2719 Level n = it->first.level();
2720 nodeT& node = it->second;
2721 if (node.has_coeff()) {
2722 // this looks funny, but is necessary for GenTensor, since you can't access a
2723 // single matrix element. Therefore make a (1^NDIM) tensor, convert to GenTensor, then
2724 // add to the original one by adding a slice.
2725 tensorT ttt(v1);
2726 ttt=t*sqrt(FunctionDefaults<NDIM>::get_cell_volume()*pow(0.5,double(NDIM*n)));
2728 node.coeff()(s) += tt;
2729 // this was the original line:
2730 // node.coeff().full_tensor()(v0) += t*sqrt(FunctionDefaults<NDIM>::get_cell_volume()*pow(0.5,double(NDIM*n)));
2731
2732 }
2733 }
2734 }
2735 if (fence) world.gop.fence();
2736 }
2737
2738 template <typename T, std::size_t NDIM>
2741 if (is_compressed()) initial_level = std::max(initial_level,1); // Otherwise zero function is confused
2742 if (coeffs.is_local(key)) {
2743 if (is_compressed()) {
2744 if (key.level() == initial_level) {
2745 coeffs.replace(key, nodeT(coeffT(), false));
2746 }
2747 else {
2748 coeffs.replace(key, nodeT(coeffT(cdata.v2k,targs), true));
2749 }
2750 }
2751 else {
2752 if (key.level()<initial_level) {
2753 coeffs.replace(key, nodeT(coeffT(), true));
2754 }
2755 else {
2756 coeffs.replace(key, nodeT(coeffT(cdata.vk,targs), false));
2757 }
2758 }
2759 }
2760 if (key.level() < initial_level) {
2761 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
2763 }
2764 }
2765
2766 }
2767
2768
2769 template <typename T, std::size_t NDIM>
2771 //PROFILE_MEMBER_FUNC(FunctionImpl);
2772 typename dcT::iterator it = coeffs.find(key).get();
2773 if (it == coeffs.end()) {
2774 // In a standard tree all children would exist but some ops (transform)
2775 // can leave the tree in a messy state. Just make the missing node as an
2776 // empty leaf.
2777 coeffs.replace(key,nodeT());
2778 it = coeffs.find(key).get();
2779 }
2780 nodeT& node = it->second;
2781 if (node.has_children()) {
2782 std::vector< Future<bool> > v = future_vector_factory<bool>(1<<NDIM);
2783 int i=0;
2784 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
2785 v[i] = woT::task(coeffs.owner(kit.key()), &implT::truncate_spawn, kit.key(), tol, TaskAttributes::generator());
2786 }
2787 return woT::task(world.rank(),&implT::truncate_op, key, tol, v);
2788 }
2789 else {
2790 // In compressed form leaves should not have coeffs ... however the
2791 // transform op could leave the tree with leaves that do have coeffs
2792 // in which case we want something sensible to happen
2793 //MADNESS_ASSERT(!node.has_coeff());
2794 if (node.has_coeff() && key.level()>1) {
2795 double dnorm = node.coeff().normf();
2796 if (dnorm < truncate_tol(tol,key)) {
2797 node.clear_coeff();
2798 }
2799 }
2800 return Future<bool>(node.has_coeff());
2801 }
2802 }
2803
2804
2805 template <typename T, std::size_t NDIM>
2806 bool FunctionImpl<T,NDIM>::truncate_op(const keyT& key, double tol, const std::vector< Future<bool> >& v) {
2807 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
2808 // If any child has coefficients, a parent cannot truncate
2809 for (int i=0; i<(1<<NDIM); ++i) if (v[i].get()) return true;
2810 nodeT& node = coeffs.find(key).get()->second;
2811
2812 // Interior nodes should always have coeffs but transform might
2813 // leave empty interior nodes ... hence just force no coeffs to
2814 // be zero coeff unless it is a leaf.
2815 if (node.has_children() && !node.has_coeff()) node.set_coeff(coeffT(cdata.v2k,targs));
2816
2817 if (key.level() > 1) { // >1 rather >0 otherwise reconstruct might get confused
2818 double dnorm = node.coeff().normf();
2819 if (dnorm < truncate_tol(tol,key)) {
2820 node.clear_coeff();
2821 if (node.has_children()) {
2822 node.set_has_children(false);
2823 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
2824 coeffs.erase(kit.key());
2825 }
2826 }
2827 }
2828 }
2829 return node.has_coeff();
2830 }
2831
2832
2833 template <typename T, std::size_t NDIM>
2834 void FunctionImpl<T,NDIM>::print_tree(std::ostream& os, Level maxlevel) const {
2835 if (world.rank() == 0) do_print_tree(cdata.key0, os, maxlevel);
2836 world.gop.fence();
2837 if (world.rank() == 0) os.flush();
2838 world.gop.fence();
2839 }
2840
2841
2842 template <typename T, std::size_t NDIM>
2843 void FunctionImpl<T,NDIM>::do_print_tree(const keyT& key, std::ostream& os, Level maxlevel) const {
2844 typename dcT::const_iterator it = coeffs.find(key).get();
2845 if (it == coeffs.end()) {
2846 //MADNESS_EXCEPTION("FunctionImpl: do_print_tree: null node pointer",0);
2847 for (int i=0; i<key.level(); ++i) os << " ";
2848 os << key << " missing --> " << coeffs.owner(key) << "\n";
2849 }
2850 else {
2851 const nodeT& node = it->second;
2852 for (int i=0; i<key.level(); ++i) os << " ";
2853 os << key << " " << node << " --> " << coeffs.owner(key) << "\n";
2854 if (key.level() < maxlevel && node.has_children()) {
2855 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
2856 do_print_tree(kit.key(),os,maxlevel);
2857 }
2858 }
2859 }
2860 }
2861
2862 template <typename T, std::size_t NDIM>
2863 void FunctionImpl<T,NDIM>::print_tree_json(std::ostream& os, Level maxlevel) const {
2864 std::multimap<Level, std::tuple<tranT, std::string>> data;
2865 if (world.rank() == 0) do_print_tree_json(cdata.key0, data, maxlevel);
2866 world.gop.fence();
2867 if (world.rank() == 0) {
2868 for (Level level = 0; level != maxlevel; ++level) {
2869 if (data.count(level) == 0)
2870 break;
2871 else {
2872 if (level > 0)
2873 os << ",";
2874 os << "\"" << level << "\":{";
2875 os << "\"level\": " << level << ",";
2876 os << "\"nodes\":{";
2877 auto range = data.equal_range(level);
2878 for (auto it = range.first; it != range.second; ++it) {
2879 os << "\"" << std::get<0>(it->second) << "\":"
2880 << std::get<1>(it->second);
2881 if (std::next(it) != range.second)
2882 os << ",";
2883 }
2884 os << "}}";
2885 }
2886 }
2887 os.flush();
2888 }
2889 world.gop.fence();
2890 }
2891
2892
2893 template <typename T, std::size_t NDIM>
2894 void FunctionImpl<T,NDIM>::do_print_tree_json(const keyT& key, std::multimap<Level, std::tuple<tranT, std::string>>& data, Level maxlevel) const {
2895 typename dcT::const_iterator it = coeffs.find(key).get();
2896 if (it == coeffs.end()) {
2897 MADNESS_EXCEPTION("FunctionImpl: do_print_tree_json: null node pointer",0);
2898 }
2899 else {
2900 const nodeT& node = it->second;
2901 std::ostringstream oss;
2902 oss << "{";
2903 node.print_json(oss);
2904 oss << ",\"owner\": " << coeffs.owner(key) << "}";
2905 auto node_json_str = oss.str();
2906 data.insert(std::make_pair(key.level(), std::make_tuple(key.translation(), node_json_str)));
2907 if (key.level() < maxlevel && node.has_children()) {
2908 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
2909 do_print_tree_json(kit.key(),data, maxlevel);
2910 }
2911 }
2912 }
2913 }
2914
2915 template <typename T, std::size_t NDIM>
2916 void FunctionImpl<T,NDIM>::print_tree_graphviz(std::ostream& os, Level maxlevel) const {
2917 // aggregate data by level, thus collect data first, then dump
2918 if (world.rank() == 0) do_print_tree_graphviz(cdata.key0, os, maxlevel);
2919 world.gop.fence();
2920 if (world.rank() == 0) os.flush();
2921 world.gop.fence();
2922 }
2923
2924 template <typename T, std::size_t NDIM>
2925 void FunctionImpl<T,NDIM>::do_print_tree_graphviz(const keyT& key, std::ostream& os, Level maxlevel) const {
2926
2927 struct uniqhash {
2928 static int64_t value(const keyT& key) {
2929 int64_t result = 0;
2930 for (int64_t j = 0; j <= key.level()-1; ++j) {
2931 result += (1 << j*NDIM);
2932 }
2933 result += key.translation()[0];
2934 return result;
2935 }
2936 };
2937
2938 typename dcT::const_iterator it = coeffs.find(key).get();
2939 if (it != coeffs.end()) {
2940 const nodeT& node = it->second;
2941 if (key.level() < maxlevel && node.has_children()) {
2942 for (KeyChildIterator<NDIM> kit(key); kit; ++kit) {
2943 os << uniqhash::value(key) << " -> " << uniqhash::value(kit.key()) << "\n";
2944 do_print_tree_graphviz(kit.key(),os,maxlevel);
2945 }
2946 }
2947 }
2948 }
2949
2950 template <typename T, std::size_t NDIM>
2952 //PROFILE_MEMBER_FUNC(FunctionImpl);
2953
2954 if (not functor) MADNESS_EXCEPTION("FunctionImpl: project: confusion about function?",0);
2955
2956 // if functor provides coeffs directly, awesome; otherwise use compute by yourself
2957 if (functor->provides_coeff()) return functor->coeff(key).full_tensor_copy();
2958
2959 MADNESS_ASSERT(cdata.npt == cdata.k); // only necessary due to use of fast transform
2960 tensorT fval(cdata.vq,false); // this will be the returned result
2961 tensorT work(cdata.vk,false); // initially evaluate the function in here
2962 tensorT workq(cdata.vq,false); // initially evaluate the function in here
2963
2964 // compute the values of the functor at the quadrature points and scale appropriately
2965 madness::fcube(key,*functor,cdata.quad_x,work);
2966 work.scale(sqrt(FunctionDefaults<NDIM>::get_cell_volume()*pow(0.5,double(NDIM*key.level()))));
2967 //return transform(work,cdata.quad_phiw);
2968 return fast_transform(work,cdata.quad_phiw,fval,workq);
2969 }
2970
2971 template <typename T, std::size_t NDIM>
2973 if (coeffs.probe(key)) {
2974 return Future<double>(coeffs.find(key).get()->second.get_norm_tree());
2975 }
2976 MADNESS_ASSERT(key.level());
2977 keyT parent = key.parent();
2978 return woT::task(coeffs.owner(parent), &implT::get_norm_tree_recursive, parent, TaskAttributes::hipri());
2979 }
2980
2981
2982 template <typename T, std::size_t NDIM>
2984 const RemoteReference< FutureImpl< std::pair<keyT,coeffT> > >& ref) const {
2985 //PROFILE_MEMBER_FUNC(FunctionImpl);
2986 keyT curr = key;
2987 while (coeffs.is_local(curr)) {
2988 if (coeffs.probe(curr)) {
2989 const nodeT& node = coeffs.find(curr).get()->second;
2990 Future< std::pair<keyT,coeffT> > result(ref);
2991 if (node.has_coeff()) {
2992 //madness::print("sock found it with coeff",curr);
2993 result.set(std::pair<keyT,coeffT>(curr,node.coeff()));
2994 }
2995 else {
2996 //madness::print("sock found it without coeff",curr);
2997 result.set(std::pair<keyT,coeffT>(curr,coeffT()));
2998 }
2999 return;
3000 }
3001 // Key::parent() of the root is the root, so without this a tree missing its root spins here
3002 MADNESS_CHECK_THROW(curr.level() > 0, "sock_it_to_me: no ancestor of the key is in the tree");
3003 curr = curr.parent();
3004 }
3005 woT::task(coeffs.owner(curr), &FunctionImpl<T,NDIM>::sock_it_to_me, curr, ref, TaskAttributes::hipri());
3006 }
3007
3008 // like sock_it_to_me, but it replaces empty node with averaged coeffs from further down the tree
3009 template <typename T, std::size_t NDIM>
3011 const RemoteReference< FutureImpl< std::pair<keyT,coeffT> > >& ref) const {
3013 if (coeffs.probe(key)) {
3014 const nodeT& node = coeffs.find(key).get()->second;
3015 Future< std::pair<keyT,coeffT> > result(ref);
3016 if (node.has_coeff()) {
3017 result.set(std::pair<keyT,coeffT>(key,node.coeff()));
3018 }
3019 else {
3020 result.set(std::pair<keyT,coeffT>(key,nodeT(coeffT(project(key),targs),false).coeff()));
3021 }
3022 }
3023 else {
3024 keyT parent = key.parent();
3025 //PROFILE_BLOCK(sitome2_send); // Too fine grain for routine profiling
3027 }
3028 }
3029
3030
3031 template <typename T, std::size_t NDIM>
3033 const keyT& keyin,
3034 const typename Future<T>::remote_refT& ref) {
3035
3037 // This is ugly. We must figure out a clean way to use
3038 // owner computes rule from the container.
3039 Vector<double,NDIM> x = xin;
3040 keyT key = keyin;
3042 ProcessID me = world.rank();
3043 while (1) {
3044 ProcessID owner = coeffs.owner(key);
3045 if (owner != me) {
3046 //PROFILE_BLOCK(eval_send); // Too fine grain for routine profiling
3047 woT::task(owner, &implT::eval, x, key, ref, TaskAttributes::hipri());
3048 return;
3049 }
3050 else {
3051 typename dcT::futureT fut = coeffs.find(key);
3052 typename dcT::iterator it = fut.get();
3053 nodeT& node = it->second;
3054 if (node.has_coeff()) {
3055 Future<T>(ref).set(eval_cube(key.level(), x, node.coeff().full_tensor()));
3056 return;
3057 }
3058 else {
3059 for (std::size_t i=0; i<NDIM; ++i) {
3060 double xi = x[i]*2.0;
3061 int li = int(xi);
3062 if (li == 2) li = 1;
3063 x[i] = xi - li;
3064 l[i] = 2*l[i] + li;
3065 }
3066 key = keyT(key.level()+1,l);
3067 }
3068 }
3069 }
3070 //MADNESS_EXCEPTION("should not be here",0);
3071 }
3072
3073
3074 template <typename T, std::size_t NDIM>
3075 std::pair<bool,T>
3077 Vector<double,NDIM> x = xin;
3078 keyT key(0);
3080 const ProcessID me = world.rank();
3081 while (key.level() <= maxlevel) {
3082 if (coeffs.owner(key) == me) {
3083 typename dcT::futureT fut = coeffs.find(key);
3084 typename dcT::iterator it = fut.get();
3085 if (it != coeffs.end()) {
3086 nodeT& node = it->second;
3087 if (node.has_coeff()) {
3088 return std::pair<bool,T>(true,eval_cube(key.level(), x, node.coeff().full_tensor()));
3089 }
3090 }
3091 }
3092 for (std::size_t i=0; i<NDIM; ++i) {
3093 double xi = x[i]*2.0;
3094 int li = int(xi);
3095 if (li == 2) li = 1;
3096 x[i] = xi - li;
3097 l[i] = 2*l[i] + li;
3098 }
3099 key = keyT(key.level()+1,l);
3100 }
3101 return std::pair<bool,T>(false,0.0);
3102 }
3103
3104 template <typename T, std::size_t NDIM>
3105 void
3107 std::size_t npt, Level maxlevel,
3108 std::pair<bool,T>* results) {
3109 const ProcessID me = world.rank();
3110
3111 // Memoize the most recently hit leaf (key + shallow coefficient copy).
3112 // Quadrature callers stream spatially coherent points, so consecutive
3113 // points usually land in the same leaf box; replaying the exact
3114 // coordinate-refinement arithmetic against the cached key costs a few
3115 // flops per level and skips the per-level container find()s that
3116 // dominate the descent. A miss falls through to the verbatim
3117 // single-point walk below (owner()+find()+Future -- no const_accessor,
3118 // which doubles NUMA descent cost). Leaves partition the domain and
3119 // interior nodes of a reconstructed function hold no coeffs, so a
3120 // translation match at the cached level identifies exactly the leaf the
3121 // scalar descent would have stopped at: results are bit-for-bit
3122 // identical to the single-point overload. No fence intervenes within a
3123 // call, so the cached node cannot be invalidated mid-call.
3124 bool have_cache = false;
3125 keyT cached_key;
3126 tensorT cached_c;
3127
3128 for (std::size_t ip=0; ip<npt; ++ip) {
3129 results[ip] = std::pair<bool,T>(false, T(0));
3130
3131 if (have_cache) {
3132 Vector<double,NDIM> x = xin[ip];
3134 for (std::size_t i=0; i<NDIM; ++i) l[i] = 0;
3135 const Level nl = cached_key.level();
3136 for (Level nn=0; nn<nl; ++nn) {
3137 for (std::size_t i=0; i<NDIM; ++i) {
3138 double xi = x[i]*2.0;
3139 int li = int(xi);
3140 if (li == 2) li = 1;
3141 x[i] = xi - li;
3142 l[i] = 2*l[i] + li;
3143 }
3144 }
3145 bool same = true;
3146 const Vector<Translation,NDIM>& lc = cached_key.translation();
3147 for (std::size_t i=0; i<NDIM; ++i) same = same && (l[i] == lc[i]);
3148 if (same) {
3149 results[ip] = std::pair<bool,T>(true, eval_cube(nl, x, cached_c));
3150 continue;
3151 }
3152 }
3153
3154 // Verbatim single-point descent (keep in sync with the scalar
3155 // overload above).
3156 Vector<double,NDIM> x = xin[ip];
3157 keyT key(0);
3159 while (key.level() <= maxlevel) {
3160 if (coeffs.owner(key) == me) {
3161 typename dcT::futureT fut = coeffs.find(key);
3162 typename dcT::iterator it = fut.get();
3163 if (it != coeffs.end()) {
3164 nodeT& node = it->second;
3165 if (node.has_coeff()) {
3166 cached_key = key;
3167 cached_c = node.coeff().full_tensor();
3168 have_cache = true;
3169 results[ip] = std::pair<bool,T>(true,
3170 eval_cube(key.level(), x, cached_c));
3171 break;
3172 }
3173 }
3174 }
3175 for (std::size_t i=0; i<NDIM; ++i) {
3176 double xi = x[i]*2.0;
3177 int li = int(xi);
3178 if (li == 2) li = 1;
3179 x[i] = xi - li;
3180 l[i] = 2*l[i] + li;
3181 }
3182 key = keyT(key.level()+1,l);
3183 }
3184 }
3185 }
3186
3187 template <typename T, std::size_t NDIM>
3188 std::vector<std::pair<bool,T>>
3190 std::vector<std::pair<bool,T>> results(xin.size(), std::pair<bool,T>(false,T(0)));
3191 eval_local_only(xin.data(), xin.size(), maxlevel, results.data());
3192 return results;
3193 }
3194
3195 template <typename T, std::size_t NDIM>
3197 const keyT& keyin,
3198 const typename Future<Level>::remote_refT& ref) {
3199
3201 // This is ugly. We must figure out a clean way to use
3202 // owner computes rule from the container.
3203 Vector<double,NDIM> x = xin;
3204 keyT key = keyin;
3206 ProcessID me = world.rank();
3207 while (1) {
3208 ProcessID owner = coeffs.owner(key);
3209 if (owner != me) {
3210 //PROFILE_BLOCK(eval_send); // Too fine grain for routine profiling
3211 woT::task(owner, &implT::evaldepthpt, x, key, ref, TaskAttributes::hipri());
3212 return;
3213 }
3214 else {
3215 typename dcT::futureT fut = coeffs.find(key);
3216 typename dcT::iterator it = fut.get();
3217 nodeT& node = it->second;
3218 if (node.has_coeff()) {
3219 Future<Level>(ref).set(key.level());
3220 return;
3221 }
3222 else {
3223 for (std::size_t i=0; i<NDIM; ++i) {
3224 double xi = x[i]*2.0;
3225 int li = int(xi);
3226 if (li == 2) li = 1;
3227 x[i] = xi - li;
3228 l[i] = 2*l[i] + li;
3229 }
3230 key = keyT(key.level()+1,l);
3231 }
3232 }
3233 }
3234 //MADNESS_EXCEPTION("should not be here",0);
3235 }
3236
3237 template <typename T, std::size_t NDIM>
3239 const keyT& keyin,
3240 const typename Future<long>::remote_refT& ref) {
3241
3243 // This is ugly. We must figure out a clean way to use
3244 // owner computes rule from the container.
3245 Vector<double,NDIM> x = xin;
3246 keyT key = keyin;
3248 ProcessID me = world.rank();
3249 while (1) {
3250 ProcessID owner = coeffs.owner(key);
3251 if (owner != me) {
3252 //PROFILE_BLOCK(eval_send); // Too fine grain for routine profiling
3253 woT::task(owner, &implT::evalR, x, key, ref, TaskAttributes::hipri());
3254 return;
3255 }
3256 else {
3257 typename dcT::futureT fut = coeffs.find(key);
3258 typename dcT::iterator it = fut.get();
3259 nodeT& node = it->second;
3260 if (node.has_coeff()) {
3261 Future<long>(ref).set(node.coeff().rank());
3262 return;
3263 }
3264 else {
3265 for (std::size_t i=0; i<NDIM; ++i) {
3266 double xi = x[i]*2.0;
3267 int li = int(xi);
3268 if (li == 2) li = 1;
3269 x[i] = xi - li;
3270 l[i] = 2*l[i] + li;
3271 }
3272 key = keyT(key.level()+1,l);
3273 }
3274 }
3275 }
3276 //MADNESS_EXCEPTION("should not be here",0);
3277 }
3278
3279
3280 template <typename T, std::size_t NDIM>
3281 void FunctionImpl<T,NDIM>::tnorm(const tensorT& t, double* lo, double* hi) {
3282 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
3284 tensorT work = copy(t);
3285 tensorT tlo = work(cdata.sh);
3286 *lo = tlo.normf();
3287 tlo.fill(0.0);
3288 *hi = work.normf();
3289 }
3290
3291 template <typename T, std::size_t NDIM>
3292 void FunctionImpl<T,NDIM>::tnorm(const GenTensor<T>& t, double* lo, double* hi) {
3294 coeffT shalf=t(cdata.sh);
3295 *lo=shalf.normf();
3296 coeffT sfull=copy(t);
3297 sfull(cdata.sh)-=shalf;
3298 *hi=sfull.normf();
3299 }
3300
3301 template <typename T, std::size_t NDIM>
3302 void FunctionImpl<T,NDIM>::tnorm(const SVDTensor<T>& t, double* lo, double* hi,
3303 const int particle) {
3304 *lo=0.0;
3305 *hi=0.0;
3307 if (t.rank()==0) return;
3308 const tensorT vec=t.flat_vector(particle-1);
3309 for (long i=0; i<t.rank(); ++i) {
3310 double lo1,hi1;
3311 tensorT c=vec(Slice(i,i),_).reshape(cdata.vk);
3312 tnorm(c, &lo1, &hi1); // note we use g instead of h, since g is 3D
3313 *lo+=lo1*t.weights(i);
3314 *hi+=hi1*t.weights(i);
3315 }
3316 }
3317
3318
3319 namespace detail {
3320 template <typename A, typename B>
3321 struct noop {
3322 void operator()(const A& a, const B& b) const {};
3323
3324 template <typename Archive> void serialize(Archive& ar) {}
3325 };
3326
3327 template <typename T, std::size_t NDIM>
3329 T q;
3331 // G++ 4.1.2 ICEs on BGP ... scaleinplace(T q) : q(q) {}
3332 scaleinplace(T q) {this->q = q;}
3333 void operator()(const Key<NDIM>& key, Tensor<T>& t) const {
3334 t.scale(q);
3335 }
3336 void operator()(const Key<NDIM>& key, FunctionNode<T,NDIM>& node) const {
3337 node.coeff().scale(q);
3338 node.scale_norms(std::abs(q));
3339 }
3340 template <typename Archive> void serialize(Archive& ar) {
3341 ar & q;
3342 }
3343 };
3344
3345 template <typename T, std::size_t NDIM>
3347 void operator()(const Key<NDIM>& key, Tensor<T>& t) const {
3348 t.emul(t);
3349 }
3350 template <typename Archive> void serialize(Archive& ar) {}
3351 };
3352
3353 template <typename T, std::size_t NDIM>
3354 struct absinplace {
3355 void operator()(const Key<NDIM>& key, Tensor<T>& t) const {t=abs(t);}
3356 template <typename Archive> void serialize(Archive& ar) {}
3357 };
3358
3359 template <typename T, std::size_t NDIM>
3361 void operator()(const Key<NDIM>& key, Tensor<T>& t) const {abs(t.emul(t));}
3362 template <typename Archive> void serialize(Archive& ar) {}
3363 };
3364
3365 }
3366
3367template <typename T, std::size_t NDIM>
3368 void FunctionImpl<T,NDIM>::scale_inplace(const T q, bool fence) {
3369 // unary_op_coeff_inplace(detail::scaleinplace<T,NDIM>(q), fence);
3371 }
3372
3373 template <typename T, std::size_t NDIM>
3375 //unary_op_value_inplace(&implT::autorefine_square_test, detail::squareinplace<T,NDIM>(), fence);
3377 }
3378
3379 template <typename T, std::size_t NDIM>
3383
3384 template <typename T, std::size_t NDIM>
3388
3389 template <typename T, std::size_t NDIM>
3391 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
3392 double p[200];
3393 double scale = pow(2.0,double(np-nc));
3394 for (int mu=0; mu<cdata.npt; ++mu) {
3395 double xmu = scale*(cdata.quad_x(mu)+lc) - lp;
3396 MADNESS_ASSERT(xmu>-1e-15 && xmu<(1+1e-15));
3398 for (int i=0; i<k; ++i) phi(i,mu) = p[i];
3399 }
3400 phi.scale(pow(2.0,0.5*np));
3401 }
3402
3403 template <typename T, std::size_t NDIM>
3404
3405 const GenTensor<T> FunctionImpl<T,NDIM>::parent_to_child(const coeffT& s, const keyT& parent, const keyT& child) const {
3406 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
3407 // An invalid parent/child means that they are out of the box
3408 // and it is the responsibility of the caller to worry about that
3409 // ... most likely the coefficients (s) are zero to reflect
3410 // zero B.C. so returning s makes handling this easy.
3411 if (parent == child || parent.is_invalid() || child.is_invalid()) return s;
3412
3413 coeffT result = fcube_for_mul<T>(child, parent, s);
3414 result.scale(sqrt(FunctionDefaults<NDIM>::get_cell_volume()*pow(0.5,double(NDIM*child.level()))));
3415 result = transform(result,cdata.quad_phiw);
3416
3417 return result;
3418 }
3419
3420
3421 template <typename T, std::size_t NDIM>
3425 "trace_local() needs a tree that holds its coefficients once");
3426 std::vector<long> v0(NDIM,0);
3427 T sum = 0.0;
3428 if (is_compressed()) {
3429 if (world.rank() == coeffs.owner(cdata.key0)) {
3430 typename dcT::const_iterator it = coeffs.find(cdata.key0).get();
3431 if (it != coeffs.end()) {
3432 const nodeT& node = it->second;
3433 if (node.has_coeff()) sum = node.coeff().full_tensor()(v0);
3434 }
3435 }
3436 }
3437 else {
3438 // on a redundant or nonstandard-with-leaves tree the internal nodes
3439 // repeat what the leaves already carry, cf. norm2sq_local()
3441 for (typename dcT::const_iterator it=coeffs.begin(); it!=coeffs.end(); ++it) {
3442 const keyT& key = it->first;
3443 const nodeT& node = it->second;
3444 if (leaves_only and node.has_children()) continue;
3445 if (node.has_coeff()) sum += node.coeff().full_tensor()(v0)*pow(0.5,NDIM*key.level()*0.5);
3446 }
3447 }
3449 }
3450
3451
3452 // Return whether l is in the interval [0, 2n).
3453 // If is_periodic, then this is checked modulo 2n. The function always
3454 // returns true, but l is *modified* to be in the interval.
3455 static inline bool enforce_bc(bool is_periodic, Level n, Translation& l) {
3456 const Translation two2n = 1ul << n;
3457 if (l < 0) {
3458 if (is_periodic) {
3459 do {
3460 l += two2n; // Periodic BC
3461 } while (l < 0);
3462 } else
3463 return false; // Zero BC
3464 } else if (l >= two2n) {
3465 if (is_periodic) {
3466 do {
3467 l -= two2n; // Periodic BC
3468 } while (l >= two2n);
3469 } else
3470 return false; // Zero BC
3471 }
3472 return true;
3473 }
3474
3475 static inline bool enforce_in_volume(Level n, const Translation& l) {
3476 Translation two2n = 1ul << n;
3477 return l >= 0 && l < two2n;
3478 }
3479
3480 // Return the key corresponding to `key` + `disp`.
3481 // If is_periodic, then translations in the key are taken modulo the box
3482 // dimensions. Otherwise, displacements outside the box are invalid.
3483 template <typename T, std::size_t NDIM>
3484 Key<NDIM> FunctionImpl<T,NDIM>::neighbor(const keyT& key, const Key<NDIM>& disp, const array_of_bools<NDIM>& is_periodic) const {
3486
3487 for (std::size_t axis=0; axis<NDIM; ++axis) {
3488 l[axis] += disp.translation()[axis];
3489
3490 //if (!enforce_bc(bc(axis,0), bc(axis,1), key.level(), l[axis])) {
3491 if (!enforce_bc(is_periodic[axis], key.level(), l[axis])) {
3492 return keyT::invalid();
3493 }
3494 }
3495 return keyT(key.level(),l);
3496 }
3497
3498 template <typename T, std::size_t NDIM>
3501
3502 for (std::size_t axis = 0; axis < NDIM; ++axis) {
3503 l[axis] += disp.translation()[axis];
3504
3505 if (!enforce_in_volume(key.level(), l[axis])) {
3506 return keyT::invalid();
3507 }
3508 }
3509 return keyT(key.level(), l);
3510 }
3511
3512 template <typename T, std::size_t NDIM>
3515 //PROFILE_MEMBER_FUNC(FunctionImpl); // Too fine grain for routine profiling
3516 typedef std::pair< Key<NDIM>,coeffT > argT;
3517 Future<argT> result;
3518 //PROFILE_BLOCK(find_me_send); // Too fine grain for routine profiling
3520 return result;
3521 }
3522
3523
3524 /// will insert
3525 /// @return s coefficient and (norm_tree, dnorm_tree) for key
3526 template <typename T, std::size_t NDIM>
3528 bool nonstandard1, bool keepleaves, bool redundant1) {
3529 if (!coeffs.probe(key)) print("missing node",key);
3530 MADNESS_ASSERT(coeffs.probe(key));
3531
3532 // get fetches remote data (here actually local)
3533 nodeT& node = coeffs.find(key).get()->second;
3534
3535 // internal node -> continue recursion
3536 if (node.has_children()) {
3537 std::vector< Future<compressT> > v = future_vector_factory<compressT>(1<<NDIM);
3538 int i=0;
3539 for (KeyChildIterator<NDIM> kit(key); kit; ++kit,++i) {
3540 //PROFILE_BLOCK(compress_send); // Too fine grain for routine profiling
3541 // readily available
3542 v[i] = woT::task(coeffs.owner(kit.key()), &implT::compress_spawn, kit.key(),
3543 nonstandard1, keepleaves, redundant1, TaskAttributes::hipri());
3544 }
3545 if (redundant1) return woT::task(world.rank(),&implT::make_redundant_op, key, v);
3546 return woT::task(world.rank(),&implT::compress_op, key, v, nonstandard1);
3547 }
3548
3549 // leaf node -> remove coefficients here and pass them back to parent for filtering
3550 // insert snorm, dnorm=0.0, normtree (=snorm), dnormtree (=0.0)
3551 else {
3552 // special case: tree has only root node: keep sum coeffs and make zero diff coeffs
3553 if (key.level()==0) {
3554 if (redundant1) {
3555 // with only the root node existing redundant and reconstructed are the same
3556 coeffT result(node.coeff());
3557 double snorm=node.coeff().normf();
3558 node.set_dnorm(0.0);
3559 node.set_snorm(snorm);
3560 node.set_norm_tree(snorm);
3561 node.set_dnorm_tree(0.0);
3562 return Future<compressT>(std::make_pair(result,std::make_pair(snorm,0.0)));
3563 } else {
3564 // compress
3565 coeffT result(node.coeff());
3566 coeffT sdcoeff(cdata.v2k,this->get_tensor_type());
3567 sdcoeff(cdata.s0)+=node.coeff();
3568 node.coeff()=sdcoeff;
3569 double snorm=node.coeff().normf();
3570 node.set_dnorm(0.0);
3571 node.set_snorm(snorm);
3572 node.set_norm_tree(snorm);
3573 node.set_dnorm_tree(0.0);
3574 return Future<compressT>(std::make_pair(result,std::make_pair(node.coeff().normf(),0.0)));
3575 }
3576
3577 } else { // this is a leaf node
3578 Future<coeffT > result(node.coeff());
3579 const double snorm = node.coeff().normf();
3581 if (not keepleaves) node.clear_coeff();
3582
3583 // norm_tree is the norm of this subtree and the value the parent
3584 // filters with, so it is the leaf norm either way -- reading it
3585 // after clear_coeff() would propagate a zero up to the root.
3586 node.set_norm_tree(snorm);
3587 node.set_dnorm_tree(0.0);
3588 // snorm, in contrast, describes the coefficients this node still
3589 // holds: zero when they were just cleared, matching
3590 // FunctionNode::recompute_snorm_and_dnorm(). The invariant
3591 // "snorm > 0 implies the node has coefficients" is what
3592 // recur_down_for_contraction_map() screens on.
3593 node.set_snorm(keepleaves ? snorm : 0.0);
3594 node.set_dnorm(0.0);
3595
3596 return Future<compressT>(std::make_pair(result,std::make_pair(snorm,0.0)));
3597 }
3598 }
3599 }
3601 template <typename T, std::size_t NDIM>
3603 const keyT& key,
3604 const coordT& plotlo, const coordT& plothi, const std::vector<long>& npt,
3605 bool eval_refine) const {
3606
3607 Tensor<T>& r = *ptr;
3608
3609 coordT h; // Increment between points in each dimension
3610 for (std::size_t i=0; i<NDIM; ++i) {
3611 if (npt[i] > 1) {
3612 h[i] = (plothi[i]-plotlo[i])/(npt[i]-1);
3613 }
3614 else {
3615 MADNESS_ASSERT(plotlo[i] == plothi[i]);
3616 h[i] = 0.0;
3617 }
3618 }
3619
3620 const Level n = key.level();
3621 const Vector<Translation,NDIM>& l = key.translation();
3622 const double twon = pow(2.0,double(n));
3623 const tensorT& coeff = coeffs.find(key).get()->second.coeff().full_tensor(); // Ugh!
3624 long ind[NDIM];
3625 coordT x;
3626
3627 coordT boxlo, boxhi;
3628 Vector<int,NDIM> boxnpt;
3629 double fac = pow(0.5,double(key.level()));
3630 int npttotal = 1;
3631 for (std::size_t d=0; d<NDIM; ++d) {
3632 // Coords of box
3633 boxlo[d] = fac*key.translation()[d];
3634 boxhi[d] = boxlo[d]+fac;
3635
3636 if (boxlo[d] > plothi[d] || boxhi[d] < plotlo[d]) {
3637 // Discard boxes out of the plot range
3638 npttotal = boxnpt[d] = 0;
3639 //print("OO range?");
3640 break;
3641 }
3642 else if (npt[d] == 1) {
3643 // This dimension is only a single point
3644 boxlo[d] = boxhi[d] = plotlo[d];
3645 boxnpt[d] = 1;
3646 }
3647 else {
3648 // Restrict to plot range
3649 boxlo[d] = std::max(boxlo[d],plotlo[d]);
3650 boxhi[d] = std::min(boxhi[d],plothi[d]);
3651
3652 // Round lo up to next plot point; round hi down
3653 double xlo = long((boxlo[d]-plotlo[d])/h[d])*h[d] + plotlo[d];
3654 if (xlo < boxlo[d]) xlo += h[d];
3655 boxlo[d] = xlo;
3656 double xhi = long((boxhi[d]-plotlo[d])/h[d])*h[d] + plotlo[d];
3657 if (xhi > boxhi[d]) xhi -= h[d];
3658 // MADNESS_ASSERT(xhi >= xlo); // nope
3659 boxhi[d] = xhi;
3660 boxnpt[d] = long(round((boxhi[d] - boxlo[d])/h[d])) + 1;
3661 }
3662 npttotal *= boxnpt[d];
3663 }
3664 //print(" box", boxlo, boxhi, boxnpt, npttotal);
3665 if (npttotal > 0) {
3666 for (IndexIterator it(boxnpt); it; ++it) {
3667 for (std::size_t d=0; d<NDIM; ++d) {
3668 double xd = boxlo[d] + it[d]*h[d]; // Sim. coords of point
3669 x[d] = twon*xd - l[d]; // Offset within box
3670 MADNESS_ASSERT(x[d]>=0.0 && x[d] <=1.0); // sanity
3671 if (npt[d] > 1) {
3672 ind[d] = long(round((xd-plotlo[d])/h[d])); // Index of plot point
3673 }
3674 else {
3675 ind[d] = 0;
3677 MADNESS_ASSERT(ind[d]>=0 && ind[d]<npt[d]); // sanity
3678 }
3679 if (eval_refine) {
3680 r(ind) = n;
3681 }
3682 else {
3683 T tmp = eval_cube(n, x, coeff);
3684 r(ind) = tmp;
3685 //print(" eval", ind, tmp, r(ind));
3686 }
3687 }
3688 }
3689 }
3690
3691 /// Set plot_refine=true to get a plot of the refinment levels of
3692 /// the given function (defaulted to false in prototype).
3693 template <typename T, std::size_t NDIM>
3695 const coordT& plothi,
3696 const std::vector<long>& npt,
3697 const bool eval_refine) const {
3699 Tensor<T> r(NDIM, &npt[0]);
3700 //r(___) = 99.0;
3702
3703 for (typename dcT::const_iterator it=coeffs.begin(); it!=coeffs.end(); ++it) {
3704 const keyT& key = it->first;
3705 const nodeT& node = it->second;
3706 if (node.has_coeff()) {
3708 archive::archive_ptr< Tensor<T> >(&r), key, plotlo, plothi, npt, eval_refine);
3710 }
3711
3712 // ITERATOR(r, if (r(IND) == 99.0) {print("BAD", IND); error("bad",0);});
3713
3714 world.taskq.fence();
3715 world.gop.sum(r.ptr(), r.size());
3716 world.gop.fence();
3718 return r;
3719 }
3721 static inline void dxprintvalue(FILE* f, const double t) {
3722 fprintf(f,"%.6e\n",t);
3724
3725 static inline void dxprintvalue(FILE* f, const double_complex& t) {
3726 fprintf(f,"%.6e %.6e\n", t.real(), t.imag());
3727 }
3728
3729 template <typename T, std::size_t NDIM>
3731 const char* filename,
3732 const Tensor<double>& cell,
3733 const std::vector<long>& npt,
3734 bool binary) {
3736 MADNESS_ASSERT(NDIM<=6);
3737 // The plot cell must be an (NDIM x 2) [lo,hi]-per-dimension tensor; an empty
3738 // or ill-shaped cell would dereference out of bounds below (cell(d,0)/(d,1)),
3739 // which previously segfaulted. Convert that into a clear error. Callers must
3740 // default an unset cell to the simulation cell first (see SCF::do_plots).
3741 MADNESS_CHECK_THROW(cell.ndim()==2 && cell.dim(0)>=static_cast<long>(NDIM)
3742 && cell.dim(1)>=2,
3743 "plotdx: plot cell must be an (NDIM x 2) [lo,hi] tensor "
3744 "(got an empty or ill-shaped cell)");
3745 const char* element[6] = {"lines","quads","cubes","cubes4D","cubes5D","cubes6D"};
3746
3747 function.verify();
3748 World& world = const_cast< Function<T,NDIM>& >(function).world();
3749 FILE *f=0;
3750 if (world.rank() == 0) {
3751 f = fopen(filename, "w");
3752 if (!f) MADNESS_EXCEPTION("plotdx: failed to open the plot file", 0);
3753
3754 fprintf(f,"object 1 class gridpositions counts ");
3755 for (std::size_t d=0; d<NDIM; ++d) fprintf(f," %ld",npt[d]);
3756 fprintf(f,"\n");
3757
3758 fprintf(f,"origin ");
3759 for (std::size_t d=0; d<NDIM; ++d) fprintf(f, " %.6e", cell(d,0));
3760 fprintf(f,"\n");
3761
3762 for (std::size_t d=0; d<NDIM; ++d) {
3763 fprintf(f,"delta ");
3764 for (std::size_t c=0; c<d; ++c) fprintf(f, " 0");
3765 double h = 0.0;
3766 if (npt[d]>1) h = (cell(d,1)-cell(d,0))/(npt[d]-1);
3767 fprintf(f," %.6e", h);
3768 for (std::size_t c=d+1; c<NDIM; ++c) fprintf(f, " 0");
3769 fprintf(f,"\n");
3770 }
3771 fprintf(f,"\n");
3772
3773 fprintf(f,"object 2 class gridconnections counts ");
3774 for (std::size_t d=0; d<NDIM; ++d) fprintf(f," %ld",npt[d]);
3775 fprintf(f,"\n");
3776 fprintf(f, "attribute \"element type\" string \"%s\"\n", element[NDIM-1]);
3777 fprintf(f, "attribute \"ref\" string \"positions\"\n");
3778 fprintf(f,"\n");
3779
3780 int npoint = 1;
3781 for (std::size_t d=0; d<NDIM; ++d) npoint *= npt[d];
3782 const char* iscomplex = "";
3783 if (TensorTypeData<T>::iscomplex) iscomplex = "category complex";
3784 const char* isbinary = "";
3785 if (binary) isbinary = "binary";
3786 fprintf(f,"object 3 class array type double %s rank 0 items %d %s data follows\n",
3787 iscomplex, npoint, isbinary);
3788 }
3789
3790 world.gop.fence();
3791 Tensor<T> r = function.eval_cube(cell, npt);
3792
3793 if (world.rank() == 0) {
3794 if (binary) {
3795 // This assumes that the values are double precision
3796 fflush(f);
3797 fwrite((void *) r.ptr(), sizeof(T), r.size(), f);
3798 fflush(f);
3799 }
3800 else {
3801 for (IndexIterator it(npt); it; ++it) {
3802 //fprintf(f,"%.6e\n",r(*it));
3803 dxprintvalue(f,r(*it));
3804 }
3805 }
3806 fprintf(f,"\n");
3807
3808 fprintf(f,"object \"%s\" class field\n",filename);
3809 fprintf(f,"component \"positions\" value 1\n");
3810 fprintf(f,"component \"connections\" value 2\n");
3811 fprintf(f,"component \"data\" value 3\n");
3812 fprintf(f,"\nend\n");
3813 fclose(f);
3814 }
3815 world.gop.fence();
3816 }
3817
3818 template <std::size_t NDIM>
3820 k = 6;
3821 thresh = 1e-4;
3822 initial_level = 2;
3823 special_level = 3;
3824 max_refine_level = 30;
3825 truncate_mode = 0;
3826 refine = true;
3827 autorefine = true;
3828 debug = false;
3829 truncate_on_project = true;
3830 apply_randomize = false;
3831 project_randomize = false;
3832 if (!bc.has_value()) bc = BoundaryConditions<NDIM>(BC_FREE);
3833 tt = TT_FULL;
3836 set_default_pmap(world);
3837 }
3838
3839 template <std::size_t NDIM>
3840 std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > > FunctionDefaults<NDIM>::make_default_pmap(World& world) {
3841 // return std::make_shared<WorldDCDefaultPmap< Key<NDIM> >>(world);
3842 return std::make_shared<LevelPmap< Key<NDIM> >>(world);
3843 // return std::make_shared<SimplePmap< Key<NDIM> >>(world);
3844 }
3845
3846 template <std::size_t NDIM>
3848 pmap = make_default_pmap(world);
3849 pmap_nproc = world.nproc();
3850 }
3851
3852
3853 template <std::size_t NDIM>
3855 std::cout << "Function Defaults:" << std::endl;
3856 std::cout << " Dimension " << ": " << NDIM << std::endl;
3857 std::cout << " k" << ": " << k << std::endl;
3858 std::cout << " thresh" << ": " << thresh << std::endl;
3859 std::cout << " initial_level" << ": " << initial_level << std::endl;
3860 std::cout << " special_level" << ": " << special_level << std::endl;
3861 std::cout << " max_refine_level" << ": " << max_refine_level << std::endl;
3862 std::cout << " truncate_mode" << ": " << truncate_mode << std::endl;
3863 std::cout << " refine" << ": " << refine << std::endl;
3864 std::cout << " autorefine" << ": " << autorefine << std::endl;
3865 std::cout << " debug" << ": " << debug << std::endl;
3866 std::cout << " truncate_on_project" << ": " << truncate_on_project << std::endl;
3867 std::cout << " apply_randomize" << ": " << apply_randomize << std::endl;
3868 std::cout << " project_randomize" << ": " << project_randomize << std::endl;
3869 std::cout << " bc" << ": " << get_bc() << std::endl;
3870 std::cout << " tt" << ": " << tt << std::endl;
3871 std::cout << " cell" << ": " << cell << std::endl;
3872 }
3873
3874 template <typename T, std::size_t NDIM>
3875 const FunctionCommonData<T,NDIM>* FunctionCommonData<T,NDIM>::data[MAXK] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3876
3877 // default values match those in FunctionDefaults::set_defaults(world)
3878 template <std::size_t NDIM> int FunctionDefaults<NDIM>::k = 6;
3879 template <std::size_t NDIM> double FunctionDefaults<NDIM>::thresh = 1e-4;
3880 template <std::size_t NDIM> int FunctionDefaults<NDIM>::initial_level = 2;
3881 template <std::size_t NDIM> int FunctionDefaults<NDIM>::special_level = 3;
3882 template <std::size_t NDIM> int FunctionDefaults<NDIM>::max_refine_level = 30;
3883 template <std::size_t NDIM> int FunctionDefaults<NDIM>::truncate_mode = 0;
3884 template <std::size_t NDIM> bool FunctionDefaults<NDIM>::refine = true;
3885 template <std::size_t NDIM> bool FunctionDefaults<NDIM>::autorefine = true;
3886 template <std::size_t NDIM> bool FunctionDefaults<NDIM>::debug = false;
3887 template <std::size_t NDIM> bool FunctionDefaults<NDIM>::truncate_on_project = true;
3888 template <std::size_t NDIM> bool FunctionDefaults<NDIM>::apply_randomize = false;
3889 template <std::size_t NDIM> bool FunctionDefaults<NDIM>::project_randomize = false;
3890 template <std::size_t NDIM> std::optional<BoundaryConditions<NDIM>> FunctionDefaults<NDIM>::bc;
3891 template <std::size_t NDIM> TensorType FunctionDefaults<NDIM>::tt = TT_FULL;
3895 template <std::size_t NDIM> double FunctionDefaults<NDIM>::cell_volume = 1.;
3896 template <std::size_t NDIM> double FunctionDefaults<NDIM>::cell_min_width = 1.;
3897 template <std::size_t NDIM> double FunctionDefaults<NDIM>::cell_geometric_mean_width = 1.;
3898 template <std::size_t NDIM> std::shared_ptr< WorldDCPmapInterface< Key<NDIM> > > FunctionDefaults<NDIM>::pmap;
3899 template <std::size_t NDIM> int FunctionDefaults<NDIM>::pmap_nproc{-1};
3900
3901}
3902
3903#endif // MADNESS_MRA_MRAIMPL_H__INCLUDED
double w(double t, double eps)
Definition DKops.h:22
double q(double t)
Definition DKops.h:18
std::complex< double > double_complex
Definition cfft.h:14
Definition test_ar.cc:118
Definition test_ar.cc:141
long dim(int i) const
Returns the size of dimension i.
Definition basetensor.h:147
long size() const
Returns the number of elements in the tensor.
Definition basetensor.h:138
This class is used to specify boundary conditions for all operators.
Definition bc.h:72
a class to track where relevant (parent) coeffs are
Definition funcimpl.h:887
Tri-diagonal operator traversing tree primarily for derivative operator.
Definition derivative.h:73
ElementaryInterface (formerly FunctorInterfaceWrapper) interfaces a c-function.
Definition function_interface.h:275
FunctionCommonData holds all Function data common for given k.
Definition function_common_data.h:52
Tensor< double > g1
The separate blocks of twoscale coefficients.
Definition function_common_data.h:105
Tensor< double > quad_phit
transpose of quad_phi
Definition function_common_data.h:102
Tensor< double > quad_phi
quad_phi(i,j) = at x[i] value of phi[j]
Definition function_common_data.h:101
static const FunctionCommonData< T, NDIM > * data[MAXK]
Definition function_common_data.h:54
Tensor< double > h0T
Definition function_common_data.h:106
Tensor< double > quad_phiw
quad_phiw(i,j) = at x[i] value of w[i]*phi[j]
Definition function_common_data.h:103
int npt
no. of quadrature points
Definition function_common_data.h:89
Tensor< double > g0
Definition function_common_data.h:105
Tensor< double > g1T
The separate blocks of twoscale coefficients.
Definition function_common_data.h:106
Tensor< double > hgT
The full twoscale coeff (2k,2k) and transpose.
Definition function_common_data.h:107
Tensor< double > quad_w
quadrature weights
Definition function_common_data.h:100
Tensor< double > h0
Definition function_common_data.h:105
int k
order of the wavelet
Definition function_common_data.h:88
static const FunctionCommonData< T, NDIM > & get(int k)
Definition function_common_data.h:111
static void _init_quadrature(int k, int npt, Tensor< double > &quad_x, Tensor< double > &quad_w, Tensor< double > &quad_phi, Tensor< double > &quad_phiw, Tensor< double > &quad_phit)
Initialize the quadrature information.
Definition mraimpl.h:93
Tensor< double > hg
Definition function_common_data.h:107
Tensor< double > hgsonly
hg[0:k,:]
Definition function_common_data.h:108
Tensor< double > quad_x
quadrature points
Definition function_common_data.h:99
Tensor< double > h1T
Definition function_common_data.h:106
Tensor< double > g0T
Definition function_common_data.h:106
Tensor< double > h1
Definition function_common_data.h:105
void _init_twoscale()
Private. Initialize the twoscale coefficients.
Definition mraimpl.h:72
static Tensor< double > make_default_cell_width()
Definition funcdefaults.h:138
static bool get_project_randomize()
Gets the random load balancing for projection flag.
Definition funcdefaults.h:305
static std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > make_default_pmap(World &world)
Makes a default process map for the given world.
Definition mraimpl.h:3840
static bool truncate_on_project
If true initial projection inserts at n-1 not n.
Definition funcdefaults.h:115
static bool apply_randomize
If true use randomization for load balancing in apply integral operator.
Definition funcdefaults.h:116
static double cell_volume
Volume of simulation cell.
Definition funcdefaults.h:122
static const double & get_thresh()
Returns the default threshold.
Definition funcdefaults.h:183
static int k
Wavelet order.
Definition funcdefaults.h:106
static double get_cell_volume()
Returns the volume of the user cell.
Definition funcdefaults.h:410
static bool get_debug()
Gets the default debug flag, which gates verbose MRA diagnostics.
Definition funcdefaults.h:272
static int truncate_mode
Truncation method.
Definition funcdefaults.h:111
static void set_default_pmap(World &world)
Definition mraimpl.h:3847
static int pmap_nproc
Number of processes assumed by pmap, -1 indicates uninitialized pmap.
Definition funcdefaults.h:127
static double thresh
Truncation threshold.
Definition funcdefaults.h:107
static std::optional< BoundaryConditions< NDIM > > bc
Default boundary conditions, not initialized by default and must be set explicitly before use.
Definition funcdefaults.h:118
static Tensor< double > rcell_width
Reciprocal of width.
Definition funcdefaults.h:121
static bool debug
Controls output of debug info.
Definition funcdefaults.h:114
static int special_level
Minimum level for fine scale projection of special boxes.
Definition funcdefaults.h:109
static double cell_min_width
Size of smallest dimension.
Definition funcdefaults.h:123
static TensorType get_tensor_type()
Returns the default tensor type.
Definition funcdefaults.h:329
static const Tensor< double > & get_cell_width()
Returns the width of each user cell dimension.
Definition funcdefaults.h:390
static double get_cell_geometric_mean_width()
Returns the geometric mean width of the user cell, volume^(1/NDIM).
Definition funcdefaults.h:400
static double cell_geometric_mean_width
volume^(1/NDIM), the mean dimension
Definition funcdefaults.h:124
static std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > pmap
Default mapping of keys to processes.
Definition funcdefaults.h:126
static const BoundaryConditions< NDIM > & get_bc()
Returns the default boundary conditions.
Definition funcdefaults.h:315
static int initial_level
Initial level for fine scale projection.
Definition funcdefaults.h:108
static bool autorefine
Whether to autorefine in multiplication, etc.
Definition funcdefaults.h:113
static Tensor< double > make_default_cell()
Definition funcdefaults.h:129
static void print()
Definition mraimpl.h:3854
static double get_cell_min_width()
Returns the minimum width of any user cell dimension.
Definition funcdefaults.h:405
static void recompute_cell_info()
Definition funcdefaults.h:147
static bool project_randomize
If true use randomization for load balancing in project/refine.
Definition funcdefaults.h:117
static Tensor< double > cell
cell[NDIM][2] Simulation cell, cell(0,0)=xlo, cell(0,1)=xhi, ...
Definition funcdefaults.h:119
static const Tensor< double > & get_cell()
Gets the user cell for the simulation.
Definition funcdefaults.h:352
static void set_defaults(World &world)
Definition mraimpl.h:3819
static int max_refine_level
Level at which to stop refinement.
Definition funcdefaults.h:110
static TensorType tt
structure of the tensor in FunctionNode
Definition funcdefaults.h:125
static Tensor< double > cell_width
Width of simulation cell in each dimension.
Definition funcdefaults.h:120
static bool refine
Whether to refine new functions.
Definition funcdefaults.h:112
Abstract base class interface required for functors used as input to Functions.
Definition function_interface.h:68
Definition funcimpl.h:6300
bool is_nonstandard() const
Definition mraimpl.h:275
T eval_cube(Level n, coordT &x, const tensorT &c) const
Definition mraimpl.h:2171
Timer timer_target_driven
Definition funcimpl.h:1156
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:2925
void change_tensor_type1(const TensorArgs &targs, bool fence)
change the tensor type of the coefficients in the FunctionNode
Definition mraimpl.h:1206
int initial_level
Initial level for refinement.
Definition funcimpl.h:1072
int max_refine_level
Do not refine below this level.
Definition funcimpl.h:1076
int special_level
Minimium level for refinement on special points.
Definition funcimpl.h:1073
compressT compress_op(const keyT &key, const std::vector< Future< compressT > > &v, bool nonstandard)
calculate the wavelet coefficients using the sum coefficients of all child nodes
Definition mraimpl.h:1783
WorldContainer< keyT, nodeT > dcT
Type of container holding the coefficients.
Definition funcimpl.h:1055
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:3196
void scale_inplace(const T q, bool fence)
In-place scale by a constant.
Definition mraimpl.h:3368
void gaxpy_oop_reconstructed(const double alpha, const implT &f, const double beta, const implT &g, const bool fence)
perform: this= alpha*f + beta*g, invoked by result
Definition mraimpl.h:225
World & world
Definition funcimpl.h:1062
bool is_redundant() const
Returns true if the function is redundant.
Definition mraimpl.h:264
FunctionNode< T, NDIM > nodeT
Type of node.
Definition funcimpl.h:1053
std::size_t nCoeff_local() const
Returns the number of coefficients in the function for this MPI rank.
Definition mraimpl.h:2056
void print_size(const std::string name) const
print tree size and size
Definition mraimpl.h:2075
void print_info() const
Prints summary of data distribution.
Definition mraimpl.h:934
void abs_inplace(bool fence)
Definition mraimpl.h:3380
void print_timer() const
Definition mraimpl.h:369
void evalR(const Vector< double, NDIM > &xin, const keyT &keyin, const typename Future< long >::remote_refT &ref)
Get the rank of leaf box of the tree at a point in simulation coordinates.
Definition mraimpl.h:3238
const FunctionCommonData< T, NDIM > & cdata
Definition funcimpl.h:1082
void do_print_grid(const std::string filename, const std::vector< keyT > &keys) const
print the grid in xyz format
Definition mraimpl.h:596
bool has_coefficients_on_leaves_only() const
Returns true if only the leaves of this tree carry its coefficients.
Definition mraimpl.h:290
Future< compressT > compress_spawn(const keyT &key, bool nonstandard, bool keepleaves, bool redundant1)
Definition mraimpl.h:3527
std::size_t nCoeff() const
Returns the number of coefficients in the function ... collective global sum.
Definition mraimpl.h:2066
keyT neighbor_in_volume(const keyT &key, const keyT &disp) const
Returns key of general neighbor that resides in-volume.
Definition mraimpl.h:3499
void compress(const TreeState newstate, bool fence)
Definition mraimpl.h:1616
Future< bool > truncate_spawn(const keyT &key, double tol)
Returns true if after truncation this node has coefficients.
Definition mraimpl.h:2770
Future< double > norm_tree_spawn(const keyT &key)
Definition mraimpl.h:1686
std::vector< keyT > local_leaf_keys() const
return the keys of the local leaf boxes
Definition mraimpl.h:570
void do_print_tree(const keyT &key, std::ostream &os, Level maxlevel) const
Functor for the do_print_tree method.
Definition mraimpl.h:2843
void unset_functor()
Definition mraimpl.h:324
void do_print_plane(const std::string filename, std::vector< Tensor< double > > plotinfo, const int xaxis, const int yaxis, const coordT el2)
print the MRA structure
Definition mraimpl.h:511
std::pair< Key< NDIM >, ShallowNode< T, NDIM > > find_datum(keyT key) const
return the a std::pair<key, node>, which MUST exist
Definition mraimpl.h:1072
void set_functor(const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > functor1)
Definition mraimpl.h:305
bool verify_tree_state_local() const
check that the tree state and the coeffs are consistent
Definition mraimpl.h:171
const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > & get_pmap() const
Definition mraimpl.h:209
Tensor< Q > fcube_for_mul(const keyT &child, const keyT &parent, const Tensor< Q > &coeff) const
Compute the function values for multiplication.
Definition funcimpl.h:2151
Timer timer_filter
Definition funcimpl.h:1154
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:2983
double get_thresh() const
Definition mraimpl.h:340
void trickle_down(bool fence)
sum all the contributions from all scales after applying an operator in mod-NS form
Definition mraimpl.h:1463
bool autorefine
If true, autorefine where appropriate.
Definition funcimpl.h:1078
void set_autorefine(bool value)
Definition mraimpl.h:349
tensorT filter(const tensorT &s) const
Transform sum coefficients at level n to sums+differences at level n-1.
Definition mraimpl.h:1259
void chop_at_level(const int n, const bool fence=true)
remove all nodes with level higher than n
Definition mraimpl.h:1222
TreeState tree_state
Definition funcimpl.h:1085
void print_tree_json(std::ostream &os=std::cout, Level maxlevel=10000) const
Definition mraimpl.h:2863
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:808
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:1164
bool is_compressed() const
Returns true if the function is compressed.
Definition mraimpl.h:252
Vector< double, NDIM > coordT
Type of vector holding coordinates.
Definition funcimpl.h:1057
Tensor< T > tensorT
Type of tensor for anything but to hold coeffs.
Definition funcimpl.h:1050
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:1173
void print_stats() const
print the number of configurations per node
Definition mraimpl.h:2115
void broaden(const array_of_bools< NDIM > &is_periodic, bool fence)
Definition mraimpl.h:1412
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:1733
void refine_op(const opT &op, const keyT &key)
Definition funcimpl.h:5132
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:2605
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:1025
std::vector< Slice > child_patch(const keyT &child) const
Returns patch referring to coeffs of child in parent box.
Definition mraimpl.h:797
void print_tree_graphviz(std::ostream &os=std::cout, Level maxlevel=10000) const
Definition mraimpl.h:2916
void set_tree_state(const TreeState &state)
Definition funcimpl.h:1539
std::size_t min_nodes() const
Returns the min number of nodes on a processor.
Definition mraimpl.h:2007
std::shared_ptr< FunctionFunctorInterface< T, NDIM > > functor
Definition funcimpl.h:1084
Timer timer_compress_svd
Definition funcimpl.h:1155
void make_redundant(const bool fence)
convert this to redundant, i.e. have sum coefficients on all levels
Definition mraimpl.h:1644
std::size_t max_nodes() const
Returns the max number of nodes on a processor.
Definition mraimpl.h:1998
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:1338
TensorArgs targs
type of tensor to be used in the FunctionNodes
Definition funcimpl.h:1080
void flo_unary_op_node_inplace(const opT &op, bool fence)
Definition funcimpl.h:2416
std::size_t size_local() const
Returns the number of coefficients in the function for each rank.
Definition mraimpl.h:2025
GenTensor< Q > values2coeffs(const keyT &key, const GenTensor< Q > &values) const
Definition funcimpl.h:2130
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:3602
T trace_local() const
Returns int(f(x),x) in local volume.
Definition mraimpl.h:3422
void print_grid(const std::string filename) const
Definition mraimpl.h:554
bool get_autorefine() const
Definition mraimpl.h:346
int k
Wavelet order.
Definition funcimpl.h:1070
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:3390
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:3514
TensorType get_tensor_type() const
Definition mraimpl.h:331
void remove_leaf_coefficients(const bool fence)
Definition mraimpl.h:1638
void insert_zero_down_to_initial_level(const keyT &key)
Initialize nodes to zero function at initial_level of refinement.
Definition mraimpl.h:2739
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:1036
void unary_op_node_inplace(const opT &op, bool fence)
Definition funcimpl.h:2325
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:2894
void finalize_sum()
after summing up we need to do some cleanup;
Definition mraimpl.h:1953
dcT coeffs
The coefficients.
Definition funcimpl.h:1087
bool exists_and_is_leaf(const keyT &key) const
Definition mraimpl.h:1382
void verify_tree() const
Verify tree is properly constructed ... global synchronization involved.
Definition mraimpl.h:113
void set_tensor_args(const TensorArgs &t)
Definition mraimpl.h:337
Range< typename dcT::const_iterator > rangeT
Definition funcimpl.h:6441
std::size_t real_size() const
Returns the number of coefficients in the function ... collective global sum.
Definition mraimpl.h:2043
bool exists_and_has_children(const keyT &key) const
Definition mraimpl.h:1377
void sum_down_spawn(const keyT &key, const coeffT &s)
is this the same as trickle_down() ?
Definition mraimpl.h:977
long box_interior[1000]
Definition funcimpl.h:3553
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:3484
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:1663
friend class FunctionImpl
Definition funcimpl.h:1060
const Tensor< double > cell
the size of the root cell in each dimension, unchangeable
Definition funcimpl.h:1075
bool has_leaves() const
Definition mraimpl.h:300
bool verify_parents_and_children() const
check that parents and children are consistent
Definition mraimpl.h:121
void reconstruct_op(const keyT &key, const coeffT &s, const bool accumulate_NS=true)
Definition mraimpl.h:2238
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:3405
void undo_redundant(const bool fence)
convert this from redundant to standard reconstructed form
Definition mraimpl.h:1654
GenTensor< T > coeffT
Type of tensor used to hold coeffs.
Definition funcimpl.h:1054
const keyT & key0() const
Returns cdata.key0.
Definition mraimpl.h:406
double finalize_apply()
after apply we need to do some cleanup;
Definition mraimpl.h:1910
bool leaves_only
Definition funcimpl.h:6446
const dcT & get_coeffs() const
Definition mraimpl.h:355
compressT make_redundant_op(const keyT &key, const std::vector< Future< compressT > > &v)
similar to compress_op, but insert only the sum coefficients in the tree
Definition mraimpl.h:1855
double norm2sq_local() const
Returns the square of the local norm ... no comms.
Definition mraimpl.h:1962
const FunctionCommonData< T, NDIM > & get_cdata() const
Definition mraimpl.h:361
void sum_down(bool fence)
After 1d push operator must sum coeffs down the tree to restore correct scaling function coefficients...
Definition mraimpl.h:1017
bool noautorefine(const keyT &key, const tensorT &t) const
Always returns false (for when autorefine is not wanted).
Definition mraimpl.h:960
double truncate_tol(double tol, const keyT &key) const
Returns the truncation threshold according to truncate_method.
Definition mraimpl.h:722
bool autorefine_square_test(const keyT &key, const nodeT &t) const
Returns true if this block of coeffs needs autorefining.
Definition mraimpl.h:966
void erase(const Level &max_level)
truncate tree at a certain level
Definition mraimpl.h:840
std::pair< coeffT, std::pair< double, double > > compressT
s coefficients plus the (snorm_tree, dnorm_tree) pair propagated up by compress
Definition funcimpl.h:5219
void reconstruct(bool fence)
Definition mraimpl.h:1584
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:3897
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:1120
static void tnorm(const tensorT &t, double *lo, double *hi)
Computes norm of low/high-order polyn. coeffs for autorefinement test.
Definition mraimpl.h:3281
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:3076
std::size_t max_depth() const
Returns the maximum depth of the tree ... collective ... global sum/broadcast.
Definition mraimpl.h:1990
std::size_t size() const
Returns the number of coefficients in the function ... collective global sum.
Definition mraimpl.h:2035
void reduce_rank(const double thresh, bool fence)
reduce the rank of the coefficients tensors
Definition mraimpl.h:1214
TreeState get_tree_state() const
Definition funcimpl.h:1543
std::shared_ptr< FunctionFunctorInterface< T, NDIM > > get_functor()
Definition mraimpl.h:312
tensorT unfilter(const tensorT &s) const
Transform sums+differences at level n to sum coefficients at level n+1.
Definition mraimpl.h:1288
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:3694
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:1516
Future< coeffT > truncate_reconstructed_spawn(const keyT &key, const double tol)
truncate using a tree in reconstructed form
Definition mraimpl.h:1709
GenTensor< Q > coeffs2values(const keyT &key, const GenTensor< Q > &coeff) const
Definition funcimpl.h:1997
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:1183
Timer timer_lr_result
Definition funcimpl.h:1153
void truncate(double tol, bool fence)
Truncate according to the threshold with optional global fence.
Definition mraimpl.h:390
bool is_reconstructed() const
Returns true if the function is compressed.
Definition mraimpl.h:258
double norm_tree_op(const keyT &key, const std::vector< Future< double > > &v)
Definition mraimpl.h:1671
void reset_timer()
Definition mraimpl.h:378
void refine_to_common_level(const std::vector< FunctionImpl< T, NDIM > * > &v, const std::vector< tensorT > &c, const keyT key)
Refine multiple functions down to the same finest level.
Definition mraimpl.h:870
int get_k() const
Definition mraimpl.h:352
FunctionImpl< T, NDIM > implT
Type of this class (implementation).
Definition funcimpl.h:1048
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:3032
bool truncate_op(const keyT &key, double tol, const std::vector< Future< bool > > &v)
Definition mraimpl.h:2806
void zero_norm_tree()
Definition mraimpl.h:1400
std::size_t max_local_depth() const
Returns the maximum local depth of the tree ... no communications.
Definition mraimpl.h:1976
tensorT project(const keyT &key) const
Definition mraimpl.h:2951
double thresh
Screening threshold.
Definition funcimpl.h:1071
double check_symmetry_local() const
Returns some asymmetry measure ... no comms.
Definition mraimpl.h:856
Future< double > get_norm_tree_recursive(const keyT &key) const
Definition mraimpl.h:2972
bool is_redundant_after_merge() const
Returns true if the function is redundant_after_merge.
Definition mraimpl.h:270
Key< NDIM > keyT
Type of key.
Definition funcimpl.h:1052
bool truncate_on_project
If true projection inserts at level n-1 not n.
Definition funcimpl.h:1079
bool is_on_demand() const
Definition mraimpl.h:285
void accumulate_timer(const double time) const
Definition mraimpl.h:364
void trickle_down_op(const keyT &key, const coeffT &s)
sum all the contributions from all scales after applying an operator in mod-NS form
Definition mraimpl.h:1474
void set_thresh(double value)
Definition mraimpl.h:343
Tensor< double > print_plane_local(const int xaxis, const int yaxis, const coordT &el2)
collect the data for a plot of the MRA structure locally on each node
Definition mraimpl.h:435
void sock_it_to_me_too(const keyT &key, const RemoteReference< FutureImpl< std::pair< keyT, coeffT > > > &ref) const
Definition mraimpl.h:3010
void broaden_op(const keyT &key, const std::vector< Future< bool > > &v)
Definition mraimpl.h:1388
void print_plane(const std::string filename, const int xaxis, const int yaxis, const coordT &el2)
Print a plane ("xy", "xz", or "yz") containing the point x to file.
Definition mraimpl.h:415
void print_tree(std::ostream &os=std::cout, Level maxlevel=10000) const
Definition mraimpl.h:2834
bool has_summable_coefficients() const
Returns true if summing over the local nodes yields the function.
Definition mraimpl.h:295
void project_refine_op(const keyT &key, bool do_refine, const std::vector< Vector< double, NDIM > > &specialpts)
Definition mraimpl.h:2617
std::size_t tree_size() const
Returns the size of the tree structure of the function ... collective global sum.
Definition mraimpl.h:2016
void add_scalar_inplace(T t, bool fence)
Adds a constant to the function. Local operation, optional fence.
Definition mraimpl.h:2698
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:3991
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:1308
void abs_square_inplace(bool fence)
Definition mraimpl.h:3385
void put_in_box(ProcessID from, long nl, long ni) const
Definition mraimpl.h:925
void unary_op_value_inplace(const opT &op, bool fence)
Definition funcimpl.h:3120
Timer timer_accumulate
Definition funcimpl.h:1151
TensorArgs get_tensor_args() const
Definition mraimpl.h:334
void average(const implT &rhs)
take the average of two functions, similar to: this=0.5*(this+rhs)
Definition mraimpl.h:1195
void diff(const DerivativeBase< T, NDIM > *D, const implT *f, bool fence)
Definition mraimpl.h:1048
void square_inplace(bool fence)
Pointwise squaring of function with optional global fence.
Definition mraimpl.h:3374
void remove_internal_coefficients(const bool fence)
Definition mraimpl.h:1633
void compute_snorm_and_dnorm(bool fence=true)
compute norm of s and d coefficients for all nodes
Definition mraimpl.h:1238
long box_leaf[1000]
Definition funcimpl.h:3552
void standard(bool fence)
Definition mraimpl.h:1897
bool is_nonstandard_with_leaves() const
Definition mraimpl.h:280
int truncate_mode
0=default=(|d|<thresh), 1=(|d|<thresh/2^n), 2=(|d|<thresh/4^n);
Definition funcimpl.h:1077
FunctionNode holds the coefficients, etc., at each node of the 2^NDIM-tree.
Definition funcimpl.h:136
bool has_coeff() const
Returns true if there are coefficients in this node.
Definition funcimpl.h:210
size_t size() const
Returns the number of coefficients in this node.
Definition funcimpl.h:252
void clear_coeff()
Clears the coefficients (has_coeff() will subsequently return false).
Definition funcimpl.h:305
bool is_leaf() const
Returns true if this does not have children.
Definition funcimpl.h:223
void set_has_children(bool flag)
Sets has_children attribute to value of flag.
Definition funcimpl.h:264
void scale_norms(const double a)
Multiply the stored norms by a, for coefficients scaled by some q with |q| = a.
Definition funcimpl.h:360
double get_norm_tree() const
Gets the value of norm_tree.
Definition funcimpl.h:326
void set_snorm(const double sn)
set the precomputed norm of the (virtual) s coefficients
Definition funcimpl.h:341
void set_is_leaf(bool flag)
Sets has_children attribute to value of !flag.
Definition funcimpl.h:290
void print_json(std::ostream &s) const
Definition funcimpl.h:503
void set_dnorm_tree(double dnorm_tree)
Sets the value of dnorm_tree.
Definition funcimpl.h:321
bool has_children() const
Returns true if this node has children.
Definition funcimpl.h:217
void set_coeff(const coeffT &coeffs)
Takes a shallow copy of the coeff — same as this->coeff()=coeff.
Definition funcimpl.h:295
void set_dnorm(const double dn)
set the precomputed norm of the (virtual) d coefficients
Definition funcimpl.h:346
coeffT & coeff()
Returns a non-const reference to the tensor containing the coeffs.
Definition funcimpl.h:237
void set_norm_tree(double norm_tree)
Sets the value of norm_tree.
Definition funcimpl.h:316
A multiresolution adaptive numerical function.
Definition mra.h:141
Implements the functionality of futures.
Definition future.h:75
A future is a possibly yet unevaluated value.
Definition future.h:370
T & get(bool dowork=true) &
Gets the value, waiting if necessary.
Definition future.h:571
remote_refT remote_ref(World &world) const
Returns a structure used to pass references to another process.
Definition future.h:672
void set(const Future< T > &other)
A.set(B), where A and B are futures ensures A has/will have the same value as B.
Definition future.h:505
RemoteReference< FutureImpl< T > > remote_refT
Definition future.h:395
Definition lowranktensor.h:59
GenTensor convert(const TensorArgs &) const
Definition gentensor.h:198
long dim(const int i) const
return the number of entries in dimension i
Definition lowranktensor.h:391
Tensor< T > full_tensor_copy() const
Definition gentensor.h:206
long ndim() const
Definition lowranktensor.h:386
constexpr bool is_full_tensor() const
Definition gentensor.h:224
void reduce_rank(const double &)
Definition gentensor.h:217
bool has_no_data() const
Definition gentensor.h:211
size_t real_size() const
Definition gentensor.h:214
GenTensor< T > & emul(const GenTensor< T > &other)
Inplace multiply by corresponding elements of argument Tensor.
Definition lowranktensor.h:639
float_scalar_type normf() const
Definition lowranktensor.h:406
long rank() const
Definition gentensor.h:212
const Tensor< T > & full_tensor() const
Definition gentensor.h:200
size_t nCoeff() const
Definition gentensor.h:215
TensorType tensor_type() const
Definition gentensor.h:221
bool has_data() const
Definition gentensor.h:210
const long * dims() const
return the number of entries in dimension i
Definition lowranktensor.h:397
IsSupported< TensorTypeData< Q >, GenTensor< T > & >::type scale(Q fac)
Inplace multiplication by scalar of supported type (legacy name).
Definition lowranktensor.h:428
constexpr bool is_svd_tensor() const
Definition gentensor.h:222
Definition indexit.h:142
Definition indexit.h:56
Iterates in lexical order thru all children of a key.
Definition key.h:624
Key is the index for a node of the 2^NDIM-tree.
Definition key.h:71
Level level() const
Definition key.h:170
bool is_neighbor_of(const Key &key, const array_of_bools< NDIM > &bperiodic) const
Assuming keys are at the same level, returns true if displaced by no more than 1 in any direction.
Definition key.h:401
bool thisKeyContains(const Vector< double, NDIM > &x, const unsigned int &dim0, const unsigned int &dim1) const
check if this MultiIndex contains point x, disregarding these two dimensions
Definition key.h:476
bool is_invalid() const
Checks if a key is invalid.
Definition key.h:120
Key parent(int generation=1) const
Returns the key of the parent.
Definition key.h:366
const Vector< Translation, NDIM > & translation() const
Definition key.h:175
static Key< NDIM > invalid()
Returns an invalid key.
Definition key.h:111
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:394
double weights(const unsigned int &i) const
return the weight
Definition srconf.h:679
const Tensor< T > flat_vector(const unsigned int &idim) const
return shallow copy of a slice of one of the vectors, flattened to (r,kVec)
Definition srconf.h:553
Definition SVDTensor.h:42
long rank() const
Definition SVDTensor.h:77
A slice defines a sub-range or patch of a dimension.
Definition slice.h:103
static TaskAttributes hipri()
Definition thread.h:457
static TaskAttributes generator()
Definition thread.h:449
Traits class to specify support of numeric types.
Definition type_data.h:56
A tensor is a multidimensional array.
Definition tensor.h:313
float_scalar_type normf() const
Returns the Frobenius norm of the tensor.
Definition tensor.h:1731
Tensor< T > & fill(T x)
Inplace fill with a scalar (legacy name).
Definition tensor.h:567
T * ptr()
Returns a pointer to the internal data.
Definition tensor.h:1845
IsSupported< TensorTypeData< Q >, Tensor< T > & >::type scale(Q x)
Inplace multiplication by scalar of supported type (legacy name).
Definition tensor.h:691
Tensor< T > & emul(const Tensor< T > &t)
Inplace multiply by corresponding elements of argument Tensor.
Definition tensor.h:1804
bool has_data() const
Definition tensor.h:1907
const TensorIterator< T > & end() const
End point for forward iteration.
Definition tensor.h:1897
A simple, fixed dimension vector.
Definition vector.h:64
iterator begin()
Returns an iterator to the beginning of the local data (no communication).
Definition worlddc.h:1552
implT::const_iterator const_iterator
Definition worlddc.h:1310
iterator end()
Returns an iterator past the end of the local data (no communication).
Definition worlddc.h:1566
Future< iterator > futureT
Definition worlddc.h:1313
implT::iterator iterator
Definition worlddc.h:1309
implT::accessor accessor
Definition worlddc.h:1311
void fence(bool debug=false)
Synchronizes all processes in communicator AND globally ensures no pending AM or tasks.
Definition worldgop.cc:177
ProcessID me
Definition world_object.h:514
detail::task_result_type< memfnT >::futureT send(ProcessID dest, memfnT memfn) const
Definition world_object.h:858
detail::task_result_type< memfnT >::futureT task(ProcessID dest, memfnT memfn, const TaskAttributes &attr=TaskAttributes()) const
Definition world_object.h:1132
A parallel world class.
Definition world.h:134
ProcessID rank() const
Returns the process rank in this World (same as MPI_Comm_rank()).
Definition world.h:344
WorldGopInterface & gop
Global operations.
Definition world.h:216
ProcessID nproc() const
Returns the number of processes in this World (same as MPI_Comm_size()).
Definition world.h:349
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
void test(World &world, bool doloadbal=false)
Definition dataloadbal.cc:224
double(* f)(const coord_3d &)
Definition derivatives.cc:54
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
Fcwf copy(Fcwf psi)
Definition fcwf.cc:374
std::vector< Fcwf > transform(World &world, std::vector< Fcwf > &a, Tensor< std::complex< double > > U)
Definition fcwf.cc:515
Provides FunctionCommonData, FunctionImpl and FunctionFactory.
static double function(const coord_3d &r)
Normalized gaussian.
Definition functionio.cc:100
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:2475
Tensor< T > transpose(const Tensor< T > &t)
Returns a new deep copy of the transpose of the input tensor.
Definition tensor.h:2039
const double beta
Definition gygi_soltion.cc:62
static const double v
Definition hatom_sf_dirac.cc:20
Key< 6 > simpt2key(const Vector< double, 6 > &pt, Level n)
Returns the box at level n that contains the given point in simulation coordinates.
Definition helium_mp2.cc:468
Tensor< double > op(const Tensor< double > &x)
Definition kain.cc:508
static double pow(const double *a, const double *b)
Definition lda.h:74
Macros and tools pertaining to the configuration of MADNESS.
#define MADNESS_PRAGMA_CLANG(x)
Definition madness_config.h:200
#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
Tensor< double > tensorT
Definition mcpfit.cc:52
static double ttt
Definition mcpfit.cc:57
void print(const tensorT &t)
Definition mcpfit.cc:140
static const bool VERIFY_TREE
Definition mra.h:57
Definition potentialmanager.cc:41
std::pair< Tensor< R > &, Tensor< R > & > eval_scratch(long need)
Definition tensor.h:2738
Namespace for all elements and tools of MADNESS.
Definition DFConvergence.h:9
bool two_scale_hg(int k, Tensor< double > *hg)
Definition twoscale.cc:151
@ BC_FREE
Definition bc.h:53
static const char * filename
Definition legendre.cc:96
static const std::vector< Slice > ___
Entire dimension.
Definition slice.h:124
static bool enforce_in_volume(Level n, const Translation &l)
Definition mraimpl.h:3475
int power(int base=2)
Definition power.h:43
Vector< double, 3 > coordT
Definition corepotential.cc:54
GenTensor< TENSOR_RESULT_TYPE(R, Q)> general_transform(const GenTensor< R > &t, const Tensor< Q > c[])
Definition gentensor.h:274
std::optional< BoundaryConditions< NDIM > > FunctionDefaults< NDIM >::bc
Definition mraimpl.h:3890
int FunctionDefaults< NDIM >::k
Definition mraimpl.h:3878
void legendre_scaling_functions(double x, long k, double *p)
Evaluate the first k Legendre scaling functions.
Definition legendre.cc:85
TreeState
Definition funcdefaults.h:60
@ nonstandard_after_apply
s and d coeffs, state after operator application
Definition funcdefaults.h:65
@ on_demand
no coeffs anywhere, but a functor providing if necessary
Definition funcdefaults.h:68
@ redundant_after_merge
s coeffs everywhere, must be summed up to yield the result
Definition funcdefaults.h:67
@ reconstructed
s coeffs at the leaves only
Definition funcdefaults.h:61
@ nonstandard
s and d coeffs in internal nodes
Definition funcdefaults.h:63
@ unknown
Definition funcdefaults.h:69
@ compressed
d coeffs in internal nodes, s and d coeffs at the root, empty leaves may be present
Definition funcdefaults.h:62
@ redundant
s coeffs everywhere
Definition funcdefaults.h:66
@ nonstandard_with_leaves
like nonstandard, with s coeffs at the leaves
Definition funcdefaults.h:64
static void user_to_sim(const Vector< double, NDIM > &xuser, Vector< double, NDIM > &xsim)
Convert user coords (cell[][]) to simulation coords ([0,1]^ndim).
Definition funcdefaults.h:469
Tensor< double > FunctionDefaults< NDIM >::cell
Definition mraimpl.h:3892
void compress(World &world, const std::vector< Function< T, NDIM > > &v, bool fence=true)
Compress a vector of functions.
Definition vmra.h:150
int64_t Translation
Definition key.h:59
Tensor< TENSOR_RESULT_TYPE(T, Q)> & general_fast_transform(const Tensor< T > &t, const Tensor< Q > *c, Tensor< TENSOR_RESULT_TYPE(T, Q)> &result, Tensor< TENSOR_RESULT_TYPE(T, Q)> &workspace)
Definition tensor.h:2579
void plotdx(const Function< T, NDIM > &f, const char *filename, const Tensor< double > &cell=FunctionDefaults< NDIM >::get_cell(), const std::vector< long > &npt=std::vector< long >(NDIM, 201L), bool binary=true)
Writes an OpenDX format file with a cube/slice of points on a uniform grid.
Definition mraimpl.h:3730
static void verify_tree(World &world, const std::vector< Function< T, NDIM > > &v)
Definition SCF.cc:77
Function< T, NDIM > sum(World &world, const std::vector< Function< T, NDIM > > &f, bool fence=true)
Returns new function — q = sum_i f[i].
Definition vmra.h:1774
static const Slice _(0,-1, 1)
ConcurrentHashMap< hashT, std::shared_ptr< GaussianConvolution1D< double > > > GaussianConvolution1DCache< double >::map
Definition convolution1d.h:1073
int Level
Definition key.h:60
std::enable_if< std::is_base_of< ProjectorBase, projT >::value, OuterProjector< projT, projQ > >::type outer(const projT &p0, const projQ &p1)
Definition projector.h:476
static constexpr double NORM_TREE_UNCOMPUTED
Definition funcimpl.h:127
Tensor< double > FunctionDefaults< NDIM >::cell_width
Definition mraimpl.h:3893
bool gauss_legendre(int n, double xlo, double xhi, double *x, double *w)
Definition legendre.cc:226
static double pop(std::vector< double > &v)
Definition SCF.cc:118
Tensor< T > fcube(const Key< NDIM > &, T(*f)(const Vector< double, NDIM > &), const Tensor< double > &)
Definition mraimpl.h:2292
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
static void dxprintvalue(FILE *f, const double t)
Definition mraimpl.h:3721
NDIM & f
Definition mra.h:2817
void error(const char *msg)
Definition world.cc:147
NDIM const Function< R, NDIM > & g
Definition mra.h:2817
double wall_time()
Returns the wall time in seconds relative to an arbitrary origin.
Definition timers.cc:48
double FunctionDefaults< NDIM >::cell_volume
Definition mraimpl.h:3895
TensorType FunctionDefaults< NDIM >::tt
Definition mraimpl.h:3891
void change_tensor_type(GenTensor< T > &, const TensorArgs &targs)
change representation to targ.tt
Definition gentensor.h:284
const Future< void > Future< void >::value
Definition future.cc:44
double imag(double x)
Definition complexfun.h:56
static bool print_timings
Definition SCF.cc:109
constexpr Vector< T, sizeof...(Ts)+1 > vec(T t, Ts... ts)
Factory function for creating a madness::Vector.
Definition vector.h:750
void scale(World &world, std::vector< Function< T, NDIM > > &v, const std::vector< Q > &factors, bool fence=true)
Scales inplace a vector of functions by distinct values.
Definition vmra.h:923
static std::vector< double > ttt
Definition SCF.cc:110
std::vector< Future< T > > future_vector_factory(std::size_t n)
Factory for a vectors of futures.
Definition future.h:889
double real(double x)
Definition complexfun.h:52
const FunctionCommonData< T, NDIM > * FunctionCommonData< T, NDIM >::data[MAXK]
Definition mraimpl.h:3875
@ same
same atoms at the same places
Definition RestartPlan.h:152
std::string name(const FuncType &type, const int ex=-1)
Definition ccpairfunction.h:28
static const int MAXK
The maximum wavelet order presently supported.
Definition funcdefaults.h:55
static bool enforce_bc(bool is_periodic, Level n, Translation &l)
Definition mraimpl.h:3455
Definition mraimpl.h:53
bool isnan(const std::complex< T > &v)
Definition mraimpl.h:55
static long abs(long a)
Definition tensor.h:214
const double mu
Definition navstokes_cosines.cc:95
static const double b
Definition nonlinschro.cc:119
static const double d
Definition nonlinschro.cc:121
static const double a
Definition nonlinschro.cc:118
static const double c
Definition relops.cc:10
static const double m
Definition relops.cc:9
static const double L
Definition rk.cc:46
static const long k
Definition rk.cc:44
const double xi
Exponent for delta function approx.
Definition siam_example.cc:60
Definition test_ar.cc:204
add two functions f and g: result=alpha * f + beta * g
Definition funcimpl.h:3836
"put" this on g
Definition funcimpl.h:2843
change representation of nodes' coeffs to low rank, optional fence
Definition funcimpl.h:2876
check symmetry wrt particle exchange
Definition funcimpl.h:2549
compute the norm of the wavelet coefficients
Definition funcimpl.h:5052
mirror dimensions of this, write result on f
Definition funcimpl.h:2777
map this on f
Definition funcimpl.h:2697
mirror dimensions of this, write result on f
Definition funcimpl.h:2727
Definition funcimpl.h:6354
reduce the rank of the nodes, optional fence
Definition funcimpl.h:2523
Changes non-standard compressed form to standard compressed form.
Definition funcimpl.h:5276
Definition funcimpl.h:5124
shallow-copy, pared-down version of FunctionNode, for special purpose only
Definition funcimpl.h:845
TensorArgs holds the arguments for creating a LowRankTensor.
Definition gentensor.h:134
double thresh
Definition gentensor.h:135
Definition mraimpl.h:3354
void operator()(const Key< NDIM > &key, Tensor< T > &t) const
Definition mraimpl.h:3355
void serialize(Archive &ar)
Definition mraimpl.h:3356
Definition mraimpl.h:3360
void operator()(const Key< NDIM > &key, Tensor< T > &t) const
Definition mraimpl.h:3361
void serialize(Archive &ar)
Definition mraimpl.h:3362
Definition mraimpl.h:3321
void operator()(const A &a, const B &b) const
Definition mraimpl.h:3322
void serialize(Archive &ar)
Definition mraimpl.h:3324
Definition mraimpl.h:3328
void operator()(const Key< NDIM > &key, FunctionNode< T, NDIM > &node) const
Definition mraimpl.h:3336
void serialize(Archive &ar)
Definition mraimpl.h:3340
T q
Definition mraimpl.h:3329
scaleinplace()
Definition mraimpl.h:3330
scaleinplace(T q)
Definition mraimpl.h:3332
void operator()(const Key< NDIM > &key, Tensor< T > &t) const
Definition mraimpl.h:3333
Definition mraimpl.h:3346
void serialize(Archive &ar)
Definition mraimpl.h:3350
void operator()(const Key< NDIM > &key, Tensor< T > &t) const
Definition mraimpl.h:3347
insert/replaces the coefficients into the function
Definition funcimpl.h:788
Definition lowrankfunction.h:387
int np
Definition tdse1d.cc:165
static const double s0
Definition tdse4.cc:83
double norm(const T i1)
Definition test_cloud.cc:85
double cpu_time()
Definition test_list.cc:43
static Function< double, D > project(World &world, const std::shared_ptr< FunctionFunctorInterface< double, D > > &functor)
Definition test_mul_sparse.cc:72
int task(int i)
Definition test_runtime.cpp:4
void e()
Definition test_sig.cc:75
#define N
Definition testconv.cc:37
static const double alpha
Definition testcosine.cc:10
constexpr std::size_t NDIM
Definition testgconv.cc:54
double h(const coord_1d &r)
Definition testgconv.cc:175
std::size_t axis
Definition testpdiff.cc:59
double k0
Definition testperiodic.cc:66
static long abs(long a)
Definition tensor.h:214
#define TENSOR_RESULT_TYPE(L, R)
This macro simplifies access to TensorResultType.
Definition type_data.h:205
Defines and implements WorldObject.
Implements WorldContainer.
Defines and implements a concurrent hashmap.
#define PROFILE_FUNC
Definition worldprofile.h:209
#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
Key< D > keyT
Definition writecoeff2.cc:11