MADNESS 0.10.1
lowrankfunction.h
Go to the documentation of this file.
1//
2// Created by Florian Bischoff on 8/10/23.
3//
4
5#ifndef MADNESS_LOWRANKFUNCTION_H
6#define MADNESS_LOWRANKFUNCTION_H
7
8
9#include<madness/mra/mra.h>
10#include<madness/mra/vmra.h>
15#include <random>
16#include <algorithm>
17
18
19
20namespace madness {
21
23 static constexpr char const *tag = "lrf";
24
29
35
36
37 void set_defaults() {
38 // initialize with: key, value, comment (optional), allowed values (optional)
39 initialize<double>("radius",2.0,"the radius");
40 initialize<double>("gamma",1.0,"the exponent of the correlation factor");
41 initialize<double>("volume_element",0.1,"initial volume covered by each grid point");
42 initialize<double>("tol",1.e-8,"rank-reduced cholesky tolerance");
43 initialize<std::string>("f12type","Slater","correlation factor",{"Slater","SlaterF12"});
44 // orthomethod removed — always use cholesky (rr_cholesky) orthonormalization
45 initialize<std::string>("transpose","slater2","transpose of the matrix",{"slater1","slater2"});
46 initialize<std::string>("gridtype","random","the grid type",{"random","twostage","harmonics","adaptive"});
47 initialize<int>("optimize",1,"number of optimization iterations");
48 initialize<int>("lmax",2,"max angular momentum for the RI harmonics");
49 initialize<std::vector<double>>("tempered",{0.05,2.0,3.0},"zeta_min,zeta_max,factor");
50 }
51 [[nodiscard]] std::string get_tag() const override {
52 return {"lrf"};
53 }
54
55
56 void read_and_set_derived_values(World& world, const commandlineparser& parser, std::string tag) {
58 }
59
60 [[nodiscard]] double radius() const {return get<double>("radius");}
61 [[nodiscard]] double gamma() const {return get<double>("gamma");}
62 [[nodiscard]] double volume_element() const {return get<double>("volume_element");}
63 [[nodiscard]] double tol() const {return get<double>("tol");}
64 [[nodiscard]] int optimize() const {return get<int>("optimize");}
65 [[nodiscard]] int lmax() const {return get<int>("lmax");}
66 [[nodiscard]] std::string gridtype() const {return get<std::string>("gridtype");}
67 // orthomethod removed — always cholesky
68 [[nodiscard]] std::string f12type() const {return get<std::string>("f12type");}
69 [[nodiscard]] std::vector<double> tempered() const {return get<std::vector<double>>("tempered");}
70 };
71
72
73 class gridbase {
74 public:
75 [[nodiscard]] double get_volume_element() const {return volume_element;}
76 [[nodiscard]] double get_radius() const {return radius;}
77
78 virtual ~gridbase() = default;
79 // visualize the grid in xyz format
80 template<std::size_t NDIM>
81 void visualize(const std::string filename, const std::vector<Vector<double,NDIM>>& grid) const {
82 print("visualizing grid to file",filename);
83 print("a total of",grid.size(),"grid points");
84 std::ofstream file(filename);
85 for (const auto& r : grid) {
86 // formatted output
87 file << std::fixed << std::setprecision(6);
88 for (int i=0; i<NDIM; ++i) file << r[i] << " ";
89 file << std::endl;
90 }
91 file.close();
92 }
93
94 protected:
95 double volume_element=0.1;
96 double radius=3;
97 bool do_print=false;
98 };
99
100 template<std::size_t NDIM>
101 class dftgrid : public gridbase {
102 public:
104 explicit dftgrid(const double volume_element, const double radius) {
105 // increase number of radial grid points until the volume element is below the threshold
106 double current_ve=1.0;
107 std::size_t nradial=10;
108 while (current_ve>volume_element) {
109 nradial+=10;
110 print("trying nradial",nradial);
111 GridBuilder tmp;
112 tmp.set_angular_order(7);
113 tmp.set_nradial(nradial);
114 tmp.make_grid();
115 double volume=4./3. *M_PI * std::pow(radius,3.0);
116 auto npoints=tmp.get_points().size();
117 current_ve=volume/npoints;
118 print("volume, npoints, volume element",volume,npoints,current_ve);
119 }
120 builder.set_nradial(nradial);
121 builder.set_angular_order(7);
122 }
123
124
125 explicit dftgrid(const std::size_t nradial, const std::size_t angular_order, const coord_3d origin=coord_3d()) {
126 static_assert(NDIM==3,"DFT Grids only defined for NDIM=3");
127 builder.set_nradial(nradial);
128 builder.set_angular_order(angular_order);
129 builder.set_origin(origin);
130 builder.make_grid();
131 }
132
133 std::vector<Vector<double,NDIM>> get_grid() const {
134 return builder.get_points();
135 }
136
137 };
138
139 /// grid with random points around the origin, with a Gaussian distribution
140 template<std::size_t NDIM>
141 class randomgrid : public gridbase {
142 public:
144 : gridbase(), origin(origin) {
145 this->volume_element=volume_element;
146 this->radius=radius;
147 }
148
149 std::vector<Vector<double,NDIM>> get_grid() const {
150 std::vector<Vector<double, NDIM>> grid;
151 long npoint_within_volume=volume()/volume_element;
152 if (do_print) print("npoint_within_volume",npoint_within_volume);
153
155 auto is_in_cell = [&cell](const Vector<double, NDIM>& r) {
156 for (size_t d = 0; d < NDIM; ++d) if (r[d] < cell(d, 0) or r[d] > cell(d, 1)) return false;
157 return true;
158 };
159 double rad=radius;
160 auto o=origin;
161 auto is_in_sphere = [&rad,&o](const Vector<double, NDIM>& r) {
162 return ((r-o).normf()<rad);
163 };
164
165 // set variance such that about 70% of all grid points sits within the radius
166 double variance=radius;
167 if (NDIM==2) variance=0.6*radius;
168 if (NDIM==3) variance=0.5*radius;
169 long maxrank=10*npoint_within_volume;
170 long rank=0;
171 for (int r=0; r<maxrank; ++r) {
172 auto tmp = gaussian_random_distribution(origin, variance);
173 if (not is_in_cell(tmp)) continue;
174 if (is_in_sphere(tmp)) ++rank;
175 grid.push_back(tmp);
176 if (rank==npoint_within_volume) break;
177 }
178 if (do_print) {
179 print("origin ",origin);
180 print("radius ",radius);
181 print("grid points in volume ",rank);
182 print("total grid points ",grid.size());
183 print("ratio ",rank/double(grid.size()));
184 print("volume element ",volume()/rank);
185 }
186 return grid;
187 }
188
190 return origin;
191 }
192
193 private:
194
195 double volume() const {
196 MADNESS_CHECK(NDIM>0 and NDIM<4);
197 if (NDIM==1) return 2.0*radius;
198 else if (NDIM==2) return constants::pi*radius*radius;
199 else if (NDIM==3) return 4.0 / 3.0 * constants::pi * std::pow(radius, 3.0);
200 else {
201 MADNESS_EXCEPTION("invalid NDIM",1);
202 return 0.0;
203 }
204 }
205
207 std::random_device rd{};
208 std::mt19937 gen{rd()};
209 Vector<double,NDIM> result;
210 for (size_t i = 0; i < NDIM; ++i) {
211 std::normal_distribution<> d{origin[i], variance};
212 result[i]=d(gen);
213 }
214
215 return result;
216 }
217
219
220 };
221
222 template<std::size_t NDIM>
225 std::vector<long> stride;
226 long index=0;
227 long n_per_dim=0;
228 long total_n=0;
230
231 cartesian_grid(const double volume_per_gridpoint, const double radius) {
232 double length_per_gridpoint=std::pow(volume_per_gridpoint,1.0/NDIM);
233 n_per_dim=ceil(2.0*radius/length_per_gridpoint);
234 print("length per gridpoint, n_per_dim",length_per_gridpoint,n_per_dim);
235 print("volume_per_gridpoint",std::pow(length_per_gridpoint,NDIM));
236 initialize(-radius,radius);
237 print("increment",increment);
238 }
239
240
241 cartesian_grid(const long n_per_dim, const double lo, const double hi)
243 initialize(lo,hi);
244 }
245
247 hivec(other.hivec), stride(other.stride), index(0), n_per_dim(other.n_per_dim),
248 total_n(other.total_n), increment(other.increment) {
249 }
250
252 cartesian_grid<NDIM> tmp(other);
253 std::swap(*this,other);
254 return *this;
255 }
256
257 void initialize(const double lo, const double hi) {
258 lovec.fill(lo);
259 hivec.fill(hi);
260 increment=(hivec-lovec)*(1.0/double(n_per_dim-1));
261 stride=std::vector<long>(NDIM,1l);
262 total_n=std::pow(n_per_dim,NDIM);
263 for (long i=NDIM-2; i>=0; --i) stride[i]=n_per_dim*stride[i+1];
264
265 }
266
267 double volume_per_gridpoint() const{
268 double volume=1.0;
269 for (int i=0; i<NDIM; ++i) volume*=(hivec[i]-lovec[i]);
270 return volume/total_n;
271 }
272
273 void operator++() {
274 index++;
275 }
276
277 bool operator()() const {
278 return index < total_n;
279 }
280
283 for (int idim=0; idim<NDIM; ++idim) {
284 tmp[idim]=(index/stride[idim])%n_per_dim;
285 }
286 return lovec+tmp*increment;
287 }
288
289 };
290
291 /// given a molecule, return a suitable grid
292 template<std::size_t NDIM>
293 class molecular_grid : public gridbase {
294
295 public:
296 /// ctor takes centers of the grid and the grid parameters
297 molecular_grid(const std::vector<Vector<double,NDIM>> origins, const LowRankFunctionParameters& params)
298 : centers(origins)
299 {
300 if (centers.size()==0) centers.push_back(Vector<double,NDIM>(0) );
301 // treat harmonics and twostage like random sampling for constructing the molecular grid
302 if (params.gridtype()=="random" or params.gridtype()=="adaptive" or params.gridtype()=="harmonics" or params.gridtype()=="twostage") grid_builder=std::make_shared<randomgrid<NDIM>>(params.volume_element(),params.radius());
303 // else if (params.gridtype()=="cartesian") grid_builder=std::make_shared<cartesian_grid<NDIM>>(params.volume_element(),params.radius());
304 else if (params.gridtype()=="dftgrid") {
305 if constexpr (NDIM==3) {
306 grid_builder=std::make_shared<dftgrid<NDIM>>(params.volume_element(),params.radius());
307 } else {
308 MADNESS_EXCEPTION("no dft grid with NDIM != 3",1);
309 }
310 } else {
311 MADNESS_EXCEPTION("no such grid type",1);
312 }
313 }
314
315
316 /// ctor takes centers of the grid and the grid builder
317 molecular_grid(const std::vector<Vector<double,NDIM>> origins, std::shared_ptr<gridbase> grid)
318 : centers(origins), grid_builder(grid) {
319 if (centers.size()==0) centers.push_back({0,0,0});
320 }
321
322 /// ctor takes molecule and grid builder
323 molecular_grid(const Molecule& molecule, std::shared_ptr<gridbase> grid)
324 : molecular_grid(molecule.get_all_coords_vec(),grid) {}
325
326 std::vector<Vector<double,NDIM>> get_grid() const {
327 MADNESS_CHECK_THROW(grid_builder,"no grid builder given in molecular_grid");
328 MADNESS_CHECK_THROW(centers.size()>0,"no centers given in molecular_grid");
329
330 // A point generated around centers[ic] is kept iff centers[ic] is its
331 // nearest center — i.e. it lies in the Voronoi cell of its generator.
332 // This eliminates the over-density that arises when neighbouring
333 // per-center Gaussian clouds overlap. With a single center the test
334 // is vacuous.
335 const bool do_voronoi = (centers.size() > 1);
336 auto in_own_voronoi_cell = [&](const Vector<double,NDIM>& p, const std::size_t ic) {
337 double d_own = (p - centers[ic]).normf();
338 for (std::size_t jc = 0; jc < centers.size(); ++jc) {
339 if (jc == ic) continue;
340 if ((p - centers[jc]).normf() < d_own) return false;
341 }
342 return true;
343 };
344
345 std::vector<Vector<double,NDIM>> grid;
346 for (std::size_t ic = 0; ic < centers.size(); ++ic) {
347 const auto& coords = centers[ic];
348 print("atom sites",coords);
349 std::vector<Vector<double,NDIM>> atomgrid;
350 if (auto builder=dynamic_cast<dftgrid<NDIM>*>(grid_builder.get())) {
351 if constexpr (NDIM==3) {
352 dftgrid<NDIM> b1(builder->builder.get_nradial(),builder->builder.get_angular_order(),coords);
353 atomgrid=b1.get_grid();
354 } else {
355 MADNESS_EXCEPTION("no DFT grid for NDIM /= 3",1);
356 }
357 } else if (auto builder=dynamic_cast<randomgrid<NDIM>*>(grid_builder.get())) {
358 randomgrid<NDIM> b1(builder->get_volume_element(),builder->get_radius(),coords);
359 atomgrid=b1.get_grid();
360 } else {
361 MADNESS_EXCEPTION("no such grid builder",1);
362 }
363
364 if (do_voronoi) {
365 std::size_t kept = 0;
366 for (const auto& p : atomgrid) {
367 if (in_own_voronoi_cell(p, ic)) {
368 grid.push_back(p);
369 ++kept;
370 }
371 }
372 print("center",ic,"generated",atomgrid.size(),"kept",kept,"after Voronoi filter");
373 } else {
374 grid.insert(grid.end(),atomgrid.begin(),atomgrid.end());
375 }
376 }
377 return grid;
378 }
379
380 private:
381 std::vector<Vector<double,NDIM>> centers;
382 std::shared_ptr<gridbase> grid_builder;
383
384 };
385
386template<std::size_t PDIM>
387struct particle {
388 std::array<int,PDIM> dims;
389
390 /// default constructor
391 particle() = default;
392
393 /// convenience for particle 1 (the left/first particle)
395 particle p;
396 for (size_t i=0; i<PDIM; ++i) p.dims[i]=i;
397 return p;
398 }
399 /// convenience for particle 2 (the right/second particle)
401 particle p;
402 for (size_t i=0; i<PDIM; ++i) p.dims[i]=i+PDIM;
403 return p;
404 }
405
406 /// return the other particle
409 if (is_first()) return particle2();
410 return particle1();
411 }
412
413 explicit particle(const int p) : particle(std::vector<int>(1,p)) {}
414 explicit particle(const int p1, const int p2) : particle(std::vector<int>({p1,p2})) {}
415 explicit particle(const int p1, const int p2,const int p3) : particle(std::vector<int>({p1,p2,p3})) {}
416 explicit particle(const std::vector<int> p) {
417 for (int i=0; i<PDIM; ++i) dims[i]=p[i];
418 }
419
420 [[nodiscard]] std::string str() const {
421 std::stringstream ss;
422 ss << *this;
423 return ss.str();
424 }
425
426
427 /// type conversion to std::array
428 std::array<int,PDIM> get_array() const {
429 return dims;
430 }
431
432
433 /// assuming two particles only
434 bool is_first() const {return dims[0]==0;}
435 /// assuming two particles only
436 bool is_last() const {return dims[0]==(PDIM);}
437
438 template<std::size_t DUMMYDIM=PDIM>
439 typename std::enable_if_t<DUMMYDIM==1, std::tuple<int>>
440 get_tuple() const {return std::tuple<int>(dims[0]);}
441
442 template<std::size_t DUMMYDIM=PDIM>
443 typename std::enable_if_t<DUMMYDIM==2, std::tuple<int,int>>
444 get_tuple() const {return std::tuple<int,int>(dims[0],dims[1]);}
445
446 template<std::size_t DUMMYDIM=PDIM>
447 typename std::enable_if_t<DUMMYDIM==3, std::tuple<int,int,int>>
448 get_tuple() const {return std::tuple<int,int,int>(dims[0],dims[1],dims[2]);}
449};
450
451template<std::size_t PDIM>
452std::ostream& operator<<(std::ostream& os, const particle<PDIM>& p) {
453 os << "(";
454 for (auto i=0; i<PDIM-1; ++i) os << p.dims[i] << ";";
455 os << p.dims[PDIM-1] << ")";
456 return os;
457}
458
459/// the low-rank functor is what the LowRankFunction will represent
460
461/// derive from this class :
462/// must implement in inner product
463/// may implement an operator()(const coord_nd&)
464template<typename T, std::size_t NDIM, std::size_t LDIM=NDIM/2>
466
467 virtual ~LRFunctorBase() {};
468 virtual std::vector<Function<T,LDIM>> inner(const std::vector<Function<T,LDIM>>& rhs,
469 const particle<LDIM> p1, const particle<LDIM> p2) const =0;
470
471 virtual Function<T,LDIM> inner(const Function<T,LDIM>& rhs, const particle<LDIM> p1, const particle<LDIM> p2) const {
472 return inner(std::vector<Function<T,LDIM>>({rhs}),p1,p2)[0];
473 }
474
475 /// evaluate the functor at a given point, e.g. for plotting
476 virtual T operator()(const Vector<T,NDIM>& r) const =0;
477
478 virtual typename Tensor<T>::scalar_type norm2() const {
479 MADNESS_EXCEPTION("L2 norm not implemented",1);
480 }
481
482 /// introspection
483 virtual std::string type() const = 0;
484
485 virtual World& world() const =0;
486
487 /// set the MRA threshold on all internal functions and reproject to the new precision
488 virtual void set_thresh(double thresh) {}
489
490 friend std::vector<Function<T,LDIM>> inner(const LRFunctorBase& functor, const std::vector<Function<T,LDIM>>& rhs,
491 const particle<LDIM> p1, const particle<LDIM> p2) {
492 return functor.inner(rhs,p1,p2);
493 }
494 friend Function<T,LDIM> inner(const LRFunctorBase& functor, const Function<T,LDIM>& rhs,
495 const particle<LDIM> p1, const particle<LDIM> p2) {
496 return functor.inner(rhs,p1,p2);
497 }
498
499};
500
501template<typename T, std::size_t NDIM, std::size_t LDIM=NDIM/2>
502struct LRFunctorF12 : public LRFunctorBase<T,NDIM> {
503// LRFunctorF12() = default;
504 LRFunctorF12(const std::shared_ptr<SeparatedConvolution<T,LDIM>> f12, const std::vector<Function<T,LDIM>>& a,
505 const std::vector<Function<T,LDIM>>& b) : f12(f12), a(a), b(b) {
506
507 // if a or b are missing, they are assumed to be 1
508 // you may not provide a or b, but if you do they have to have the same size because they are summed up
509 if (a.size()>0 and b.size()>0)
510 MADNESS_CHECK_THROW(a.size()==b.size(), "a and b must have the same size");
511 if (a.size()==0) this->a.resize(b.size());
512 if (b.size()==0) this->b.resize(a.size());
513 MADNESS_CHECK_THROW(this->a.size()==this->b.size(), "a and b must have the same size");
514 }
515
516 /// delegate to the other ctor with vector arguments
518 const Function<T,LDIM>& a, const Function<T,LDIM>& b)
519 : LRFunctorF12(f12,std::vector<Function<T,LDIM>>({a}), std::vector<Function<T,LDIM>>({b})) {}
520
521
522 std::string type() const override {return "LRFunctorF12";}
523private:
524 std::shared_ptr<SeparatedConvolution<T,LDIM>> f12; ///< a two-particle function
525 std::vector<Function<T,LDIM>> a,b; ///< the lo-dim functions
526public:
527
528 [[nodiscard]] World& world() const override {return f12->get_world();}
529
530 /// access the F12 operator
531 const std::shared_ptr<SeparatedConvolution<T,LDIM>>& get_f12() const { return f12; }
532 /// access the a functions (particle 1 pre-multipliers)
533 const std::vector<Function<T,LDIM>>& get_a() const { return a; }
534 /// access the b functions (particle 2 pre-multipliers)
535 const std::vector<Function<T,LDIM>>& get_b() const { return b; }
536
537 void set_thresh(double thresh) override {
538 for (auto& f : a) if (f.is_initialized()) f.set_thresh(thresh);
539 for (auto& f : b) if (f.is_initialized()) f.set_thresh(thresh);
540 }
541
542 /// macrotask for \sum_ia premultiply_ia * f12 * postmultiply_ia * rhs, batched over rhs
544 public:
546 name = "MacroTaskLRFInner";
547 partitioner->set_max_batch_size(30);
548 }
549
550 // rhs is batched (first vector); a, b are passed whole; f12 is passed via its tensors
551 typedef std::tuple<
552 const std::vector<Function<T,LDIM>>&, // rhs – batched
553 const std::vector<Function<T,LDIM>>&, // a – whole
554 const std::vector<Function<T,LDIM>>&, // b – whole
555 const Tensor<T>&, // f12 stored_coeffs
556 const Tensor<double>&, // f12 stored_exponents
557 const double&, // f12 info.lo
558 const double&, // f12 info.thresh
559 const double&, // f12 info.mu
560 const bool& // p1.is_first()
562
563 using resultT = std::vector<Function<T,LDIM>>;
564
565 resultT allocator(World& world, const argtupleT& argtuple) const {
566 std::size_t n = std::get<0>(argtuple).size();
568 }
569
571 const std::vector<Function<T,LDIM>>& rhs_batch,
572 const std::vector<Function<T,LDIM>>& a,
573 const std::vector<Function<T,LDIM>>& b,
574 const Tensor<T>& coeff,
575 const Tensor<double>& expnt,
576 const double lo,
577 const double thresh,
578 const double mu,
579 const bool p1_is_first) const {
580 World& world = rhs_batch.front().world();
581 // reconstruct operator from tensors so every task has identical numerics
582 auto f12_local = SeparatedConvolution<T,LDIM>(world, coeff, expnt, lo, thresh,
583 FunctionDefaults<LDIM>::get_bc().lattice_range(),
585
586 auto tmp2 = zero_functions_compressed<T,LDIM>(world, rhs_batch.size());
587 if (a.empty()) {
588 tmp2 = apply(world, f12_local, rhs_batch);
589 } else {
590 for (std::size_t ia = 0; ia < a.size(); ++ia) {
591 const auto& premultiply = p1_is_first ? a[ia] : b[ia];
592 const auto& postmultiply = p1_is_first ? b[ia] : a[ia];
593 auto tmp = copy(world, rhs_batch);
594 if (premultiply.is_initialized()) tmp = rhs_batch * premultiply;
595 auto tmp1 = apply(world, f12_local, tmp);
596 if (postmultiply.is_initialized()) tmp1 = tmp1 * postmultiply;
597 tmp2 += tmp1;
598 }
599 }
600 return truncate(tmp2,thresh*0.3);
601 }
602 };
603
604 std::vector<Function<T,LDIM>> inner(const std::vector<Function<T,LDIM>>& rhs,
605 const particle<LDIM> p1, const particle<LDIM> p2) const override {
606 // functor is now \sum_i a_i(1) b_i(2) f12
607 // result(1) = \sum_i \int a_i(1) f(1,2) b_i(2) rhs(2) d2
608 // = \sum_i a_i(1) \int f(1,2) b_i(2) rhs(2) d2
609 World& world = rhs.front().world();
610 // MacroTask cannot serialize uninitialized Function objects. Replace any
611 // uninitialized entries (representing an implicit factor of 1) with an
612 // explicit constant-1 Function so the cloud transfer is well-defined.
613 auto sanitize = [&world](const std::vector<Function<T,LDIM>>& v) {
614 bool any_uninit=false;
615 for (const auto& f : v) if (not f.is_initialized()) { any_uninit=true; break; }
616 if (not any_uninit) return v;
618 .functor([](const Vector<double,LDIM>& r){return T(1);});
619 std::vector<Function<T,LDIM>> out=v;
620 for (auto& f : out) if (not f.is_initialized()) f=one;
621 return out;
622 };
623 auto a_safe = sanitize(a);
624 auto b_safe = sanitize(b);
625 MacroTaskLRFInner task_op;
626 MacroTask mt(world, task_op);
627 return mt(rhs, a_safe, b_safe,
628 f12->stored_coeffs, f12->stored_exponents,
629 f12->info.lo, f12->info.thresh, f12->info.mu,
630 p1.is_first());
631 }
632
633 typename Tensor<T>::scalar_type norm2() const override {
635 [](const Vector<double, LDIM>& r) { return 1.0; });
636 std::vector<Function<T, LDIM>> pre, post;
637 std::size_t sz = a.size();
638 if (sz == 0) {
639 pre = std::vector<Function<T, LDIM>>(1, one);
640 post = std::vector<Function<T, LDIM>>(1, one);
641 } else {
642 pre = (a.front().is_initialized()) ? a : std::vector<Function<T, LDIM>>(sz, one);
643 post = (b.front().is_initialized()) ? b : std::vector<Function<T, LDIM>>(sz, one);
644 }
645
646 const SeparatedConvolution<T,LDIM>& f12a=*(f12);
647 // Prefer the specialized combine rule when available; fall back to
648 // the generic outer-product construction for SepConvs built from
649 // raw (c, α) tensors whose OperatorInfo type is UNDEFINED.
650 auto build_f12sq = [&]() -> SeparatedConvolution<T,LDIM> {
652 return SeparatedConvolution<T,LDIM>::combine(f12a, f12a);
653 } else {
655 "LRFunctorF12::norm2: cannot combine f12 with itself and no "
656 "stored (c, α) available for generic fallback");
660 f12a.info.lo, f12a.info.thresh, /*prune=*/true);
661 }
662 };
663 const SeparatedConvolution<T,LDIM> f12sq = build_f12sq();
664
665 // \int f(1,2)^2 d1d2 = \int f(1,2)^2 pre(1)^2 post(2)^2 d1 d2
666 // || \sum_i f(1,2) a_i(1) b_i(2) || = \int ( \sum_{ij} a_i(1) a_j(1) f(1,2)^2 b_i(1) b_j(2) ) d1d2
667 std::vector<Function<T,LDIM>> aa,bb;
668 for (std::size_t i=0; i<pre.size(); ++i) {
669 aa=append(aa,(pre[i]*pre));
670 bb=append(bb,(post[i]*post));
671 }
672// typename Tensor<T>::scalar_type term1 =madness::inner(mul(world(),post,post),f12sq(mul(world(),pre,pre)));
673 typename Tensor<T>::scalar_type term1 =madness::inner(bb,f12sq(aa));
674 return sqrt(term1);
675
676 }
677
678 T operator()(const Vector<double,NDIM>& r) const override {
679
680 if (a.size()==0) return 0.0;
681 auto split = [](const Vector<double,NDIM>& r) {
682 Vector<double,LDIM> first, second;
683 for (size_t i=0; i<LDIM; ++i) {
684 first[i]=r[i];
685 second[i]=r[i+LDIM];
686 }
687 return std::make_pair(first,second);
688 };
689
690 double gamma=f12->info.mu;
691 auto [first,second]=split(r);
692
693
694 double result=0.0;
695 for (std::size_t ia=0; ia<a.size(); ++ia) {
696 // a[ia](first) reconstructs a non-reconstructed function, which fences: fine from the
697 // main thread, a deadlock from inside a task (e.g. projecting this functor), so
698 // reconstruct a and b before using the functor in FunctionFactory::functor()
699 double result1=1.0;
700 if (a[ia].is_initialized()) result1*=a[ia](first);
701 if (b[ia].is_initialized()) result1*=b[ia](second);
702 if (f12->info.type==OT_SLATER) result1*=exp(-gamma*(first-second).normf());
703 else if (f12->info.type==OT_F12) result1*=(1.0-exp(-gamma* madness::inner(first-second,first-second)));
704 else if (f12->info.type==OT_GAUSS) result1*=exp(-gamma* madness::inner(first-second,first-second));
705 else {
706 MADNESS_EXCEPTION("no such operator_type",1);
707 }
708 result+=result1;
709 }
710 return result;
711
712 }
713};
714
715template<typename T, std::size_t NDIM, std::size_t LDIM=NDIM/2>
716struct LRFunctorPure : public LRFunctorBase<T,NDIM> {
717 LRFunctorPure() = default;
718 explicit LRFunctorPure(const Function<T,NDIM>& f) : f(f) {}
719 [[nodiscard]] World& world() const override {return f.world();}
720
721 void set_thresh(double thresh) override {
722 if (f.is_initialized()) f.set_thresh(thresh);
723 }
724
725 Function<T, NDIM> f; ///< a hi-dim function
726
727 std::vector<Function<T,LDIM>> inner(const std::vector<Function<T,LDIM>>& rhs,
728 const particle<LDIM> p1, const particle<LDIM> p2) const override {
729 return madness::innerXX<LDIM>(f,rhs,p1.get_array(),p2.get_array());
730 }
731
732 std::string type() const override {return "LRFunctorPure";}
733
734 /// evaluate the functor at a given point, e.g. for plotting
735 T operator()(const Vector<double,NDIM>& r) const override {
736 return f(r);
737 }
738
739 typename Tensor<T>::scalar_type norm2() const override {
740 return f.norm2();
741 }
742};
743
744
745 /// LowRankFunction represents a hi-dimensional (NDIM) function as a sum of products of low-dimensional (LDIM) functions
746
747 /// a LowRankFunction can be created from a hi-dim function directly, or from a composite like f(1,2) phi(1) psi(2),
748 /// where f(1,2) is a two-particle function (e.g. a Slater function)
749 /// the representation is canonical: f(1,2) = \sum_i g_i(1) h_i(2)
750 /// for the time being we don't require g or h to be orthogonal or normalized
751 template<typename T, std::size_t NDIM, std::size_t LDIM=NDIM/2>
753 public:
754
755 double rank_revealing_tol=1.e-8; // rrcd tol
756 bool do_print=false;
757 std::vector<Function<T,LDIM>> g,h;
760
761 LowRankFunction() = default;
762
764 double tol) :
765 rank_revealing_tol(tol), g(g), h(h) {
766 MADNESS_CHECK_THROW(this->g.size()==this->h.size(),"inconsistent sizes in LRF");
767 }
768
769 /// shallow copy ctor
772 g(other.g), h(other.h) {
773 }
774
775 World& world() const {
776 MADNESS_CHECK_THROW(g.size()>0, "cannot get world from empty LowRankFunction");
777 return g.front().world();
778 }
779
780 /// deep copy
781 friend LowRankFunction copy(const LowRankFunction& other) {
783 other.rank_revealing_tol);
784 }
785
786 /// serialize to an archive (e.g. cloud or file)
787 template<typename Archive>
788 void serialize(const Archive& ar) {
789 try {
790 std::size_t gsize=g.size();
791 std::size_t hsize=g.size();
792 ar & gsize & hsize & rank_revealing_tol;
793 g.resize(gsize); // noop for saving
794 h.resize(hsize); // noop for saving
795 for (int i=0; i<gsize; ++i) ar & g[i];
796 for (int i=0; i<hsize; ++i) ar & h[i];
797 } catch (const std::exception& e) {
798 std::string msg ="serialization error in LowRankFunction: "+ std::string(e.what());
799 MADNESS_EXCEPTION(msg.c_str(),1);
800 }
801 }
802
804 hashT h1=0;
805 for (const auto& aa : f.g) hash_combine(h1,hash_value(aa.get_impl()));
806 for (const auto& bb : f.h) hash_combine(h1,hash_value(bb.get_impl()));
807 hash_combine(h1,hash_value(f.rank_revealing_tol));
808 return h1;
809 }
810
811
812 /// customized function to store this to the cloud
813
814 /// will store g and h elements individually
817 records+=cloud.store(world,g);
818 records+=cloud.store(world,h);
819 records+=cloud.store(world,rank_revealing_tol);
820 return records;
821 }
822
823 /// customized function to load this from the cloud
824
825 /// @param[inout] recordlist: containing the keys of the member variables -> will be reduced by the keys which are used
826 void cloud_load(World& world, const Cloud& cloud, Recordlist<Cloud::keyT>& recordlist) {
827 // load bookkeeping stuff in a vector
828 g=cloud.forward_load<std::vector<Function<double,3>>>(world,recordlist);
829 h=cloud.forward_load<std::vector<Function<double,3>>>(world,recordlist);
830 rank_revealing_tol=cloud.forward_load<double>(world,recordlist);
831 }
832
833 LowRankFunction& operator=(const LowRankFunction& f) { // Assignment required for storage in vector
834 if (this == &f) return *this;
835 rank_revealing_tol = f.rank_revealing_tol;
836 do_print = f.do_print;
837 g = f.g;
838 h = f.h;
839 return *this;
840 }
841
842 /// function evaluation
843 T operator()(const Vector<double,NDIM>& r) const {
844 Vector<double,LDIM> first, second;
845 for (int i=0; i<LDIM; ++i) {
846 first[i]=r[i];
847 second[i]=r[i+LDIM];
848 }
849 double result=0.0;
850 Tensor<T> gvec(g.size()), hvec(h.size());
851 for (int i=0; i<g.size(); ++i) gvec(i)=g[i](first);
852 for (int i=0; i<h.size(); ++i) hvec(i)=h[i](second);
853 result=gvec.trace(hvec);
854 return result;
855 }
856
857 /*
858 * arithmetic section
859 */
860
861 /// addition
863 LowRankFunction<T,NDIM> result=copy(*this);
864 result+=b;
865 return result;
866 }
867 /// subtraction
869 LowRankFunction<T,NDIM> result=copy(*this);
870 result-=b;
871 return result;
872 }
873
874 /// in-place addition
876 g=append(g,copy(b.g));
877 h=append(h,copy(b.h));
878 return *this;
879 }
880
881 /// in-place subtraction
883 g=append(g,copy(b.g)*T(-1.0));
884 h=append(h,copy(b.h));
885 return *this;
886 }
887
888 /// scale by a scalar
889 template<typename Q>
893
894 /// out-of-place scale by a scalar (no type conversion)
895 LowRankFunction operator*(const T a) const {
897 }
898
899 /// multiplication with a scalar
900 friend LowRankFunction operator*(const T a, const LowRankFunction& other) {
901 return other*a;
902 }
903
904 /// in-place scale by a scalar (no type conversion)
906 g=g*a;
907 return *this;
908 }
909
910 /// l2 norm
912 auto g_ij=matrix_inner(world(),g,g);
913 auto h_ij=matrix_inner(world(),h,h);
914 // ||this||^2 = <g_i| g_k> <h_i| h_k>
915 return sqrt(g_ij.trace(h_ij));
916 }
917
918 std::vector<Function<T,LDIM>> get_functions(const particle<LDIM>& p) const {
919 MADNESS_CHECK(p.is_first() or p.is_last());
920 if (p.is_first()) return g;
921 return h;
922 }
923
924 std::vector<Function<T,LDIM>> get_g() const {return g;}
925 std::vector<Function<T,LDIM>> get_h() const {return h;}
926
928 Tensor<long> r(2);
929 r(0l)=g.size();
930 r(1l)=h.size();
931 MADNESS_ASSERT(r(0l)==r(1l));
932 return r;
933 }
934
935 /// return the size in GByte
936 double size() const {
937 if (g.size()==0) return 0.0;
938 double sz=get_size(g.front().world(),g);
939 sz+=get_size(world(),h);
940 return sz;
941 }
942
943 void print_size(std::string msg="") const {
944 if (msg=="") msg="LRF";
945 std::size_t rank=g.size();
946 double size=this->size();
947 char buf[50];
948 snprintf(buf, sizeof(buf), "%s rank, size: %zu, %.2f GB", msg.c_str(), rank,size);
949 if (world().rank()==0) print(buf);
950 }
951
952 /// f(1,2) = \sum_i g_i(1) h_i(2)
954 if (g.size()==0) return Function<T,NDIM>();
955 MADNESS_ASSERT(g.size()==h.size());
956 auto fapprox=hartree_product(g[0],h[0]);
957 for (int i=1; i<g.size(); ++i) fapprox+=hartree_product(g[i],h[i]);
958 return fapprox;
959 }
960
961 /// remove linear dependencies in g and h; result stays in canonical form
962 /// f(1,2) = \sum_i g_i(1) h_i(2)
963 /// {g} and {h} are not necessarily orthogonal, but they are linearly independent
964 void remove_linear_dependencies(double tol=-1.0) {
965 if (tol<0.0) tol=rank_revealing_tol;
966 if (g.size()==0) return;
967 World& world=g.front().world();
968
971 auto [pg,Xg,Xg_inv]=rr_cholesky_matrix_and_reorder(g,ovlp_g,tol);
972 auto [ph,Xh,Xh_inv]=rr_cholesky_matrix_and_reorder(h,ovlp_h,tol);
973 // cite from rr_cholesky_matrix_and_reorder
974 // pv: reordered original, linearly-independent functions,
975 // X: the (r,r) transformation matrix from pv to orthonormalized functions:
976 // v_ortho_i = v_p X_ip = pv_j X_ji
977 // X_inv: its (r,p) "inverse" from original functions to orthonormalized functions:
978 // v_p = v_ortho_i X_inv_ip
979 // note that X is not the inverse of X_inv, that would be X_full
980 // g h = pg X X^(-1) X^(-T) X^T ph
981 // absorb the coupling matrix M = Xg . Xh^T into g to keep the canonical form
982 auto XXinv_g=inner(Xg,Xg_inv);
983 auto XXinv_h=inner(Xh,Xh_inv);
984 auto M = inner(XXinv_g,XXinv_h,1,1); // Xg . Xh^T
985 g=transform(world,pg,M);
986 h=ph;
987 }
988
992
993
994 /// perform RRCD on the overlap matrix of the functions, reorder the functions according to the pivoting,
995 /// and return the upper triangular matrix from the Cholesky decomposition
996
997 /// note: the rr_cholesky is more efficient than a full SVD for removing linear dependencies, but it does not
998 /// give an orthonormal basis, so an additional orthonormalization step is needed if orthogonality is desired.
999 /// To orthonormalize:
1000 /// auto [pv, X] = rr_cholesky_matrix_and_reorder(v,ovlp,tol);
1001 /// v_ortho=transform(world,pv,X); // v_ortho_i = sum_j v_j U_{ji}^(-1)
1002 /// @param[in] v the input functions
1003 /// @param[in] ovlp the overlap matrix of the input functions, will be destroyed in-place by the rr_cholesky
1004 /// @param[in] tol the tolerance for linear dependence in the rr_cholesky
1005 /// @return a tuple containing
1006 /// pv: reordered original, linearly-independent functions,
1007 /// X: the (r,r) transformation matrix from pv to orthonormalized functions:
1008 /// v_ortho_i = v_p X_pi = pv_j X_ji
1009 /// X_inv: its (r,p) "inverse" from original functions to orthonormalized functions:
1010 /// v_p = v_ortho_i X_inv_ip
1011 /// note that X is not the inverse of X_inv, that would be X_full
1012 /// but v_p(x) = pv_i(x) X_ij X_inv_jp is numerically the same
1013 static std::tuple<std::vector<Function<T,LDIM>>, Tensor<T>, Tensor<T>>
1014 rr_cholesky_matrix_and_reorder(const std::vector<Function<T,LDIM>>& v, Tensor<T> ovlp, const double tol) {
1015 int rank;
1016 Tensor<int> piv;
1017
1018 rr_cholesky(ovlp,tol,piv,rank); // destroys ovlp and gives back Upper ∆ Matrix from CCD
1019
1020 // rearrange and truncate the functions according to the pivoting of the rr_cholesky
1021 std::vector<Function<T,LDIM> > pv(rank);
1022 for(integer i=0;i<rank;++i) pv[i]=v[piv[i]];
1023
1024 // compute transformation matrix v -> w = v_ortho
1025 // w_i = v_p X_pi
1026 // = v_piv(i) X_ij
1027 // v_p = w_i X^(-1)_ip = w_i Xinv_ip
1028 // pv_i = piv(v_p) // pv is not orthogonal or normalized, just linearly independent
1029 // this returns: pv, X_ij, X_inv_ip
1030
1031 // no need to invert all of ovlp, only the upper left rank x rank block
1032 Tensor<T> U=ovlp(Slice(0,rank-1),Slice(0,rank-1));
1033 Tensor<T> Xinv=ovlp(Slice(0,rank-1),_); // has dimensions (rank,original_size)
1034 Tensor<T> X=inverse(U); // has dimensions (rank,rank)
1035
1036 // sanity check
1037 // result = |i~> = sum_r |i> U_{ir}^(-1)
1038 // with <i~|j~> = sum_{r} U_{ir}^(-1) <i|j> U_{jp}^(-1)
1039 // = sum_{r} U_{ir}^(-1) (U^T U)_{ij} U_{jr}^(-1)
1040 // = sum_{r} U_{ir}^(-1) U_{ip} U_{jp} U_{jp}^(-1)
1041 // = delta_{ij} // has matrix dimension (r,r)
1042
1043 // permute X_inv, so that the following identity holds:
1044 // also the same: v_p(x) = pv_i(x) X_ij X_inv_jq P_qp
1045 Tensor<T> tmp=copy(Xinv);
1046 for (int i=0; i<tmp.dim(1); ++i) Xinv(_,piv(i))=tmp(_,i);
1047
1048 return std::make_tuple(pv,X,Xinv);
1049 }
1050
1051 private:
1052 /// orthonormalize the argument vector via rank-revealing Cholesky
1053 std::vector<Function<T,LDIM>> orthonormalize(const std::vector<Function<T,LDIM>>& g) const {
1054 if (g.size()==0) return g;
1055 auto ovlp=matrix_inner(g.front().world(),g,g);
1057 double tight_thresh=FunctionDefaults<LDIM>::get_thresh()*0.1;
1058 return truncate(g2,tight_thresh);
1059 }
1060
1061 public:
1062
1063 /// optimize the lrf using the lrfunctor
1064
1065 /// @param[in] nopt number of iterations (wrt to Alg. 4.3 in Halko)
1066 void optimize(const LRFunctorBase<T,NDIM>& lrfunctor1, const long nopt=1) {
1067 timer t(world());
1069 for (int i=0; i<nopt; ++i) {
1070 // orthonormalize h
1072 t.tag("ortho1");
1073 g=truncate(inner(lrfunctor1,h,p2,p1));
1074 t.tag("inner1");
1076 t.tag("ortho2");
1077 h=truncate(inner(lrfunctor1,g,p1,p1));
1078 t.tag("inner2");
1079 }
1080 }
1081
1082 /// compute the l2 error |functor - \sum_i g_ih_i|_2
1083
1084 /// \int (f(1,2) - gh(1,2))^2 = \int f(1,2)^2 - 2\int f(1,2) gh(1,2) + \int gh(1,2)^2
1085 /// since we are subtracting large numbers the numerics are sensitive, and NaN may be returned..
1086 double l2error(const LRFunctorBase<T,NDIM>& lrfunctor1) const {
1087
1088 timer t(world());
1090
1091 // \int f(1,2)^2 d1d2
1092 double term1 = lrfunctor1.norm2();
1093 term1=term1*term1;
1094 t.tag("computing term1");
1095
1096 // \int f(1,2) \sum_i g_i(1) h_i(2) d1d2
1097 // = \sum_i \int (\int f(1,2) g_i(1) d1) h_i(2) d2
1098 double term2=madness::inner(g,inner(lrfunctor1,h,p2,p1));
1099 t.tag("computing term2");
1100
1101 auto tmp1=matrix_inner(world(),h,h);
1102 auto tmp2=matrix_inner(world(),g,g);
1103 double term3=tmp1.trace(tmp2);
1104 t.tag("computing term3");
1105
1106 double arg=term1-2.0*term2+term3;
1107 if (arg<0.0) {
1108 print("negative l2 error");
1109 arg*=-1.0;
1110// throw std::runtime_error("negative argument in l2error");
1111 }
1112 double error=sqrt(arg)/sqrt(term1);
1113 if (world().rank()==0 and do_print) {
1114 print("term1,2,3, error",term1, term2, term3, " --",error);
1115 }
1116
1117 return error;
1118 }
1119
1120 /// Cheap relative L2 error via Pythagoras (canonical form only).
1121 ///
1122 /// When h is orthonormal AND g is the reprojection of h
1123 /// (g_k = <f(r1,r2) | h_k(r2)>_{r2}), the following identity holds:
1124 /// ||f - sum_k g_k h_k||^2 = ||f||^2 - sum_k ||g_k||^2
1125 /// (cross and self terms collapse to the same sum_k ||g_k||^2).
1126 /// No functor applications are needed — only norms of the stored g.
1127 ///
1128 /// @param[in] f_norm_sq precomputed ||f||^2 (typically lrfunctor.norm2()^2)
1129 /// @pre the LRF is in canonical form and g holds the reprojected factors.
1130 double l2error_pythagoras(double f_norm_sq) const {
1131 MADNESS_CHECK_THROW(f_norm_sq > 0.0,
1132 "l2error_pythagoras requires a positive ||f||^2");
1133 if (g.size()==0) return 0.0;
1134 auto gnorms = norm2s(g.front().world(), g);
1135 double sum_gk_sq = 0.0;
1136 for (double n : gnorms) sum_gk_sq += n * n;
1137 double arg = f_norm_sq - sum_gk_sq;
1138 if (arg < 0.0) arg = -arg; // numerical noise near convergence
1139 // print("l2 error via Pythagoras: (abs., rel.)", sqrt(arg),sqrt(arg) / sqrt(f_norm_sq));
1140 return sqrt(arg) / sqrt(f_norm_sq);
1141 }
1142
1143 };
1144
1145 /// compute the inner product to 2 LowRankFunctions
1146 template<typename T, std::size_t NDIM>
1148 World& world=a.world();
1149
1150 // result = <a.g_i| b.g_k> <a.h_i| b.h_k>
1151 auto g_ik=matrix_inner(world,a.g,b.g);
1152 auto h_jl=matrix_inner(world,a.h,b.h);
1153 return g_ik.trace(h_jl);
1154 }
1155
1156 /**
1157 * inner product: LowRankFunction lrf; Function f, g; double d
1158 * lrf(1,3) = inner(lrf(1,2), lrf(2,3))
1159 * lrf(1,3) = inner(lrf(1,2), f(2,3))
1160 * g(1) = inner(lrf(1,2), f(2))
1161 * d = inner(lrf(1,2), f(1,2))
1162 * d = inner(lrf(1,2), lrf(1,2))
1163 */
1164
1165 /// lrf(1,3) = inner(full(1,2), lrf(2,3))
1166
1167 /// @param[in] f1 the first function
1168 /// @param[in] f2 the second function
1169 /// @param[in] p1 the integration variable of the first function
1170 /// @param[in] p2 the integration variable of the second function
1171 template<typename T, std::size_t NDIM, std::size_t PDIM>
1173 const particle<PDIM> p1, const particle<PDIM> p2) {
1174 auto result=inner(f2,f1,p2,p1);
1175 std::swap(result.g,result.h);
1176 return result;
1177 }
1178
1179 /// lrf(1,3) = inner(lrf(1,2), full(2,3))
1180
1181 /// @param[in] f1 the first function
1182 /// @param[in] f2 the second function
1183 /// @param[in] p1 the integration variable of the first function
1184 /// @param[in] p2 the integration variable of the second function
1185 template<typename T, std::size_t NDIM, std::size_t PDIM>
1187 const particle<PDIM> p1, const particle<PDIM> p2) {
1188 static_assert(TensorTypeData<T>::iscomplex==false, "complex inner in LowRankFunction not implemented");
1189 World& world=f1.world();
1190 static_assert(2*PDIM==NDIM);
1191 // int f(1,2) k(2,3) d2 = \sum \int g_i(1) h_i(2) k(2,3) d2
1192 // = \sum g_i(1) \int h_i(2) k(2,3) d2
1193 // = \sum g_i(1) k_i(3)
1195 if (p1.is_last()) { // integrate over 2: result(1,3) = lrf(1,2) f(2,3)
1196 result.g = f1.g;
1198 result.h=innerXX<PDIM>(f2,f1.h,p2.get_array(),particle<PDIM>::particle1().get_array());
1199 } else if (p1.is_first()) { // integrate over 1: result(2,3) = lrf(1,2) f(1,3)
1200 // int f(1,2) k(1,3) d1 = \sum \int g_i(1) h_i(2) k(1,3) d1
1201 // = \sum h_i(2) \int g_i(1) k(1,3) d1
1202 // = \sum h_i(2) k_i(3)
1203 result.g = f1.h; // correct! second variable of f1 becomes first variable of result
1205 result.h=innerXX<PDIM>(f2,f1.g,p2.get_array(),particle<PDIM>::particle1().get_array());
1206 }
1207 return result;
1208 }
1209
1210 /// lrf(1,3) = inner(lrf(1,2), lrf(2,3))
1211
1212 /// @param[in] f1 the first function
1213 /// @param[in] f2 the second function
1214 /// @param[in] p1 the integration variable of the first function
1215 /// @param[in] p2 the integration variable of the second function
1216 template<typename T, std::size_t NDIM, std::size_t PDIM>
1218 const particle<PDIM> p1, const particle<PDIM> p2) {
1219 World& world=f1.world();
1220 static_assert(2*PDIM==NDIM);
1221
1222 // integrate over 2: result(1,3) =
1223 // p1,p2 = 1,0: inner(lrf(1,2) ,lrf(2,3) ) = \sum_ik g1_i(1) <h1_i(2) g2_k(2)> h2_k(3)
1224 // p1,p2 = 0,0: inner(lrf(2,1) ,lrf(2,3) ) = \sum_ik h1_i(1) <g1_i(2) g2_k(2)> h2_k(3)
1225 // p1,p2 = 0,1: inner(lrf(2,1) ,lrf(3,2) ) = \sum_ik h1_i(1) <g1_i(2) h2_k(2)> g2_k(3)
1226 // p1,p2 = 1,1: inner(lrf(1,2) ,lrf(3,2) ) = \sum_ik g1_i(1) <h1_i(2) h2_k(2)> g2_k(3)
1227 auto matrix=matrix_inner(world,f1.get_functions(p1),f2.get_functions(p2));
1228 // absorb the coupling matrix into g to keep the canonical form: gg_k(1) = \sum_i f1_i(1) matrix_ik
1229 auto gg=transform(world,f1.get_functions(p1.complement()),matrix);
1230 auto hh=copy(world,f2.get_functions(p2.complement()));
1231 return LowRankFunction<T,NDIM>(gg,hh,f1.rank_revealing_tol);
1232 }
1233
1234 /// f(1) = inner(lrf(1,2), f(2))
1235
1236 /// @param[in] f1 the first function
1237 /// @param[in] vf vector of the second functions
1238 /// @param[in] p1 the integration variable of the first function
1239 /// @param[in] p2 the integration variable of the second function, dummy variable for consistent notation
1240 template<typename T, std::size_t NDIM, std::size_t PDIM>
1241 std::vector<Function<T,NDIM-PDIM>> inner(const LowRankFunction<T,NDIM>& f1, const std::vector<Function<T,PDIM>>& vf,
1243 World& world=f1.world();
1244 static_assert(2*PDIM==NDIM);
1245 MADNESS_CHECK(p2.is_first());
1246
1247 // inner(lrf(1,2), f_k(2) ) = \sum_j g1_j(1) <h1_j(2) f_k(2)>
1248 // inner(lrf(2,1), f_k(2) ) = \sum_j h1_j(1) <g1_j(2) f_k(2)>
1249 auto matrix_jk=matrix_inner(world,f1.get_functions(p1),vf);
1250 return transform(world,f1.get_functions(p1.complement()),matrix_jk);
1251 }
1252
1253 /// f(1) = inner(lrf(1,2), f(2))
1254
1255 /// @param[in] f1 the first function
1256 /// @param[in] vf the second function
1257 /// @param[in] p1 the integration variable of the first function
1258 /// @param[in] p2 the integration variable of the second function, dummy variable for consistent notation
1259 template<typename T, std::size_t NDIM, std::size_t PDIM>
1262 return inner(f1,std::vector<Function<T,PDIM>>({f2}),p1,p2)[0];
1263 }
1264
1265 /// Factory class to compute a low-rank approximation of a given hi-dimensional function
1266 /// f(r1,r2) using randomized projection and rank-revealing Cholesky decomposition (RRCD).
1267 ///
1268 /// The approximation takes the canonical form
1269 /// f(r1,r2) ≈ Σ_i g_i(r1) h_i(r2)
1270 /// where h are orthonormalized backprojected functions and g their reprojections.
1271 ///
1272 /// ## Error analysis
1273 ///
1274 /// The L2 error ||f - f_approx|| has three independent sources that add in quadrature:
1275 ///
1276 /// ε_total² ≈ ε_sampling² + ε_truncation² + ε_conditioning²
1277 ///
1278 /// ### 1. Sampling error (grid coverage)
1279 ///
1280 /// The grid probes f's column space via localized Gaussians. If the grid misses
1281 /// regions where f has significant weight, those contributions cannot be represented.
1282 /// Controlled by: volume_element (ve), radius, center placement.
1283 ///
1284 /// Heuristic: for well-localized functions (Gaussians on atomic centers), ve ≈ 0.1
1285 /// with radius ≈ 2-3 suffices for errors down to ~1e-3. Finer grids increase
1286 /// Y-formation cost linearly (O(grid_size) functor applications) but the rank
1287 /// saturates quickly — most extra grid points are linearly dependent.
1288 ///
1289 /// ### 2. Truncation error (rank reduction)
1290 ///
1291 /// The RRCD with tolerance tol discards Y components with overlap eigenvalues < tol.
1292 /// For Gaussian kernels the eigenvalues decay rapidly, giving truncation error that
1293 /// scales roughly as tol^(0.3-0.5) (empirically). Setting tol = ε² gives truncation
1294 /// error ~ ε.
1295 ///
1296 /// ### 3. Conditioning (eliminated by power-iteration algorithm)
1297 ///
1298 /// The current algorithm orthonormalizes h = f·Y (not Y), so the overlap
1299 /// <h|h> has eigenvalues weighted by σ_k² (singular values of f). Rank
1300 /// reduction on <h|h> is always well-conditioned — no half-metric or
1301 /// full-metric amplification. The result is canonical by construction
1302 /// (no coupling metric), and conditioning is not an error source.
1303 ///
1304 /// ### Parameter heuristics for a target error ε
1305 ///
1306 /// tol = ε² (truncation error ~ √tol ~ ε)
1307 /// ve ~ C · ε^(2/LDIM) with C = 2/1/0.5 for LDIM=1/2/3
1308 ///
1309 /// ### Algorithm (project())
1310 ///
1311 /// 1. Build grid around origins (Gaussian-distributed, σ² = 0.5·radius)
1312 /// 2. Form Y basis: multi-scale Gaussian RHS at grid points
1313 /// 3. Power-iteration projection: Y → h_raw → rr_cholesky(<h|h>) → h_ortho → g
1314 /// 4. Tol sweep: incrementally tighten rr_cholesky tolerance, reuse cached <h|h>
1315 /// 5. If grid-limited: halve ve, rebuild Y, re-project from scratch
1316 /// 6. If thresh-limited: tighten MRA thresh, rebuild Y, re-project
1317 /// 7. L2 error via Pythagoras: ||f||² − Σ||g_k||² (no functor applications)
1318 ///
1319 /// The project() method automates parameter selection from a single
1320 /// target L2 error.
1321 template<typename T, std::size_t NDIM, std::size_t LDIM=NDIM/2>
1323 public:
1324
1327
1329 std::vector<Vector<double,LDIM>> origins; ///< origins of the molecular grid
1330
1333 : parameters(param), origins(origins) {}
1334
1337
1339
1341 origins=centers;
1342 return *this;
1343 }
1344 LowRankFunctionFactory& set_radius(const double radius) {
1345 parameters.set_user_defined_value("radius",radius);
1346 return *this;
1347 }
1348 LowRankFunctionFactory& set_volume_element(const double volume_element) {
1349 parameters.set_user_defined_value("volume_element",volume_element);
1350 return *this;
1351 }
1353 parameters.set_user_defined_value("tol",rrtol);
1354 return *this;
1355 }
1356 // set_orthomethod removed — always use cholesky
1357 // set_canonicalize removed — the representation is always canonical
1358 LowRankFunctionFactory& set_gridtype(const std::string& gridtype) {
1359 parameters.set_user_defined_value("gridtype",gridtype);
1360 return *this;
1361 }
1363 parameters.set_user_defined_value("adaptive_coarse_factor",factor);
1364 return *this;
1365 }
1367 parameters.set_user_defined_value("adaptive_refine_radius",ratio);
1368 return *this;
1369 }
1371 parameters.set_user_defined_value("adaptive_significance_ratio",ratio);
1372 return *this;
1373 }
1375 parameters.set_user_defined_value("adaptive_max_centers",max_centers);
1376 return *this;
1377 }
1379 parameters.set_user_defined_value("adaptive_min_centers",min_centers);
1380 return *this;
1381 }
1382
1384 std::vector<Function<T,LDIM>> Y;
1385 std::vector<double> norms;
1386 std::vector<std::size_t> significant_indices;
1387 };
1388
1389 private:
1390 std::vector<Vector<double,LDIM>> make_uniform_random_grid_in_cell(const double volume_element) const {
1392 double volume = 1.0;
1393 for (size_t d = 0; d < LDIM; ++d) volume *= (cell(d,1) - cell(d,0));
1394 long npoint = std::max(1l, long(volume / volume_element));
1395
1396 std::random_device rd{};
1397 std::mt19937 gen{rd()};
1398 std::vector<std::uniform_real_distribution<double>> dist;
1399 for (size_t d = 0; d < LDIM; ++d) dist.emplace_back(cell(d,0), cell(d,1));
1400
1401 std::vector<Vector<double,LDIM>> grid;
1402 grid.reserve(npoint);
1403 for (long i = 0; i < npoint; ++i) {
1405 for (size_t d = 0; d < LDIM; ++d) r[d] = dist[d](gen);
1406 grid.push_back(r);
1407 }
1408 return grid;
1409 }
1410
1411 public:
1412
1413
1414 /// Numerically stable projection using power-iteration.
1415 ///
1416 /// this method orthonormalizes h = f·Y. The overlap <h|h> has eigenvalues
1417 /// weighted by σ_k² (singular values of f), making the rank reduction well-conditioned.
1418 /// The result is canonical by construction (no metric).
1419 ///
1420 /// Algorithm:
1421 /// 1. rr_cholesky(<Y|Y>, tol_coarse) → pY (coarse rank reduction)
1422 /// 2. h_raw = inner(f, pY, p1, p1) (backproject to r2)
1423 /// 3. rr_cholesky(<h_raw|h_raw>, tol) → ph (well-conditioned rank)
1424 /// 4. orthonormalize ph → h_ortho (via Cholesky factor)
1425 /// 5. g = inner(f, h_ortho, p2, p1) (reproject to r1)
1426 /// 6. return LowRankFunction(g, h_ortho) (canonical)
1427 ///
1428 /// @param[in] lrfunctor the functor
1429 /// @param[in] Y the probe basis from Yformer
1430 /// @param[in] tol the target Cholesky tolerance
1431 /// @return canonical LowRankFunction
1433 const LRFunctorBase<T,NDIM>& lrfunctor,
1434 const std::vector<Function<T,LDIM>>& Y,
1435 const double tol) const
1436 {
1437 World& world = lrfunctor.world();
1438 timer t1(world);
1439 t1.do_print = true;
1440
1441 double tight_thresh = FunctionDefaults<LDIM>::get_thresh() * 0.1;
1442
1443 // Step 1: coarse rank reduction on Y (cheap, removes exact lindep only)
1444 // Use TIGHT tolerance so we don't prematurely discard info; the
1445 // authoritative rank reduction happens on <h|h> below.
1446 double tol_coarse = std::max(1.e-14, tol * 0.01);
1447 auto ovlp_Y = matrix_inner(world, Y, Y);
1449 Y, ovlp_Y, tol_coarse);
1450 t1.tag("stable: rr_cholesky on Y (coarse)");
1451 print("stable: Y.size =", Y.size(), "pY.size =", pY.size());
1452
1453 // Step 2: backproject pY to r2 space — h_raw inherits σ_k² conditioning
1454 auto h_raw = truncate(inner(lrfunctor, pY, p1, p1), tight_thresh);
1455 t1.tag("stable: backprojection (h_raw)");
1456
1457 // Step 3: rank reduction on <h|h> — well-conditioned
1458 auto ovlp_h = matrix_inner(world, h_raw, h_raw);
1460 h_raw, ovlp_h, tol);
1461 t1.tag("stable: rr_cholesky on h");
1462 print("stable: h_raw.size =", h_raw.size(), "ph.size =", ph.size());
1463
1464 // Step 4: orthonormalize ph → h_ortho via Cholesky factor X = U^{-1}
1465 // Since <h|h> is well-conditioned, this orthonormalization is stable
1466 auto h_ortho = truncate(transform(world, ph, Ut_h), tight_thresh);
1467 t1.tag("stable: orthonormalization");
1468
1469 // Step 5: reproject to r1 space — g lives in r1 and is well-behaved
1470 auto g = truncate(inner(lrfunctor, h_ortho, p2, p1), tight_thresh);
1471 t1.tag("stable: reprojection (g)");
1472
1473 // Step 6: canonical form, no metric
1474 LowRankFunction<T,NDIM> result(g, h_ortho, tol);
1475 print("stable: final rank =", g.size());
1476
1477 return result;
1478 }
1479
1480 /// State for the stable power-iteration projection.
1481 /// Stores h_raw and its overlap for incremental tol-tightening on <h|h>.
1483 std::vector<Function<T,LDIM>> h_raw; ///< backprojected h (before orthonorm)
1484 std::vector<Function<T,LDIM>> h_ortho; ///< orthonormalized h
1485 std::vector<Function<T,LDIM>> g; ///< reprojected g
1486 Tensor<T> ovlp_h; ///< cached <h_raw|h_raw>
1487 double tol = 0.0;
1488 double f_norm_sq = -1.0; ///< cached ||f||^2 for Pythagoras l2error
1489
1490 long rank() const { return g.size(); }
1491 };
1492
1493 /// Build a grid around the given origins (or uniform random if no origins).
1494 std::vector<Vector<double,LDIM>> build_grid(double ve, long max_points = 0) const {
1495 std::vector<Vector<double,LDIM>> grid;
1496 if (!origins.empty()) {
1498 grid = mg.get_grid();
1499 } else {
1501 }
1502 if (max_points > 0 && long(grid.size()) > max_points)
1503 grid.resize(max_points);
1504 return grid;
1505 }
1506
1507 /// Form Y basis from grid, with fallback to loose significance threshold.
1508 std::vector<Function<T,LDIM>> form_Y(
1509 const LRFunctorBase<T,NDIM>& lrfunctor,
1510 const std::vector<Vector<double,LDIM>>& grid,
1511 const LowRankFunctionParameters& params) const
1512 {
1513 auto yresult = Yformer(lrfunctor, grid, params);
1514 auto Y = yresult.Y;
1515 if (Y.empty()) {
1516 yresult = Yformer(lrfunctor, grid, params, 30.0, 0.0);
1517 Y = yresult.Y;
1518 }
1519 return Y;
1520 }
1521
1522 /// RAII guard for temporarily changing FunctionDefaults and functor thresh.
1539
1540 /// Stable projection using power iteration.
1541 ///
1542 /// If prev state is empty, does full projection (Y → h → ortho → g).
1543 /// If prev has content, incrementally extends: rr_cholesky on ovlp_h with
1544 /// tighter tol, orthonormalize and reproject only the new functions.
1545 ///
1546 /// The overlap matrix ovlp_h is cached and reused across calls for pivot
1547 /// consistency (parallel matrix_inner is non-deterministic).
1549 const LRFunctorBase<T,NDIM>& lrfunctor,
1550 const std::vector<Function<T,LDIM>>& Y,
1551 const double tol,
1552 const ProjectionState& prev) const
1553 {
1554 World& world = lrfunctor.world();
1555 timer t1(world);
1556 t1.do_print = true;
1557 double tight_thresh = FunctionDefaults<LDIM>::get_thresh() * 0.1;
1558
1559 ProjectionState state;
1560 state.tol = tol;
1561 // cache ||f||^2 for cheap Pythagoras l2error (canonical form)
1562 if (prev.f_norm_sq > 0.0) {
1563 state.f_norm_sq = prev.f_norm_sq;
1564 } else {
1565 double fn = lrfunctor.norm2();
1566 state.f_norm_sq = fn * fn;
1567 t1.tag("stable: ||f||^2");
1568 }
1569
1570 if (prev.rank() == 0) {
1571 // --- full projection ---
1572 // coarse rank reduction on Y
1573 double tol_coarse = std::max(1.e-14, tol * 0.01);
1574 auto ovlp_Y = matrix_inner(world, Y, Y);
1576 Y, ovlp_Y, tol_coarse);
1577 t1.tag("stable: rr_cholesky on Y");
1578
1579 // backproject to h_raw
1580 state.h_raw = truncate(inner(lrfunctor, pY, p1, p1), tight_thresh);
1581 t1.tag("stable: backprojection (h_raw)");
1582
1583 // cache <h|h> and do authoritative rank reduction
1584 state.ovlp_h = matrix_inner(world, state.h_raw, state.h_raw);
1586 state.h_raw, copy(state.ovlp_h), tol);
1587 t1.tag("stable: rr_cholesky on h");
1588
1589 state.h_ortho = truncate(transform(world, ph, Ut_h), tight_thresh);
1590 t1.tag("stable: orthonormalization");
1591
1592 state.g = truncate(inner(lrfunctor, state.h_ortho, p2, p1), tight_thresh);
1593 t1.tag("stable: reprojection (g)");
1594 LowRankFunction<T,NDIM> lrf(state.g, state.h_ortho, tol);
1595 double current_error = lrf.l2error_pythagoras(state.f_norm_sq);
1596 t1.tag("stable: compute error in optimization");
1597
1598
1599 print("stable: pY =", pY.size(), "h_raw =", state.h_raw.size(),
1600 "rank =", state.g.size());
1601
1602 } else {
1603 // --- incremental tol-tightening on <h|h> ---
1604 // reuse prev.h_raw and prev.ovlp_h (must be same — cached)
1605 state.h_raw = prev.h_raw;
1606 state.ovlp_h = prev.ovlp_h;
1607
1608 Tensor<T> ovlp_work = copy(state.ovlp_h);
1610 state.h_raw, ovlp_work, tol);
1611 t1.tag("stable: rr_cholesky on h (incremental)");
1612
1613 long r_prev = prev.rank();
1614 long r_new = ph.size();
1615
1616 if (r_new <= r_prev) {
1617 state.h_ortho = prev.h_ortho;
1618 state.g = prev.g;
1619 } else {
1620 // only orthonormalize and reproject the new functions
1621 Tensor<T> X_new_cols = Ut_h(_, Slice(r_prev, r_new - 1));
1622 auto h_ortho_new = truncate(transform(world, ph, X_new_cols), tight_thresh);
1623 t1.tag("stable: orthonormalization (new only)");
1624 auto g_new = truncate(inner(lrfunctor, h_ortho_new, p2, p1), tight_thresh);
1625 t1.tag("stable: reprojection (new only)");
1626
1627 state.h_ortho = append(prev.h_ortho, h_ortho_new);
1628 state.g = append(prev.g, g_new);
1629 }
1630 print("stable incremental: r_prev =", r_prev, "r_new =", state.g.size());
1631 }
1632
1633 return state;
1634 }
1635
1636 /// Diagnose the dominant error source.
1637 /// With the stable (canonical) algorithm, conditioning is not an issue.
1638 /// Thresh-limited only if:
1639 /// - the last tol-tightening did not improve the error by at least 20%
1640 /// (error >= 0.8 * prev_error), AND
1641 /// - sqrt(rank) * thresh > 0.3 * error (realistic noise combination), AND
1642 /// - tol is at the floor (~1e-14), i.e. tol-tightening has no more room.
1643 /// The sqrt(rank) factor replaces the worst-case rank factor: for canonical
1644 /// form with uncorrelated truncation noise, combined error scales like
1645 /// sqrt(rank) * thresh, not rank * thresh. The rank-linear bound triggers
1646 /// spuriously at moderate rank. The tol-floor guard prevents switching to
1647 /// expensive thresh work when grid augmentation hasn't been tried yet.
1648 /// Tol-limited: tol probe on ovlp_h shows rank increase (preferred when available).
1649 /// Grid-limited: neither of the above — try more grid points.
1650 std::string diagnose_error(double error, double prev_error, long rank,
1651 double tol, double thresh,
1652 const Tensor<T>& ovlp_h) const {
1653 double eps_trunc = std::sqrt(double(rank)) * thresh;
1654 bool error_stalled = (prev_error > 0 && error >= prev_error * 0.8);
1655 bool tol_at_floor = (tol <= 1.01e-14);
1656 print(" diagnosis: sqrt(rank)*thresh =", eps_trunc, "error =", error,
1657 "rank =", rank, "tol =", tol,
1658 "stalled =", error_stalled, "tol_at_floor =", tol_at_floor);
1659
1660 // tol probe on <h|h> — check first, prefer tol if available
1661 double tol_probe = std::max(1.e-14, tol * 0.01);
1662 if (tol_probe < tol && ovlp_h.size() > 0) {
1663 Tensor<T> ovlp_copy = copy(ovlp_h);
1664 int rank_probe;
1665 Tensor<integer> piv_probe;
1666 rr_cholesky(ovlp_copy, tol_probe, piv_probe, rank_probe);
1667 print(" tol probe on <h|h>: rank", rank, "->", rank_probe);
1668 if (rank_probe > rank * 1.1) {
1669 print(" -> tol-limited");
1670 return "tol";
1671 }
1672 }
1673
1674 // thresh: only when error stalled AND realistic noise bound is significant
1675 // AND we've already exhausted tol headroom (else grid should be tried first).
1676 if (error_stalled && tol_at_floor && eps_trunc > 0.3 * error) {
1677 print(" -> thresh-limited");
1678 return "thresh";
1679 }
1680 print(" -> grid-limited");
1681 return "grid";
1682 }
1683
1684 /// Adaptively project a high-dimensional functor to a low-rank representation.
1685 ///
1686 /// Uses the numerically stable power-iteration algorithm:
1687 /// Y → h = f·Y → orthonormalize h → g = f·h_ortho → canonical LRF
1688 ///
1689 /// Single refinement loop with three actions:
1690 /// - tol-limited: tighten tol on <h|h>, incrementally extend h_ortho and g
1691 /// - grid-limited: halve ve and re-project from scratch (denser Y sampling)
1692 /// - thresh-limited: tighten MRA thresh, reform everything
1693 /// - tol-degraded: revert to best state, route to thresh or grid
1694 ///
1695 /// @param[in] lrfunctor the high-dimensional functor to approximate
1696 /// @param[in] target_l2error the desired L2 error (default: FunctionDefaults thresh)
1697 /// @param[in] max_iter maximum refinement iterations (default: 5)
1698 /// @return canonical low-rank approximation
1700 const LRFunctorBase<T,NDIM>& lrfunctor,
1701 const double target_l2error = FunctionDefaults<NDIM>::get_thresh(),
1702 const int max_iter = 5) const
1703 {
1704 World& world = lrfunctor.world();
1705 timer t1(world);
1706 t1.do_print = true;
1707 const double eps = target_l2error;
1708 const long max_Y_size = 5000;
1709
1710 double tol = std::max(1.e-14, std::min(1.e-3, eps * eps));
1711 double current_thresh = FunctionDefaults<LDIM>::get_thresh();
1712 double ve = parameters.volume_element();
1713
1714 if (world.rank()==0) print("project: eps =", eps, "tol =", tol,
1715 "ve =", ve, "thresh =", current_thresh);
1716 t1.tag("project: parameter setup");
1717
1719 local_params.set_derived_value("volume_element", ve);
1720 local_params.set_derived_value("tol", tol);
1721
1722 std::vector<Vector<double,LDIM>> grid;
1723 if (world.rank()==0) grid=build_grid(ve);
1724 // broadcast grid from rank0
1726 if (world.rank()==0) print("project: initial grid size", grid.size());
1727 t1.tag("project: grid construction");
1728
1729 auto Y = form_Y(lrfunctor, grid, local_params);
1730 MADNESS_CHECK_THROW(!Y.empty(), "project: no basis functions");
1731 if (world.rank()==0) print("project: initial Y size", Y.size());
1732 t1.tag("project: Yforming");
1733
1734 // initial stable projection
1735 ProjectionState empty_state;
1736 auto state = project_stable(lrfunctor, Y, tol, empty_state);
1737 auto lrf = LowRankFunction<T,NDIM>(state.g, state.h_ortho,
1738 tol);
1739 t1.tag("project: initial projection");
1740
1741 double current_error = lrf.l2error_pythagoras(state.f_norm_sq);
1742 long current_rank = state.rank();
1743 if (world.rank()==0) print("project: iter 0, l2error =", current_error,
1744 "rank =", current_rank, "target =", eps);
1745 t1.tag("project: l2error");
1746
1747 if (current_error <= eps) {
1748 if (world.rank()==0) print("project: converged at iteration 0");
1749 return lrf;
1750 }
1751
1752 // ThreshGuard for optional thresh-tightening
1753 std::unique_ptr<ThreshGuard> thresh_guard;
1754 double prev_error = -1.0;
1755 int iter = 0;
1756
1757 // track best state seen across all iterations
1758 auto best_lrf = lrf;
1759 double best_error = current_error;
1760
1761 while (iter <= max_iter) {
1762 if (state.ovlp_h.size() == 0) state.ovlp_h=matrix_inner(world,state.h_ortho,state.h_ortho);
1763 auto diagnosis = diagnose_error(current_error, prev_error, current_rank,
1764 tol, current_thresh, state.ovlp_h);
1765 prev_error = current_error;
1766
1767 // --- tol-limited: try incremental tol-tightening ---
1768 if (diagnosis == "tol") {
1769 auto prev_state = state;
1770 auto prev_lrf = lrf;
1771 double prev_tol = tol;
1772
1773 tol = std::max(1.e-14, tol * 0.01);
1774 state = project_stable(lrfunctor, Y, tol, prev_state);
1775 lrf = LowRankFunction<T,NDIM>(state.g, state.h_ortho,
1776 tol);
1777 t1.tag("project: tol refinement iter " + std::to_string(iter));
1778
1779 current_error = lrf.l2error_pythagoras(state.f_norm_sq);
1780 current_rank = state.rank();
1781 print("project: iter", iter, "(tol), l2error =",
1782 current_error, "rank =", current_rank);
1783 t1.tag("project: l2error iter " + std::to_string(iter));
1784 if (current_error <= eps) return lrf;
1785 if (current_error < best_error) {
1786 best_error = current_error;
1787 best_lrf = lrf;
1788 }
1789
1790 if (current_error > prev_error * 1.1) {
1791 // tol made it worse — revert. Tol-degradation is a strong
1792 // thresh-limit signal: we're trying to resolve singular values
1793 // smaller than the current MRA thresh can represent, so the
1794 // new directions are numerical noise. Route to thresh-tightening
1795 // (if not already done); otherwise grid augmentation is the
1796 // only remaining avenue.
1797 print("project: tol degraded, reverting");
1798 state = prev_state;
1799 lrf = prev_lrf;
1800 tol = prev_tol;
1801 current_error = prev_error;
1802 current_rank = state.rank();
1803 diagnosis = thresh_guard ? "grid" : "thresh";
1804 // NB: do NOT ++iter here — the branch below does so
1805 } else {
1806 continue; // tol succeeded — don't count as iteration
1807 }
1808 }
1809
1810 // --- grid-limited (or tol-degraded fallthrough): fresh Y at finer ve ---
1811 if (diagnosis == "grid") {
1812 ++iter;
1813 if (iter>max_iter) break;
1814 ve *= 0.5;
1815 print("project: grid-limited, halving ve to", ve, "and re-projecting from scratch");
1816 local_params.set_derived_value("volume_element", ve);
1817
1818 auto new_grid = build_grid(ve, max_Y_size);
1819 if (new_grid.empty()) break;
1820 print("project: new grid size", new_grid.size());
1821
1822 Y = form_Y(lrfunctor, new_grid, local_params);
1823 t1.tag("project: grid Yforming iter " + std::to_string(iter));
1824 if (Y.empty()) break;
1825 print("project: new Y size", Y.size());
1826
1827 // reset tol and prev_error for a fresh tol sweep
1828 tol = std::max(1.e-14, std::min(1.e-3, eps * eps));
1829 prev_error = -1.0;
1830
1831 ProjectionState fresh;
1832 state = project_stable(lrfunctor, Y, tol, fresh);
1833 lrf = LowRankFunction<T,NDIM>(state.g, state.h_ortho,
1834 tol);
1835 t1.tag("project: grid projection iter " + std::to_string(iter));
1836
1837 current_error = lrf.l2error_pythagoras(state.f_norm_sq);
1838 current_rank = state.rank();
1839 print("project: iter", iter, "(grid ve=", ve, "), l2error =",
1840 current_error, "rank =", current_rank);
1841 t1.tag("project: l2error iter " + std::to_string(iter));
1842 if (current_error <= eps) return lrf;
1843
1844 // stagnation: grid halving didn't beat the previous best
1845 if (current_error >= best_error * 0.9) {
1846 print("project: grid halving stagnated (best=", best_error,
1847 "), stopping");
1848 break;
1849 }
1850 if (current_error < best_error) {
1851 best_error = current_error;
1852 best_lrf = lrf;
1853 }
1854 continue;
1855 }
1856
1857 // --- thresh-limited: tighten thresh, reform everything ---
1858 if (diagnosis == "thresh") {
1859 ++iter;
1860 if (iter>max_iter) break;
1861 if (thresh_guard) {
1862 print("project: thresh already tightened, giving up");
1863 break;
1864 }
1865 current_thresh *= 0.1;
1866 if (world.rank() == 0) print("project: tightening thresh to", current_thresh);
1867 thresh_guard = std::make_unique<ThreshGuard>(current_thresh,
1868 const_cast<LRFunctorBase<T,NDIM>&>(lrfunctor));
1869 t1.tag("project: thresh tightening");
1870
1871 Y = form_Y(lrfunctor, grid, local_params);
1872 if (Y.empty()) break;
1873 t1.tag("project: tight Yforming");
1874
1875 tol = std::max(1.e-14, std::min(1.e-3, eps * eps));
1876 ProjectionState empty;
1877 state = project_stable(lrfunctor, Y, tol, empty);
1878 lrf = LowRankFunction<T,NDIM>(state.g, state.h_ortho,
1879 tol);
1880 t1.tag("project: tight projection");
1881
1882 current_error = lrf.l2error_pythagoras(state.f_norm_sq);
1883 current_rank = state.rank();
1884 if (world.rank()==0) print("project: iter", iter, "(thresh), l2error =",
1885 current_error, "rank =", current_rank);
1886 t1.tag("project: l2error iter " + std::to_string(iter));
1887 if (current_error <= eps) return lrf;
1888 }
1889 }
1890
1891 if (world.rank()==0) print("WARNING project: did NOT converge to target", eps, "; achieved", best_error);
1892 return best_lrf;
1893 }
1894
1895 private:
1896 /// Build a Taylor-expansion-based Y basis spanning the range of an F12 operator.
1897 ///
1898 /// For each Gaussian term c_m exp(-alpha_m r^2) in the operator's GFit
1899 /// expansion and each multi-index k with |k| <= max_order, emits
1900 /// phi_{m,k}(r) = r^k * exp(-alpha_m |r|^2)
1901 /// when the Taylor coefficient |c_m * prod_d (2 alpha_m)^{k_d}/k_d!|
1902 /// exceeds coeff_cutoff. These monomial-Gaussians probe the operator's
1903 /// range analytically rather than by random sampling.
1904 std::vector<Function<T,LDIM>> build_taylor_y(
1905 const LRFunctorF12<T,NDIM>& functor,
1906 const int max_order,
1907 const double coeff_cutoff) const
1908 {
1909 World& world = functor.world();
1910 auto f12 = functor.get_f12();
1911 // Prefer the SepConv's cached (c, α) — populated by both ctors.
1912 // Falling back to GFit(info) requires info.hi > 0, which the
1913 // explicit (coeff, expnt, lo, thresh) ctor leaves at zero.
1914 Tensor<T> coeffs = f12->stored_coeffs;
1915 Tensor<double> expnts = f12->stored_exponents;
1916 if (coeffs.size() == 0) {
1917 GFit<T, LDIM> fit(f12->info);
1918 coeffs = fit.coeffs();
1919 expnts = fit.exponents();
1920 }
1921 const long M = coeffs.dim(0);
1922
1923 auto multi_indices = generate_multi_indices(max_order);
1924
1925 std::vector<Function<T,LDIM>> Y;
1926 long skipped = 0;
1927 for (long m = 0; m < M; ++m) {
1928 double cm = coeffs(m);
1929 double am = expnts(m);
1930 for (const auto& kidx : multi_indices) {
1931 double coeff_mk = cm;
1932 for (std::size_t d = 0; d < LDIM; ++d) {
1933 for (int j = 0; j < kidx[d]; ++j) {
1934 coeff_mk *= (2.0 * am) / double(j + 1);
1935 }
1936 }
1937 if (std::abs(coeff_mk) < coeff_cutoff) { ++skipped; continue; }
1938
1939 std::array<int, LDIM> k_copy = kidx;
1942 .functor([k_copy, am](const Vector<double,LDIM>& r) -> T {
1943 double val = std::exp(-am * madness::inner(r, r));
1944 for (std::size_t d = 0; d < LDIM; ++d) {
1945 for (int p = 0; p < k_copy[d]; ++p) val *= r[d];
1946 }
1947 return T(val);
1948 });
1949 Y.push_back(phi);
1950 }
1951 }
1952 print("build_taylor_y: M =", M, "max_order =", max_order,
1953 "Y =", Y.size(), "(skipped", skipped, "below cutoff", coeff_cutoff, ")");
1954 return Y;
1955 }
1956
1957 /// Generate all multi-indices k = (k_1, ..., k_LDIM) with total degree |k| <= max_order.
1958 static std::vector<std::array<int, LDIM>> generate_multi_indices(int max_order) {
1959 std::vector<std::array<int, LDIM>> result;
1960 std::array<int, LDIM> k{};
1961 std::function<void(std::size_t, int)> recurse = [&](std::size_t dim, int remaining) {
1962 if (dim == LDIM) {
1963 result.push_back(k);
1964 return;
1965 }
1966 for (int ki = 0; ki <= remaining; ++ki) {
1967 k[dim] = ki;
1968 recurse(dim + 1, remaining - ki);
1969 }
1970 };
1971 recurse(0, max_order);
1972 return result;
1973 }
1974
1975 public:
1976 /// Construct LRF directly from the Gaussian expansion of an F12 operator.
1977 ///
1978 /// Instead of random-Y probing, uses the known separable structure:
1979 /// each Gaussian term c_m exp(-alpha_m |r1-r2|^2) is Taylor-expanded via
1980 /// exp(2 alpha_m r1.r2) = sum_k (2 alpha)^|k| r1^k r2^k / k!
1981 /// giving explicit g and h basis functions. After rr_cholesky rank
1982 /// reduction, yields a canonical LRF accurate to the operator's Gaussian
1983 /// fit precision (~1e-8), bypassing the O(1/r^{3/2}) error floor of
1984 /// random probing for Slater-type kernels.
1985 ///
1986 /// @param[in] functor the F12 functor with operator and a,b functions
1987 /// @param[in] target_error controls coefficient cutoff and rank reduction tol
1988 /// @param[in] max_taylor_order max total degree of Taylor expansion per Gaussian term
1989 /// @return canonical LowRankFunction
1991 const LRFunctorF12<T,NDIM>& functor,
1992 const double target_error = FunctionDefaults<NDIM>::get_thresh(),
1993 const int max_taylor_order = 15) const
1994 {
1995 World& world = functor.world();
1996 timer t1(world);
1997 t1.do_print = true;
1998
1999 double coeff_cutoff = target_error * target_error * 1.e-4;
2000 auto Y = build_taylor_y(functor, max_taylor_order, coeff_cutoff);
2001 t1.tag("direct: Y construction");
2002
2003 if (Y.empty()) {
2004 print("WARNING project_from_operator: no significant Y terms");
2005 return LowRankFunction<T,NDIM>();
2006 }
2007
2008 // 4. Use project_stable with the Taylor-constructed Y basis
2009 // This lets the SeparatedConvolution handle coefficient summation
2010 // correctly: h_raw = K*(a*Y) sums over ALL Gaussian terms, preserving
2011 // cancellations that the pure Taylor construction loses.
2012 double tol = std::max(1.e-14, std::min(1.e-3, target_error * target_error));
2013 ProjectionState empty;
2014 auto state = project_stable(functor, Y, tol, empty);
2015 auto lrf = LowRankFunction<T,NDIM>(state.g, state.h_ortho, tol);
2016
2017 double current_error = lrf.l2error_pythagoras(state.f_norm_sq);
2018 print("direct: Pythagoras error =", current_error, "rank =", state.rank());
2019 t1.tag("direct: projection");
2020
2021 // incremental tol-tightening if needed
2022 while (current_error > target_error && state.ovlp_h.size() > 0) {
2023 double tighter = std::max(1.e-14, tol * 0.01);
2024 if (tighter >= tol) break;
2025 auto state2 = project_stable(functor, Y, tighter, state);
2026 auto lrf2 = LowRankFunction<T,NDIM>(state2.g, state2.h_ortho, tighter);
2027 double error2 = lrf2.l2error_pythagoras(state2.f_norm_sq);
2028 print("direct: tol", tol, "->", tighter, ": error =", error2, "rank =", state2.rank());
2029 if (error2 >= current_error * 0.9) break; // stagnated
2030 lrf = lrf2;
2031 state = state2;
2032 current_error = error2;
2033 tol = tighter;
2034 t1.tag("direct: tol tightening");
2035 }
2036
2037 print("direct: final error =", current_error, "rank =", lrf.rank());
2038 return lrf;
2039 }
2040
2041
2042 /// apply a rhs on grid points to the hi-dim function and form Y = A_ij w_j (in Halko's language).
2043 /// The RHS selection (localized Gaussian/exponential vs harmonics) is controlled by
2044 /// the single `gridtype` parameter: values "random"/"adaptive"/"twostage" use
2045 /// localized Gaussian RHS (the previous "exponential" behavior), whereas
2046 /// "harmonics" uses the RI harmonics-based RHS.
2048 const std::vector<Vector<double,LDIM>>& grid,
2050 const double exponent=30.0,
2051 const double significance_tol=-1.0) const {
2052
2053 World& world=lrfunctor1.world();
2054 std::vector<Function<double,LDIM>> Y;
2055 if (parameters.gridtype()=="harmonics") { // use harmonics-based LHS
2056 Y = harmonic_basis(world, parameters.tempered(), parameters.lmax(), origins);
2057 } else {
2058 // default: use localized Gaussian RHS (for gridtype values other than "harmonics")
2059 std::vector<Function<double,LDIM>> omega;
2060 for (const auto& point : grid) {
2061 double coeff=std::pow(2.0*exponent/constants::pi,0.25*LDIM);
2062 omega.push_back(FunctionFactory<double,LDIM>(world)
2063 // .thresh(1.e-6) // make sure this is not undersampled
2064 .special_points({point})
2065 .functor([&point,&exponent,&coeff](const Vector<double,LDIM>& r)
2066 {
2067 auto r_rel=r-point;
2068 return coeff*exp(-exponent*madness::inner(r_rel,r_rel));
2069 }));
2070 }
2071 Y=inner(lrfunctor1,omega,p2,p1);
2072 }
2073 auto norms=norm2s(world,Y);
2074 std::vector<Function<double,LDIM>> Ynormalized;
2075 std::vector<std::size_t> significant_indices;
2076 const double ytol = (significance_tol<0.0) ? parameters.tol() : significance_tol;
2077
2078 for (size_t i=0; i<Y.size(); ++i) {
2079 if (norms[i]>ytol) {
2080 Ynormalized.push_back(Y[i]);
2081 significant_indices.push_back(i);
2082 }
2083 }
2084 if (not Ynormalized.empty()) normalize(world,Ynormalized);
2085 return {Ynormalized,norms,significant_indices};
2086 }
2087
2088 /// return a set of solid harmonic functions up to lmax with a zeta range on the given (atomic) centers
2089
2090 /// @param[in] World
2091 /// @param[in] zeta_range range of the Gaussian exponent zeta, given as {zeta_min, zeta_max, zeta_step}
2092 /// for even-tempered progression
2093 /// @param[in] lmax maximum angular momentum of the solid harmonics
2094 /// @param[in] centers the centers of the solid harmonics, typically the atomic positions
2095 static std::vector<Function<T, LDIM>> harmonic_basis(World& world,
2096 const std::vector<double> zeta_range, const int lmax,
2097 const std::vector<Vector<double, LDIM>> centers)
2098 {
2099 std::vector<Function<T, LDIM>> harmonics;
2100 // harmonics-based Y
2101 struct GaussianFunction : public FunctionFunctorInterface<double, LDIM>
2102 {
2103 std::vector<long> ijk; // angular momentum
2104 Vector<double, LDIM> center;
2105 double zeta = 1.0;
2106 GaussianFunction() = default;
2107
2108 GaussianFunction(const std::vector<long>& ijk, const Vector<double, LDIM>& center, const double zeta)
2109 : ijk(ijk), center(center), zeta(zeta)
2110 {
2111 }
2112
2113 double operator()(const Vector<double, LDIM>& r) const override
2114 {
2115 auto r_rel = r - center;
2116 double val = exp(-zeta * madness::inner(r_rel, r_rel));
2117 for (int d = 0; d < LDIM; ++d) val *= std::pow(r_rel[d], ijk[d]);
2118 return val;
2119 }
2120 };
2121
2122 // compute the monomial exponents for the Cartesian Gaussian functions up to a certain angular momentum
2123 std::vector<std::vector<long>> types;
2124 for (int l = 0; l <= lmax; ++l)
2125 {
2126 std::vector<long> ijk(LDIM, 0);
2127 std::function<void(int, int)> generate_ijk = [&](int pos, int remaining_l)
2128 {
2129 if (pos == LDIM - 1)
2130 {
2131 ijk[pos] = remaining_l;
2132 types.push_back(ijk);
2133 return;
2134 }
2135 for (int i = 0; i <= remaining_l; ++i)
2136 {
2137 ijk[pos] = i;
2138 generate_ijk(pos + 1, remaining_l - i);
2139 }
2140 };
2141 generate_ijk(0, l);
2142 }
2143
2144 {
2145 std::vector<double> zetas;
2146 double z = zeta_range[0];
2147 while (z < zeta_range[1])
2148 {
2149 zetas.push_back(z);
2150 z *= zeta_range[2];
2151 if (zetas.size() > 100)
2152 {
2153 print("too many zetas in even-tempered basis, check your parameters.tempered", zeta_range);
2154 break;
2155 }
2156 }
2157
2158 for (auto type : types)
2159 {
2160 for (auto zeta : zetas)
2161 {
2162 for (auto& center : centers)
2163 {
2164 GaussianFunction gf(type, center, zeta);
2166 harmonics.push_back(f);
2167 }
2168 }
2169 }
2170 }
2171 return harmonics;
2172 }
2173
2174
2175 };
2176
2177
2178} // namespace madness
2179
2180#endif //MADNESS_LOWRANKFUNCTION_H
Definition IntegratorXX.h:29
std::vector< madness::Vector< double, 3 > > get_points() const
get the grid points
Definition IntegratorXX.h:105
void set_nradial(const std::size_t nradial1)
number of radial gridpoints on the interval [0,\inf)
Definition IntegratorXX.h:69
void set_angular_order(const std::size_t order)
a quadrature of a give order will integrate a spherical harmonic of that order exactly
Definition IntegratorXX.h:59
std::size_t get_angular_order() const
a quadrature of a give order will integrate a spherical harmonic of that order exactly
Definition IntegratorXX.h:64
std::size_t get_nradial() const
number of radial gridpoints on the interval [0,\inf)
Definition IntegratorXX.h:74
void make_grid()
Definition IntegratorXX.h:83
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
cloud class
Definition cloud.h:338
recordlistT store(madness::World &world, const T &source)
Definition cloud.h:821
T forward_load(madness::World &world, recordlistT &recordlist) const
load a single object from the cloud, recordlist is consumed while loading elements
Definition cloud.h:761
FunctionDefaults holds default paramaters as static class members.
Definition funcdefaults.h:101
static int get_k()
Returns the default wavelet order.
Definition funcdefaults.h:170
static void set_thresh(double value)
Sets the default threshold.
Definition funcdefaults.h:190
static const double & get_thresh()
Returns the default threshold.
Definition funcdefaults.h:183
static const BoundaryConditions< NDIM > & get_bc()
Returns the default boundary conditions.
Definition funcdefaults.h:315
static const Tensor< double > & get_cell()
Gets the user cell for the simulation.
Definition funcdefaults.h:352
FunctionFactory implements the named-parameter idiom for Function.
Definition function_factory.h:86
FunctionFactory & special_points(const std::vector< Vector< double, NDIM > > &special_points)
Definition function_factory.h:216
FunctionFactory & functor(const std::shared_ptr< FunctionFunctorInterface< T, NDIM > > &f)
Definition function_factory.h:141
FunctionFactory & f(T(*f)(const coordT &))
Definition function_factory.h:187
Abstract base class interface required for functors used as input to Functions.
Definition function_interface.h:68
virtual coeffT coeff(const keyT &) const
Definition function_interface.h:138
FunctionFunctorInterface()
Definition function_interface.h:77
A multiresolution adaptive numerical function.
Definition mra.h:141
Definition gfit.h:59
macrotask for \sum_ia premultiply_ia * f12 * postmultiply_ia * rhs, batched over rhs
Definition lowrankfunction.h:543
resultT operator()(const std::vector< Function< T, LDIM > > &rhs_batch, const std::vector< Function< T, LDIM > > &a, const std::vector< Function< T, LDIM > > &b, const Tensor< T > &coeff, const Tensor< double > &expnt, const double lo, const double thresh, const double mu, const bool p1_is_first) const
Definition lowrankfunction.h:570
MacroTaskLRFInner()
Definition lowrankfunction.h:545
std::tuple< const std::vector< Function< T, LDIM > > &, const std::vector< Function< T, LDIM > > &, const std::vector< Function< T, LDIM > > &, const Tensor< T > &, const Tensor< double > &, const double &, const double &, const double &, const bool & > argtupleT
Definition lowrankfunction.h:561
resultT allocator(World &world, const argtupleT &argtuple) const
Definition lowrankfunction.h:565
std::vector< Function< T, LDIM > > resultT
Definition lowrankfunction.h:563
LowRankFunction< T, NDIM > project(const LRFunctorBase< T, NDIM > &lrfunctor, const double target_l2error=FunctionDefaults< NDIM >::get_thresh(), const int max_iter=5) const
Definition lowrankfunction.h:1699
LowRankFunctionFactory(const LowRankFunctionParameters param, const Molecule &molecule)
Definition lowrankfunction.h:1335
std::vector< Function< T, LDIM > > form_Y(const LRFunctorBase< T, NDIM > &lrfunctor, const std::vector< Vector< double, LDIM > > &grid, const LowRankFunctionParameters &params) const
Form Y basis from grid, with fallback to loose significance threshold.
Definition lowrankfunction.h:1508
const particle< LDIM > p2
Definition lowrankfunction.h:1326
std::string diagnose_error(double error, double prev_error, long rank, double tol, double thresh, const Tensor< T > &ovlp_h) const
Definition lowrankfunction.h:1650
static std::vector< Function< T, LDIM > > harmonic_basis(World &world, const std::vector< double > zeta_range, const int lmax, const std::vector< Vector< double, LDIM > > centers)
return a set of solid harmonic functions up to lmax with a zeta range on the given (atomic) centers
Definition lowrankfunction.h:2095
LowRankFunctionFactory & set_adaptive_significance_ratio(const double ratio)
Definition lowrankfunction.h:1370
LowRankFunctionFactory & set_radius(const double radius)
Definition lowrankfunction.h:1344
const particle< LDIM > p1
Definition lowrankfunction.h:1325
LowRankFunctionFactory & set_rank_revealing_tol(const double rrtol)
Definition lowrankfunction.h:1352
LowRankFunctionFactory(const LowRankFunctionParameters param, const std::vector< Vector< double, LDIM > > origins={})
Definition lowrankfunction.h:1332
LowRankFunctionFactory & set_adaptive_refine_radius(const double ratio)
Definition lowrankfunction.h:1366
YFormationResult Yformer(const LRFunctorBase< T, NDIM > &lrfunctor1, const std::vector< Vector< double, LDIM > > &grid, const LowRankFunctionParameters &parameters, const double exponent=30.0, const double significance_tol=-1.0) const
Definition lowrankfunction.h:2047
LowRankFunction< T, NDIM > project_from_Y_stable(const LRFunctorBase< T, NDIM > &lrfunctor, const std::vector< Function< T, LDIM > > &Y, const double tol) const
Definition lowrankfunction.h:1432
LowRankFunctionFactory & set_centers(const std::vector< Vector< double, LDIM > > centers)
Definition lowrankfunction.h:1340
LowRankFunction< T, NDIM > project_from_operator(const LRFunctorF12< T, NDIM > &functor, const double target_error=FunctionDefaults< NDIM >::get_thresh(), const int max_taylor_order=15) const
Definition lowrankfunction.h:1990
static std::vector< std::array< int, LDIM > > generate_multi_indices(int max_order)
Generate all multi-indices k = (k_1, ..., k_LDIM) with total degree |k| <= max_order.
Definition lowrankfunction.h:1958
LowRankFunctionFactory & set_adaptive_max_centers(const int max_centers)
Definition lowrankfunction.h:1374
LowRankFunctionFactory & set_gridtype(const std::string &gridtype)
Definition lowrankfunction.h:1358
std::vector< Function< T, LDIM > > build_taylor_y(const LRFunctorF12< T, NDIM > &functor, const int max_order, const double coeff_cutoff) const
Definition lowrankfunction.h:1904
LowRankFunctionParameters parameters
Definition lowrankfunction.h:1328
LowRankFunctionFactory & set_adaptive_coarse_factor(const double factor)
Definition lowrankfunction.h:1362
LowRankFunctionFactory & set_adaptive_min_centers(const int min_centers)
Definition lowrankfunction.h:1378
LowRankFunctionFactory & set_volume_element(const double volume_element)
Definition lowrankfunction.h:1348
std::vector< Vector< double, LDIM > > build_grid(double ve, long max_points=0) const
Build a grid around the given origins (or uniform random if no origins).
Definition lowrankfunction.h:1494
ProjectionState project_stable(const LRFunctorBase< T, NDIM > &lrfunctor, const std::vector< Function< T, LDIM > > &Y, const double tol, const ProjectionState &prev) const
Definition lowrankfunction.h:1548
std::vector< Vector< double, LDIM > > origins
origins of the molecular grid
Definition lowrankfunction.h:1329
LowRankFunctionFactory(const LowRankFunctionFactory &other)=default
std::vector< Vector< double, LDIM > > make_uniform_random_grid_in_cell(const double volume_element) const
Definition lowrankfunction.h:1390
LowRankFunction represents a hi-dimensional (NDIM) function as a sum of products of low-dimensional (...
Definition lowrankfunction.h:752
void optimize(const LRFunctorBase< T, NDIM > &lrfunctor1, const long nopt=1)
optimize the lrf using the lrfunctor
Definition lowrankfunction.h:1066
friend LowRankFunction operator*(const T a, const LowRankFunction &other)
multiplication with a scalar
Definition lowrankfunction.h:900
double rank_revealing_tol
Definition lowrankfunction.h:755
std::vector< Function< T, LDIM > > get_h() const
Definition lowrankfunction.h:925
std::vector< Function< T, LDIM > > get_functions(const particle< LDIM > &p) const
Definition lowrankfunction.h:918
void print_size(std::string msg="") const
Definition lowrankfunction.h:943
friend hashT hash_value(const LowRankFunction< T, NDIM > &f)
Definition lowrankfunction.h:803
LowRankFunction operator-(const LowRankFunction &b) const
subtraction
Definition lowrankfunction.h:868
LowRankFunction operator*(const Q a) const
scale by a scalar
Definition lowrankfunction.h:890
void reorthonormalize()
Definition lowrankfunction.h:989
double l2error_pythagoras(double f_norm_sq) const
Definition lowrankfunction.h:1130
std::vector< Function< T, LDIM > > orthonormalize(const std::vector< Function< T, LDIM > > &g) const
orthonormalize the argument vector via rank-revealing Cholesky
Definition lowrankfunction.h:1053
LowRankFunction operator*(const T a) const
out-of-place scale by a scalar (no type conversion)
Definition lowrankfunction.h:895
TensorTypeData< T >::scalar_type norm2() const
l2 norm
Definition lowrankfunction.h:911
LowRankFunction(const LowRankFunction &other)
shallow copy ctor
Definition lowrankfunction.h:770
bool do_print
Definition lowrankfunction.h:756
void remove_linear_dependencies(double tol=-1.0)
Definition lowrankfunction.h:964
void cloud_load(World &world, const Cloud &cloud, Recordlist< Cloud::keyT > &recordlist)
customized function to load this from the cloud
Definition lowrankfunction.h:826
LowRankFunction & operator*=(const T a)
in-place scale by a scalar (no type conversion)
Definition lowrankfunction.h:905
LowRankFunction & operator=(const LowRankFunction &f)
Definition lowrankfunction.h:833
const particle< LDIM > p2
Definition lowrankfunction.h:759
Function< T, NDIM > reconstruct() const
f(1,2) = \sum_i g_i(1) h_i(2)
Definition lowrankfunction.h:953
std::vector< Function< T, LDIM > > get_g() const
Definition lowrankfunction.h:924
static std::tuple< std::vector< Function< T, LDIM > >, Tensor< T >, Tensor< T > > rr_cholesky_matrix_and_reorder(const std::vector< Function< T, LDIM > > &v, Tensor< T > ovlp, const double tol)
Definition lowrankfunction.h:1014
void serialize(const Archive &ar)
serialize to an archive (e.g. cloud or file)
Definition lowrankfunction.h:788
const particle< LDIM > p1
Definition lowrankfunction.h:758
LowRankFunction & operator-=(const LowRankFunction &b)
in-place subtraction
Definition lowrankfunction.h:882
std::vector< Function< T, LDIM > > h
Definition lowrankfunction.h:757
LowRankFunction & operator+=(const LowRankFunction &b)
in-place addition
Definition lowrankfunction.h:875
double l2error(const LRFunctorBase< T, NDIM > &lrfunctor1) const
compute the l2 error |functor - \sum_i g_ih_i|_2
Definition lowrankfunction.h:1086
LowRankFunction(std::vector< Function< T, LDIM > > g, std::vector< Function< T, LDIM > > h, double tol)
Definition lowrankfunction.h:763
LowRankFunction operator+(const LowRankFunction &b) const
addition
Definition lowrankfunction.h:862
Tensor< long > rank() const
Definition lowrankfunction.h:927
std::vector< Function< T, LDIM > > g
Definition lowrankfunction.h:757
Recordlist< Cloud::keyT > cloud_store(World &world, Cloud &cloud) const
customized function to store this to the cloud
Definition lowrankfunction.h:815
World & world() const
Definition lowrankfunction.h:775
friend LowRankFunction copy(const LowRankFunction &other)
deep copy
Definition lowrankfunction.h:781
double size() const
return the size in GByte
Definition lowrankfunction.h:936
T operator()(const Vector< double, NDIM > &r) const
function evaluation
Definition lowrankfunction.h:843
MacroTaskOperationBase()
Definition macrotaskq.h:1642
std::shared_ptr< MacroTaskPartitioner > partitioner
Definition macrotaskq.h:1641
std::string name
Definition macrotaskq.h:1640
Definition macrotaskq.h:999
Definition molecule.h:129
void read_input_and_commandline_options(World &world, const commandlineparser &parser, const std::string tag)
Definition chem/QCCalculationParametersBase.h:339
T get(const std::string key) const
Definition chem/QCCalculationParametersBase.h:313
void initialize(const std::string &key, const T &value, const std::string comment="", const std::vector< T > allowed_values={})
Definition chem/QCCalculationParametersBase.h:394
void set_derived_value(const std::string &key, const T &value)
Definition chem/QCCalculationParametersBase.h:436
QCCalculationParametersBase()
ctor for testing
Definition chem/QCCalculationParametersBase.h:383
Definition operator.h:158
Tensor< Q > stored_coeffs
Definition operator.h:169
static SeparatedConvolution< Q, NDIM > combine_generic(World &world, const Tensor< Q > &cA, const Tensor< double > &aA, const Tensor< Q > &cB, const Tensor< double > &aB, double lo, double thresh, bool prune=true)
Definition operator.h:1962
static SeparatedConvolution< Q, NDIM > combine(const SeparatedConvolution< Q, NDIM > &left, const SeparatedConvolution< Q, NDIM > &right)
Definition operator.h:1877
OperatorInfo info
Definition operator.h:163
static bool can_combine(const SeparatedConvolution< Q, NDIM > &left, const SeparatedConvolution< Q, NDIM > &right)
Definition operator.h:1829
Tensor< double > stored_exponents
Definition operator.h:170
A slice defines a sub-range or patch of a dimension.
Definition slice.h:103
Traits class to specify support of numeric types.
Definition type_data.h:56
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
A simple, fixed dimension vector.
Definition vector.h:64
void broadcast_serializable(objT &obj, ProcessID root)
Broadcast a serializable object.
Definition worldgop.h:774
A parallel world class.
Definition world.h:134
ProcessID rank() const
Returns the process rank in this World (same as MPI_Comm_rank()).
Definition world.h:344
WorldGopInterface & gop
Global operations.
Definition world.h:216
Objects that implement their own parallel archive interface should derive from this class.
Definition parallel_archive.h:58
Definition lowrankfunction.h:101
std::vector< Vector< double, NDIM > > get_grid() const
Definition lowrankfunction.h:133
dftgrid(const double volume_element, const double radius)
Definition lowrankfunction.h:104
GridBuilder builder
Definition lowrankfunction.h:103
dftgrid(const std::size_t nradial, const std::size_t angular_order, const coord_3d origin=coord_3d())
Definition lowrankfunction.h:125
Definition lowrankfunction.h:73
bool do_print
Definition lowrankfunction.h:97
double get_radius() const
Definition lowrankfunction.h:76
double volume_element
Definition lowrankfunction.h:95
double radius
Definition lowrankfunction.h:96
double get_volume_element() const
Definition lowrankfunction.h:75
virtual ~gridbase()=default
void visualize(const std::string filename, const std::vector< Vector< double, NDIM > > &grid) const
Definition lowrankfunction.h:81
given a molecule, return a suitable grid
Definition lowrankfunction.h:293
std::vector< Vector< double, NDIM > > get_grid() const
Definition lowrankfunction.h:326
molecular_grid(const std::vector< Vector< double, NDIM > > origins, std::shared_ptr< gridbase > grid)
ctor takes centers of the grid and the grid builder
Definition lowrankfunction.h:317
std::vector< Vector< double, NDIM > > centers
Definition lowrankfunction.h:381
std::shared_ptr< gridbase > grid_builder
Definition lowrankfunction.h:382
molecular_grid(const Molecule &molecule, std::shared_ptr< gridbase > grid)
ctor takes molecule and grid builder
Definition lowrankfunction.h:323
molecular_grid(const std::vector< Vector< double, NDIM > > origins, const LowRankFunctionParameters &params)
ctor takes centers of the grid and the grid parameters
Definition lowrankfunction.h:297
grid with random points around the origin, with a Gaussian distribution
Definition lowrankfunction.h:141
static Vector< double, NDIM > gaussian_random_distribution(const Vector< double, NDIM > origin, double variance)
Definition lowrankfunction.h:206
Vector< double, NDIM > get_origin() const
Definition lowrankfunction.h:189
std::vector< Vector< double, NDIM > > get_grid() const
Definition lowrankfunction.h:149
randomgrid(const double volume_element, const double radius, const Vector< double, NDIM > origin=Vector< double, NDIM >(0.0))
Definition lowrankfunction.h:143
Vector< double, NDIM > origin
Definition lowrankfunction.h:218
double volume() const
Definition lowrankfunction.h:195
Definition y.cc:25
int integer
Definition crayio.c:25
double(* f)(const coord_3d &)
Definition derivatives.cc:54
double(* f1)(const coord_3d &)
Definition derivatives.cc:55
char * p(char *buf, const char *name, int k, int initial_level, double thresh, int order)
Definition derivatives.cc:72
double(* f2)(const coord_3d &)
Definition derivatives.cc:56
void orthonormalize(std::vector< Spinor > &arg, const AnsatzT ansatz)
Definition dirac-hatom.cc:1242
static double lo
Definition dirac-hatom.cc:23
std::vector< Spinor > truncate(std::vector< Spinor > arg)
Definition dirac-hatom.cc:503
Tensor< std::complex< double > > matrix_inner(World &world, std::vector< Fcwf > &a, std::vector< Fcwf > &b)
Definition fcwf.cc:469
Fcwf apply(World &world, real_convolution_3d &op, const Fcwf &psi)
Definition fcwf.cc:317
std::complex< double > inner(const Fcwf &psi, const Fcwf &phi)
Definition fcwf.cc:311
Fcwf copy(Fcwf psi)
Definition fcwf.cc:374
std::vector< Fcwf > transform(World &world, std::vector< Fcwf > &a, Tensor< std::complex< double > > U)
Definition fcwf.cc:515
Tensor< typename Tensor< T >::scalar_type > arg(const Tensor< T > &t)
Return a new tensor holding the argument of each element of t (complex types only).
Definition tensor.h:2772
static const double v
Definition hatom_sf_dirac.cc:20
Declares the macrotaskq and MacroTaskBase classes.
#define MADNESS_CHECK(condition)
Check a condition — even in a release build the condition is always evaluated so it can have side eff...
Definition madness_exception.h:182
#define MADNESS_EXCEPTION(msg, value)
Macro for throwing a MADNESS exception.
Definition madness_exception.h:119
#define MADNESS_ASSERT(condition)
Assert a condition that should be free of side-effects since in release builds this might be a no-op.
Definition madness_exception.h:134
#define MADNESS_CHECK_THROW(condition, msg)
Check a condition — even in a release build the condition is always evaluated so it can have side eff...
Definition madness_exception.h:207
void print(const tensorT &t)
Definition mcpfit.cc:140
Main include file for MADNESS and defines Function interface.
constexpr double pi
Mathematical constant .
Definition constants.h:48
Namespace for all elements and tools of MADNESS.
Definition DFConvergence.h:9
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
static const char * filename
Definition legendre.cc:96
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
std::vector< double > grid({0.00000000000000e+00, 7.74564534039568e-10, 2.47256327461087e-08, 1.86997862087340e-07, 7.83531011839395e-07, 2.37369448442132e-06, 5.85385578447464e-06, 1.25192693640128e-05, 2.41120079015646e-05, 4.28530598081574e-05, 7.14571735608571e-05, 1.13129528705579e-04, 1.71543841230856e-04, 2.50802052874775e-04, 3.55376294767219e-04, 4.90034340610786e-04, 6.59750258771429e-04, 8.69602422403842e-04, 1.12466142949409e-03, 1.42987080942386e-03, 1.78992364014940e-03, 2.20913836324745e-03, 2.69133715810767e-03, 3.23973021906902e-03, 3.85680917042725e-03, 4.54425265659531e-03, 5.30284686331574e-03, 6.13242336803442e-03, 7.03181629276860e-03, 7.99884025229928e-03, 9.03029006708050e-03, 1.01219626578657e-02, 1.12687009724886e-02, 1.24644592296948e-02, 1.37023882155871e-02, 1.49749388498821e-02, 1.62739817657269e-02, 1.75909402310371e-02, 1.89169333923840e-02, 2.02429265537309e-02, 2.15598850190411e-02, 2.28589279348859e-02, 2.41314785691809e-02, 2.53694075550732e-02, 2.65651658122794e-02, 2.77119041269022e-02, 2.88035767176875e-02, 2.98350265324687e-02, 3.08020504919994e-02, 3.17014434167336e-02, 3.25310199214522e-02, 3.32896141281727e-02, 3.39770576143407e-02, 3.45941365656990e-02, 3.51425296266603e-02, 3.56247284215205e-02, 3.60439431446186e-02, 3.64039959753441e-02, 3.67092053552739e-02, 3.69642643623641e-02, 3.71741165259965e-02, 3.73438324441572e-02, 3.74784904900007e-02, 3.75830647318932e-02, 3.76623229435371e-02, 3.77207372560624e-02, 3.77624096112071e-02, 3.77910137249598e-02, 3.78097547768664e-02, 3.78213475154040e-02, 3.78280129289835e-02, 3.78314930902835e-02, 3.78330832537561e-02, 3.78336797869059e-02, 3.78338420591352e-02, 3.78338660102034e-02, 3.78338692887670e-02, 3.78339467173722e-02, 3.78344713082705e-02, 3.78363997704733e-02, 3.78415404238543e-02, 3.78527910300104e-02, 3.78743388654655e-02, 3.79118156730933e-02, 3.79724014263881e-02, 3.80648723179728e-02, 3.81995899976738e-02, 3.83884307919462e-02, 3.86446553881524e-02, 3.89827212156132e-02, 3.94180414519212e-02, 3.99666961805422e-02, 4.06451026796855e-02, 4.14696530921280e-02, 4.24563287754274e-02, 4.36203014320401e-02, 4.49755316463183e-02, 4.65343756946706e-02, 4.83072114386611e-02, 5.03020937588608e-02, 5.25244493483274e-02, 5.49768197749344e-02, 5.76586605651183e-02, 6.05662026884007e-02, 6.36923812686800e-02, 6.70268346561297e-02, 7.05559752077735e-02, 7.42631312932333e-02, 7.81287582138778e-02, 8.21307139477169e-02, 8.62445939566306e-02, 9.04441177619647e-02, 9.47015586503668e-02, 9.89882067501835e-02, 1.03274854850000e-01, 1.07532295738402e-01, 1.11731819543736e-01, 1.15845699552650e-01, 1.19847655286489e-01, 1.23713282207134e-01, 1.27420438292594e-01, 1.30949578844237e-01, 1.34284032231687e-01, 1.37410210811966e-01, 1.40317752935249e-01, 1.42999593725433e-01, 1.45451964152040e-01, 1.47674319741506e-01, 1.49669202061706e-01, 1.51442037805696e-01, 1.53000881854049e-01, 1.54356112068327e-01, 1.55520084724940e-01, 1.56506760408239e-01, 1.57331310820682e-01, 1.58009717319825e-01, 1.58558372048446e-01, 1.58993692284754e-01, 1.59331758112215e-01, 1.59587982708421e-01, 1.59776823502693e-01, 1.59911541182394e-01, 1.60004012073979e-01, 1.60064597827274e-01, 1.60102074634902e-01, 1.60123622470357e-01, 1.60134873076513e-01, 1.60140013729894e-01, 1.60141942192096e-01, 1.60142466782995e-01, 1.60142544211600e-01, 1.60142551561710e-01, 1.60142701413062e-01, 1.60143716679379e-01, 1.60147448926215e-01, 1.60157397883103e-01, 1.60179171729209e-01, 1.60220874304751e-01, 1.60293404996033e-01, 1.60410659555492e-01, 1.60589622976194e-01, 1.60850348663762e-01, 1.61215821451274e-01, 1.61711705392906e-01, 1.62365980655838e-01, 1.63208477113433e-01, 1.64270315334478e-01, 1.65583268477170e-01, 1.67179061053879e-01, 1.69088622564332e-01, 1.71341315543301e-01, 1.73964158589697e-01, 1.76981065407121e-01, 1.80412120776561e-01, 1.84272913700736e-01, 1.88573946723051e-01, 1.93320138663612e-01, 1.98510435776210e-01, 2.04137543672572e-01, 2.10187789353851e-01, 2.16641119414426e-01, 2.23471237026998e-01, 2.30645876773227e-01, 2.38127212845837e-01, 2.45872392711143e-01, 2.53834185077787e-01, 2.61961728055316e-01, 2.70201360784824e-01, 2.78497519653254e-01, 2.86793678521684e-01, 2.95033311251191e-01, 3.03160854228721e-01, 3.11122646595364e-01, 3.18867826460670e-01, 3.26349162533280e-01, 3.33523802279509e-01, 3.40353919892081e-01, 3.46807249952656e-01, 3.52857495633936e-01, 3.58484603530297e-01, 3.63674900642895e-01, 3.68421092583456e-01, 3.72722125605771e-01, 3.76582918529946e-01, 3.80013973899386e-01, 3.83030880716811e-01, 3.85653723763206e-01, 3.87906416742175e-01, 3.89815978252628e-01, 3.91411770829337e-01, 3.92724723972029e-01, 3.93786562193074e-01, 3.94629058650669e-01, 3.95283333913601e-01, 3.95779217855233e-01, 3.96144690642745e-01, 3.96405416330313e-01, 3.96584379751016e-01, 3.96701634310474e-01, 3.96774165001756e-01, 3.96815867577298e-01, 3.96837641423404e-01, 3.96847590380292e-01, 3.96851322627128e-01, 3.96852337893446e-01, 3.96852487744797e-01, 3.96852501080501e-01, 3.96852763595511e-01, 3.96854542175721e-01, 3.96861080460548e-01, 3.96878509402610e-01, 3.96916653612757e-01, 3.96989709691015e-01, 3.97116771576032e-01, 3.97322182348883e-01, 3.97635696933973e-01, 3.98092445611658e-01, 3.98732694042811e-01, 3.99601401444597e-01, 4.00747584484612e-01, 4.02223500212562e-01, 4.04083666765013e-01, 4.06383745508240e-01, 4.09179312589000e-01, 4.12524551422180e-01, 4.16470900356858e-01, 4.21065691550599e-01, 4.26350817893211e-01, 4.32361464629548e-01, 4.39124941137697e-01, 4.46659646152579e-01, 4.54974196640938e-01, 4.64066746612100e-01, 4.73924517493193e-01, 4.84523556430928e-01, 4.95828733144949e-01, 5.07793979903267e-01, 5.20362772980513e-01, 5.33468847761119e-01, 5.47037133628609e-01, 5.60984889100643e-01, 5.75223012480244e-01, 5.89657498736383e-01, 6.04191009524582e-01, 6.18724520312781e-01, 6.33159006568921e-01, 6.47397129948521e-01, 6.61344885420555e-01, 6.74913171288045e-01, 6.88019246068651e-01, 7.00588039145897e-01, 7.12553285904216e-01, 7.23858462618236e-01, 7.34457501555971e-01, 7.44315272437064e-01, 7.53407822408226e-01, 7.61722372896585e-01, 7.69257077911467e-01, 7.76020554419616e-01, 7.82031201155953e-01, 7.87316327498565e-01, 7.91911118692306e-01, 7.95857467626984e-01, 7.99202706460164e-01, 8.01998273540924e-01, 8.04298352284151e-01, 8.06158518836602e-01, 8.07634434564552e-01, 8.08780617604567e-01, 8.09649325006353e-01, 8.10289573437506e-01, 8.10746322115191e-01, 8.11059836700281e-01, 8.11265247473132e-01, 8.11392309358149e-01, 8.11465365436407e-01, 8.11503509646554e-01, 8.11520938588616e-01, 8.11527476873443e-01, 8.11529255453653e-01, 8.11529517968663e-01, 8.11529541176345e-01, 8.11529996288764e-01, 8.11533079746512e-01, 8.11544414925490e-01, 8.11574630828117e-01, 8.11640760013437e-01, 8.11767414594025e-01, 8.11987697014585e-01, 8.12343809961018e-01, 8.12887338428862e-01, 8.13679186466493e-01, 8.14789161138720e-01, 8.16295206552722e-01, 8.18282301065180e-01, 8.20841040761609e-01, 8.24065941688939e-01, 8.28053501868532e-01, 8.32900071579870e-01, 8.38699586575474e-01, 8.45541223590310e-01, 8.53507040609252e-01, 8.62669665762836e-01, 8.73090098389325e-01, 8.84815683732401e-01, 8.97878318988171e-01, 9.12292943068421e-01, 9.28056355648415e-01, 9.45146402996031e-01, 9.63521558948635e-01, 9.83120919457849e-01, 1.00386461862596e+00, 1.02565466339202e+00, 1.04837617327936e+00, 1.07189900117812e+00, 1.09607970128622e+00, 1.12076380133619e+00, 1.14578832833438e+00, 1.17098453044675e+00, 1.19618073255911e+00, 1.22120525955731e+00, 1.24588935960728e+00, 1.27007005971537e+00, 1.29359288761414e+00, 1.31631439750148e+00, 1.33810444226754e+00, 1.35884814143565e+00, 1.37844750194486e+00, 1.39682265789747e+00, 1.41391270524508e+00, 1.42967611782508e+00, 1.44409074190533e+00, 1.45715337716110e+00, 1.46887896250417e+00, 1.47929939513066e+00, 1.48846202028425e+00, 1.49642783730319e+00, 1.50326947431802e+00, 1.50906898931363e+00, 1.51391555902497e+00, 1.51790311920456e+00, 1.52112802013189e+00, 1.52368675982832e+00, 1.52567385434078e+00, 1.52717989975478e+00, 1.52828987442701e+00, 1.52908172246464e+00, 1.52962525093248e+00, 1.52998136387891e+00, 1.53020164629947e+00, 1.53032830088006e+00, 1.53039443006538e+00, 1.53042464596801e+00, 1.53043598114699e+00, 1.53043906460474e+00, 1.53043951971715e+00, 1.53043956057345e+00, 1.53044036881866e+00, 1.53044584480621e+00, 1.53046597522602e+00, 1.53051963638178e+00, 1.53063707680903e+00, 1.53086200575658e+00, 1.53125321066044e+00, 1.53188564029607e+00, 1.53285090571065e+00, 1.53425716788373e+00, 1.53622839887814e+00, 1.53890302152796e+00, 1.54243195096192e+00, 1.54697607896990e+00, 1.55270325889653e+00, 1.55978486392298e+00, 1.56839200485204e+00, 1.57869150446938e+00, 1.59084173390576e+00, 1.60498842193063e+00, 1.62126055060600e+00, 1.63976645013905e+00, 1.66059020209859e+00, 1.68378845349035e+00, 1.70938773469079e+00, 1.73738236216545e+00, 1.76773299256309e+00, 1.80036587856233e+00, 1.83517285918360e+00, 1.87201209863831e+00, 1.91070956866812e+00, 1.95106125024279e+00, 1.99283601194713e+00, 2.03577910489527e+00, 2.07961619803354e+00, 2.12405786366203e+00, 2.16880441129773e+00, 2.21355095893343e+00, 2.25799262456193e+00, 2.30182971770019e+00, 2.34477281064834e+00, 2.38654757235268e+00, 2.42689925392735e+00, 2.46559672395716e+00, 2.50243596341186e+00, 2.53724294403314e+00, 2.56987583003238e+00, 2.60022646043001e+00, 2.62822108790467e+00, 2.65382036910512e+00, 2.67701862049687e+00, 2.69784237245642e+00, 2.71634827198947e+00, 2.73262040066483e+00, 2.74676708868971e+00, 2.75891731812608e+00, 2.76921681774343e+00, 2.77782395867248e+00, 2.78490556369893e+00, 2.79063274362556e+00, 2.79517687163354e+00, 2.79870580106750e+00, 2.80138042371732e+00, 2.80335165471173e+00, 2.80475791688482e+00, 2.80572318229939e+00, 2.80635561193503e+00, 2.80674681683888e+00, 2.80697174578644e+00, 2.80708918621368e+00, 2.80714284736945e+00, 2.80716297778926e+00, 2.80716845377681e+00, 2.80716926202201e+00, 2.80716933652781e+00, 2.80717083214942e+00, 2.80718096521951e+00, 2.80721821566121e+00, 2.80731751323041e+00, 2.80753483148951e+00, 2.80795105244894e+00, 2.80867495963022e+00, 2.80984524239094e+00, 2.81163142287735e+00, 2.81423364814557e+00, 2.81788132295423e+00, 2.82283059256804e+00, 2.82936071868432e+00, 2.83776942436573e+00, 2.84836731472069e+00, 2.86147150815776e+00, 2.87739863756603e+00, 2.89645740105067e+00, 2.91894085730732e+00, 2.94511867090741e+00, 2.97522951738903e+00, 3.00947385695645e+00, 3.04800727879293e+00, 3.09093460564947e+00, 3.13830493080142e+00, 3.19010773712238e+00, 3.24627022150018e+00, 3.30665591781433e+00, 3.37106467900872e+00, 3.43923404429894e+00, 3.51084198217487e+00, 3.58551096454407e+00, 3.66281329305810e+00, 3.74227756629515e+00, 3.82339614690749e+00, 3.90563346187864e+00, 3.98843494737088e+00, 4.07123643286313e+00, 4.15347374783428e+00, 4.23459232844661e+00, 4.31405660168366e+00, 4.39135893019769e+00, 4.46602791256689e+00, 4.53763585044283e+00, 4.60580521573305e+00, 4.67021397692744e+00, 4.73059967324159e+00, 4.78676215761938e+00, 4.83856496394034e+00, 4.88593528909229e+00, 4.92886261594884e+00, 4.96739603778531e+00, 5.00164037735273e+00, 5.03175122383435e+00, 5.05792903743445e+00, 5.08041249369110e+00, 5.09947125717573e+00, 5.11539838658400e+00, 5.12850258002107e+00, 5.13910047037603e+00, 5.14750917605745e+00, 5.15403930217373e+00, 5.15898857178754e+00, 5.16263624659620e+00, 5.16523847186442e+00, 5.16702465235083e+00, 5.16819493511155e+00, 5.16891884229283e+00, 5.16933506325225e+00, 5.16955238151135e+00, 5.16965167908056e+00, 5.16968892952225e+00, 5.16969906259234e+00, 5.16970055821395e+00, 5.16970070074519e+00, 5.16970361247163e+00, 5.16972333987315e+00, 5.16979586028538e+00, 5.16998917613145e+00, 5.17041225862441e+00, 5.17122257158139e+00, 5.17263189841936e+00, 5.17491024424232e+00, 5.17838764046389e+00, 5.18345374010175e+00, 5.19055515605250e+00, 5.20019056052898e+00, 5.21290362959218e+00, 5.22927398050981e+00, 5.24990630974935e+00, 5.27541799408998e+00, 5.30642546508522e+00, 5.34352970658452e+00, 5.38730125510908e+00, 5.43826510271255e+00, 5.49688591095665e+00, 5.56355394250644e+00, 5.63857210361471e+00, 5.72214446673726e+00, 5.81436660831299e+00, 5.91521805324665e+00, 6.02455706599185e+00, 6.14211796971732e+00, 6.26751111140535e+00, 6.40022552357701e+00, 6.53963426446189e+00, 6.68500234967725e+00, 6.83549712169932e+00, 6.99020084039182e+00, 7.14812522029963e+00, 7.30822758986854e+00, 7.46942830557509e+00, 7.63062902128164e+00, 7.79073139085055e+00, 7.94865577075836e+00, 8.10335948945085e+00, 8.25385426147293e+00, 8.39922234668829e+00, 8.53863108757317e+00, 8.67134549974483e+00, 8.79673864143286e+00, 8.91429954515833e+00, 9.02363855790353e+00, 9.12449000283719e+00, 9.21671214441292e+00, 9.30028450753547e+00, 9.37530266864374e+00, 9.44197070019353e+00, 9.50059150843763e+00, 9.55155535604110e+00, 9.59532690456566e+00, 9.63243114606496e+00, 9.66343861706020e+00, 9.68895030140082e+00, 9.70958263064037e+00, 9.72595298155800e+00, 9.73866605062120e+00, 9.74830145509768e+00, 9.75540287104843e+00, 9.76046897068629e+00, 9.76394636690786e+00, 9.76622471273082e+00, 9.76763403956879e+00, 9.76844435252577e+00, 9.76886743501873e+00, 9.76906075086480e+00, 9.76913327127703e+00, 9.76915299867855e+00, 9.76915591040499e+00, 9.76915619860098e+00, 9.76916219846504e+00, 9.76920284848150e+00, 9.76935228306099e+00, 9.76975062707579e+00, 9.77062242513200e+00, 9.77229214503906e+00, 9.77519618483832e+00, 9.77989091339106e+00, 9.78705638895934e+00, 9.79749552527532e+00, 9.81212860682633e+00, 9.83198319082184e+00, 9.85817956879146e+00, 9.89191209222870e+00, 9.93442679048652e+00, 9.98699582179647e+00, 1.00508893966709e+01, 1.01273458942923e+01, 1.02175409544910e+01, 1.03225563687840e+01, 1.04433496124935e+01, 1.05807248555829e+01, 1.07353062625751e+01, 1.09075143424092e+01, 1.10975460386012e+01, 1.13053591604470e+01, 1.15306616495989e+01, 1.17729060559758e+01, 1.20312894658455e+01, 1.23047589865396e+01, 1.25920227503353e+01, 1.28915662583656e+01, 1.32016737478116e+01, 1.35204541357752e+01, 1.38458709746296e+01, 1.41757757494884e+01, 1.45079437615262e+01, 1.48401117735640e+01, 1.51700165484228e+01, 1.54954333872772e+01, 1.58142137752408e+01, 1.61243212646868e+01, 1.64238647727170e+01, 1.67111285365127e+01, 1.69845980572069e+01, 1.72429814670766e+01, 1.74852258734535e+01, 1.77105283626053e+01, 1.79183414844512e+01, 1.81083731806431e+01, 1.82805812604773e+01, 1.84351626674695e+01, 1.85725379105589e+01, 1.86933311542684e+01, 1.87983465685614e+01, 1.88885416287600e+01, 1.89649981263815e+01, 1.90288917012559e+01, 1.90814607325659e+01, 1.91239754308237e+01, 1.91577079542609e+01, 1.91839043322306e+01, 1.92037589162261e+01, 1.92183919977771e+01, 1.92288311340931e+01, 1.92359966096613e+01, 1.92406913382141e+01, 1.92435953780133e+01, 1.92452650979204e+01, 1.92461368959766e+01, 1.92465352399914e+01, 1.92466846745709e+01, 1.92467253245873e+01, 1.92467313244514e+01, 1.92467319433609e+01, 1.92467450814034e+01, 1.92468340936939e+01, 1.92471613140832e+01, 1.92480335772770e+01, 1.92499425738442e+01, 1.92535987985263e+01, 1.92599578423078e+01, 1.92702379990799e+01, 1.92859284083041e+01, 1.93087872289342e+01, 1.93408296294082e+01, 1.93843056757497e+01, 1.94416684964889e+01, 1.95155333909890e+01, 1.96086288188291e+01, 1.97237404546042e+01, 1.98636497079429e+01, 2.00310682866674e+01, 2.02285705167748e+01, 2.04585252224186e+01, 2.07230290096769e+01, 2.10238427883022e+01, 2.13623333059298e+01, 2.17394213608060e+01, 2.21555382047478e+01, 2.26105914517851e+01, 2.31039415749319e+01, 2.36343898099582e+01, 2.42001779979100e+01, 2.47990005951181e+01, 2.54280287686536e+01, 2.60839461849717e+01, 2.67629957981511e+01, 2.74610366597973e+01, 2.81736095129742e+01, 2.88960097044501e+01, 2.96233657592419e+01, 3.03507218140337e+01, 3.10731220055095e+01, 3.17856948586865e+01, 3.24837357203327e+01, 3.31627853335120e+01, 3.38187027498302e+01, 3.44477309233657e+01, 3.50465535205737e+01, 3.56123417085256e+01, 3.61427899435518e+01, 3.66361400666986e+01, 3.70911933137359e+01, 3.75073101576777e+01, 3.78843982125540e+01, 3.82228887301816e+01, 3.85237025088068e+01, 3.87882062960652e+01, 3.90181610017090e+01, 3.92156632318163e+01, 3.93830818105409e+01, 3.95229910638796e+01, 3.96381026996546e+01, 3.97311981274948e+01, 3.98050630219949e+01, 3.98624258427341e+01, 3.99059018890755e+01, 3.99379442895496e+01, 3.99608031101797e+01, 3.99764935194039e+01, 3.99867736761760e+01, 3.99931327199574e+01, 3.99967889446395e+01, 3.99986979412068e+01, 3.99995702044006e+01, 3.99998974247898e+01, 3.99999864370804e+01, 3.99999995751228e+01})
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
int FunctionDefaults< NDIM >::k
Definition mraimpl.h:3878
@ reconstructed
s coeffs at the leaves only
Definition funcdefaults.h:61
Tensor< double > FunctionDefaults< NDIM >::cell
Definition mraimpl.h:3892
void hash_combine(hashT &seed, const T &v)
Combine hash values.
Definition worldhash.h:261
std::vector< Function< TENSOR_RESULT_TYPE(T, R), NDIM > > innerXX(const Function< T, LDIM > &f, const std::vector< Function< R, KDIM > > &vg, const std::array< int, CDIM > v1, const std::array< int, CDIM > v2, int task=0)
Computes the partial scalar/inner product between two functions, returns a low-dim function.
Definition mra.h:2831
static const Slice _(0,-1, 1)
Tensor< T > inverse(const Tensor< T > &a_in)
invert general square matrix A
Definition lapack.cc:832
@ OT_SLATER
1/r
Definition operatorinfo.h:15
@ OT_GAUSS
exp(-r)
Definition operatorinfo.h:16
@ OT_F12
exp(-r2)
Definition operatorinfo.h:17
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
NDIM & f
Definition mra.h:2817
void error(const char *msg)
Definition world.cc:147
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
NDIM const Function< R, NDIM > & g
Definition mra.h:2817
std::size_t hashT
The hash value type.
Definition worldhash.h:146
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
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
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
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
Vector< double, 3 > coord_3d
Definition funcplot.h:1074
Function< T, KDIM+LDIM > hartree_product(const std::vector< Function< T, KDIM > > &left, const std::vector< Function< T, LDIM > > &right)
Performs a Hartree/outer product on the two given low-dimensional function vectors.
Definition mra.h:2068
double get_size(World &world, const std::vector< Function< T, NDIM > > &v)
Definition vmra.h:2183
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
Definition mraimpl.h:53
static long abs(long a)
Definition tensor.h:214
const double mu
Definition navstokes_cosines.cc:95
static const double b
Definition nonlinschro.cc:119
static const double d
Definition nonlinschro.cc:121
static const double a
Definition nonlinschro.cc:118
std::ostream & operator<<(std::ostream &s, const PointGroup &g)
Definition pointgroup.h:292
double Q(double a)
Definition relops.cc:20
static const double m
Definition relops.cc:9
the low-rank functor is what the LowRankFunction will represent
Definition lowrankfunction.h:465
virtual ~LRFunctorBase()
Definition lowrankfunction.h:467
virtual Tensor< T >::scalar_type norm2() const
Definition lowrankfunction.h:478
friend std::vector< Function< T, LDIM > > inner(const LRFunctorBase &functor, const std::vector< Function< T, LDIM > > &rhs, const particle< LDIM > p1, const particle< LDIM > p2)
Definition lowrankfunction.h:490
virtual Function< T, LDIM > inner(const Function< T, LDIM > &rhs, const particle< LDIM > p1, const particle< LDIM > p2) const
Definition lowrankfunction.h:471
virtual World & world() const =0
friend Function< T, LDIM > inner(const LRFunctorBase &functor, const Function< T, LDIM > &rhs, const particle< LDIM > p1, const particle< LDIM > p2)
Definition lowrankfunction.h:494
virtual std::vector< Function< T, LDIM > > inner(const std::vector< Function< T, LDIM > > &rhs, const particle< LDIM > p1, const particle< LDIM > p2) const =0
virtual T operator()(const Vector< T, NDIM > &r) const =0
evaluate the functor at a given point, e.g. for plotting
virtual std::string type() const =0
introspection
virtual void set_thresh(double thresh)
set the MRA threshold on all internal functions and reproject to the new precision
Definition lowrankfunction.h:488
Definition lowrankfunction.h:502
std::vector< Function< T, LDIM > > b
the lo-dim functions
Definition lowrankfunction.h:525
Tensor< T >::scalar_type norm2() const override
Definition lowrankfunction.h:633
std::vector< Function< T, LDIM > > inner(const std::vector< Function< T, LDIM > > &rhs, const particle< LDIM > p1, const particle< LDIM > p2) const override
Definition lowrankfunction.h:604
const std::vector< Function< T, LDIM > > & get_a() const
access the a functions (particle 1 pre-multipliers)
Definition lowrankfunction.h:533
LRFunctorF12(const std::shared_ptr< SeparatedConvolution< T, LDIM > > f12, const Function< T, LDIM > &a, const Function< T, LDIM > &b)
delegate to the other ctor with vector arguments
Definition lowrankfunction.h:517
World & world() const override
Definition lowrankfunction.h:528
std::string type() const override
introspection
Definition lowrankfunction.h:522
std::vector< Function< T, LDIM > > a
Definition lowrankfunction.h:525
const std::vector< Function< T, LDIM > > & get_b() const
access the b functions (particle 2 pre-multipliers)
Definition lowrankfunction.h:535
T operator()(const Vector< double, NDIM > &r) const override
You should implement this to return f(x).
Definition lowrankfunction.h:678
std::shared_ptr< SeparatedConvolution< T, LDIM > > f12
a two-particle function
Definition lowrankfunction.h:524
void set_thresh(double thresh) override
set the MRA threshold on all internal functions and reproject to the new precision
Definition lowrankfunction.h:537
LRFunctorF12(const std::shared_ptr< SeparatedConvolution< T, LDIM > > f12, const std::vector< Function< T, LDIM > > &a, const std::vector< Function< T, LDIM > > &b)
Definition lowrankfunction.h:504
const std::shared_ptr< SeparatedConvolution< T, LDIM > > & get_f12() const
access the F12 operator
Definition lowrankfunction.h:531
std::string type() const override
introspection
Definition lowrankfunction.h:732
LRFunctorPure(const Function< T, NDIM > &f)
Definition lowrankfunction.h:718
Function< T, NDIM > f
a hi-dim function
Definition lowrankfunction.h:725
void set_thresh(double thresh) override
set the MRA threshold on all internal functions and reproject to the new precision
Definition lowrankfunction.h:721
World & world() const override
Definition lowrankfunction.h:719
std::vector< Function< T, LDIM > > inner(const std::vector< Function< T, LDIM > > &rhs, const particle< LDIM > p1, const particle< LDIM > p2) const override
Definition lowrankfunction.h:727
T operator()(const Vector< double, NDIM > &r) const override
evaluate the functor at a given point, e.g. for plotting
Definition lowrankfunction.h:735
Tensor< T >::scalar_type norm2() const override
Definition lowrankfunction.h:739
Definition lowrankfunction.h:1482
std::vector< Function< T, LDIM > > h_ortho
orthonormalized h
Definition lowrankfunction.h:1484
long rank() const
Definition lowrankfunction.h:1490
double f_norm_sq
cached ||f||^2 for Pythagoras l2error
Definition lowrankfunction.h:1488
std::vector< Function< T, LDIM > > g
reprojected g
Definition lowrankfunction.h:1485
Tensor< T > ovlp_h
cached <h_raw|h_raw>
Definition lowrankfunction.h:1486
double tol
Definition lowrankfunction.h:1487
std::vector< Function< T, LDIM > > h_raw
backprojected h (before orthonorm)
Definition lowrankfunction.h:1483
double orig_ld
Definition lowrankfunction.h:1524
double orig_nd
Definition lowrankfunction.h:1524
~ThreshGuard()
Definition lowrankfunction.h:1533
ThreshGuard(double tight, LRFunctorBase< T, NDIM > &f)
Definition lowrankfunction.h:1526
LRFunctorBase< T, NDIM > & functor
Definition lowrankfunction.h:1525
Definition lowrankfunction.h:1383
std::vector< Function< T, LDIM > > Y
Definition lowrankfunction.h:1384
std::vector< std::size_t > significant_indices
Definition lowrankfunction.h:1386
std::vector< double > norms
Definition lowrankfunction.h:1385
Definition lowrankfunction.h:22
std::vector< double > tempered() const
Definition lowrankfunction.h:69
static constexpr char const * tag
Definition lowrankfunction.h:23
double tol() const
Definition lowrankfunction.h:63
int lmax() const
Definition lowrankfunction.h:65
void set_defaults()
Definition lowrankfunction.h:37
int optimize() const
Definition lowrankfunction.h:64
double gamma() const
Definition lowrankfunction.h:61
double volume_element() const
Definition lowrankfunction.h:62
LowRankFunctionParameters(World &world, const commandlineparser &parser)
Definition lowrankfunction.h:30
std::string get_tag() const override
Definition lowrankfunction.h:51
std::string gridtype() const
Definition lowrankfunction.h:66
LowRankFunctionParameters()
Definition lowrankfunction.h:25
std::string f12type() const
Definition lowrankfunction.h:68
void read_and_set_derived_values(World &world, const commandlineparser &parser, std::string tag)
Definition lowrankfunction.h:56
double radius() const
Definition lowrankfunction.h:60
double thresh
Definition operatorinfo.h:68
double lo
Definition operatorinfo.h:67
Definition cloud.h:70
long total_n
Definition lowrankfunction.h:228
long index
Definition lowrankfunction.h:226
void operator++()
Definition lowrankfunction.h:273
bool operator()() const
Definition lowrankfunction.h:277
Vector< double, NDIM > hivec
Definition lowrankfunction.h:224
long n_per_dim
Definition lowrankfunction.h:227
cartesian_grid(const double volume_per_gridpoint, const double radius)
Definition lowrankfunction.h:231
cartesian_grid & operator=(const cartesian_grid< NDIM > &other)
Definition lowrankfunction.h:251
double volume_per_gridpoint() const
Definition lowrankfunction.h:267
void initialize(const double lo, const double hi)
Definition lowrankfunction.h:257
Vector< double, NDIM > lovec
Definition lowrankfunction.h:224
Vector< double, NDIM > increment
Definition lowrankfunction.h:229
Vector< double, NDIM > get_coordinates() const
Definition lowrankfunction.h:281
std::vector< long > stride
Definition lowrankfunction.h:225
cartesian_grid(const long n_per_dim, const double lo, const double hi)
Definition lowrankfunction.h:241
cartesian_grid(const cartesian_grid< NDIM > &other)
Definition lowrankfunction.h:246
very simple command line parser
Definition commandlineparser.h:28
Definition lowrankfunction.h:387
std::array< int, PDIM > dims
Definition lowrankfunction.h:388
particle(const int p1, const int p2, const int p3)
Definition lowrankfunction.h:415
particle complement() const
return the other particle
Definition lowrankfunction.h:407
static particle particle1()
convenience for particle 1 (the left/first particle)
Definition lowrankfunction.h:394
bool is_first() const
assuming two particles only
Definition lowrankfunction.h:434
std::array< int, PDIM > get_array() const
type conversion to std::array
Definition lowrankfunction.h:428
bool is_last() const
assuming two particles only
Definition lowrankfunction.h:436
particle(const std::vector< int > p)
Definition lowrankfunction.h:416
static particle particle2()
convenience for particle 2 (the right/second particle)
Definition lowrankfunction.h:400
particle(const int p)
Definition lowrankfunction.h:413
std::string str() const
Definition lowrankfunction.h:420
particle()=default
default constructor
particle(const int p1, const int p2)
Definition lowrankfunction.h:414
std::enable_if_t< DUMMYDIM==2, std::tuple< int, int > > get_tuple() const
Definition lowrankfunction.h:444
std::enable_if_t< DUMMYDIM==3, std::tuple< int, int, int > > get_tuple() const
Definition lowrankfunction.h:448
std::enable_if_t< DUMMYDIM==1, std::tuple< int > > get_tuple() const
Definition lowrankfunction.h:440
Definition timing_utilities.h:9
double tag(const std::string msg)
Definition timing_utilities.h:45
bool do_print
Definition timing_utilities.h:12
InputParameters param
Definition tdse.cc:203
static const double omega
Definition tdse_example.cc:51
hashT hash_value(const Key &key)
Definition test_hashdc.cc:67
void split(const Range< ConcurrentHashMap< int, int >::iterator > &range)
Definition test_hashthreaded.cc:63
double dist(const Vector< double, 3 > v1, const Vector< double, 3 > v2)
distance between v1 and v2
Definition test_localizer.cc:38
void e()
Definition test_sig.cc:75
static double g2(const Vector< double, D > &r)
Definition test_state_archive_hdf5.cpp:38
double aa
Definition testbsh.cc:68
std::vector< double > fit(size_t m, size_t n, const std::vector< double > N, const std::vector< double > &f)
Definition testfuns.cc:36
constexpr coord_t one(1.0)
constexpr std::size_t NDIM
Definition testgconv.cc:54
static Molecule molecule
Definition testperiodicdft.cc:39
Defines operations on vectors of Functions.
const double zeta
Definition vnucso.cc:82