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