Doxygen 1.17.0
Toolkit for Adaptive Stochastic Modeling and Non-Intrusive ApproximatioN: Tasmanian v8.3
Loading...
Searching...
No Matches
tsgGridSequence.hpp
1/*
2 * Copyright (c) 2017, Miroslav Stoyanov
3 *
4 * This file is part of
5 * Toolkit for Adaptive Stochastic Modeling And Non-Intrusive ApproximatioN: TASMANIAN
6 *
7 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
12 * and the following disclaimer in the documentation and/or other materials provided with the distribution.
13 *
14 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
18 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
20 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
21 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 *
24 * UT-BATTELLE, LLC AND THE UNITED STATES GOVERNMENT MAKE NO REPRESENTATIONS AND DISCLAIM ALL WARRANTIES, BOTH EXPRESSED AND IMPLIED.
25 * THERE ARE NO EXPRESS OR IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY PATENT,
26 * COPYRIGHT, TRADEMARK, OR OTHER PROPRIETARY RIGHTS, OR THAT THE SOFTWARE WILL ACCOMPLISH THE INTENDED RESULTS OR THAT THE SOFTWARE OR ITS USE WILL NOT RESULT IN INJURY OR DAMAGE.
27 * THE USER ASSUMES RESPONSIBILITY FOR ALL LIABILITIES, PENALTIES, FINES, CLAIMS, CAUSES OF ACTION, AND COSTS AND EXPENSES, CAUSED BY, RESULTING FROM OR ARISING OUT OF,
28 * IN WHOLE OR IN PART THE USE, STORAGE OR DISPOSAL OF THE SOFTWARE.
29 */
30
31#ifndef __TASMANIAN_SPARSE_GRID_GLOBAL_NESTED_HPP
32#define __TASMANIAN_SPARSE_GRID_GLOBAL_NESTED_HPP
33
34#include "tsgGridCore.hpp"
35
36namespace TasGrid{
37
38#ifndef __TASMANIAN_DOXYGEN_SKIP
39class GridSequence final : public BaseCanonicalGrid{
40public:
41 GridSequence(AccelerationContext const *acc) : BaseCanonicalGrid(acc), rule(rule_none){}
42 friend struct GridReaderVersion5<GridSequence>;
43 GridSequence(AccelerationContext const *acc, const GridSequence *seq, int ibegin, int iend);
44 GridSequence(AccelerationContext const *acc, int cnum_dimensions, int cnum_outputs, int depth, TypeDepth type, TypeOneDRule crule, const std::vector<int> &anisotropic_weights, const std::vector<int> &level_limits);
45 GridSequence(AccelerationContext const *acc, int cnum_dimensions, int depth, TypeDepth type, TypeOneDRule crule, const std::vector<int> &anisotropic_weights, const std::vector<int> &level_limits);
46 GridSequence(AccelerationContext const *acc, MultiIndexSet &&pset, int cnum_outputs, TypeOneDRule crule);
47 ~GridSequence() = default;
48
49 GridSequence(GridSequence &&) = default;
50 GridSequence &operator = (GridSequence &&) = default;
51
52 bool isSequence() const override{ return true; }
53
54 void write(std::ostream &os, bool iomode) const override{ if (iomode == mode_ascii) write<mode_ascii>(os); else write<mode_binary>(os); }
55
56 template<bool iomode> void write(std::ostream &os) const;
57
58 void updateGrid(int depth, TypeDepth type, const std::vector<int> &anisotropic_weights, const std::vector<int> &level_limits);
59
60 TypeOneDRule getRule() const override{ return rule; }
61
62 void getLoadedPoints(double *x) const override;
63 void getNeededPoints(double *x) const override;
64 void getPoints(double *x) const override; // returns the loaded points unless no points are loaded, then returns the needed points
65
66 void getQuadratureWeights(double weights[]) const override;
67 void getInterpolationWeights(const double x[], double weights[]) const override;
68 void getDifferentiationWeights(const double x[], double weights[]) const override;
69
70 void loadNeededValues(const double *vals) override;
71
72 void evaluate(const double x[], double y[]) const override;
73 void integrate(double q[], double *conformal_correction) const override;
74 void differentiate(const double x[], double jacobian[]) const override;
75
76 void evaluateBatch(const double x[], int num_x, double y[]) const override;
77
78 void evaluateBatchGPU(const double gpu_x[], int cpu_num_x, double gpy_y[]) const override;
79 void evaluateHierarchicalFunctionsGPU(const double x[], int num_x, double y[]) const override;
80 void evaluateBatchGPU(const float gpu_x[], int cpu_num_x, float gpy_y[]) const override;
81 template<typename T> void evaluateBatchGPUtempl(const T gpu_x[], int cpu_num_x, T gpy_y[]) const;
82 void evaluateHierarchicalFunctionsGPU(const float gpu_x[], int num_x, float gpu_y[]) const override;
83
84 void evaluateHierarchicalFunctions(const double x[], int num_x, double y[]) const override;
85
86 void estimateAnisotropicCoefficients(TypeDepth type, int output, std::vector<int> &weights) const;
87 void setAnisotropicRefinement(TypeDepth type, int min_growth, int output, const std::vector<int> &level_limits);
88 void setSurplusRefinement(double tolerance, int output, const std::vector<int> &level_limits);
89 void clearRefinement() override;
90 void mergeRefinement() override;
91
92 void beginConstruction() override;
93 void writeConstructionData(std::ostream &ofs, bool) const override;
94 void readConstructionData(std::istream &ifs, bool) override;
95 std::vector<double> getCandidateConstructionPoints(TypeDepth type, const std::vector<int> &weights, const std::vector<int> &level_limits);
96 std::vector<double> getCandidateConstructionPoints(TypeDepth type, int output, const std::vector<int> &level_limits);
97 std::vector<double> getCandidateConstructionPoints(std::function<double(const int *)> getTensorWeight, const std::vector<int> &level_limits);
98 void loadConstructedPoint(const double x[], const std::vector<double> &y) override;
99 void loadConstructedPoint(const double x[], int numx, const double y[]) override;
100 void finishConstruction() override;
101
102 void setHierarchicalCoefficients(const double c[]) override;
103 void integrateHierarchicalFunctions(double integrals[]) const override;
104
105 std::vector<int> getPolynomialSpace(bool interpolation) const;
106
107 const double* getSurpluses() const;
108
109 void updateAccelerationData(AccelerationContext::ChangeType change) const override;
110
111 double getNode(int i) const{ return nodes[i]; }
112
113protected:
114 void evalHierarchicalFunctions(const double x[], double fvalues[]) const;
115
117 void prepareSequence(int num_external);
118 std::vector<double> cacheBasisIntegrals() const;
119
120 template<typename T>
121 std::vector<std::vector<T>> cacheBasisValues(const T x[]) const{
122 std::vector<std::vector<T>> cache(num_dimensions);
123 for(int j=0; j<num_dimensions; j++){
124 cache[j].resize(max_levels[j] + 1);
125 T b = 1.0;
126 T this_x = x[j];
127 cache[j][0] = b;
128 for(int i=0; i<max_levels[j]; i++){
129 b *= (this_x - nodes[i]);
130 cache[j][i+1] = b;
131 }
132 for(int i=1; i<=max_levels[j]; i++){
133 cache[j][i] /= coeff[i];
134 }
135 }
136 return cache;
137 }
138
139 template<typename T>
140 std::vector<std::vector<T>> cacheBasisDerivatives(const T x[]) const {
141 std::vector<std::vector<T>> cache(num_dimensions);
142 for(int j=0; j<num_dimensions; j++){
143 cache[j].resize(max_levels[j] + 1);
144 T this_x = x[j];
145 T b = 1.0;
146 T s = 1.0;
147 cache[j][0] = 0.0;
148 if (max_levels[j] > 0) cache[j][1] = 1.0 / coeff[1];
149 for(int i=2; i <= max_levels[j]; i++){
150 s *= (this_x - nodes[i-1]);
151 b *= (this_x - nodes[i-2]);
152 s += b;
153 cache[j][i] = s / coeff[i];
154 }
155 }
156 return cache;
157 }
158
159 std::vector<int> getMultiIndex(const double x[]);
160 void expandGrid(const std::vector<int> &point, const std::vector<double> &values, const std::vector<double> &surplus);
161 void loadConstructedPoints();
162 void recomputeSurpluses();
163
167 enum class TranspMode {
169 value,
171 derivative
172 };
173 template<TranspMode mode> void applyTransformationTransposed(double weights[]) const;
174
175 double evalBasis(const int f[], const int p[]) const; // evaluate function corresponding to f at p
176
177 void clearGpuNodes() const;
178 void clearGpuSurpluses() const;
179
180private:
181 TypeOneDRule rule;
182
183 Data2D<double> surpluses;
184 std::vector<double> nodes;
185 std::vector<double> coeff;
186
187 std::vector<int> max_levels;
188
189 // specialize below for the float case
190 std::optional<CudaSequenceData<double>>& getGpuCacheOverload(double) const{ return gpu_cache; }
191 std::optional<CudaSequenceData<float>>& getGpuCacheOverload(float) const{ return gpu_cachef; }
192 template<typename T> std::optional<CudaSequenceData<T>>& getGpuCache() const{
193 return getGpuCacheOverload(static_cast<T>(0.0));
194 }
195 template<typename T>
196 void loadGpuNodes() const{
197 auto& ccache = getGpuCache<T>();
198 if (!ccache) ccache = CudaSequenceData<T>{};
199 if (!ccache->num_nodes.empty()) return;
200
201 ccache->nodes.load(acceleration, nodes);
202 ccache->coeff.load(acceleration, coeff);
203
204 std::vector<int> num_nodes(num_dimensions);
205 std::transform(max_levels.begin(), max_levels.end(), num_nodes.begin(), [](int i)->int{ return i+1; });
206 ccache->num_nodes.load(acceleration, num_nodes);
207
208 const MultiIndexSet *work = (points.empty()) ? &needed : &points;
209 int num_points = work->getNumIndexes();
210 Data2D<int> transpoints(work->getNumIndexes(), num_dimensions);
211 for(int i=0; i<num_points; i++){
212 for(int j=0; j<num_dimensions; j++){
213 transpoints.getStrip(j)[i] = work->getIndex(i)[j];
214 }
215 }
216 ccache->points.load(acceleration, transpoints.totalSize(), transpoints.data());
217 }
218 template<typename T> void loadGpuSurpluses() const{
219 auto& ccache = getGpuCache<T>();
220 if (!ccache) ccache = CudaSequenceData<T>{};
221 if (ccache->surpluses.empty()) ccache->surpluses.load(acceleration, surpluses.totalSize(), surpluses.data());
222 }
223 mutable std::optional<CudaSequenceData<double>> gpu_cache;
224 mutable std::optional<CudaSequenceData<float>> gpu_cachef;
225
226 std::unique_ptr<SimpleConstructData> dynamic_values;
227};
228
229// Old version reader
230template<> struct GridReaderVersion5<GridSequence>{
231 template<typename iomode> static void read(std::istream &is, GridSequence *grid) {
232 grid->num_dimensions = IO::readNumber<iomode, int>(is);
233 grid->num_outputs = IO::readNumber<iomode, int>(is);
234 grid->rule = IO::readRule<iomode>(is);
235
236 if (IO::readFlag<iomode>(is)) grid->points = MultiIndexSet(is, iomode());
237 if (IO::readFlag<iomode>(is)) grid->needed = MultiIndexSet(is, iomode());
238
239 if (IO::readFlag<iomode>(is))
240 grid->surpluses = IO::readData2D<iomode, double>(is, grid->num_outputs, grid->points.getNumIndexes());
241
242 if (grid->num_outputs > 0) grid->values = StorageSet(is, iomode());
243
244 grid->prepareSequence(0);
245 }
246};
247#endif // __TASMANIAN_DOXYGEN_SKIP
248
249}
250
251#endif
TypeOneDRule
Used to specify the one dimensional family of rules that induces the sparse grid.
Definition tsgEnumerates.hpp:288
@ rule_none
Null rule, should never be used as input (default rule for an empty grid).
Definition tsgEnumerates.hpp:290
void loadNeededValues(std::function< void(double const x[], double y[], size_t thread_id)> model, TasmanianSparseGrid &grid, size_t num_threads)
Loads the current grid with model values, does not perform any refinement.
Definition tsgLoadNeededValues.hpp:104
Encapsulates the Tasmanian Sparse Grid module.
Definition TasmanianSparseGrid.hpp:68