MADNESS 0.10.1
vmra.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 $Id$
32*/
33#ifndef MADNESS_MRA_VMRA_H__INCLUDED
34#define MADNESS_MRA_VMRA_H__INCLUDED
35
36/*!
37 \file vmra.h
38 \brief Defines operations on vectors of Functions
39 \ingroup mra
40
41 This file defines a number of operations on vectors of functions.
42 Assume v is a vector of NDIM-D functions of a certain type.
43
44
45 Operations on array of functions
46
47 *) copying: deep copying of vectors of functions to vector of functions
48 \code
49 vector2 = copy(world, vector1,fence);
50 \endcode
51
52 *) compress: convert multiwavelet representation to legendre representation
53 \code
54 compress(world, vector, fence);
55 \endcode
56
57 *) reconstruct: convert representation to multiwavelets
58 \code
59 reconstruct(world, vector, fence);
60 \endcode
61
62 *) make_nonstandard: convert to non-standard form
63 \code
64 make_nonstandard(world, v, fence);
65 \endcode
66
67 *) standard: convert to standard form
68 \code
69 standard(world, v, fence);
70 \endcode
71
72 *) truncate: truncating vectors of functions to desired precision
73 \code
74 truncate(world, v, tolerance, fence);
75 \endcode
76
77
78 *) zero function: create a vector of zero functions of length n
79 \code
80 v=zero(world, n);
81 \endcode
82
83 *) transform: transform a representation from one basis to another
84 \code
85 transform(world, vector, tensor, tolerance, fence )
86 \endcode
87
88 Setting thresh-hold for precision
89
90 *) set_thresh: setting a finite thresh-hold for a vector of functions
91 \code
92 void set_thresh(World& world, std::vector< Function<T,NDIM> >& v, double thresh, bool fence=true);
93 \endcode
94
95 Arithmetic Operations on arrays of functions
96
97 *) conjugation: conjugate a vector of complex functions
98
99 *) add
100 *) sub
101 *) mul
102 - mul_sparse
103 *) square
104 *) gaxpy
105 *) apply
106
107 Norms, inner-products, blas-1 like operations on vectors of functions
108
109 *) inner
110 *) matrix_inner
111 *) norm_tree
112 *) normalize
113 *) norm2
114 - norm2s
115 *) scale(world, v, alpha);
116
117
118
119
120*/
121
122#include <madness/mra/mra.h>
125#include <cstdio>
126#include <algorithm>
127
128namespace madness {
129
130
131 /// get tree state of a vector of functions
132
133 /// @return TreeState::unknown if the vector is empty or if the functions have different tree states
134 template <typename T, std::size_t NDIM>
136 if (v.size()==0) return TreeState::unknown;
137 // return unknown if any function is not initialized
138 if (std::any_of(v.begin(), v.end(), [](const Function<T,NDIM>& f) {return not f.is_initialized();})) {
139 return TreeState::unknown;
140 }
141 TreeState state=v[0].get_impl()->get_tree_state();
142 for (const auto& f : v) {
143 if (f.get_impl()->get_tree_state()!=state) state=TreeState::unknown;
144 }
145 return state;
146 }
147
148 /// Compress a vector of functions
149 template <typename T, std::size_t NDIM>
150 void compress(World& world,
151 const std::vector< Function<T,NDIM> >& v,
152 bool fence=true) {
153 PROFILE_BLOCK(Vcompress);
155 }
156
157
158 /// reconstruct a vector of functions
159
160 /// implies fence
161 /// return v for chaining
162 template <typename T, std::size_t NDIM>
163 const std::vector< Function<T,NDIM> >& reconstruct(const std::vector< Function<T,NDIM> >& v) {
165 }
166
167 /// compress a vector of functions
168
169 /// implies fence
170 /// return v for chaining
171 template <typename T, std::size_t NDIM>
172 const std::vector< Function<T,NDIM> >& compress(const std::vector< Function<T,NDIM> >& v) {
174 }
175
176 /// Reconstruct a vector of functions
177 template <typename T, std::size_t NDIM>
178 void reconstruct(World& world,
179 const std::vector< Function<T,NDIM> >& v,
180 bool fence=true) {
181 PROFILE_BLOCK(Vreconstruct);
183 }
184
185 /// change tree_state of a vector of functions to redundant
186 template <typename T, std::size_t NDIM>
188 const std::vector< Function<T,NDIM> >& v,
189 bool fence=true) {
190
191 PROFILE_BLOCK(Vcompress);
193 }
194
195 /// refine the functions according to the autorefine criteria
196 template <typename T, std::size_t NDIM>
197 void refine(World& world, const std::vector<Function<T,NDIM> >& vf,
198 bool fence=true) {
199 for (const auto& f : vf) f.refine(false);
200 if (fence) world.gop.fence();
201 }
202
203 /// refine all functions to a common (finest) level
204
205 /// if functions are not initialized (impl==NULL) they are ignored
206 template <typename T, std::size_t NDIM>
207 void refine_to_common_level(World& world, std::vector<Function<T,NDIM> >& vf,
208 bool fence=true) {
209
210 reconstruct(world,vf);
212 std::vector<FunctionImpl<T,NDIM>*> v_ptr;
213
214 // push initialized function pointers into the vector v_ptr
215 for (unsigned int i=0; i<vf.size(); ++i) {
216 if (vf[i].is_initialized()) v_ptr.push_back(vf[i].get_impl().get());
217 }
218
219 // sort and remove duplicates to not confuse the refining function
220 std::sort(v_ptr.begin(),v_ptr.end());
221 typename std::vector<FunctionImpl<T, NDIM>*>::iterator it;
222 it = std::unique(v_ptr.begin(), v_ptr.end());
223 v_ptr.resize( std::distance(v_ptr.begin(),it) );
224
225 std::vector< Tensor<T> > c(v_ptr.size());
226 v_ptr[0]->refine_to_common_level(v_ptr, c, key0);
227 if (fence) v_ptr[0]->world.gop.fence();
228 if (VERIFY_TREE)
229 for (unsigned int i=0; i<vf.size(); i++) vf[i].verify_tree();
230 }
231
232 /// Generates non-standard form of a vector of functions
233 template <typename T, std::size_t NDIM>
235 std::vector< Function<T,NDIM> >& v,
236 bool fence= true) {
237 PROFILE_BLOCK(Vnonstandard);
239 }
240
241
242 /// Generates standard form of a vector of functions
243 template <typename T, std::size_t NDIM>
244 void standard(World& world,
245 std::vector< Function<T,NDIM> >& v,
246 bool fence=true) {
247 PROFILE_BLOCK(Vstandard);
249 }
250
251
252 /// change tree state of the functions
253
254 /// might not respect fence
255 /// @return v for chaining
256 template <typename T, std::size_t NDIM>
257 const std::vector<Function<T,NDIM>>& change_tree_state(const std::vector<Function<T,NDIM>>& v,
258 const TreeState finalstate,
259 const bool fence=true) {
260 // fast return
261 if (v.size()==0) return v;
262 if (get_tree_state(v)==finalstate) return v;
263
264 // find initialized function with world
265 Function<T,NDIM> dummy;
266 for (const auto& f : v)
267 if (f.is_initialized()) {
268 dummy=f;
269 break;
270 }
271 if (not dummy.is_initialized()) return v;
272 World& world=dummy.world();
273
274
275 // if a tree state cannot directly be changed to finalstate, we need to go via intermediate
276 auto change_initial_to_intermediate =[](const std::vector<Function<T,NDIM>>& v,
277 const TreeState initialstate,
278 const TreeState intermediatestate) {
279 int must_fence=0;
280 for (auto& f : v) {
281 if (f.is_initialized() and f.get_impl()->get_tree_state()==initialstate) {
282 f.change_tree_state(intermediatestate,false);
283 must_fence=1;
284 }
285 }
286 return must_fence;
287 };
288
289 int do_fence=0;
290 if (finalstate==compressed) {
291 do_fence+=change_initial_to_intermediate(v,redundant,TreeState::reconstructed);
292 }
293 if (finalstate==nonstandard) {
294 do_fence+=change_initial_to_intermediate(v,compressed,TreeState::reconstructed);
295 do_fence+=change_initial_to_intermediate(v,redundant,TreeState::reconstructed);
296 }
297 if (finalstate==nonstandard_with_leaves) {
298 do_fence+=change_initial_to_intermediate(v,compressed,TreeState::reconstructed);
299 do_fence+=change_initial_to_intermediate(v,nonstandard,TreeState::reconstructed);
300 do_fence+=change_initial_to_intermediate(v,redundant,TreeState::reconstructed);
301 }
302 if (finalstate==redundant) {
303 do_fence+=change_initial_to_intermediate(v,compressed,TreeState::reconstructed);
304 do_fence+=change_initial_to_intermediate(v,nonstandard,TreeState::reconstructed);
305 do_fence+=change_initial_to_intermediate(v,nonstandard_with_leaves,TreeState::reconstructed);
306 }
307 if (do_fence>0) world.gop.fence();
308
309 for (unsigned int i=0; i<v.size(); ++i) v[i].change_tree_state(finalstate,fence);
310 if (fence) world.gop.fence();
311
312 return v;
313 }
314
315 /// ensure v has the requested tree state, change the tree state of v if necessary and no fence is given
316 template<typename T, std::size_t NDIM>
318 const TreeState state, bool fence) {
319 // fast return
320 if (get_tree_state(v)==state) return true;;
321
322 // if there is a fence we can simply change the tree state, might be a no-op
323 if (fence) change_tree_state(v,state,true);
324
325 // check success, throw if not
326 bool ok=get_tree_state(v)==state;
327 if (not ok) {
328 print("ensure_tree_state_respecting_fence failed");
329 throw std::runtime_error("ensure_tree_state_respecting_fence failed");
330 }
331 return ok;
332 }
333
334 /// Truncates a vector of functions
335 template <typename T, std::size_t NDIM>
336 void truncate(World& world,
337 std::vector< Function<T,NDIM> >& v,
338 double tol=0.0,
339 bool fence=true) {
340 PROFILE_BLOCK(Vtruncate);
341
342 // truncate in compressed form only for low-dimensional functions
343 // compression is very expensive if low-rank tensor approximations are used
344 if (NDIM<4) compress(world, v);
345
346 for (auto& vv: v) {
347 vv.truncate(tol, false);
348 }
349
350 if (fence) world.gop.fence();
351 }
352
353 /// Truncates a vector of functions
354
355 /// @return the truncated vector for chaining
356 template <typename T, std::size_t NDIM>
357 std::vector< Function<T,NDIM> > truncate(std::vector< Function<T,NDIM> > v,
358 double tol=0.0, bool fence=true) {
359 if (v.size()>0) truncate(v[0].world(),v,tol,fence);
360 return v;
361 }
362
363 /// reduces the tensor rank of the coefficient tensor (if applicable)
364
365 /// @return the vector for chaining
366 template <typename T, std::size_t NDIM>
367 std::vector< Function<T,NDIM> > reduce_rank(std::vector< Function<T,NDIM> > v,
368 double thresh=0.0, bool fence=true) {
369 if (v.size()==0) return v;
370 for (auto& vv : v) vv.reduce_rank(thresh,false);
371 if (fence) v[0].world().gop.fence();
372 return v;
373 }
374
375
376 /// Pre-stages the neighbor coefficients that differentiating v with each of grad will need
377
378 /// Differentiating then serves those neighbors locally instead of fetching them one at a time.
379 /// One halo per function holds every operator's pushes, so it pays when several functions are
380 /// differentiated together. `clear_halo` frees them afterwards.
381 template <typename T, std::size_t NDIM>
382 void stage_halo(World& world,
383 const std::vector< std::shared_ptr< Derivative<T,NDIM> > >& grad,
384 const std::vector< Function<T,NDIM> >& v,
385 bool fence=true)
386 {
387 for (const auto& f : v) MADNESS_CHECK(f.is_reconstructed());
388 for (const auto& D : grad)
389 for (const auto& f : v) D->stage_halo(f.get_impl().get(), false);
390 if (fence) world.gop.fence();
391 }
392
393 /// Discards the neighbor halos staged on v
394
395 /// Requires a quiescent window: it frees tables the derivative may still be reading.
396 template <typename T, std::size_t NDIM>
397 void clear_halo(const std::vector< Function<T,NDIM> >& v)
398 {
399 for (const auto& f : v) f.get_impl()->halo_clear();
400 }
401
402 /// Applies a derivative operator to a vector of functions
403 template <typename T, std::size_t NDIM>
404 std::vector< Function<T,NDIM> >
405 apply(World& world,
406 const Derivative<T,NDIM>& D,
407 const std::vector< Function<T,NDIM> >& v,
408 bool fence=true)
409 {
410 reconstruct(world, v);
411 std::vector< Function<T,NDIM> > df(v.size());
412 for (unsigned int i=0; i<v.size(); ++i) {
413 df[i] = D(v[i],false);
414 }
415 if (fence) world.gop.fence();
416 return df;
417 }
418
419 /// Generates a vector of zero functions with a given tree state
420 template <typename T, std::size_t NDIM>
421 std::vector< Function<T,NDIM> >
422 zero_functions_tree_state(World& world, int n, const TreeState state, bool fence=true) {
423 std::vector< Function<T,NDIM> > r(n);
424 for (int i=0; i<n; ++i) {
425 if (state==compressed)
426 r[i] = Function<T,NDIM>(FunctionFactory<T,NDIM>(world).fence(false).compressed(true).initial_level(1));
427 else if (state==reconstructed)
428 r[i] = Function<T,NDIM>(FunctionFactory<T,NDIM>(world).fence(false));
429 else {
430 print("zero_functions_tree_state: unknown tree state");
431 throw std::runtime_error("zero_functions_tree_state: unknown tree state");
432 }
433 }
434
435 if (n && fence) world.gop.fence();
436 return r;
437
438 }
439
440 /// Generates a vector of zero functions (reconstructed)
441 template <typename T, std::size_t NDIM>
442 std::vector< Function<T,NDIM> >
443 zero_functions(World& world, int n, bool fence=true) {
445 }
446
447 /// Generates a vector of zero functions (compressed)
448 template <typename T, std::size_t NDIM>
449 std::vector< Function<T,NDIM> >
450 zero_functions_compressed(World& world, int n, bool fence=true) {
451 return zero_functions_tree_state<T,NDIM>(world,n,compressed,fence);
452 }
453
454 /// Generates a vector of zero functions, either compressed or reconstructed, depending on tensor type
455 template <typename T, std::size_t NDIM>
456 std::vector< Function<T,NDIM> >
457 zero_functions_auto_tree_state(World& world, int n, bool fence=true) {
459 return zero_functions_tree_state<T,NDIM>(world,n,state,fence);
460 }
461
462
463
464 /// orthonormalize the vectors
465 template<typename T, std::size_t NDIM>
466 std::vector<Function<T,NDIM>> orthonormalize(const std::vector<Function<T,NDIM> >& vf_in) {
467 if (vf_in.size()==0) return std::vector<Function<T,NDIM>>();
468 World& world=vf_in.front().world();
469 auto vf=copy(world,vf_in);
470 normalize(world,vf);
471 if (vf.size()==1) return copy(world,vf_in);
472 double maxq;
473 double trantol=0.0;
474 auto Q2=[](const Tensor<T>& s) {
475 Tensor<T> Q = -0.5*s;
476 for (int i=0; i<s.dim(0); ++i) Q(i,i) += 1.5;
477 return Q;
478 };
479
480 do {
481 Tensor<T> Q = Q2(matrix_inner(world, vf, vf));
482 maxq=0.0;
483 for (int i=0; i<Q.dim(0); ++i)
484 for (int j=0; j<i; ++j)
485 maxq = std::max(maxq,std::abs(Q(i,j)));
486
487 vf = transform(world, vf, Q, trantol, true);
488 truncate(world, vf);
489
490 } while (maxq>0.01);
491 normalize(world,vf);
492 return vf;
493 }
494
495
496 /// return a matrix that orthonormalizes the vectors v_ortho = transform(world,v,result);
497 template<typename T>
499
500 int n=ovlp.dim(0);
501 Tensor<T> U;
503 syev(ovlp, U, s);
504
505 // transform s to s^{-1/2} in-place
506 for(size_t i = 0; i < n; ++i) {
507 const auto s_i = s(i);
508 s(i) = 1.0 / sqrt(s_i);
509 }
510
511 // save Ut before U gets modified with s^{-1/2}
512 const Tensor<T> Ut = conj_transpose(U);
513
514 for(size_t i = 0; i < n; ++i){
515 for(size_t j = 0; j < n; ++j){
516 U(i, j) = U(i, j) * s(j);
517 }
518 }
519
520 Tensor<T> X = inner(U, Ut, 1, 0);
521 return X;
522 }
523
524
525 /// symmetric orthonormalization (see e.g. Szabo/Ostlund)
526
527 /// @param[in] the vector to orthonormalize
528 /// @param[in] overlap matrix
529 template <typename T, std::size_t NDIM>
530 std::vector<Function<T,NDIM> > orthonormalize_symmetric(
531 const std::vector<Function<T,NDIM> >& v,
532 const Tensor<T>& ovlp,
533 double lindep = 1e-12) {
534 if(v.empty()) return v;
535
536 World& world = v.front().world();
537 const size_t n = v.size();
538
539 Tensor<T> U;
541 syev(ovlp, U, s);
542 lindep *= s(s.size() - 1); // eigenvalues are in ascending order
543
544 // transform s to s^{-1/2} in-place
545 int rank = 0, nlindep = 0;
546 for(size_t i = 0; i < n; ++i) {
547 const auto s_i = s(i);
548 s(i) = 1.0 / sqrt(s_i);
549 (s_i > lindep) ? rank++ : nlindep++;
550 }
551 MADNESS_ASSERT(size_t(nlindep + rank) == n);
552
553 // warn of linearly dependent vectors and values
554 if (nlindep > 0) {
555 if (world.rank() == 0)
556 print("WARNING: linear dependencies detected in ", nlindep,
557 " functions, rank = ", rank);
558 }
559
560 // save Ut before U gets modified with s^{-1/2}
561 const Tensor<T> Ut = conj_transpose(U);
562
563 for(size_t i = 0; i < n; ++i){
564 for(size_t j = 0; j < n; ++j){
565 U(i, j) = U(i, j) * s(j);
566 }
567 }
568
569 Tensor<T> X = inner(U, Ut, 1, 0);
570
571 return transform(world, v, X);
572 }
573
574 /// convenience routine for symmetric orthonormalization (see e.g. Szabo/Ostlund)
575 /// overlap matrix is calculated
576 /// @param[in] the vector to orthonormalize
577 template <typename T, std::size_t NDIM>
578 std::vector<Function<T,NDIM> > orthonormalize_symmetric(const std::vector<Function<T,NDIM> >& v,
579 double lindep = 1e-12){
580 if(v.empty()) return v;
581
582 Tensor<T> ovlp = matrix_inner(v.front().world(), v, v, /* sym= */ true);
583
584 return orthonormalize_symmetric(v, ovlp, lindep);
585 }
586
587 /// compute the transformation matrix for canonical orthonormalization (see e.g. Szabo/Ostlund)
588
589 /// @param[in] overlap matrix
590 /// @param[in] lindep linear dependency threshold relative to largest eigenvalue
591 /// @return the transformation matrix, i.e. the matrix U in the canonical orthonormalization,
592 /// such that transform(world,v,U) gives the orthonormalized vector
593 template<typename T, std::size_t NDIM>
594 Tensor<T> canonical_orthonormalization_matrix(World& world, const Tensor<T> ovlp, double lindep = 1e-12) {
595 Tensor<T> U;
597 syev(ovlp, U, s);
598 lindep *= s(s.size() - 1); // eigenvalues are in ascending order
599 const size_t n = ovlp.dim(0);
600
601 // transform s to s^{-1/2} in-place
602 size_t rank = 0, nlindep = 0;
603 for(size_t i = 0; i < n; ++i) {
604 const auto s_i = s(i);
605 if (s_i > lindep) {
606 s(i) = 1.0 / sqrt(s_i);
607 rank++;
608 } else {
609 nlindep++;
610 }
611 }
612 MADNESS_ASSERT(size_t(nlindep + rank) == n);
613
614 // remove linearly dependent vectors and values
615 if (nlindep > 0) {
616 if (world.rank() == 0)
617 print("Linear dependencies detected: removed ", nlindep,
618 " functions, rank = ", rank, s(nlindep),s(n-1));
619 U = U(_, Slice(nlindep, -1));
620 s = s(Slice(nlindep, -1));
621 }
622
623 // modify U in-place, U is now transformation matrix (U * s^{-1/2})
624 for(size_t i = 0; i < n; ++i){
625 for(size_t j = 0; j < rank; ++j){
626 U(i, j) = U(i, j) * s(j);
627 }
628 }
629
630 return U;
631 }
632
633 /// canonical orthonormalization (see e.g. Szabo/Ostlund)
634 /// @param[in] the vector to orthonormalize
635 /// @param[in] overlap matrix
636 /// @param[in] lindep linear dependency threshold relative to largest eigenvalue
637 template <typename T, std::size_t NDIM>
638 std::vector<Function<T,NDIM> > orthonormalize_canonical(
639 const std::vector<Function<T,NDIM> >& v,
640 const Tensor<T>& ovlp,
641 double lindep = 1e-12) {
642
643 if(v.empty()) return v;
644 World& world = v.front().world();
646 return transform(world, v, U);
647 }
648
649 /// convenience routine for canonical routine for symmetric orthonormalization (see e.g. Szabo/Ostlund)
650 /// overlap matrix is calculated
651 /// @param[in] the vector to orthonormalize
652 template <typename T, std::size_t NDIM>
653 std::vector<Function<T,NDIM> > orthonormalize_canonical(const std::vector<Function<T,NDIM> >& v,
654 double lindep = 1e-12){
655 if(v.empty()) return v;
656
657 Tensor<T> ovlp = matrix_inner(v.front().world(), v, v, /* sym= */ true);
658
659 return orthonormalize_canonical(v, ovlp, lindep);
660 }
661
662 /// cholesky orthonormalization without pivoting
663 /// @param[in] the vector to orthonormalize
664 /// @param[in] overlap matrix, destroyed on return!
665 template <typename T, std::size_t NDIM>
666 std::vector<Function<T,NDIM> > orthonormalize_cd(
667 const std::vector<Function<T,NDIM> >& v,
668 Tensor<T>& ovlp) {
669
670 if (v.empty()) return v;
671
672 cholesky(ovlp); // destroys ovlp and gives back Upper ∆ Matrix from CD
673
674 Tensor<T> L = transpose(ovlp);
675 Tensor<T> Linv = inverse(L);
676 Tensor<T> U = transpose(Linv);
677
678 World& world=v.front().world();
679 return transform(world, v, U);
680
681 }
682
683 /// convenience routine for cholesky orthonormalization without pivoting
684 /// @param[in] the vector to orthonormalize
685 /// @param[in] overlap matrix
686 template <typename T, std::size_t NDIM>
687 std::vector<Function<T,NDIM> > orthonormalize_cd(const std::vector<Function<T,NDIM> >& v){
688 if(v.empty()) return v;
689
690 World& world=v.front().world();
691 Tensor<T> ovlp = matrix_inner(world, v, v, /* sym= */ true);
692
693 return orthonormalize_cd(v,ovlp);
694 }
695
696 /// @param[in] the vector to orthonormalize
697 /// @param[in] overlap matrix, will be destroyed on return!
698 /// @param[in] tolerance for numerical rank reduction
699 /// @param[out] pivoting vector, no allocation on input needed
700 /// @param[out] rank
701 /// @return orthonormalized vector (may or may not be truncated)
702 template <typename T, std::size_t NDIM>
703 std::vector<Function<T,NDIM> > orthonormalize_rrcd(
704 const std::vector<Function<T,NDIM> >& v,
705 Tensor<T>& ovlp,
706 const double tol,
707 Tensor<integer>& piv,
708 int& rank) {
709
710 if (v.empty()) {
711 return v;
712 }
713
714 rr_cholesky(ovlp,tol,piv,rank); // destroys ovlp and gives back Upper ∆ Matrix from CCD
715
716 // rearrange and truncate the functions according to the pivoting of the rr_cholesky
717 std::vector<Function<T,NDIM> > pv(rank);
718 for(integer i=0;i<rank;++i){
719 pv[i]=v[piv[i]];
720 }
721 // no need to invert all of ovlp, only the upper left rank x rank block
722 // ex. with a (3,3) matrix ovlp with rank=2
723 // | i > L_{ir}
724 // (1 2 3) (a b // 0 c // 0 0) = ( a + 2b )
725 ovlp=ovlp(Slice(0,rank-1),Slice(0,rank-1));
726
727 // result = |i~> = sum_r |i> U_{ir}^(-1)
728 // with <i~|j~> = sum_{r} U_{ir}^(-1) <i|j> U_{jp}^(-1)
729 // = sum_{r} U_{ir}^(-1) (U^T U)_{ij} U_{jr}^(-1)
730 // = sum_{r} U_{ir}^(-1) U_{ip} U_{jp} U_{jp}^(-1)
731 // = delta_{ij} // has matrix dimension (r,r)
732 Tensor<T> L = transpose(ovlp); // fbischoff thinks the transpose is not necessary here
733 Tensor<T> Linv = inverse(L);
734 Tensor<T> U = transpose(Linv); // fbischoff thinks the transpose is not necessary here
735
736 World& world=v.front().world();
737 return transform(world, pv, U);
738 }
739
740 /// convenience routine for orthonormalize_cholesky: orthonormalize_cholesky without information on pivoting and rank
741 /// @param[in] the vector to orthonormalize
742 /// @param[in] overlap matrix
743 /// @param[in] tolerance for numerical rank reduction
744 template <typename T, std::size_t NDIM>
745 std::vector<Function<T,NDIM> > orthonormalize_rrcd(const std::vector<Function<T,NDIM> >& v, Tensor<T> ovlp , const double tol) {
746 Tensor<integer> piv;
747 int rank;
748 return orthonormalize_rrcd(v,ovlp,tol,piv,rank);
749 }
750
751 /// convenience routine for orthonormalize_cholesky: computes the overlap matrix and then calls orthonormalize_cholesky
752 /// @param[in] the vector to orthonormalize
753 /// @param[in] tolerance for numerical rank reduction
754 template <typename T, std::size_t NDIM>
755 std::vector<Function<T,NDIM> > orthonormalize_rrcd(const std::vector<Function<T,NDIM> >& v, const double tol) {
756 if (v.empty()) {
757 return v;
758 }
759 // compute overlap
760 World& world=v.front().world();
761 Tensor<T> ovlp = matrix_inner(world, v, v, /* sym= */ true);
762 return orthonormalize_rrcd(v,ovlp,tol);
763 }
764
765 /// combine two vectors
766 template <typename T, std::size_t NDIM>
767 std::vector<Function<T,NDIM> > append(const std::vector<Function<T,NDIM> > & lhs, const std::vector<Function<T,NDIM> > & rhs){
768 std::vector<Function<T,NDIM> > v=lhs;
769 for (std::size_t i = 0; i < rhs.size(); ++i) v.push_back(rhs[i]);
770 return v;
771 }
772
773 template <typename T, std::size_t NDIM>
774 std::vector<Function<T,NDIM> > flatten(const std::vector< std::vector<Function<T,NDIM> > >& vv){
775 std::vector<Function<T,NDIM> >result;
776 for(const auto& x:vv) result=append(result,x);
777 return result;
778 }
779
780 template<typename T, std::size_t NDIM>
781 std::vector<std::shared_ptr<FunctionImpl<T,NDIM>>> get_impl(const std::vector<Function<T,NDIM>>& v) {
782 std::vector<std::shared_ptr<FunctionImpl<T,NDIM>>> result;
783 for (auto& f : v) result.push_back(f.get_impl());
784 return result;
785 }
786
787 template<typename T, std::size_t NDIM>
788 void set_impl(std::vector<Function<T,NDIM>>& v, const std::vector<std::shared_ptr<FunctionImpl<T,NDIM>>> vimpl) {
789 MADNESS_CHECK(vimpl.size()==v.size());
790 for (std::size_t i=0; i<vimpl.size(); ++i) v[i].set_impl(vimpl[i]);
791 }
792
793 template<typename T, std::size_t NDIM>
794 std::vector<Function<T,NDIM>> impl2function(const std::vector<std::shared_ptr<FunctionImpl<T,NDIM>>> vimpl) {
795 std::vector<Function<T,NDIM>> v(vimpl.size());
796 for (std::size_t i=0; i<vimpl.size(); ++i) v[i].set_impl(vimpl[i]);
797 return v;
798 }
799
800
801 /// Transforms a vector of functions according to new[i] = sum[j] old[j]*c[j,i]
802
803 /// Uses sparsity in the transformation matrix --- set small elements to
804 /// zero to take advantage of this.
805 template <typename T, typename R, std::size_t NDIM>
806 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> >
808 const std::vector< Function<T,NDIM> >& v,
809 const Tensor<R>& c,
810 bool fence=true) {
811
812 PROFILE_BLOCK(Vtransformsp);
813 typedef TENSOR_RESULT_TYPE(T,R) resultT;
814 int n = v.size(); // n is the old dimension
815 int m = c.dim(1); // m is the new dimension
816 MADNESS_CHECK(n==c.dim(0));
817
818 std::vector< Function<resultT,NDIM> > vc = zero_functions_compressed<resultT,NDIM>(world, m);
819 compress(world, v);
820
821 for (int i=0; i<m; ++i) {
822 for (int j=0; j<n; ++j) {
823 if (c(j,i) != R(0.0)) vc[i].gaxpy(resultT(1.0),v[j],resultT(c(j,i)),false);
824 }
825 }
826
827 if (fence) world.gop.fence();
828 return vc;
829 }
830
831 /// Transforms a vector of functions according to new[i] = sum[j] old[j]*c[j,i]
832
833 /// all trees are in reconstructed state, final trees have to be summed down if no fence is present
834 template <typename T, typename R, std::size_t NDIM>
835 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> >
837 const std::vector< Function<T,NDIM> >& v,
838 const Tensor<R>& c,
839 bool fence=true) {
840
841 PROFILE_BLOCK(Vtransformsp);
842 typedef TENSOR_RESULT_TYPE(T,R) resultT;
843 int n = v.size(); // n is the old dimension
844 int m = c.dim(1); // m is the new dimension
845 MADNESS_CHECK(n==c.dim(0));
846
847 // if we fence set the right tree state here, otherwise it has to be correct from the start.
849 for (const auto& vv : v) MADNESS_CHECK_THROW(
850 vv.get_impl()->get_tree_state()==reconstructed,"trees have to be reconstructed in transform_reconstructed");
851
852 std::vector< Function<resultT,NDIM> > result = zero_functions<resultT,NDIM>(world, m);
853
854 for (int i=0; i<m; ++i) {
855 result[i].get_impl()->set_tree_state(redundant_after_merge);
856 for (int j=0; j<n; ++j) {
857 if (c(j,i) != R(0.0)) v[j].get_impl()->accumulate_trees(*(result[i].get_impl()),resultT(c(j,i)),true);
858 }
859 }
860
861 // if we fence we can as well finish the job here. Otherwise no harm done, as the tree state is well-defined.
862 if (fence) {
863 world.gop.fence();
864 // for (auto& r : vc) r.sum_down(false);
865 for (auto& r : result) r.get_impl()->finalize_sum();
866 world.gop.fence();
867 }
868 return result;
869 }
870
871 /// this version of transform uses Function::vtransform and screens
872 /// using both elements of `c` and `v`
873 template <typename L, typename R, std::size_t NDIM>
874 std::vector< Function<TENSOR_RESULT_TYPE(L,R),NDIM> >
875 transform(World& world, const std::vector< Function<L,NDIM> >& v,
876 const Tensor<R>& c, double tol, bool fence=true) {
877 PROFILE_BLOCK(Vtransform);
878 MADNESS_ASSERT(v.size() == (unsigned int)(c.dim(0)));
879
880 std::vector< Function<TENSOR_RESULT_TYPE(L,R),NDIM> > vresult
882
883 compress(world, v, true);
884 vresult[0].vtransform(v, c, vresult, tol, fence);
885 return vresult;
886 }
887
888 template <typename T, typename R, std::size_t NDIM>
889 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> >
891 const std::vector< Function<T,NDIM> >& v,
892 const DistributedMatrix<R>& c,
893 bool fence=true) {
895
896 typedef TENSOR_RESULT_TYPE(T,R) resultT;
897 long n = v.size(); // n is the old dimension
898 long m = c.rowdim(); // m is the new dimension
899 MADNESS_ASSERT(n==c.coldim());
900
901 // new(i) = sum(j) old(j) c(j,i)
902
903 Tensor<T> tmp(n,m);
904 c.copy_to_replicated(tmp); // for debugging
905 tmp = transpose(tmp);
906
907 std::vector< Function<resultT,NDIM> > vc = zero_functions_compressed<resultT,NDIM>(world, m);
908 compress(world, v);
909
910 for (int i=0; i<m; ++i) {
911 for (int j=0; j<n; ++j) {
912 if (tmp(j,i) != R(0.0)) vc[i].gaxpy(1.0,v[j],tmp(j,i),false);
913 }
914 }
915
916 if (fence) world.gop.fence();
917 return vc;
918 }
919
920
921 /// Scales inplace a vector of functions by distinct values
922 template <typename T, typename Q, std::size_t NDIM>
923 void scale(World& world,
924 std::vector< Function<T,NDIM> >& v,
925 const std::vector<Q>& factors,
926 bool fence=true) {
927 PROFILE_BLOCK(Vscale);
928 for (unsigned int i=0; i<v.size(); ++i) v[i].scale(factors[i],false);
929 if (fence) world.gop.fence();
930 }
931
932 /// Scales inplace a vector of functions by the same
933 template <typename T, typename Q, std::size_t NDIM>
934 void scale(World& world,
935 std::vector< Function<T,NDIM> >& v,
936 const Q factor,
937 bool fence=true) {
938 PROFILE_BLOCK(Vscale);
939 for (unsigned int i=0; i<v.size(); ++i) v[i].scale(factor,false);
940 if (fence) world.gop.fence();
941 }
942
943 namespace detail {
944 /// put a vector of functions into a state whose coefficients sum to ||f||^2
945
946 /// norm2sq_local() adds up the nodes of a tree, which is the norm only in
947 /// a state that carries the coefficients once; where the duplicates are
948 /// the interior nodes it skips them, so the redundant and
949 /// nonstandard-with-leaves trees left behind by mul_sparse() and friends
950 /// need no conversion at all. The rest are reconstructed, and that is a
951 /// mutation: it discards the interior coefficients. So fence first, or
952 /// the removal tasks race a task still reading those coefficients, e.g. a
953 /// mul_sparse(..., fence=false) that has not been fenced yet.
954 /// Cf. Function::norm2(), which does the same for a single function.
955 /// The branch is taken on the tree state, which is replicated, so all
956 /// ranks take the same branch and the global ops stay collective.
957 template <typename T, std::size_t NDIM>
958 void reconstruct_for_norm(World& world, const std::vector<Function<T,NDIM>>& v) {
959 if (v.size()==0) return; // nothing to sum, and nothing to fence for
960 if (std::all_of(v.begin(), v.end(), [](const Function<T,NDIM>& f) {
961 return (not f.is_initialized()) or f.get_impl()->has_summable_coefficients();}))
962 return;
963 MADNESS_CHECK_THROW(std::none_of(v.begin(), v.end(),
964 [](const Function<T,NDIM>& f) {return f.is_initialized() and f.is_on_demand();}),
965 "norm2/norm2s are not defined for an on-demand function; materialize it first");
966 world.gop.fence();
967 reconstruct(world,v);
968 }
969 }
970
971 /// Computes the 2-norms of a vector of functions
972
973 /// Reconstructs the functions if their state does not admit a direct sum;
974 /// see detail::reconstruct_for_norm for what that costs.
975 template <typename T, std::size_t NDIM>
976 std::vector<double> norm2s(World& world,
977 const std::vector< Function<T,NDIM> >& v) {
978 PROFILE_BLOCK(Vnorm2);
979 std::vector<double> norms(v.size());
980 if (v.size()==0) return norms; // &norms[0] below is UB on an empty container
982 for (unsigned int i=0; i<v.size(); ++i) norms[i] = v[i].norm2sq_local();
983 world.gop.sum(&norms[0], norms.size());
984 for (unsigned int i=0; i<v.size(); ++i) norms[i] = sqrt(norms[i]);
985 world.gop.fence();
986 return norms;
987 }
988 /// Computes the 2-norms of a vector of functions
989
990 /// Reconstructs the functions if their state does not admit a direct sum;
991 /// see detail::reconstruct_for_norm for what that costs.
992 template <typename T, std::size_t NDIM>
993 Tensor<double> norm2s_T(World& world, const std::vector<Function<T, NDIM>>& v) {
994 PROFILE_BLOCK(Vnorm2);
995 Tensor<double> norms(v.size());
996 if (v.size()==0) return norms; // &norms[0] below is UB on an empty container
998 for (unsigned int i = 0; i < v.size(); ++i) norms[i] = v[i].norm2sq_local();
999 world.gop.sum(&norms[0], norms.size());
1000 for (unsigned int i = 0; i < v.size(); ++i) norms[i] = sqrt(norms[i]);
1001 world.gop.fence();
1002 return norms;
1003 }
1004
1005 /// Computes the 2-norm of a vector of functions
1006
1007 /// Reconstructs the functions if their state does not admit a direct sum;
1008 /// see detail::reconstruct_for_norm for what that costs.
1009 template <typename T, std::size_t NDIM>
1010 double norm2(World& world,const std::vector< Function<T,NDIM> >& v) {
1011 PROFILE_BLOCK(Vnorm2);
1012 if (v.size()==0) return 0.0;
1014 std::vector<double> norms(v.size());
1015 for (unsigned int i=0; i<v.size(); ++i) norms[i] = v[i].norm2sq_local();
1016 world.gop.sum(&norms[0], norms.size());
1017 for (unsigned int i=1; i<v.size(); ++i) norms[0] += norms[i];
1018 world.gop.fence();
1019 return sqrt(norms[0]);
1020 }
1021
1022 inline double conj(double x) {
1023 return x;
1024 }
1025
1026 inline double conj(float x) {
1027 return x;
1028 }
1029
1030// !!! FIXME: this task is broken because FunctionImpl::inner_local forces a
1031// future on return from WorldTaskQueue::reduce, which will causes a deadlock if
1032// run inside a task. This behavior must be changed before this task can be used
1033// again.
1034//
1035// template <typename T, typename R, std::size_t NDIM>
1036// struct MatrixInnerTask : public TaskInterface {
1037// Tensor<TENSOR_RESULT_TYPE(T,R)> result; // Must be a copy
1038// const Function<T,NDIM>& f;
1039// const std::vector< Function<R,NDIM> >& g;
1040// long jtop;
1041//
1042// MatrixInnerTask(const Tensor<TENSOR_RESULT_TYPE(T,R)>& result,
1043// const Function<T,NDIM>& f,
1044// const std::vector< Function<R,NDIM> >& g,
1045// long jtop)
1046// : result(result), f(f), g(g), jtop(jtop) {}
1047//
1048// void run(World& world) {
1049// for (long j=0; j<jtop; ++j) {
1050// result(j) = f.inner_local(g[j]);
1051// }
1052// }
1053//
1054// private:
1055// /// Get the task id
1056//
1057// /// \param id The id to set for this task
1058// virtual void get_id(std::pair<void*,unsigned short>& id) const {
1059// PoolTaskInterface::make_id(id, *this);
1060// }
1061// }; // struct MatrixInnerTask
1062
1063
1064
1065 template <typename T, std::size_t NDIM>
1067 const std::vector< Function<T,NDIM> >& f,
1068 const std::vector< Function<T,NDIM> >& g,
1069 bool sym=false)
1070 {
1073 const int64_t n = A.coldim();
1074 const int64_t m = A.rowdim();
1075 MADNESS_ASSERT(int64_t(f.size()) == n && int64_t(g.size()) == m);
1076
1077 // Assume we can always create an ichunk*jchunk matrix locally
1078 const int ichunk = 1000;
1079 const int jchunk = 1000; // 1000*1000*8 = 8 MBytes
1080 for (int64_t ilo=0; ilo<n; ilo+=ichunk) {
1081 int64_t ihi = std::min(ilo + ichunk, n);
1082 std::vector< Function<T,NDIM> > ivec(f.begin()+ilo, f.begin()+ihi);
1083 for (int64_t jlo=0; jlo<m; jlo+=jchunk) {
1084 int64_t jhi = std::min(jlo + jchunk, m);
1085 std::vector< Function<T,NDIM> > jvec(g.begin()+jlo, g.begin()+jhi);
1086
1087 Tensor<T> P = matrix_inner(A.get_world(), ivec, jvec);
1088 A.copy_from_replicated_patch(ilo, ihi - 1, jlo, jhi - 1, P);
1089 }
1090 }
1091 return A;
1092 }
1093
1094 /// Computes the matrix inner product of two function vectors - q(i,j) = inner(f[i],g[j])
1095
1096 /// For complex types symmetric is interpreted as Hermitian.
1097
1098 /// The current parallel loop is non-optimal but functional.
1099 template <typename T, typename R, std::size_t NDIM>
1101 const std::vector< Function<T,NDIM> >& f,
1102 const std::vector< Function<R,NDIM> >& g,
1103 bool sym=false)
1104 {
1105 world.gop.fence();
1106 auto tensor_type = [](const std::vector<Function<T,NDIM>>& v) {
1107 return v.front().get_impl()->get_tensor_type();
1108 };
1109 TreeState operating_state=tensor_type(f)==TT_FULL ? compressed : redundant;
1110 ensure_tree_state_respecting_fence(f,operating_state,true);
1111 ensure_tree_state_respecting_fence(g,operating_state,true);
1112
1113 std::vector<const FunctionImpl<T,NDIM>*> left(f.size());
1114 std::vector<const FunctionImpl<R,NDIM>*> right(g.size());
1115 for (unsigned int i=0; i<f.size(); i++) left[i] = f[i].get_impl().get();
1116 for (unsigned int i=0; i<g.size(); i++) right[i]= g[i].get_impl().get();
1117
1119
1120 world.gop.fence();
1121 world.gop.sum(r.ptr(),f.size()*g.size());
1122
1123 return r;
1124 }
1125
1126 /// Computes the matrix inner product of two function vectors - q(i,j) = inner(f[i],g[j])
1127
1128 /// For complex types symmetric is interpreted as Hermitian.
1129 ///
1130 /// The current parallel loop is non-optimal but functional.
1131 template <typename T, typename R, std::size_t NDIM>
1133 const std::vector< Function<T,NDIM> >& f,
1134 const std::vector< Function<R,NDIM> >& g,
1135 bool sym=false) {
1136 PROFILE_BLOCK(Vmatrix_inner);
1137 long n=f.size(), m=g.size();
1138 Tensor< TENSOR_RESULT_TYPE(T,R) > r(n,m);
1139 if (sym) MADNESS_ASSERT(n==m);
1140
1141 world.gop.fence();
1142 compress(world, f);
1143 if ((void*)(&f) != (void*)(&g)) compress(world, g);
1144
1145 for (long i=0; i<n; ++i) {
1146 long jtop = m;
1147 if (sym) jtop = i+1;
1148 for (long j=0; j<jtop; ++j) {
1149 r(i,j) = f[i].inner_local(g[j]);
1150 if (sym) r(j,i) = conj(r(i,j));
1151 }
1152 }
1153
1154// for (long i=n-1; i>=0; --i) {
1155// long jtop = m;
1156// if (sym) jtop = i+1;
1157// world.taskq.add(new MatrixInnerTask<T,R,NDIM>(r(i,_), f[i], g, jtop));
1158// }
1159 world.gop.fence();
1160 world.gop.sum(r.ptr(),n*m);
1161
1162// if (sym) {
1163// for (int i=0; i<n; ++i) {
1164// for (int j=0; j<i; ++j) {
1165// r(j,i) = conj(r(i,j));
1166// }
1167// }
1168// }
1169 return r;
1170 }
1171
1172 /// Computes the element-wise inner product of two function vectors - q(i) = inner(f[i],g[i])
1173
1174 /// works in reconstructed or compressed state, state is chosen based on TensorType
1175 template <typename T, typename R, std::size_t NDIM>
1177 const std::vector< Function<T,NDIM> >& f,
1178 const std::vector< Function<R,NDIM> >& g) {
1179 PROFILE_BLOCK(Vinnervv);
1180 long n=f.size(), m=g.size();
1181 MADNESS_CHECK(n==m);
1182 Tensor< TENSOR_RESULT_TYPE(T,R) > r(n);
1183 if (n==0) return r;
1184
1185 auto tensor_type = [](const std::vector<Function<T,NDIM>>& v) {
1186 return v.front().get_impl()->get_tensor_type();
1187 };
1188 TreeState operating_state=tensor_type(f)==TT_FULL ? compressed : redundant;
1189 ensure_tree_state_respecting_fence(f,operating_state,true);
1190 ensure_tree_state_respecting_fence(g,operating_state,true);
1191
1192 for (long i=0; i<n; ++i) r(i) = f[i].inner_local(g[i]);
1193
1194 world.taskq.fence();
1195 world.gop.sum(r.ptr(),n);
1196 world.gop.fence();
1197 return r;
1198 }
1199
1200
1201 /// Computes the inner product of a function with a function vector - q(i) = inner(f,g[i])
1202
1203 /// works in reconstructed or compressed state, state is chosen based on TensorType
1204 template <typename T, typename R, std::size_t NDIM>
1206 const Function<T,NDIM>& f,
1207 const std::vector< Function<R,NDIM> >& g) {
1208 PROFILE_BLOCK(Vinner);
1209 long n=g.size();
1210 Tensor< TENSOR_RESULT_TYPE(T,R) > r(n);
1211
1212 auto tensor_type = [](const std::vector<Function<T,NDIM>>& v) {
1213 return v.front().get_impl()->get_tensor_type();
1214 };
1215 TreeState operating_state=tensor_type(g)==TT_FULL ? compressed : redundant;
1216 f.change_tree_state(operating_state,false);
1217 ensure_tree_state_respecting_fence(g,operating_state,true);
1218 world.gop.fence();
1219
1220 for (long i=0; i<n; ++i) {
1221 r(i) = f.inner_local(g[i]);
1222 }
1223
1224 world.taskq.fence();
1225 world.gop.sum(r.ptr(),n);
1226 world.gop.fence();
1227 return r;
1228 }
1229
1230 /// inner function with right signature for the nonlinear solver
1231 /// this is needed for the KAIN solvers and other functions
1232 template <typename T, typename R, std::size_t NDIM>
1233 TENSOR_RESULT_TYPE(T,R) inner( const std::vector< Function<T,NDIM> >& f,
1234 const std::vector< Function<R,NDIM> >& g){
1235 MADNESS_ASSERT(f.size()==g.size());
1236 if(f.empty()) return 0.0;
1237 else return inner(f[0].world(),f,g).sum();
1238 }
1239
1240
1241 /// Multiplies a function against a vector of functions --- q[i] = a * v[i]
1242 template <typename T, typename R, std::size_t NDIM>
1243 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1244 mul(World& world,
1245 const Function<T,NDIM>& a,
1246 const std::vector< Function<R,NDIM> >& v,
1247 bool fence=true) {
1248 PROFILE_BLOCK(Vmul);
1249 make_redundant(world, v, false);
1250 a.make_redundant(false);
1251 world.gop.fence();
1252 return vmulXX(a, v, 0.0, fence);
1253 }
1254
1255 /// Multiplies a function against a vector of functions using sparsity of a and v[i] --- q[i] = a * v[i]
1256 ///
1257 /// Box pairs whose estimated contribution falls below the tolerance are skipped instead
1258 /// of being multiplied. Both inputs are made redundant; the screening reads their
1259 /// norm_tree and dnorm_tree.
1260 ///
1261 /// Leaves both inputs in redundant form. Function is a shallow handle, so this is visible
1262 /// to the caller: logically const, not bitwise const. Converting back is not free, so a
1263 /// caller that reuses the operands afterwards must do it itself.
1264 ///
1265 /// @param[in] tol target absolute accuracy of the product; the safety margin is applied
1266 /// internally (FunctionImpl::MUL_SCREENING_SAFETY), so pass the accuracy
1267 /// wanted, not a pre-scaled value. tol=0 multiplies exactly. The criterion
1268 /// estimates the neglected cross terms rather than bounding them: the error
1269 /// tracks tol up to a measured O(1-20) constant and decays as ~tol^0.75
1270 /// rather than ~tol (see test_mul_sparse.cc). The meaning differs from the
1271 /// earlier norm_tree-based screen, so a previously tuned value needs
1272 /// re-checking.
1273 /// @param[in] do_make_redundant if false, both inputs must already be redundant
1274 template <typename T, typename R, std::size_t NDIM>
1275 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1277 const Function<T,NDIM>& a,
1278 const std::vector< Function<R,NDIM> >& v,
1279 double tol,
1280 bool fence=true,
1281 bool do_make_redundant=true) {
1282 PROFILE_BLOCK(Vmulsp);
1283 if (do_make_redundant) {
1284 try {
1287 } catch (...) {
1288 print("could not respect fence in mul_sparse");
1289 a.make_redundant(false);
1290 make_redundant(world, v, false);
1291 world.gop.fence();
1292 }
1293 } else if (!v.empty()) {
1294 MADNESS_CHECK_THROW(a.get_impl()->get_tree_state() == TreeState::redundant,
1295 "mul_sparse: left input must be redundant when do_make_redundant=false");
1297 "mul_sparse: right inputs must be redundant when do_make_redundant=false");
1298 }
1299 return vmulXX(a, v, tol, fence);
1300 }
1301
1302 /// Multiplies two vectors of functions using sparsity of a[i] and b[i] --- q[i] = a[i] * b[i]
1303 ///
1304 /// Box pairs whose estimated contribution falls below the tolerance are skipped instead
1305 /// of being multiplied. Both inputs are made redundant; the screening reads their
1306 /// norm_tree and dnorm_tree.
1307 ///
1308 /// Leaves both inputs in redundant form. Function is a shallow handle, so this is visible
1309 /// to the caller: logically const, not bitwise const. Converting back is not free, so a
1310 /// caller that reuses the operands afterwards must do it itself.
1311 ///
1312 /// @param[in] tol target absolute accuracy of the product; the safety margin is applied
1313 /// internally (FunctionImpl::MUL_SCREENING_SAFETY), so pass the accuracy
1314 /// wanted, not a pre-scaled value. tol=0 multiplies exactly. The criterion
1315 /// estimates the neglected cross terms rather than bounding them: the error
1316 /// tracks tol up to a measured O(1-20) constant and decays as ~tol^0.75
1317 /// rather than ~tol (see test_mul_sparse.cc). The meaning differs from the
1318 /// earlier norm_tree-based screen, so a previously tuned value needs
1319 /// re-checking.
1320 /// @param[in] do_make_redundant if false, both inputs must already be redundant
1321 template <typename T, typename R, std::size_t NDIM>
1322 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1324 const std::vector< Function<T,NDIM> >& a,
1325 const std::vector< Function<R,NDIM> >& b,
1326 double tol,
1327 bool fence=true,
1328 bool do_make_redundant=true) {
1329 PROFILE_BLOCK(Vmulvv);
1330 if (do_make_redundant) {
1331 try {
1334 } catch (...) {
1335 print("could not respect fence in mul_sparse");
1336 make_redundant(world, a, false);
1337 make_redundant(world, b, false);
1338 world.gop.fence();
1339 }
1340 }
1341 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> > q(a.size());
1342 for (unsigned int i=0; i<a.size(); ++i) {
1343 q[i] = mul_sparse(a[i], b[i], tol, false, false);
1344 }
1345 if (fence) world.gop.fence();
1346 return q;
1347 }
1348
1349
1350 /// Outer product of a vector of functions with a vector of functions using sparsity
1351
1352 /// \tparam T type parameter for first factor
1353 /// \tparam R type parameter for second factor
1354 /// \tparam NDIM dimension of first and second factors
1355 /// \param world the world
1356 /// \param f first vector of functions
1357 /// \param g second vector of functions
1358 /// \param tol target absolute accuracy of each product; see mul_sparse for the
1359 /// semantics, including the internal safety margin and tol=0
1360 /// \param fence force fence (will always fence if necessary)
1361 /// \param symm if true, only compute f(i) * g(j) for j<=i
1362 /// \return fg(i,j) = f(i) * g(j), as a vector of vectors
1363 template <typename T, typename R, std::size_t NDIM>
1364 std::vector<std::vector<Function<TENSOR_RESULT_TYPE(T, R), NDIM> > >
1366 const std::vector<Function<R, NDIM> > &f,
1367 const std::vector<Function<R, NDIM> > &g,
1368 double tol,
1369 bool fence = true,
1370 bool symm = false) {
1371 PROFILE_BLOCK(Vmulsp);
1372 bool same=(&f == &g);
1373 make_redundant(world, f, false);
1374 if (not same) make_redundant(world, g, false);
1375 world.gop.fence();
1376
1377 std::vector<std::vector<Function<R,NDIM> > >result(f.size());
1378 std::vector<Function<R,NDIM>> g_i;
1379 for (int64_t i=f.size()-1; i>=0; --i) {
1380 if (!symm)
1381 result[i]= vmulXX(f[i], g, tol, false);
1382 else {
1383 if (g_i.empty()) g_i = g;
1384 g_i.resize(i+1); // this shrinks g_i down to single function for i=0
1385 result[i]= vmulXX(f[i], g_i, tol, false);
1386 }
1387 }
1388 if (fence) world.gop.fence();
1389 return result;
1390 }
1391
1392 /// Makes the norm tree for all functions in a vector
1393 template <typename T, std::size_t NDIM>
1394 void norm_tree(World& world,
1395 const std::vector< Function<T,NDIM> >& v,
1396 bool fence=true)
1397 {
1398 PROFILE_BLOCK(Vnorm_tree);
1399 for (unsigned int i=0; i<v.size(); ++i) {
1400 v[i].norm_tree(false);
1401 }
1402 if (fence) world.gop.fence();
1403 }
1404
1405 /// Multiplies two vectors of functions q[i] = a[i] * b[i]; see mul_sparse to screen
1406 template <typename T, typename R, std::size_t NDIM>
1407 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1408 mul(World& world,
1409 const std::vector< Function<T,NDIM> >& a,
1410 const std::vector< Function<R,NDIM> >& b,
1411 bool fence=true,
1412 bool do_make_redundant=true) {
1413 PROFILE_BLOCK(Vmulvv);
1414 if (do_make_redundant) {
1415 try {
1418 } catch (...) {
1419 print("could not respect fence in mul");
1420 make_redundant(world, a, false);
1421 make_redundant(world, b, false);
1422 world.gop.fence();
1423 }
1424 }
1425 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> > q(a.size());
1426 for (unsigned int i=0; i<a.size(); ++i) {
1427 q[i] = mul(a[i], b[i], false, false);
1428 }
1429 if (fence) world.gop.fence();
1430 return q;
1431 }
1432
1433
1434 /// multiply a high-dimensional function with a low-dimensional function
1435
1436 /// @param[in] f NDIM function of NDIM dimensions
1437 /// @param[in] g LDIM function of LDIM
1438 /// @param[in] v dimension indices of f to multiply
1439 /// @return h[i](0,1,2,3) = f(0,1,2,3) * g[i](1,2,3) for v={1,2,3}
1440 template<typename T, std::size_t NDIM, std::size_t LDIM>
1441 std::vector<Function<T,NDIM> > partial_mul(const Function<T,NDIM> f, const std::vector<Function<T,LDIM> > g,
1442 const int particle) {
1443
1444 World& world=f.world();
1445 std::vector<Function<T,NDIM> > result(g.size());
1446 for (auto& r : result) r.set_impl(f, false);
1447
1448 FunctionImpl<T,NDIM>* fimpl=f.get_impl().get();
1449// fimpl->make_redundant(false);
1450 fimpl->change_tree_state(redundant,false);
1451 make_redundant(world,g,false);
1452 world.gop.fence();
1453
1454 for (std::size_t i=0; i<result.size(); ++i) {
1455 FunctionImpl<T,LDIM>* gimpl=g[i].get_impl().get();
1456 result[i].get_impl()->multiply(fimpl,gimpl,particle); // stupid naming inconsistency
1457 }
1458 world.gop.fence();
1459
1460 fimpl->undo_redundant(false);
1461 for (auto& ig : g) ig.get_impl()->undo_redundant(false);
1462 world.gop.fence();
1463 return result;
1464 }
1465
1466 template<typename T, std::size_t NDIM, std::size_t LDIM>
1467 std::vector<Function<T,NDIM> > multiply(const Function<T,NDIM> f, const std::vector<Function<T,LDIM> > g,
1468 const std::tuple<int,int,int> v) {
1469 return partial_mul<T,NDIM,LDIM>(f,g,std::array<int,3>({std::get<0>(v),std::get<1>(v),std::get<2>(v)}));
1470 }
1471
1472
1473/// Computes the square of a vector of functions --- q[i] = v[i]**2
1474 template <typename T, std::size_t NDIM>
1475 std::vector< Function<T,NDIM> >
1477 const std::vector< Function<T,NDIM> >& v,
1478 bool fence=true) {
1479 return mul<T,T,NDIM>(world, v, v, fence);
1480// std::vector< Function<T,NDIM> > vsq(v.size());
1481// for (unsigned int i=0; i<v.size(); ++i) {
1482// vsq[i] = square(v[i], false);
1483// }
1484// if (fence) world.gop.fence();
1485// return vsq;
1486 }
1487
1488
1489 /// Computes the square of a vector of functions --- q[i] = abs(v[i])**2
1490 template <typename T, std::size_t NDIM>
1491 std::vector< Function<typename Tensor<T>::scalar_type,NDIM> >
1492 abssq(World& world,
1493 const std::vector< Function<T,NDIM> >& v,
1494 bool fence=true) {
1495 typedef typename Tensor<T>::scalar_type scalartype;
1496 reconstruct(world,v);
1497 std::vector<Function<scalartype,NDIM> > result(v.size());
1498 for (size_t i=0; i<v.size(); ++i) result[i]=abs_square(v[i],false);
1499 if (fence) world.gop.fence();
1500 return result;
1501 }
1502
1503
1504 /// Sets the threshold in a vector of functions
1505 template <typename T, std::size_t NDIM>
1506 void set_thresh(World& world, std::vector< Function<T,NDIM> >& v, double thresh, bool fence=true) {
1507 for (unsigned int j=0; j<v.size(); ++j) {
1508 v[j].set_thresh(thresh,false);
1509 }
1510 if (fence) world.gop.fence();
1511 }
1512
1513 /// Returns the complex conjugate of the vector of functions
1514 template <typename T, std::size_t NDIM>
1515 std::vector< Function<T,NDIM> >
1516 conj(World& world,
1517 const std::vector< Function<T,NDIM> >& v,
1518 bool fence=true) {
1519 PROFILE_BLOCK(Vconj);
1520 std::vector< Function<T,NDIM> > r = copy(world, v); // Currently don't have oop conj
1521 for (unsigned int i=0; i<v.size(); ++i) {
1522 r[i].conj(false);
1523 }
1524 if (fence) world.gop.fence();
1525 return r;
1526 }
1527
1528 /// Returns a deep copy of a vector of functions
1529 template <typename T, typename R, std::size_t NDIM>
1530 std::vector< Function<R,NDIM> > convert(World& world,
1531 const std::vector< Function<T,NDIM> >& v, bool fence=true) {
1532 PROFILE_BLOCK(Vcopy);
1533 std::vector< Function<R,NDIM> > r(v.size());
1534 for (unsigned int i=0; i<v.size(); ++i) {
1535 r[i] = convert<T,R,NDIM>(v[i], false);
1536 }
1537 if (fence) world.gop.fence();
1538 return r;
1539 }
1540
1541
1542 /// Returns a deep copy of a vector of functions
1543 template <typename T, std::size_t NDIM>
1544 std::vector< Function<T,NDIM> >
1545 copy(World& world,
1546 const std::vector< Function<T,NDIM> >& v,
1547 bool fence=true) {
1548 PROFILE_BLOCK(Vcopy);
1549 std::vector< Function<T,NDIM> > r(v.size());
1550 for (unsigned int i=0; i<v.size(); ++i) {
1551 r[i] = copy(v[i], false);
1552 }
1553 if (fence) world.gop.fence();
1554 return r;
1555 }
1556
1557
1558 /// Returns a deep copy of a vector of functions
1559 template <typename T, std::size_t NDIM>
1560 std::vector< Function<T,NDIM> >
1561 copy(const std::vector< Function<T,NDIM> >& v, bool fence=true) {
1562 PROFILE_BLOCK(Vcopy);
1563 std::vector< Function<T,NDIM> > r(v.size());
1564 if (v.size()>0) r=copy(v.front().world(),v,fence);
1565 return r;
1566 }
1567
1568 /// Returns a vector of `n` deep copies of a function
1569 template <typename T, std::size_t NDIM>
1570 std::vector< Function<T,NDIM> >
1572 const Function<T,NDIM>& v,
1573 const unsigned int n,
1574 bool fence=true) {
1575 PROFILE_BLOCK(Vcopy1);
1576 std::vector< Function<T,NDIM> > r(n);
1577 for (unsigned int i=0; i<n; ++i) {
1578 r[i] = copy(v, false);
1579 }
1580 if (fence) world.gop.fence();
1581 return r;
1582 }
1583
1584 /// Create a new copy of the function with different distribution and optional
1585 /// fence
1586
1587 /// Works in either basis. Different distributions imply
1588 /// asynchronous communication and the optional fence is
1589 /// collective.
1590 //
1591 /// Returns a deep copy of a vector of functions
1592
1593 template <typename T, std::size_t NDIM>
1594 std::vector<Function<T, NDIM>> copy(World& world,
1595 const std::vector<Function<T, NDIM>>& v,
1596 const std::shared_ptr<WorldDCPmapInterface<Key<NDIM>>>& pmap,
1597 bool fence = true) {
1598 PROFILE_BLOCK(Vcopy);
1599 std::vector<Function<T, NDIM>> r(v.size());
1600 for (unsigned int i = 0; i < v.size(); ++i) {
1601 r[i] = copy(v[i], pmap, false);
1602 }
1603 if (fence) world.gop.fence();
1604 return r;
1605 }
1606
1607 /// owner[j] = j % nranks. For redistribute_to_batches.
1608 inline std::vector<ProcessID> assign_round_robin(std::size_t nfunc, int nranks) {
1609 MADNESS_CHECK(nranks > 0);
1610 std::vector<ProcessID> owner(nfunc);
1611 for (std::size_t j = 0; j < nfunc; ++j) owner[j] = ProcessID(j % std::size_t(nranks));
1612 return owner;
1613 }
1614
1615 /// Cost-balanced assignment: descending cost, each function to the least-loaded
1616 /// rank (LPT greedy). Deterministic for a replicated cost[] (stable sort, index
1617 /// tie-break), so owner[] agrees across ranks. For redistribute_to_batches.
1618 /// @param[in] cost per-function cost proxy (>= 0), identical on every rank
1619 inline std::vector<ProcessID> assign_cost_aware(const std::vector<double>& cost, int nranks) {
1620 MADNESS_CHECK(nranks > 0);
1621 const std::size_t nfunc = cost.size();
1622 std::vector<ProcessID> owner(nfunc);
1623 std::vector<std::size_t> order(nfunc);
1624 for (std::size_t j = 0; j < nfunc; ++j) order[j] = j;
1625 // descending cost; ascending index breaks ties -> stable and reproducible
1626 std::stable_sort(order.begin(), order.end(),
1627 [&](std::size_t a, std::size_t b) { return cost[a] > cost[b]; });
1628 std::vector<double> load(std::size_t(nranks), 0.0);
1629 for (std::size_t k = 0; k < nfunc; ++k) {
1630 int best = 0; // least-loaded rank; smallest
1631 for (int r = 1; r < nranks; ++r) // rank index breaks ties
1632 if (load[std::size_t(r)] < load[std::size_t(best)]) best = r;
1633 const std::size_t j = order[k];
1634 owner[j] = ProcessID(best);
1635 load[std::size_t(best)] += std::max(1.0, cost[j]); // floor: zero-cost funcs still rotate
1636 }
1637 return owner;
1638 }
1639
1640 /// Global coefficient count per function -- one reduction, identical on every rank,
1641 /// so safe for a deterministic assignment. A proxy for convolution cost; does not
1642 /// predict result-tree refinement.
1643 template <typename T, std::size_t NDIM>
1644 std::vector<double> function_costs(World& world, const std::vector<Function<T, NDIM>>& v) {
1645 std::vector<double> cost(v.size(), 0.0);
1646 for (std::size_t j = 0; j < v.size(); ++j) cost[j] = double(v[j].size_local());
1647 if (!v.empty()) world.gop.sum(cost.data(), cost.size());
1648 return cost;
1649 }
1650
1651 /// Move each v[j] so its whole tree lives on rank owner[j], via the coalesced
1652 /// WorldContainer transport (bulk AMs, erase-after-copy: streams, no 2x transient).
1653 /// State-preserving. Each function gets its OWN single-owner pmap (Key<NDIM> is
1654 /// function-agnostic), and the pmap outlives the call -- until redistributed again,
1655 /// every operation on v[j] runs on rank owner[j] alone.
1656 ///
1657 /// @param[in,out] v functions to localize (moved in place)
1658 /// @param[in] owner destination rank per function; MUST be identical on every
1659 /// rank (checked collectively)
1660 /// @param[in] cap_bytes soft cap per message (0 => ~1 MiB, sized for the default
1661 /// MAD_BUFFER_SIZE; lower it if that buffer was shrunk)
1662 /// @param[in] rotate stagger destinations to reduce incast
1663 template <typename T, std::size_t NDIM>
1665 std::vector<Function<T, NDIM>>& v,
1666 const std::vector<ProcessID>& owner,
1667 std::size_t cap_bytes = 0,
1668 bool rotate = true) {
1669 MADNESS_CHECK(owner.size() == v.size());
1670 if (v.empty()) return;
1671
1672 // owner[] must agree across ranks -- divergence silently corrupts ownership
1673 {
1674 long h = 0;
1675 for (std::size_t j = 0; j < owner.size(); ++j) h += long(owner[j]) * long(j + 1);
1676 long hmax = h, hmin = h;
1677 world.gop.max(hmax);
1678 world.gop.min(hmin);
1679 MADNESS_CHECK(hmax == hmin);
1680 }
1681
1682 // chunk cap in #boxes; box size bounded by the functions' own k, not
1683 // FunctionDefaults (v may carry its own k)
1684 if (cap_bytes == 0) cap_bytes = 1024 * 1024; // ~1 MiB, under the default RMI buffer
1685 long kmax = 1;
1686 for (const auto& f : v) kmax = std::max(kmax, long(f.k()));
1687 std::size_t box_bytes = sizeof(T);
1688 for (std::size_t d = 0; d < NDIM; ++d) box_bytes *= std::size_t(2 * kmax);
1689 const std::size_t cap_boxes = std::max<std::size_t>(1, cap_bytes / box_bytes);
1690
1691 // fence, phase1, fence, phase2, fence: the middle fence is REQUIRED -- phase1
1692 // iterates the ConcurrentHashMap and needs a quiescent window (see worlddc.h)
1693 world.gop.fence();
1694 for (std::size_t j = 0; j < v.size(); ++j) {
1695 auto pmap = std::shared_ptr<WorldDCPmapInterface<Key<NDIM>>>(
1696 new WorldDCSingleOwnerPmap<Key<NDIM>>(owner[j]));
1697 v[j].get_impl()->get_coeffs().redistribute_coalesced_phase1(pmap);
1698 }
1699 world.gop.fence();
1700 for (std::size_t j = 0; j < v.size(); ++j)
1701 v[j].get_impl()->get_coeffs().redistribute_coalesced_phase2(cap_boxes, rotate);
1702 world.gop.fence();
1703 }
1704
1705 /// Returns new vector of functions --- q[i] = a[i] + b[i]
1706 template <typename T, typename R, std::size_t NDIM>
1707 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1708 add(World& world,
1709 const std::vector< Function<T,NDIM> >& a,
1710 const std::vector< Function<R,NDIM> >& b,
1711 bool fence=true) {
1712 PROFILE_BLOCK(Vadd);
1713 MADNESS_ASSERT(a.size() == b.size());
1714 compress(world, a);
1715 compress(world, b);
1716
1717 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> > r(a.size());
1718 for (unsigned int i=0; i<a.size(); ++i) {
1719 r[i] = add(a[i], b[i], false);
1720 }
1721 if (fence) world.gop.fence();
1722 return r;
1723 }
1724
1725 /// Returns new vector of functions --- q[i] = a + b[i]
1726 template <typename T, typename R, std::size_t NDIM>
1727 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1728 add(World& world,
1729 const Function<T,NDIM> & a,
1730 const std::vector< Function<R,NDIM> >& b,
1731 bool fence=true) {
1732 PROFILE_BLOCK(Vadd1);
1733 a.compress();
1734 compress(world, b);
1735
1736 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> > r(b.size());
1737 for (unsigned int i=0; i<b.size(); ++i) {
1738 r[i] = add(a, b[i], false);
1739 }
1740 if (fence) world.gop.fence();
1741 return r;
1742 }
1743 template <typename T, typename R, std::size_t NDIM>
1744 inline std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1745 add(World& world,
1746 const std::vector< Function<R,NDIM> >& b,
1747 const Function<T,NDIM> & a,
1748 bool fence=true) {
1749 return add(world, a, b, fence);
1750 }
1751
1752 /// Returns new vector of functions --- q[i] = a[i] - b[i]
1753 template <typename T, typename R, std::size_t NDIM>
1754 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
1755 sub(World& world,
1756 const std::vector< Function<T,NDIM> >& a,
1757 const std::vector< Function<R,NDIM> >& b,
1758 bool fence=true) {
1759 PROFILE_BLOCK(Vsub);
1760 MADNESS_ASSERT(a.size() == b.size());
1761 compress(world, a);
1762 compress(world, b);
1763
1764 std::vector< Function<TENSOR_RESULT_TYPE(T,R),NDIM> > r(a.size());
1765 for (unsigned int i=0; i<a.size(); ++i) {
1766 r[i] = sub(a[i], b[i], false);
1767 }
1768 if (fence) world.gop.fence();
1769 return r;
1770 }
1771
1772 /// Returns new function --- q = sum_i f[i]
1773 template <typename T, std::size_t NDIM>
1774 Function<T, NDIM> sum(World& world, const std::vector<Function<T,NDIM> >& f,
1775 bool fence=true) {
1776
1777 compress(world, f);
1779
1780 for (unsigned int i=0; i<f.size(); ++i) r.gaxpy(1.0,f[i],1.0,false);
1781 if (fence) world.gop.fence();
1782 return r;
1783 }
1784
1785 template <typename T, std::size_t NDIM>
1787 const std::vector<Function<T, NDIM>>& f,
1788 const std::vector<Function<T, NDIM>>& g,
1789 bool sym=false)
1790 {
1793 const int64_t n = A.coldim();
1794 const int64_t m = A.rowdim();
1795 MADNESS_ASSERT(int64_t(f.size()) == n && int64_t(g.size()) == m);
1796
1797 // Assume we can always create an ichunk*jchunk matrix locally
1798 const int ichunk = 1000;
1799 const int jchunk = 1000; // 1000*1000*8 = 8 MBytes
1800 for (int64_t ilo = 0; ilo < n; ilo += ichunk) {
1801 int64_t ihi = std::min(ilo + ichunk, n);
1802 std::vector<Function<T, NDIM>> ivec(f.begin() + ilo, f.begin() + ihi);
1803 for (int64_t jlo = 0; jlo < m; jlo += jchunk) {
1804 int64_t jhi = std::min(jlo + jchunk, m);
1805 std::vector<Function<T, NDIM>> jvec(g.begin() + jlo, g.begin() + jhi);
1806
1807 Tensor<T> P = matrix_dot(A.get_world(), ivec, jvec, sym);
1808 A.copy_from_replicated_patch(ilo, ihi - 1, jlo, jhi - 1, P);
1809 }
1810 }
1811 return A;
1812 }
1813
1814 /// Computes the matrix dot product of two function vectors - q(i,j) = dot(f[i],g[j])
1815
1816 /// For complex types symmetric is interpreted as Hermitian.
1817 ///
1818 /// The current parallel loop is non-optimal but functional.
1819 template <typename T, typename R, std::size_t NDIM>
1821 const std::vector<Function<T, NDIM>>& f,
1822 const std::vector<Function<R, NDIM>>& g,
1823 bool sym=false)
1824 {
1825 world.gop.fence();
1826 compress(world, f);
1827 // if ((void*)(&f) != (void*)(&g)) compress(world, g);
1828 compress(world, g);
1829
1830 std::vector<const FunctionImpl<T, NDIM>*> left(f.size());
1831 std::vector<const FunctionImpl<R, NDIM>*> right(g.size());
1832 for (unsigned int i = 0; i < f.size(); i++) left[i] = f[i].get_impl().get();
1833 for (unsigned int i = 0; i < g.size(); i++) right[i] = g[i].get_impl().get();
1834
1836
1837 world.gop.fence();
1838 world.gop.sum(r.ptr(), f.size() * g.size());
1839
1840 return r;
1841 }
1842
1843 /// Computes the matrix dot product of two function vectors - q(i,j) = dot(f[i],g[j])
1844
1845 /// For complex types symmetric is interpreted as Hermitian.
1846 ///
1847 /// The current parallel loop is non-optimal but functional.
1848 template <typename T, typename R, std::size_t NDIM>
1850 const std::vector< Function<T,NDIM> >& f,
1851 const std::vector< Function<R,NDIM> >& g,
1852 bool sym=false) {
1853 PROFILE_BLOCK(Vmatrix_dot);
1854 long n=f.size(), m=g.size();
1855 Tensor< TENSOR_RESULT_TYPE(T,R) > r(n,m);
1856 if (sym) MADNESS_ASSERT(n==m);
1857
1858 world.gop.fence();
1859 compress(world, f);
1860 if ((void*)(&f) != (void*)(&g)) compress(world, g);
1861
1862 for (long i=0; i<n; ++i) {
1863 long jtop = m;
1864 if (sym) jtop = i+1;
1865 for (long j=0; j<jtop; ++j) {
1866 if (sym) {
1867 r(j,i) = f[i].dot_local(g[j]);
1868 if (i != j)
1869 r(i,j) = conj(r(j,i));
1870 } else
1871 r(i,j) = f[i].dot_local(g[j]);
1872 }
1873 }
1874
1875 world.gop.fence();
1876 world.gop.sum(r.ptr(),n*m);
1877
1878 return r;
1879 }
1880
1881 /// Multiplies and sums two vectors of functions r = \sum_i a[i] * b[i]
1882 template <typename T, typename R, std::size_t NDIM>
1883 Function<TENSOR_RESULT_TYPE(T,R), NDIM>
1885 const std::vector< Function<T,NDIM> >& a,
1886 const std::vector< Function<R,NDIM> >& b,
1887 double tol,
1888 bool fence=true,
1889 bool do_make_redundant=true) {
1890 MADNESS_CHECK(a.size()==b.size());
1891 return sum(world,mul_sparse(world,a,b,tol,/*fence=*/true,do_make_redundant),fence);
1892 }
1893
1894 /// Multiplies and sums two vectors of functions r = \sum_i a[i] * b[i]; see dot_sparse for screening
1895 template <typename T, typename R, std::size_t NDIM>
1896 Function<TENSOR_RESULT_TYPE(T,R), NDIM>
1897 dot(World& world,
1898 const std::vector< Function<T,NDIM> >& a,
1899 const std::vector< Function<R,NDIM> >& b,
1900 bool fence=true,
1901 bool do_make_redundant=true) {
1902 MADNESS_CHECK(a.size()==b.size());
1903 return sum(world,mul(world,a,b,/*fence=*/true,do_make_redundant),fence);
1904 }
1905
1906 /// out-of-place gaxpy for two vectors: result[i] = alpha * a[i] + beta * b[i]
1907 template <typename T, typename Q, typename R, std::size_t NDIM>
1908 std::vector<Function<TENSOR_RESULT_TYPE(Q,TENSOR_RESULT_TYPE(T,R)),NDIM> >
1910 const std::vector< Function<T,NDIM> >& a,
1911 Q beta,
1912 const std::vector< Function<R,NDIM> >& b,
1913 bool fence=true) {
1914
1915 MADNESS_ASSERT(a.size() == b.size());
1916 typedef TENSOR_RESULT_TYPE(Q,TENSOR_RESULT_TYPE(T,R)) resultT;
1917 if (a.size()==0) return std::vector<Function<resultT,NDIM> >();
1918
1919 auto tensor_type = [](const std::vector<Function<T,NDIM>>& v) {
1920 return v.front().get_impl()->get_tensor_type();
1921 };
1922
1923 // gaxpy can be done either in reconstructed or in compressed state
1924 World& world=a[0].world();
1925 std::vector<Function<resultT,NDIM> > result(a.size());
1926
1927 TreeState operating_state=tensor_type(a)==TT_FULL ? compressed : reconstructed;
1928 try {
1929 ensure_tree_state_respecting_fence(a,operating_state,fence);
1930 ensure_tree_state_respecting_fence(b,operating_state,fence);
1931 } catch (...) {
1932 print("could not respect fence in gaxpy");
1933 change_tree_state(a,operating_state,true);
1934 change_tree_state(b,operating_state,true);
1935 }
1936
1937 if (operating_state==compressed) {
1938 for (unsigned int i=0; i<a.size(); ++i) result[i]=gaxpy_oop(alpha, a[i], beta, b[i], false);
1939 } else {
1940 for (unsigned int i=0; i<a.size(); ++i) result[i]=gaxpy_oop_reconstructed(alpha, a[i], beta, b[i], false);
1941 }
1942
1943 if (fence) world.gop.fence();
1944 return result;
1945 }
1946
1947
1948 /// out-of-place gaxpy for a vectors and a function: result[i] = alpha * a[i] + beta * b
1949 template <typename T, typename Q, typename R, std::size_t NDIM>
1950 std::vector<Function<TENSOR_RESULT_TYPE(Q,TENSOR_RESULT_TYPE(T,R)),NDIM> >
1952 const std::vector< Function<T,NDIM> >& a,
1953 Q beta,
1954 const Function<R,NDIM>& b,
1955 bool fence=true) {
1956
1957 typedef TENSOR_RESULT_TYPE(Q,TENSOR_RESULT_TYPE(T,R)) resultT;
1958 if (a.size()==0) return std::vector<Function<resultT,NDIM> >();
1959
1960 World& world=a[0].world();
1961 try {
1963 // ensure_tree_state_respecting_fence({b},compressed,fence);
1965 } catch (...) {
1966 print("could not respect fence in gaxpy_oop");
1967 compress(world,a);
1968 b.compress();
1969 }
1970 std::vector<Function<resultT,NDIM> > result(a.size());
1971 for (unsigned int i=0; i<a.size(); ++i) {
1972 result[i]=gaxpy_oop(alpha, a[i], beta, b, false);
1973 }
1974 if (fence) world.gop.fence();
1975 return result;
1976 }
1977
1978
1979 /// Generalized A*X+Y for vectors of functions ---- a[i] = alpha*a[i] + beta*b[i]
1980 template <typename T, typename Q, typename R, std::size_t NDIM>
1981 void gaxpy(Q alpha, std::vector<Function<T,NDIM>>& a, Q beta, const std::vector<Function<R,NDIM>>& b, const bool fence) {
1982 if (a.size() == 0) return;
1983 World& world=a.front().world();
1984 gaxpy(world,alpha,a,beta,b,fence);
1985 }
1986
1987 /// Generalized A*X+Y for vectors of functions ---- a[i] = alpha*a[i] + beta*b[i]
1988 template <typename T, typename Q, typename R, std::size_t NDIM>
1989 void gaxpy(World& world,
1990 Q alpha,
1991 std::vector< Function<T,NDIM> >& a,
1992 Q beta,
1993 const std::vector< Function<R,NDIM> >& b,
1994 bool fence=true) {
1995 PROFILE_BLOCK(Vgaxpy);
1996 MADNESS_ASSERT(a.size() == b.size());
1997 if (a.empty()) return;
1998
1999 auto tensor_type = [](const std::vector<Function<T,NDIM>>& v) {
2000 return v.front().get_impl()->get_tensor_type();
2001 };
2002
2003 // gaxpy can be done either in reconstructed or in compressed state
2004 bool do_in_reconstructed_state=tensor_type(a)!=TT_FULL;
2005 TreeState operating_state=do_in_reconstructed_state ? reconstructed : compressed;
2006
2007 if (operating_state==compressed) {
2008 // this is strict: both vectors have to be compressed
2009 try {
2010 ensure_tree_state_respecting_fence(a,operating_state,fence);
2011 ensure_tree_state_respecting_fence(b,operating_state,fence);
2012 } catch (...) {
2013 print("could not respect fence in gaxpy");
2014 change_tree_state(a,operating_state,true);
2015 change_tree_state(b,operating_state,true);
2016 }
2017 MADNESS_CHECK_THROW(get_tree_state(a)==get_tree_state(b),"gaxpy requires same tree state for all functions");
2018 MADNESS_CHECK_THROW(get_tree_state(a)==operating_state,"gaxpy requires reconstructed/compressed tree state for all functions");
2019 } else {
2020 // both vectors can be reconstructed or redundant_after_merge, and they don't have to be the same
2021 TreeState astate=get_tree_state(a);
2022 TreeState bstate=get_tree_state(b);
2023 if (not (astate==reconstructed or astate==redundant_after_merge)) {
2024 try {
2025 ensure_tree_state_respecting_fence(a,operating_state,fence);
2026 } catch (...) {
2027 print("could not respect fence in gaxpy for a");
2029 }
2030 }
2031 if (not (bstate==reconstructed or bstate==redundant_after_merge)) {
2032 try {
2033 ensure_tree_state_respecting_fence(b,operating_state,fence);
2034 } catch (...) {
2035 print("could not respect fence in gaxpy for b");
2037 }
2038 }
2039 }
2040
2041 // finally do the work
2042 for (unsigned int i=0; i<a.size(); ++i) {
2043 a[i].gaxpy(alpha, b[i], beta, false);
2044 }
2045 if (fence and (get_tree_state(a)==redundant_after_merge)) {
2046 for (unsigned int i=0; i<a.size(); ++i) a[i].get_impl()->finalize_sum();
2047 }
2048
2049 if (fence) world.gop.fence();
2050 }
2051
2052
2053 /// Applies a vector of operators to a vector of functions --- q[i] = apply(op[i],f[i])
2054 template <typename opT, typename R, std::size_t NDIM>
2055 std::vector< Function<TENSOR_RESULT_TYPE(typename opT::opT,R), NDIM> >
2056 apply(World& world,
2057 const std::vector< std::shared_ptr<opT> >& op,
2058 const std::vector< Function<R,NDIM> > f) {
2059
2060 PROFILE_BLOCK(Vapplyv);
2061 MADNESS_ASSERT(f.size()==op.size());
2062
2063 std::vector< Function<R,NDIM> >& ncf = *const_cast< std::vector< Function<R,NDIM> >* >(&f);
2064
2065// reconstruct(world, f);
2066 make_nonstandard(world, ncf);
2067
2068 std::vector< Function<TENSOR_RESULT_TYPE(typename opT::opT,R), NDIM> > result(f.size());
2069 for (unsigned int i=0; i<f.size(); ++i) {
2070 result[i] = apply_only(*op[i], f[i], false);
2071 result[i].get_impl()->set_tree_state(nonstandard_after_apply);
2072 }
2073
2074 world.gop.fence();
2075
2076 standard(world, ncf, false); // restores promise of logical constness
2077 reconstruct(result);
2078 world.gop.fence();
2079
2080 return result;
2081 }
2082
2083
2084 /// Applies an operator to a vector of functions --- q[i] = apply(op,f[i])
2085 template <typename T, typename R, std::size_t NDIM, std::size_t KDIM>
2086 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
2088 const std::vector< Function<R,NDIM> > f) {
2089 return apply(op.get_world(),op,f);
2090 }
2091
2092
2093 /// Applies an operator to a vector of functions --- q[i] = apply(op,f[i])
2094 template <typename T, typename R, std::size_t NDIM, std::size_t KDIM>
2095 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> >
2096 apply(World& world,
2098 const std::vector< Function<R,NDIM> > f) {
2099 PROFILE_BLOCK(Vapply);
2100
2101 std::vector< Function<R,NDIM> >& ncf = *const_cast< std::vector< Function<R,NDIM> >* >(&f);
2102 bool print_timings=(NDIM==6) and (world.rank()==0) and op.print_timings;
2103
2104 double wall0=wall_time();
2105// reconstruct(world, f);
2106 make_nonstandard(world, ncf);
2107 double wall1=wall_time();
2108 if (print_timings) printf("timer: %20.20s %8.2fs\n", "make_nonstandard", wall1-wall0);
2109
2110 std::vector< Function<TENSOR_RESULT_TYPE(T,R), NDIM> > result(f.size());
2111 for (unsigned int i=0; i<f.size(); ++i) {
2112 result[i] = apply_only(op, f[i], false);
2113 }
2114
2115 world.gop.fence();
2116
2117 // restores promise of logical constness
2118 if (op.destructive()) {
2119 for (auto& ff : ncf) ff.clear(false);
2120 world.gop.fence();
2121 } else {
2122 reconstruct(world,f);
2123 }
2124
2125 // svd-tensor requires some cleanup after apply
2126 if (result[0].get_impl()->get_tensor_type()==TT_2D) {
2127 for (auto& r : result) r.get_impl()->finalize_apply();
2128 }
2129
2130 if (print_timings) {
2131 for (auto& r : result) r.get_impl()->print_timer();
2132 op.print_timer();
2133 }
2134 reconstruct(world, result);
2135
2136 return result;
2137 }
2138
2139 /// Normalizes a vector of functions --- v[i] = v[i].scale(1.0/v[i].norm2())
2140 template <typename T, std::size_t NDIM>
2141 void normalize(World& world, std::vector< Function<T,NDIM> >& v, bool fence=true) {
2142 PROFILE_BLOCK(Vnormalize);
2143 std::vector<double> nn = norm2s(world, v);
2144 for (unsigned int i=0; i<v.size(); ++i) v[i].scale(1.0/nn[i],false);
2145 if (fence) world.gop.fence();
2146 }
2147
2148 template <typename T, std::size_t NDIM>
2149 void print_size(World &world, const std::vector<Function<T,NDIM> > &v, const std::string &msg = "vectorfunction" ){
2150 if(v.empty()){
2151 if(world.rank()==0) std::cout << "print_size: " << msg << " is empty" << std::endl;
2152 }else if(v.size()==1){
2153 v.front().print_size(msg);
2154 }else{
2155 for(auto x:v){
2156 // print("impl",x.get_impl().get());
2157 x.print_size(msg);
2158 }
2159 }
2160 }
2161
2162 /// return the size of a vector of functions for each rank
2163 template <typename T, std::size_t NDIM>
2164 double get_size_local(World& world, const std::vector< Function<T,NDIM> >& v){
2165 double size=0.0;
2166 for(auto x:v){
2167 if (x.is_initialized()) size+=x.size_local();
2168 }
2169 const double d=sizeof(T);
2170 const double fac=1024*1024*1024;
2171 return size/fac*d;
2172 }
2173
2174 /// return the size of a function for each rank
2175 template <typename T, std::size_t NDIM>
2177 return get_size_local(f.world(),std::vector<Function<T,NDIM> >(1,f));
2178 }
2179
2180
2181 // gives back the size in GB
2182 template <typename T, std::size_t NDIM>
2183 double get_size(World& world, const std::vector< Function<T,NDIM> >& v) {
2184 return get_size(v);
2185 }
2186
2187 // gives back the size in GB
2188 template <typename T, std::size_t NDIM>
2189 double get_size(const std::vector< Function<T,NDIM> >& v) {
2190 if (v.empty()) return 0.0;
2191
2192 const double d=sizeof(T);
2193 const double fac=1024*1024*1024;
2194
2195 double size=0.0;
2196 for(unsigned int i=0;i<v.size();i++){
2197 if (v[i].is_initialized()) size+=v[i].size();
2198 }
2199
2200 return size/fac*d;
2201
2202 }
2203
2204 // gives back the size in GB
2205 template <typename T, std::size_t NDIM>
2206 double get_size(const Function<T,NDIM> & f){
2207 const double d=sizeof(T);
2208 const double fac=1024*1024*1024;
2209 double size=f.size();
2210 return size/fac*d;
2211 }
2212
2213 /// apply op on the input vector yielding an output vector of functions
2214
2215 /// @param[in] op the operator working on vin
2216 /// @param[in] vin vector of input Functions; needs to be refined to common level!
2217 /// @return vector of output Functions vout = op(vin)
2218 template <typename T, typename opT, std::size_t NDIM>
2219 std::vector<Function<T,NDIM> > multi_to_multi_op_values(const opT& op,
2220 const std::vector< Function<T,NDIM> >& vin,
2221 const bool fence=true) {
2222 MADNESS_ASSERT(vin.size()>0);
2223 MADNESS_ASSERT(vin[0].is_initialized()); // might be changed
2224 World& world=vin[0].world();
2225 Function<T,NDIM> dummy;
2226 dummy.set_impl(vin[0], false);
2227 std::vector<Function<T,NDIM> > vout=zero_functions<T,NDIM>(world, op.get_result_size());
2228 for (auto& out : vout) out.set_impl(vin[0],false);
2229 dummy.multi_to_multi_op_values(op, vin, vout, fence);
2230 return vout;
2231 }
2232
2233
2234
2235
2236 // convenience operators
2237
2238 /// result[i] = a[i] + b[i]
2239 template <typename T, std::size_t NDIM>
2240 std::vector<Function<T,NDIM> > operator+(const std::vector<Function<T,NDIM> >& lhs,
2241 const std::vector<Function<T,NDIM>>& rhs) {
2242 MADNESS_CHECK(lhs.size() == rhs.size());
2243 return gaxpy_oop(1.0,lhs,1.0,rhs);
2244 }
2245
2246 /// result[i] = a[i] - b[i]
2247 template <typename T, std::size_t NDIM>
2248 std::vector<Function<T,NDIM> > operator-(const std::vector<Function<T,NDIM> >& lhs,
2249 const std::vector<Function<T,NDIM> >& rhs) {
2250 MADNESS_CHECK(lhs.size() == rhs.size());
2251 return gaxpy_oop(1.0,lhs,-1.0,rhs);
2252 }
2253
2254 /// result[i] = a[i] + b
2255 template <typename T, std::size_t NDIM>
2256 std::vector<Function<T,NDIM> > operator+(const std::vector<Function<T,NDIM> >& lhs,
2257 const Function<T,NDIM>& rhs) {
2258 // MADNESS_CHECK(lhs.size() == rhs.size()); // no!!
2259 return gaxpy_oop(1.0,lhs,1.0,rhs);
2260 }
2261
2262 /// result[i] = a[i] - b
2263 template <typename T, std::size_t NDIM>
2264 std::vector<Function<T,NDIM> > operator-(const std::vector<Function<T,NDIM> >& lhs,
2265 const Function<T,NDIM>& rhs) {
2266 // MADNESS_CHECK(lhs.size() == rhs.size()); // no
2267 return gaxpy_oop(1.0,lhs,-1.0,rhs);
2268 }
2269
2270 /// result[i] = a + b[i]
2271 template <typename T, std::size_t NDIM>
2272 std::vector<Function<T,NDIM> > operator+(const Function<T,NDIM>& lhs,
2273 const std::vector<Function<T,NDIM> >& rhs) {
2274 // MADNESS_CHECK(lhs.size() == rhs.size()); // no
2275 return gaxpy_oop(1.0,rhs,1.0,lhs);
2276 }
2277
2278 /// result[i] = a - b[i]
2279 template <typename T, std::size_t NDIM>
2280 std::vector<Function<T,NDIM> > operator-(const Function<T,NDIM>& lhs,
2281 const std::vector<Function<T,NDIM> >& rhs) {
2282// MADNESS_CHECK(lhs.size() == rhs.size()); // no
2283 return gaxpy_oop(-1.0,rhs,1.0,lhs);
2284 }
2285
2286
2287 template <typename T, typename R, std::size_t NDIM>
2288 std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> > operator*(const R fac,
2289 const std::vector<Function<T,NDIM> >& rhs) {
2290 if (rhs.size()>0) {
2291 std::vector<Function<T,NDIM> > tmp=copy(rhs[0].world(),rhs);
2292 scale(tmp[0].world(),tmp,TENSOR_RESULT_TYPE(T,R)(fac));
2293 return tmp;
2294 }
2295 return std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> >();
2296 }
2297
2298 template <typename T, typename R, std::size_t NDIM>
2299 std::vector<Function<T,NDIM> > operator*(const std::vector<Function<T,NDIM> >& rhs,
2300 const R fac) {
2301 if (rhs.size()>0) {
2302 std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> > tmp=copy(rhs[0].world(),rhs);
2303 scale(tmp[0].world(),tmp,TENSOR_RESULT_TYPE(T,R)(fac));
2304 return tmp;
2305 }
2306 return std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> >();
2307 }
2308
2309 /// multiply a vector of functions with a function: r[i] = v[i] * a
2310 template <typename T, typename R, std::size_t NDIM>
2312 const std::vector<Function<R,NDIM> >& v) {
2313 if (v.size()>0) return mul(v[0].world(),a,v,true);
2314 return std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> >();
2315 }
2316
2317
2318 /// multiply a vector of functions with a function: r[i] = a * v[i]
2319 template <typename T, typename R, std::size_t NDIM>
2320 std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> > operator*(const std::vector<Function<T,NDIM> >& v,
2321 const Function<R,NDIM>& a) {
2322 if (v.size()>0) return mul(v[0].world(),a,v,true);
2323 return std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> >();
2324 }
2325
2326
2327 template <typename T, std::size_t NDIM>
2328 std::vector<Function<T,NDIM> > operator+=(std::vector<Function<T,NDIM> >& lhs, const std::vector<Function<T,NDIM> >& rhs) {
2329 MADNESS_CHECK(lhs.size() == rhs.size());
2330 if (lhs.size() > 0) gaxpy(lhs.front().world(), 1.0, lhs, 1.0, rhs);
2331 return lhs;
2332 }
2333
2334 template <typename T, std::size_t NDIM>
2335 std::vector<Function<T,NDIM> > operator-=(std::vector<Function<T,NDIM> >& lhs,
2336 const std::vector<Function<T,NDIM> >& rhs) {
2337 MADNESS_CHECK(lhs.size() == rhs.size());
2338 if (lhs.size() > 0) gaxpy(lhs.front().world(), 1.0, lhs, -1.0, rhs);
2339 return lhs;
2340 }
2341
2342 /// return the real parts of the vector's function (if complex)
2343 template <typename T, std::size_t NDIM>
2344 std::vector<Function<typename Tensor<T>::scalar_type,NDIM> >
2345 real(const std::vector<Function<T,NDIM> >& v, bool fence=true) {
2346 std::vector<Function<typename Tensor<T>::scalar_type,NDIM> > result(v.size());
2347 for (std::size_t i=0; i<v.size(); ++i) result[i]=real(v[i],false);
2348 if (fence and result.size()>0) result[0].world().gop.fence();
2349 return result;
2350 }
2351
2352 /// return the imaginary parts of the vector's function (if complex)
2353 template <typename T, std::size_t NDIM>
2354 std::vector<Function<typename Tensor<T>::scalar_type,NDIM> >
2355 imag(const std::vector<Function<T,NDIM> >& v, bool fence=true) {
2356 std::vector<Function<typename Tensor<T>::scalar_type,NDIM> > result(v.size());
2357 for (std::size_t i=0; i<v.size(); ++i) result[i]=imag(v[i],false);
2358 if (fence and result.size()>0) result[0].world().gop.fence();
2359 return result;
2360 }
2361
2362 /// shorthand gradient operator
2363
2364 /// returns the differentiated function f in all NDIM directions
2365 /// @param[in] f the function on which the grad operator works on
2366 /// @param[in] refine refinement before diff'ing makes the result more accurate
2367 /// @param[in] fence fence after completion; if reconstruction is needed always fence
2368 /// @return the vector \frac{\partial}{\partial x_i} f
2369 template <typename T, std::size_t NDIM>
2370 std::vector<Function<T,NDIM> > grad(const Function<T,NDIM>& f,
2371 bool refine=false, bool fence=true) {
2372
2373 World& world=f.world();
2374 f.reconstruct();
2375 if (refine) f.refine(); // refine to make result more precise
2376
2377 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2379
2380 std::vector<Function<T,NDIM> > result(NDIM);
2381 for (size_t i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),f,false);
2382 if (fence) world.gop.fence();
2383 return result;
2384 }
2385
2386 // BLM first derivative
2387 template <typename T, std::size_t NDIM>
2388 std::vector<Function<T,NDIM> > grad_ble_one(const Function<T,NDIM>& f,
2389 bool refine=false, bool fence=true) {
2390
2391 World& world=f.world();
2392 f.reconstruct();
2393 if (refine) f.refine(); // refine to make result more precise
2394
2395 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2397
2398 // Read in new coeff for each operator
2399 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_ble1();
2400
2401 std::vector<Function<T,NDIM> > result(NDIM);
2402 for (unsigned int i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),f,false);
2403 if (fence) world.gop.fence();
2404 return result;
2405 }
2406
2407 // BLM second derivative
2408 template <typename T, std::size_t NDIM>
2409 std::vector<Function<T,NDIM> > grad_ble_two(const Function<T,NDIM>& f,
2410 bool refine=false, bool fence=true) {
2411
2412 World& world=f.world();
2413 f.reconstruct();
2414 if (refine) f.refine(); // refine to make result more precise
2415
2416 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2418
2419 // Read in new coeff for each operator
2420 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_ble2();
2421
2422 std::vector<Function<T,NDIM> > result(NDIM);
2423 for (unsigned int i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),f,false);
2424 if (fence) world.gop.fence();
2425 return result;
2426 }
2427
2428 // Bspline first derivative
2429 template <typename T, std::size_t NDIM>
2430 std::vector<Function<T,NDIM> > grad_bspline_one(const Function<T,NDIM>& f,
2431 bool refine=false, bool fence=true) {
2432
2433 World& world=f.world();
2434 f.reconstruct();
2435 if (refine) f.refine(); // refine to make result more precise
2436
2437 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2439
2440 // Read in new coeff for each operator
2441 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_bspline1();
2442
2443 std::vector<Function<T,NDIM> > result(NDIM);
2444 for (unsigned int i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),f,false);
2445 if (fence) world.gop.fence();
2446 return result;
2447 }
2448
2449 // Bpsline second derivative
2450 template <typename T, std::size_t NDIM>
2451 std::vector<Function<T,NDIM> > grad_bpsline_two(const Function<T,NDIM>& f,
2452 bool refine=false, bool fence=true) {
2453
2454 World& world=f.world();
2455 f.reconstruct();
2456 if (refine) f.refine(); // refine to make result more precise
2457
2458 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2460
2461 // Read in new coeff for each operator
2462 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_bspline2();
2463
2464 std::vector<Function<T,NDIM> > result(NDIM);
2465 for (unsigned int i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),f,false);
2466 if (fence) world.gop.fence();
2467 return result;
2468 }
2469
2470 // Bspline third derivative
2471 template <typename T, std::size_t NDIM>
2472 std::vector<Function<T,NDIM> > grad_bspline_three(const Function<T,NDIM>& f,
2473 bool refine=false, bool fence=true) {
2474
2475 World& world=f.world();
2476 f.reconstruct();
2477 if (refine) f.refine(); // refine to make result more precise
2478
2479 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2481
2482 // Read in new coeff for each operator
2483 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_bspline3();
2484
2485 std::vector<Function<T,NDIM> > result(NDIM);
2486 for (unsigned int i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),f,false);
2487 if (fence) world.gop.fence();
2488 return result;
2489 }
2490
2491
2492
2493 /// which first derivative the div_* variants use
2494
2495 /// abgv is the default ABGV operator; bspline and ble are the smoothing
2496 /// first derivatives, cf. Derivative::set_bspline1() and set_ble1() and the
2497 /// grad_bspline_one() / grad_ble_one() gradients.
2498 enum class DerivMethod { abgv, bspline, ble };
2499
2500 /// shorthand div operator, with a choice of first derivative
2501
2502 /// returns the dot product of nabla with a vector f
2503 /// @param[in] v the vector of functions on which the div operator works on
2504 /// @param[in] method which first derivative to use
2505 /// @param[in] do_refine refinement before diff'ing makes the result more accurate
2506 /// @param[in] fence fence after completion; currently always fences
2507 /// @return the divergence \sum_i \frac{\partial}{\partial x_i} v_i
2508 /// TODO: add this to operator fusion
2509 template <typename T, std::size_t NDIM>
2511 const DerivMethod method, bool do_refine=false, bool fence=true) {
2512
2513 MADNESS_ASSERT(v.size()>0);
2514 World& world=v[0].world();
2515 reconstruct(world,v);
2516 if (do_refine) refine(world,v); // refine to make result more precise
2517
2518 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2520
2521 // read in new coeff for each operator, as grad_bspline_one()/grad_ble_one() do
2522 if (method==DerivMethod::bspline)
2523 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_bspline1();
2524 else if (method==DerivMethod::ble)
2525 for (unsigned int i=0; i<NDIM; ++i) (*grad[i]).set_ble1();
2526
2527 std::vector<Function<T,NDIM> > result(NDIM);
2528 for (size_t i=0; i<NDIM; ++i) result[i]=apply(*(grad[i]),v[i],false);
2529 world.gop.fence();
2530 return sum(world,result,fence);
2531 }
2532
2533 /// div with the ABGV derivative
2534 template <typename T, std::size_t NDIM>
2536 bool do_refine=false, bool fence=true) {
2537 return div_deriv(v,DerivMethod::abgv,do_refine,fence);
2538 }
2539
2540 /// div with the b-spline smoothing first derivative
2541 template <typename T, std::size_t NDIM>
2543 bool do_refine=false, bool fence=true) {
2544 return div_deriv(v,DerivMethod::bspline,do_refine,fence);
2545 }
2546
2547 /// div with the BLE smoothing first derivative
2548 template <typename T, std::size_t NDIM>
2550 bool do_refine=false, bool fence=true) {
2551 return div_deriv(v,DerivMethod::ble,do_refine,fence);
2552 }
2553
2554 /// shorthand div operator, with the default (ABGV) derivative
2555 template <typename T, std::size_t NDIM>
2557 bool do_refine=false, bool fence=true) {
2558 return div_abgv(v,do_refine,fence);
2559 }
2560
2561 /// shorthand rot operator
2562
2563 /// returns the cross product of nabla with a vector f
2564 /// @param[in] f the vector of functions on which the rot operator works on
2565 /// @param[in] refine refinement before diff'ing makes the result more accurate
2566 /// @param[in] fence fence after completion; currently always fences
2567 /// @return the vector \frac{\partial}{\partial x_i} f
2568 /// TODO: add this to operator fusion
2569 template <typename T, std::size_t NDIM>
2570 std::vector<Function<T,NDIM> > rot(const std::vector<Function<T,NDIM> >& v,
2571 bool do_refine=false, bool fence=true) {
2572
2573 MADNESS_ASSERT(v.size()==3);
2574 World& world=v[0].world();
2575 reconstruct(world,v);
2576 if (do_refine) refine(world,v); // refine to make result more precise
2577
2578 std::vector< std::shared_ptr< Derivative<T,NDIM> > > grad=
2580
2581 std::vector<Function<T,NDIM> > d(NDIM),dd(NDIM);
2582 d[0]=apply(*(grad[1]),v[2],false); // Dy z
2583 d[1]=apply(*(grad[2]),v[0],false); // Dz x
2584 d[2]=apply(*(grad[0]),v[1],false); // Dx y
2585 dd[0]=apply(*(grad[2]),v[1],false); // Dz y
2586 dd[1]=apply(*(grad[0]),v[2],false); // Dx z
2587 dd[2]=apply(*(grad[1]),v[0],false); // Dy x
2588 world.gop.fence();
2589
2590 compress(world,d,false);
2591 compress(world,dd,false);
2592 world.gop.fence();
2593 d[0].gaxpy(1.0,dd[0],-1.0,false);
2594 d[1].gaxpy(1.0,dd[1],-1.0,false);
2595 d[2].gaxpy(1.0,dd[2],-1.0,false);
2596
2597 world.gop.fence();
2598 reconstruct(d);
2599 return d;
2600 }
2601
2602 /// shorthand cross operator
2603
2604 /// returns the cross product of vectors f and g
2605 /// @param[in] f the vector of functions on which the rot operator works on
2606 /// @param[in] g the vector of functions on which the rot operator works on
2607 /// @param[in] fence fence after completion; currently always fences
2608 /// @return the vector \frac{\partial}{\partial x_i} f, in redundant state
2609 /// TODO: add this to operator fusion
2610 template <typename T, typename R, std::size_t NDIM>
2611 std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> > cross(const std::vector<Function<T,NDIM> >& f,
2612 const std::vector<Function<R,NDIM> >& g,
2613 bool do_refine=false, bool fence=true) {
2614
2615 MADNESS_ASSERT(f.size()==3);
2616 MADNESS_ASSERT(g.size()==3);
2617 World& world=f[0].world();
2620
2621 std::vector<Function<TENSOR_RESULT_TYPE(T,R),NDIM> > d(f.size()),dd(f.size());
2622
2623 d[0]=mul(f[1],g[2],false);
2624 d[1]=mul(f[2],g[0],false);
2625 d[2]=mul(f[0],g[1],false);
2626
2627 dd[0]=mul(f[2],g[1],false);
2628 dd[1]=mul(f[0],g[2],false);
2629 dd[2]=mul(f[1],g[0],false);
2630 world.gop.fence();
2631
2632 compress(world,d,false);
2633 compress(world,dd,false);
2634 world.gop.fence();
2635
2636 d[0].gaxpy(1.0,dd[0],-1.0,false);
2637 d[1].gaxpy(1.0,dd[1],-1.0,false);
2638 d[2].gaxpy(1.0,dd[2],-1.0,false);
2639 world.gop.fence();
2640
2641 make_redundant(world, d);
2642 return d;
2643 }
2644
2645 template<typename T, std::size_t NDIM>
2646 void load_balance(World& world, std::vector<Function<T,NDIM> >& vf) {
2647
2648 struct LBCost {
2649 LBCost() = default;
2650 double operator()(const Key<NDIM>& key, const FunctionNode<T,NDIM>& node) const {
2651 return node.coeff().size();
2652 }
2653 };
2654
2655 LoadBalanceDeux<6> lb(world);
2656 for (const auto& f : vf) lb.add_tree(f, LBCost());
2658
2659 }
2660
2661 /// load a vector of functions
2662 template<typename T, size_t NDIM>
2663 void load_function(World& world, std::vector<Function<T,NDIM> >& f,
2664 const std::string name) {
2665 if (world.rank()==0) print("loading vector of functions",name);
2667 std::size_t fsize=0;
2668 ar & fsize;
2669 f.resize(fsize);
2670 for (std::size_t i=0; i<fsize; ++i) ar & f[i];
2671 }
2672
2673 /// save a vector of functions
2674 template<typename T, size_t NDIM>
2675 void save_function(const std::vector<Function<T,NDIM> >& f, const std::string name) {
2676 if (f.size()>0) {
2677 World& world=f.front().world();
2678 if (world.rank()==0) print("saving vector of functions",name);
2680 std::size_t fsize=f.size();
2681 ar & fsize;
2682 for (std::size_t i=0; i<fsize; ++i) ar & f[i];
2683 }
2684 }
2685
2686
2687}
2688#endif // MADNESS_MRA_VMRA_H__INCLUDED
double q(double t)
Definition DKops.h:18
real_convolution_3d A(World &world)
Definition DKops.h:230
Definition test_ar.cc:118
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
Implements derivatives operators with variety of boundary conditions on simulation domain.
Definition derivative.h:337
Definition distributed_matrix.h:68
Manages data associated with a row/column/block distributed array.
Definition distributed_matrix.h:388
static void redistribute(World &world, const std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > &newpmap)
Sets the default process map and redistributes all functions using the old map.
Definition funcdefaults.h:458
static TensorType get_tensor_type()
Returns the default tensor type.
Definition funcdefaults.h:329
FunctionFactory implements the named-parameter idiom for Function.
Definition function_factory.h:86
FunctionFactory & compressed(bool value=true)
Definition function_factory.h:168
FunctionImpl holds all Function state to facilitate shallow copy semantics.
Definition funcimpl.h:1043
static Tensor< TENSOR_RESULT_TYPE(T, R) > inner_local(const std::vector< const FunctionImpl< T, NDIM > * > &left, const std::vector< const FunctionImpl< R, NDIM > * > &right, bool sym)
Definition funcimpl.h:6857
void undo_redundant(const bool fence)
convert this from redundant to standard reconstructed form
Definition mraimpl.h:1654
void change_tree_state(const TreeState finalstate, bool fence=true)
change the tree state of this function, might or might not respect fence!
Definition mraimpl.h:1516
static Tensor< TENSOR_RESULT_TYPE(T, R)> dot_local(const std::vector< const FunctionImpl< T, NDIM > * > &left, const std::vector< const FunctionImpl< R, NDIM > * > &right, bool sym)
Definition funcimpl.h:6909
FunctionNode holds the coefficients, etc., at each node of the 2^NDIM-tree.
Definition funcimpl.h:136
coeffT & coeff()
Returns a non-const reference to the tensor containing the coeffs.
Definition funcimpl.h:237
A multiresolution adaptive numerical function.
Definition mra.h:141
World & world() const
Returns the world.
Definition mra.h:764
Function< T, NDIM > & gaxpy(const T &alpha, const Function< Q, NDIM > &other, const R &beta, bool fence=true)
Inplace, general bi-linear operation in wavelet basis. No communication except for optional fence.
Definition mra.h:1162
void set_impl(const std::shared_ptr< FunctionImpl< T, NDIM > > &impl)
Replace current FunctionImpl with provided new one.
Definition mra.h:737
void multi_to_multi_op_values(const opT &op, const std::vector< Function< T, NDIM > > &vin, std::vector< Function< T, NDIM > > &vout, const bool fence=true)
apply op on the input vector yielding an output vector of functions
Definition mra.h:1755
bool is_initialized() const
Returns true if the function is initialized.
Definition mra.h:169
long size() const
Definition lowranktensor.h:490
Key is the index for a node of the 2^NDIM-tree.
Definition key.h:71
Definition lbdeux.h:255
std::shared_ptr< WorldDCPmapInterface< keyT > > load_balance(double fac=1.0, bool printstuff=false)
Actually does the partitioning of the tree.
Definition lbdeux.h:411
void add_tree(const Function< T, NDIM > &f, const costT &costfn, bool fence=false)
Accumulates cost from a function.
Definition lbdeux.h:316
Definition operator.h:158
A slice defines a sub-range or patch of a dimension.
Definition slice.h:103
A tensor is a multidimensional array.
Definition tensor.h:313
TensorTypeData< T >::scalar_type scalar_type
C++ typename of the real type associated with a complex type.
Definition tensor.h:405
T * ptr()
Returns a pointer to the internal data.
Definition tensor.h:1845
A simple, fixed dimension vector.
Definition vector.h:64
Interface to be provided by any process map.
Definition worlddc.h:128
Definition worlddc.h:312
void max(T *buf, size_t nelem)
Inplace global max while still processing AM & tasks.
Definition worldgop.h:902
void fence(bool debug=false)
Synchronizes all processes in communicator AND globally ensures no pending AM or tasks.
Definition worldgop.cc:177
void min(T *buf, size_t nelem)
Inplace global min while still processing AM & tasks.
Definition worldgop.h:896
void sum(T *buf, size_t nelem)
Inplace global sum while still processing AM & tasks.
Definition worldgop.h:890
void fence()
Returns after all local tasks have completed.
Definition world_task_queue.h:1384
A parallel world class.
Definition world.h:134
WorldTaskQueue & taskq
Task queue.
Definition world.h:215
ProcessID rank() const
Returns the process rank in this World (same as MPI_Comm_rank()).
Definition world.h:344
WorldGopInterface & gop
Global operations.
Definition world.h:216
An archive for storing local or parallel data, wrapping a BinaryFstreamInputArchive.
Definition parallel_archive.h:366
An archive for storing local or parallel data wrapping a BinaryFstreamOutputArchive.
Definition parallel_archive.h:321
int integer
Definition crayio.c:25
static const double R
Definition csqrt.cc:46
Declaration and initialization of tree traversal functions and generic derivative.
Tensor< T > conj_transpose(const Tensor< T > &t)
Returns a new deep copy of the complex conjugate transpose of the input tensor.
Definition tensor.h:2048
Tensor< T > transpose(const Tensor< T > &t)
Returns a new deep copy of the transpose of the input tensor.
Definition tensor.h:2039
const double beta
Definition gygi_soltion.cc:62
static const double v
Definition hatom_sf_dirac.cc:20
Tensor< double > op(const Tensor< double > &x)
Definition kain.cc:508
#define rot(x, k)
Definition lookup3.c:84
#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_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
Main include file for MADNESS and defines Function interface.
static const bool VERIFY_TREE
Definition mra.h:57
Definition potentialmanager.cc:41
void reconstruct_for_norm(World &world, const std::vector< Function< T, NDIM > > &v)
put a vector of functions into a state whose coefficients sum to ||f||^2
Definition vmra.h:958
Namespace for all elements and tools of MADNESS.
Definition DFConvergence.h:9
void save_function(const std::vector< Function< T, NDIM > > &f, const std::string name)
save a vector of functions
Definition vmra.h:2675
bool ensure_tree_state_respecting_fence(const std::vector< Function< T, NDIM > > &v, const TreeState state, bool fence)
ensure v has the requested tree state, change the tree state of v if necessary and no fence is given
Definition vmra.h:317
void rr_cholesky(Tensor< T > &A, typename Tensor< T >::scalar_type tol, Tensor< integer > &piv, int &rank)
Compute the rank-revealing Cholesky factorization.
Definition lapack.cc:1213
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:187
std::vector< Function< T, NDIM > > orthonormalize_rrcd(const std::vector< Function< T, NDIM > > &v, Tensor< T > &ovlp, const double tol, Tensor< integer > &piv, int &rank)
Definition vmra.h:703
double FunctionDefaults< NDIM >::thresh
Definition mraimpl.h:3879
Function< double, NDIM > abssq(const Function< double_complex, NDIM > &z, bool fence=true)
Returns a new function that is the square of the absolute value of the input.
Definition mra.h:3114
Function< TENSOR_RESULT_TYPE(L, R), NDIM > gaxpy_oop(TENSOR_RESULT_TYPE(L, R) alpha, const Function< L, NDIM > &left, TENSOR_RESULT_TYPE(L, R) beta, const Function< R, NDIM > &right, bool fence=true)
Returns new function alpha*left + beta*right optional fence and no automatic compression.
Definition mra.h:2153
Function< typename TensorTypeData< Q >::scalar_type, NDIM > abs_square(const Function< Q, NDIM > &func)
Definition complexfun.h:121
std::vector< double > function_costs(World &world, const std::vector< Function< T, NDIM > > &v)
Definition vmra.h:1644
Function< T, NDIM > square(const Function< T, NDIM > &f, bool fence=true)
Create a new function that is the square of f - global comm only if not reconstructed.
Definition mra.h:3082
Function< TENSOR_RESULT_TYPE(L, R), NDIM > sub(const Function< L, NDIM > &left, const Function< R, NDIM > &right, bool fence=true)
Same as operator- but with optional fence and no automatic compression.
Definition mra.h:2208
std::vector< ProcessID > assign_round_robin(std::size_t nfunc, int nranks)
owner[j] = j % nranks. For redistribute_to_batches.
Definition vmra.h:1608
std::vector< Function< T, NDIM > > reduce_rank(std::vector< Function< T, NDIM > > v, double thresh=0.0, bool fence=true)
reduces the tensor rank of the coefficient tensor (if applicable)
Definition vmra.h:367
std::shared_ptr< WorldDCPmapInterface< Key< NDIM > > > FunctionDefaults< NDIM >::pmap
Definition mraimpl.h:3898
Tensor< double > norm2s_T(World &world, const std::vector< Function< T, NDIM > > &v)
Computes the 2-norms of a vector of functions.
Definition vmra.h:993
std::vector< double > norm2s(World &world, const std::vector< Function< T, NDIM > > &v)
Computes the 2-norms of a vector of functions.
Definition vmra.h:976
Function< TENSOR_RESULT_TYPE(T, R), NDIM > dot_sparse(World &world, const std::vector< Function< T, NDIM > > &a, const std::vector< Function< R, NDIM > > &b, double tol, bool fence=true, bool do_make_redundant=true)
Multiplies and sums two vectors of functions r = \sum_i a[i] * b[i].
Definition vmra.h:1884
Function< T, NDIM > div_abgv(const std::vector< Function< T, NDIM > > &v, bool do_refine=false, bool fence=true)
div with the ABGV derivative
Definition vmra.h:2535
std::vector< Function< T, NDIM > > grad_bspline_one(const Function< T, NDIM > &f, bool refine=false, bool fence=true)
Definition vmra.h:2430
void set_impl(std::vector< Function< T, NDIM > > &v, const std::vector< std::shared_ptr< FunctionImpl< T, NDIM > > > vimpl)
Definition vmra.h:788
int FunctionDefaults< NDIM >::k
Definition mraimpl.h:3878
Function< Q, NDIM > convert(const Function< T, NDIM > &f, bool fence=true)
Type conversion implies a deep copy. No communication except for optional fence.
Definition mra.h:2286
Function< TENSOR_RESULT_TYPE(Q, T), NDIM > mul(const Q alpha, const Function< T, NDIM > &f, bool fence=true)
Returns new function equal to alpha*f(x) with optional fence.
Definition mra.h:1938
Function< TENSOR_RESULT_TYPE(T, R), NDIM > dot(World &world, const std::vector< Function< T, NDIM > > &a, const std::vector< Function< R, NDIM > > &b, bool fence=true, bool do_make_redundant=true)
Multiplies and sums two vectors of functions r = \sum_i a[i] * b[i]; see dot_sparse for screening.
Definition vmra.h:1897
std::vector< Function< T, NDIM > > orthonormalize_symmetric(const std::vector< Function< T, NDIM > > &v, const Tensor< T > &ovlp, double lindep=1e-12)
symmetric orthonormalization (see e.g. Szabo/Ostlund)
Definition vmra.h:530
std::vector< std::shared_ptr< FunctionImpl< T, NDIM > > > get_impl(const std::vector< Function< T, NDIM > > &v)
Definition vmra.h:781
Function< T, NDIM > div(const std::vector< Function< T, NDIM > > &v, bool do_refine=false, bool fence=true)
shorthand div operator, with the default (ABGV) derivative
Definition vmra.h:2556
std::vector< Function< T, NDIM > > orthonormalize_cd(const std::vector< Function< T, NDIM > > &v, Tensor< T > &ovlp)
Definition vmra.h:666
std::vector< Function< T, NDIM > > copy_n(World &world, const Function< T, NDIM > &v, const unsigned int n, bool fence=true)
Returns a vector of n deep copies of a function.
Definition vmra.h:1571
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:1394
tensorT Q2(const tensorT &s)
Given overlap matrix, return rotation with 2nd order error to orthonormalize the vectors.
Definition SCF.cc:140
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:807
std::vector< Function< TENSOR_RESULT_TYPE(T, R), NDIM > > cross(const std::vector< Function< T, NDIM > > &f, const std::vector< Function< R, NDIM > > &g, bool do_refine=false, bool fence=true)
shorthand cross operator
Definition vmra.h:2611
TreeState
Definition funcdefaults.h:60
@ nonstandard_after_apply
s and d coeffs, state after operator application
Definition funcdefaults.h:65
@ redundant_after_merge
s coeffs everywhere, must be summed up to yield the result
Definition funcdefaults.h:67
@ reconstructed
s coeffs at the leaves only
Definition funcdefaults.h:61
@ nonstandard
s and d coeffs in internal nodes
Definition funcdefaults.h:63
@ unknown
Definition funcdefaults.h:69
@ compressed
d coeffs in internal nodes, s and d coeffs at the root, empty leaves may be present
Definition funcdefaults.h:62
@ redundant
s coeffs everywhere
Definition funcdefaults.h:66
@ nonstandard_with_leaves
like nonstandard, with s coeffs at the leaves
Definition funcdefaults.h:64
Function< T, NDIM > conj(const Function< T, NDIM > &f, bool fence=true)
Return the complex conjugate of the input function with the same distribution and optional fence.
Definition mra.h:2300
void cholesky(Tensor< T > &A)
Compute the Cholesky factorization.
Definition lapack.cc:1184
std::vector< std::vector< Function< TENSOR_RESULT_TYPE(T, R), NDIM > > > matrix_mul_sparse(World &world, const std::vector< Function< R, NDIM > > &f, const std::vector< Function< R, NDIM > > &g, double tol, bool fence=true, bool symm=false)
Outer product of a vector of functions with a vector of functions using sparsity.
Definition vmra.h:1365
Function< T, NDIM > div_bspline(const std::vector< Function< T, NDIM > > &v, bool do_refine=false, bool fence=true)
div with the b-spline smoothing first derivative
Definition vmra.h:2542
void standard(World &world, std::vector< Function< T, NDIM > > &v, bool fence=true)
Generates standard form of a vector of functions.
Definition vmra.h:244
void truncate(World &world, std::vector< Function< T, NDIM > > &v, double tol=0.0, bool fence=true)
Truncates a vector of functions.
Definition vmra.h:336
void compress(World &world, const std::vector< Function< T, NDIM > > &v, bool fence=true)
Compress a vector of functions.
Definition vmra.h:150
const std::vector< Function< T, NDIM > > & reconstruct(const std::vector< Function< T, NDIM > > &v)
reconstruct a vector of functions
Definition vmra.h:163
std::vector< Function< T, NDIM > > impl2function(const std::vector< std::shared_ptr< FunctionImpl< T, NDIM > > > vimpl)
Definition vmra.h:794
std::vector< Function< T, NDIM > > grad_bpsline_two(const Function< T, NDIM > &f, bool refine=false, bool fence=true)
Definition vmra.h:2451
void set_thresh(World &world, std::vector< Function< T, NDIM > > &v, double thresh, bool fence=true)
Sets the threshold in a vector of functions.
Definition vmra.h:1506
double norm2(World &world, const std::vector< Function< T, NDIM > > &v)
Computes the 2-norm of a vector of functions.
Definition vmra.h:1010
Function< T, NDIM > div_ble(const std::vector< Function< T, NDIM > > &v, bool do_refine=false, bool fence=true)
div with the BLE smoothing first derivative
Definition vmra.h:2549
std::vector< ProcessID > assign_cost_aware(const std::vector< double > &cost, int nranks)
Definition vmra.h:1619
std::vector< Function< T, NDIM > > flatten(const std::vector< std::vector< Function< T, NDIM > > > &vv)
Definition vmra.h:774
std::vector< CCPairFunction< T, NDIM > > operator*(const double fac, const std::vector< CCPairFunction< T, NDIM > > &arg)
Definition ccpairfunction.h:1111
static void verify_tree(World &world, const std::vector< Function< T, NDIM > > &v)
Definition SCF.cc:77
std::vector< Function< T, NDIM > > multi_to_multi_op_values(const opT &op, const std::vector< Function< T, NDIM > > &vin, const bool fence=true)
apply op on the input vector yielding an output vector of functions
Definition vmra.h:2219
std::vector< CCPairFunction< T, NDIM > > operator+(const CCPairFunction< T, NDIM > c1, const CCPairFunction< T, NDIM > &c2)
Definition ccpairfunction.h:1066
static const Slice _(0,-1, 1)
std::vector< std::shared_ptr< Derivative< T, NDIM > > > gradient_operator(World &world, const BoundaryConditions< NDIM > &bc=FunctionDefaults< NDIM >::get_bc(), int k=FunctionDefaults< NDIM >::get_k())
Convenience function returning vector of derivative operators implementing grad ( ).
Definition derivative.h:801
Tensor< T > inverse(const Tensor< T > &a_in)
invert general square matrix A
Definition lapack.cc:832
void load_balance(const real_function_6d &f, const bool leaf)
do some load-balancing
Definition madness/chem/mp2.cc:70
TreeState get_tree_state(const Function< T, NDIM > &f)
get tree state of a function
Definition mra.h:3130
std::vector< CCPairFunction< T, NDIM > > operator-(const std::vector< CCPairFunction< T, NDIM > > c1, const std::vector< CCPairFunction< T, NDIM > > &c2)
Definition ccpairfunction.h:1082
std::vector< Function< T, NDIM > > partial_mul(const Function< T, NDIM > f, const std::vector< Function< T, LDIM > > g, const int particle)
multiply a high-dimensional function with a low-dimensional function
Definition vmra.h:1441
Function< T, NDIM > gaxpy_oop_reconstructed(const double alpha, const Function< T, NDIM > &left, const double beta, const Function< T, NDIM > &right, const bool fence=true)
Returns new function alpha*left + beta*right optional fence, having both addends reconstructed.
Definition mra.h:2171
std::vector< Function< TENSOR_RESULT_TYPE(T, R), NDIM > > transform_reconstructed(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:836
std::vector< Function< T, NDIM > > append(const std::vector< Function< T, NDIM > > &lhs, const std::vector< Function< T, NDIM > > &rhs)
combine two vectors
Definition vmra.h:767
void redistribute_to_batches(World &world, std::vector< Function< T, NDIM > > &v, const std::vector< ProcessID > &owner, std::size_t cap_bytes=0, bool rotate=true)
Definition vmra.h:1664
@ TT_2D
Definition gentensor.h:120
@ TT_FULL
Definition gentensor.h:120
Function< T, NDIM > div_deriv(const std::vector< Function< T, NDIM > > &v, const DerivMethod method, bool do_refine=false, bool fence=true)
shorthand div operator, with a choice of first derivative
Definition vmra.h:2510
void print_size(World &world, const std::vector< Function< T, NDIM > > &v, const std::string &msg="vectorfunction")
Definition vmra.h:2149
NDIM & f
Definition mra.h:2817
Function< TENSOR_RESULT_TYPE(L, R), NDIM > add(const Function< L, NDIM > &left, const Function< R, NDIM > &right, bool fence=true)
Same as operator+ but with optional fence and no automatic compression.
Definition mra.h:2163
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:3143
std::vector< CCPairFunction< T, NDIM > > & operator-=(std::vector< CCPairFunction< T, NDIM > > &rhs, const std::vector< CCPairFunction< T, NDIM > > &lhs)
Definition ccpairfunction.h:1104
std::vector< Function< T, NDIM > > orthonormalize(const std::vector< Function< T, NDIM > > &vf_in)
orthonormalize the vectors
Definition vmra.h:466
NDIM const Function< R, NDIM > & g
Definition mra.h:2817
double wall_time()
Returns the wall time in seconds relative to an arbitrary origin.
Definition timers.cc:48
std::vector< Function< T, NDIM > > grad_ble_one(const Function< T, NDIM > &f, bool refine=false, bool fence=true)
Definition vmra.h:2388
Function< TENSOR_RESULT_TYPE(typename opT::opT, R), NDIM > apply_only(const opT &op, const Function< R, NDIM > &f, bool fence=true)
Apply operator ONLY in non-standard form - required other steps missing !!
Definition mra.h:2380
std::vector< Function< T, NDIM > > grad_bspline_three(const Function< T, NDIM > &f, bool refine=false, bool fence=true)
Definition vmra.h:2472
void print(const T &t, Ts &&... ts)
Print items to std::cout (items separated by spaces) and terminate with a new line.
Definition print.h:232
DerivMethod
which first derivative the div_* variants use
Definition vmra.h:2498
@ bspline
Definition vmra.h:2498
@ ble
Definition vmra.h:2498
@ abgv
Definition vmra.h:2498
static const int kmax
Definition twoscale.cc:52
std::vector< Function< T, NDIM > > zero_functions_compressed(World &world, int n, bool fence=true)
Generates a vector of zero functions (compressed).
Definition vmra.h:450
double imag(double x)
Definition complexfun.h:56
void load_function(World &world, std::vector< Function< T, NDIM > > &f, const std::string name)
load a vector of functions
Definition vmra.h:2663
Tensor< T > canonical_orthonormalization_matrix(World &world, const Tensor< T > ovlp, double lindep=1e-12)
compute the transformation matrix for canonical orthonormalization (see e.g. Szabo/Ostlund)
Definition vmra.h:594
std::vector< Function< TENSOR_RESULT_TYPE(L, R), D > > vmulXX(const Function< L, D > &left, const std::vector< Function< R, D > > &vright, double tol, bool fence=true)
Use the vmra/mul(...) interface instead.
Definition mra.h:2043
void refine_to_common_level(World &world, std::vector< Function< T, NDIM > > &vf, bool fence=true)
refine all functions to a common (finest) level
Definition vmra.h:207
std::vector< Function< T, NDIM > > grad_ble_two(const Function< T, NDIM > &f, bool refine=false, bool fence=true)
Definition vmra.h:2409
static bool print_timings
Definition SCF.cc:109
CCPairFunction< T, NDIM > apply(const SeparatedConvolution< T, NDIM/2 > &op, const CCPairFunction< T, NDIM > &arg)
apply the operator to the argument
Definition ccpairfunction.h:901
void normalize(World &world, std::vector< Function< T, NDIM > > &v, bool fence=true)
Normalizes a vector of functions — v[i] = v[i].scale(1.0/v[i].norm2()).
Definition vmra.h:2141
void stage_halo(World &world, const std::vector< std::shared_ptr< Derivative< T, NDIM > > > &grad, const std::vector< Function< T, NDIM > > &v, bool fence=true)
Pre-stages the neighbor coefficients that differentiating v with each of grad will need.
Definition vmra.h:382
bool FunctionDefaults< NDIM >::refine
Definition mraimpl.h:3884
std::vector< Function< T, NDIM > > zero_functions(World &world, int n, bool fence=true)
Generates a vector of zero functions (reconstructed).
Definition vmra.h:443
Function< TENSOR_RESULT_TYPE(L, R), NDIM > mul_sparse(const Function< L, NDIM > &left, const Function< R, NDIM > &right, double tol, bool fence=true, bool do_make_redundant=true)
Sparse multiplication; the scalar interface redirects to the vector one in vmra.h.
Definition mra.h:1983
std::vector< Function< T, NDIM > > grad(const Function< T, NDIM > &f, bool refine=false, bool fence=true)
shorthand gradient operator
Definition vmra.h:2370
Function< T, CCPairFunction< T, NDIM >::LDIM > inner(const CCPairFunction< T, NDIM > &c, const Function< T, CCPairFunction< T, NDIM >::LDIM > &f, const std::tuple< int, int, int > v1, const std::tuple< int, int, int > v2)
Definition ccpairfunction.h:1007
Tensor< T > orthonormalize_symmetric_matrix(Tensor< T > ovlp)
return a matrix that orthonormalizes the vectors v_ortho = transform(world,v,result);
Definition vmra.h:498
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:2633
void scale(World &world, std::vector< Function< T, NDIM > > &v, const std::vector< Q > &factors, bool fence=true)
Scales inplace a vector of functions by distinct values.
Definition vmra.h:923
std::vector< Function< T, NDIM > > zero_functions_auto_tree_state(World &world, int n, bool fence=true)
Generates a vector of zero functions, either compressed or reconstructed, depending on tensor type.
Definition vmra.h:457
DistributedMatrix< T > matrix_dot(const DistributedMatrixDistribution &d, const std::vector< Function< T, NDIM > > &f, const std::vector< Function< T, NDIM > > &g, bool sym=false)
Definition vmra.h:1786
void load(Function< T, NDIM > &f, const std::string name)
Definition mra.h:3181
std::vector< Function< T, NDIM > > zero_functions_tree_state(World &world, int n, const TreeState state, bool fence=true)
Generates a vector of zero functions with a given tree state.
Definition vmra.h:422
double real(double x)
Definition complexfun.h:52
std::vector< CCPairFunction< T, NDIM > > & operator+=(std::vector< CCPairFunction< T, NDIM > > &lhs, const CCPairFunction< T, NDIM > &rhs)
Definition ccpairfunction.h:1090
@ same
same atoms at the same places
Definition RestartPlan.h:152
std::vector< Function< T, NDIM > > orthonormalize_canonical(const std::vector< Function< T, NDIM > > &v, const Tensor< T > &ovlp, double lindep=1e-12)
Definition vmra.h:638
Tensor< TENSOR_RESULT_TYPE(T, R) > matrix_dot_old(World &world, const std::vector< Function< T, NDIM > > &f, const std::vector< Function< R, NDIM > > &g, bool sym=false)
Computes the matrix dot product of two function vectors - q(i,j) = dot(f[i],g[j]).
Definition vmra.h:1849
std::string name(const FuncType &type, const int ex=-1)
Definition ccpairfunction.h:28
void clear_halo(const std::vector< Function< T, NDIM > > &v)
Discards the neighbor halos staged on v.
Definition vmra.h:397
void matrix_inner(DistributedMatrix< T > &A, const std::vector< Function< T, NDIM > > &f, const std::vector< Function< T, NDIM > > &g, bool sym=false)
Definition distpm.cc:46
double get_size(World &world, const std::vector< Function< T, NDIM > > &v)
Definition vmra.h:2183
double get_size_local(World &world, const std::vector< Function< T, NDIM > > &v)
return the size of a vector of functions for each rank
Definition vmra.h:2164
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:2239
int FunctionDefaults< NDIM >::initial_level
Definition mraimpl.h:3880
void syev(const Tensor< T > &A, Tensor< T > &V, Tensor< typename Tensor< T >::scalar_type > &e)
Real-symmetric or complex-Hermitian eigenproblem.
Definition lapack.cc:979
Tensor< TENSOR_RESULT_TYPE(T, R) > matrix_inner_old(World &world, const std::vector< Function< T, NDIM > > &f, const std::vector< Function< R, NDIM > > &g, bool sym=false)
Computes the matrix inner product of two function vectors - q(i,j) = inner(f[i],g[j]).
Definition vmra.h:1132
void make_nonstandard(World &world, std::vector< Function< T, NDIM > > &v, bool fence=true)
Generates non-standard form of a vector of functions.
Definition vmra.h:234
void gaxpy(const double a, ScalarResult< T > &left, const double b, const T &right, const bool fence=true)
the result type of a macrotask must implement gaxpy
Definition macrotaskq.h:243
int distance(const madness::Hash_private::HashIterator< hashT > &it, const madness::Hash_private::HashIterator< hashT > &jt)
Definition worldhashmap.h:616
static long abs(long a)
Definition tensor.h:214
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 size_t nfunc
Definition pcr.cc:63
double Q(double a)
Definition relops.cc:20
static const double c
Definition relops.cc:10
static const double m
Definition relops.cc:9
static const double L
Definition rk.cc:46
Definition test_ar.cc:204
Definition mp2.h:63
double operator()(const Key< 6 > &key, const FunctionNode< double, 6 > &node) const
Definition mp2.h:70
LBCost(double leaf_value=1.0, double parent_value=1.0)
Definition mp2.h:67
Definition lowrankfunction.h:387
Definition dirac-hatom.cc:112
std::string ok(const bool b)
Definition test6.cc:48
AtomicInt sum
Definition test_atomicint.cc:46
int P
Definition test_binsorter.cc:9
static const std::size_t D
Definition test_function_hdf5.cpp:36
void e()
Definition test_sig.cc:75
static const double alpha
Definition testcosine.cc:10
constexpr std::size_t NDIM
Definition testgconv.cc:54
double h(const coord_1d &r)
Definition testgconv.cc:175
#define TENSOR_RESULT_TYPE(L, R)
This macro simplifies access to TensorResultType.
Definition type_data.h:205
#define PROFILE_FUNC
Definition worldprofile.h:209
#define PROFILE_BLOCK(name)
Definition worldprofile.h:208
int ProcessID
Used to clearly identify process number/rank.
Definition worldtypes.h:43