forked from ORNL/TASMANIAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsgGridLocalPolynomial.cpp
1976 lines (1745 loc) · 89.7 KB
/
tsgGridLocalPolynomial.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017, Miroslav Stoyanov
*
* This file is part of
* Toolkit for Adaptive Stochastic Modeling And Non-Intrusive ApproximatioN: TASMANIAN
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* 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.
*
* UT-BATTELLE, LLC AND THE UNITED STATES GOVERNMENT MAKE NO REPRESENTATIONS AND DISCLAIM ALL WARRANTIES, BOTH EXPRESSED AND IMPLIED.
* 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,
* 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.
* 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,
* IN WHOLE OR IN PART THE USE, STORAGE OR DISPOSAL OF THE SOFTWARE.
*/
#ifndef __TASMANIAN_SPARSE_GRID_LPOLY_CPP
#define __TASMANIAN_SPARSE_GRID_LPOLY_CPP
#include "tsgGridLocalPolynomial.hpp"
#include "tsgTPLWrappers.hpp"
namespace TasGrid{
template<bool iomode> void GridLocalPolynomial::write(std::ostream &os) const{
if (iomode == mode_ascii){ os << std::scientific; os.precision(17); }
IO::writeNumbers<iomode, IO::pad_line>(os, num_dimensions, num_outputs, order, top_level);
IO::writeRule<iomode>(RuleLocal::getRule(effective_rule), os);
IO::writeFlag<iomode, IO::pad_auto>(!points.empty(), os);
if (!points.empty()) points.write<iomode>(os);
if (iomode == mode_ascii){ // backwards compatible: surpluses and needed, or needed and surpluses
IO::writeFlag<iomode, IO::pad_auto>((surpluses.getNumStrips() != 0), os);
if (!surpluses.empty()) surpluses.writeVector<iomode, IO::pad_line>(os);
IO::writeFlag<iomode, IO::pad_auto>(!needed.empty(), os);
if (!needed.empty()) needed.write<iomode>(os);
}else{
IO::writeFlag<iomode, IO::pad_auto>(!needed.empty(), os);
if (!needed.empty()) needed.write<iomode>(os);
IO::writeFlag<iomode, IO::pad_auto>((surpluses.getNumStrips() != 0), os);
if (!surpluses.empty()) surpluses.writeVector<iomode, IO::pad_line>(os);
}
IO::writeFlag<iomode, IO::pad_auto>((parents.getNumStrips() != 0), os);
if (!parents.empty()) parents.writeVector<iomode, IO::pad_line>(os);
IO::writeNumbers<iomode, IO::pad_rspace>(os, static_cast<int>(roots.size()));
if (roots.size() > 0){ // the tree is empty, can happend when using dynamic construction
IO::writeVector<iomode, IO::pad_line>(roots, os);
IO::writeVector<iomode, IO::pad_line>(pntr, os);
IO::writeVector<iomode, IO::pad_line>(indx, os);
}
if (num_outputs > 0) values.write<iomode>(os);
}
template void GridLocalPolynomial::write<mode_ascii>(std::ostream &) const;
template void GridLocalPolynomial::write<mode_binary>(std::ostream &) const;
GridLocalPolynomial::GridLocalPolynomial(AccelerationContext const *acc, int cnum_dimensions, int cnum_outputs, int depth, int corder, TypeOneDRule crule, const std::vector<int> &level_limits)
: BaseCanonicalGrid(acc, cnum_dimensions, cnum_outputs, MultiIndexSet(), MultiIndexSet(), StorageSet()),
order(corder),
effective_rule(RuleLocal::getEffectiveRule(order, (crule == rule_semilocalp and order < 2) ? rule_localp : crule))
{
MultiIndexSet tensors = MultiIndexManipulations::selectTensors((size_t) num_dimensions, depth, type_level, [&](int i) -> int{ return i; }, std::vector<int>(), level_limits);
switch(effective_rule) {
case RuleLocal::erule::pwc:
needed = MultiIndexManipulations::generateNestedPoints(tensors,
[&](int l) -> int{ return RuleLocal::getNumPoints<RuleLocal::erule::pwc>(l); });
break;
case RuleLocal::erule::localp:
needed = MultiIndexManipulations::generateNestedPoints(tensors,
[&](int l) -> int{ return RuleLocal::getNumPoints<RuleLocal::erule::localp>(l); });
break;
case RuleLocal::erule::semilocalp:
needed = MultiIndexManipulations::generateNestedPoints(tensors,
[&](int l) -> int{ return RuleLocal::getNumPoints<RuleLocal::erule::semilocalp>(l); });
break;
case RuleLocal::erule::localp0:
needed = MultiIndexManipulations::generateNestedPoints(tensors,
[&](int l) -> int{ return RuleLocal::getNumPoints<RuleLocal::erule::localp0>(l); });
break;
default: // case RuleLocal::erule::localpb:
needed = MultiIndexManipulations::generateNestedPoints(tensors,
[&](int l) -> int{ return RuleLocal::getNumPoints<RuleLocal::erule::localpb>(l); });
break;
};
buildTree();
if (num_outputs == 0){
points = std::move(needed);
needed = MultiIndexSet();
parents = HierarchyManipulations::computeDAGup(points, effective_rule);
}else{
values.resize(num_outputs, needed.getNumIndexes());
}
}
GridLocalPolynomial::GridLocalPolynomial(AccelerationContext const *acc, GridLocalPolynomial const *pwpoly, int ibegin, int iend) :
BaseCanonicalGrid(acc, *pwpoly, ibegin, iend),
order(pwpoly->order),
top_level(pwpoly->top_level),
surpluses((num_outputs == pwpoly->num_outputs) ? pwpoly->surpluses : pwpoly->surpluses.splitData(ibegin, iend)),
parents(pwpoly->parents),
roots(pwpoly->roots),
pntr(pwpoly->pntr),
indx(pwpoly->indx),
effective_rule(pwpoly->effective_rule){
if (pwpoly->dynamic_values){
dynamic_values = Utils::make_unique<SimpleConstructData>(*pwpoly->dynamic_values);
if (num_outputs != pwpoly->num_outputs) dynamic_values->restrictData(ibegin, iend);
}
}
GridLocalPolynomial::GridLocalPolynomial(AccelerationContext const *acc, int cnum_dimensions, int cnum_outputs, int corder, TypeOneDRule crule,
std::vector<int> &&pnts, std::vector<double> &&vals, std::vector<double> &&surps)
: BaseCanonicalGrid(acc, cnum_dimensions, cnum_outputs, MultiIndexSet(cnum_dimensions, std::move(pnts)), MultiIndexSet(),
StorageSet(cnum_outputs, static_cast<int>(vals.size() / cnum_outputs), std::move(vals))),
order(corder),
surpluses(Data2D<double>(cnum_outputs, points.getNumIndexes(), std::move(surps))),
effective_rule(RuleLocal::getEffectiveRule(order, crule)){
buildTree();
}
struct localp_loaded{};
struct localp_needed{};
template<RuleLocal::erule eff_rule, typename points_mode>
void GridLocalPolynomial::getPoints(double *x) const {
int num_points = (std::is_same<points_mode, localp_loaded>::value) ? points.getNumIndexes() : needed.getNumIndexes();
Utils::Wrapper2D<double> split(num_dimensions, x);
#pragma omp parallel for schedule(static)
for(int i=0; i<num_points; i++) {
int const *p = (std::is_same<points_mode, localp_loaded>::value) ? points.getIndex(i) : needed.getIndex(i);
double *s = split.getStrip(i);
for(int j=0; j<num_dimensions; j++)
s[j] = RuleLocal::getNode<eff_rule>(p[j]);
}
}
void GridLocalPolynomial::getLoadedPoints(double *x) const{
using pmode = localp_loaded;
switch(effective_rule) {
case RuleLocal::erule::pwc:
getPoints<RuleLocal::erule::pwc, pmode>(x);
break;
case RuleLocal::erule::localp:
getPoints<RuleLocal::erule::localp, pmode>(x);
break;
case RuleLocal::erule::semilocalp:
getPoints<RuleLocal::erule::semilocalp, pmode>(x);
break;
case RuleLocal::erule::localp0:
getPoints<RuleLocal::erule::localp0, pmode>(x);
break;
default: // case RuleLocal::erule::localpb:
getPoints<RuleLocal::erule::localpb, pmode>(x);
break;
};
}
void GridLocalPolynomial::getNeededPoints(double *x) const{
using pmode = localp_needed;
switch(effective_rule) {
case RuleLocal::erule::pwc:
getPoints<RuleLocal::erule::pwc, pmode>(x);
break;
case RuleLocal::erule::localp:
getPoints<RuleLocal::erule::localp, pmode>(x);
break;
case RuleLocal::erule::semilocalp:
getPoints<RuleLocal::erule::semilocalp, pmode>(x);
break;
case RuleLocal::erule::localp0:
getPoints<RuleLocal::erule::localp0, pmode>(x);
break;
default: // case RuleLocal::erule::localpb:
getPoints<RuleLocal::erule::localpb, pmode>(x);
break;
};
}
void GridLocalPolynomial::getPoints(double *x) const{
if (points.empty()){ getNeededPoints(x); }else{ getLoadedPoints(x); }
}
void GridLocalPolynomial::evaluate(const double x[], double y[]) const{
std::fill_n(y, num_outputs, 0.0);
std::vector<int> sindx; // dummy variables, never references in mode 0 below
std::vector<double> svals;
walkTree<0>(points, x, sindx, svals, y);
}
void GridLocalPolynomial::evaluateBatchOpenMP(const double x[], int num_x, double y[]) const{
if (num_x == 1){ evaluate(x, y); return; }
Utils::Wrapper2D<double const> xwrap(num_dimensions, x);
Utils::Wrapper2D<double> ywrap(num_outputs, y);
#pragma omp parallel for
for(int i=0; i<num_x; i++)
evaluate(xwrap.getStrip(i), ywrap.getStrip(i));
}
void GridLocalPolynomial::evaluateBatch(const double x[], int num_x, double y[]) const{
switch(acceleration->mode){
case accel_gpu_magma:
case accel_gpu_cuda: {
acceleration->setDevice();
if ((order == -1) || (order > 2) || (num_x == 1)){
// GPU evaluations are available only for order 0, 1, and 2. Cubic will come later, but higher order will not be supported.
// cannot use GPU to accelerate the evaluation of a single vector
evaluateGpuMixed(x, num_x, y);
return;
}
GpuVector<double> gpu_x(acceleration, num_dimensions, num_x, x), gpu_result(acceleration, num_x, num_outputs);
evaluateBatchGPU(gpu_x.data(), num_x, gpu_result.data());
gpu_result.unload(acceleration, y);
break;
}
case accel_gpu_cublas: {
acceleration->setDevice();
evaluateGpuMixed(x, num_x, y);
break;
}
case accel_cpu_blas: {
if (acceleration->algorithm_select == AccelerationContext::algorithm_sparse or
(acceleration->algorithm_select == AccelerationContext::algorithm_autoselect and num_outputs <= 1024)){
evaluateBatchOpenMP(x, num_x, y);
return;
}
std::vector<int> sindx, spntr;
std::vector<double> svals;
buildSpareBasisMatrix(x, num_x, 32, spntr, sindx, svals); // build sparse matrix corresponding to x
int num_points = points.getNumIndexes();
double nnz = (double) spntr[num_x];
double total_size = ((double) num_x) * ((double) num_points);
if ((acceleration->algorithm_select == AccelerationContext::algorithm_dense)
or ((acceleration->algorithm_select == AccelerationContext::algorithm_autoselect) and (nnz / total_size > 0.1))){
// potentially wastes a lot of memory
Data2D<double> A(num_points, num_x, 0.0);
for(int i=0; i<num_x; i++){
double *row = A.getStrip(i);
for(int j=spntr[i]; j<spntr[i+1]; j++) row[sindx[j]] = svals[j];
}
TasBLAS::denseMultiply(num_outputs, num_x, num_points, 1.0, surpluses.getStrip(0), A.getStrip(0), 0.0, y);
}else{
Utils::Wrapper2D<double> ywrap(num_outputs, y);
#pragma omp parallel for
for(int i=0; i<num_x; i++){
double *this_y = ywrap.getStrip(i);
std::fill(this_y, this_y + num_outputs, 0.0);
for(int j=spntr[i]; j<spntr[i+1]; j++){
double v = svals[j];
const double *s = surpluses.getStrip(sindx[j]);
for(int k=0; k<num_outputs; k++) this_y[k] += v * s[k];
}
}
}
break;
}
default: {
evaluateBatchOpenMP(x, num_x, y);
break;
}
}
}
void GridLocalPolynomial::loadNeededValuesGPU(const double *vals){
updateValues(vals);
std::vector<int> levels = HierarchyManipulations::computeLevels(points, effective_rule);
std::vector<Data2D<int>> lpnts = HierarchyManipulations::splitByLevels(points, levels);
std::vector<Data2D<double>> lvals = HierarchyManipulations::splitByLevels(values, levels);
Data2D<double> allx(num_dimensions, points.getNumIndexes());
getPoints(allx.data());
std::vector<Data2D<double>> lx = HierarchyManipulations::splitByLevels(allx, levels);
MultiIndexSet cumulative_poitns((size_t) num_dimensions, lpnts[0].release());
StorageSet cumulative_surpluses = StorageSet(num_outputs, cumulative_poitns.getNumIndexes(), lvals[0].release());
for(size_t l = 1; l < lpnts.size(); l++){ // loop over the levels
// note that level_points.getNumIndexes() == lx[l].getNumStrips() == lvals[l].getNumStrips()
MultiIndexSet level_points(num_dimensions, lpnts[l].release());
GridLocalPolynomial upper_grid(acceleration, num_dimensions, num_outputs, order, getRule(),
std::vector<int>(cumulative_poitns.begin(), cumulative_poitns.end()), // copy cumulative_poitns
std::vector<double>(Utils::size_mult(num_outputs, cumulative_poitns.getNumIndexes())), // dummy values, will not be read or used
std::vector<double>(cumulative_surpluses.begin(), cumulative_surpluses.end())); // copy the cumulative_surpluses
Data2D<double> upper_evaluate(num_outputs, level_points.getNumIndexes());
int batch_size = 20000; // needs tuning
if (acceleration->algorithm_select == AccelerationContext::algorithm_dense){
// dense uses lots of memory, try to keep it contained to about 4GB
batch_size = 536870912 / upper_grid.getNumPoints() - 2 * (num_outputs + num_dimensions);
if (batch_size < 100) batch_size = 100; // use at least 100 points
}
for(int i=0; i<level_points.getNumIndexes(); i += batch_size)
upper_grid.evaluateBatch(lx[l].getStrip(i), std::min(batch_size, level_points.getNumIndexes() - i), upper_evaluate.getStrip(i));
double *level_surps = lvals[l].getStrip(0); // maybe use BLAS here
const double *uv = upper_evaluate.getStrip(0);
for(size_t i=0, s = upper_evaluate.getTotalEntries(); i < s; i++) level_surps[i] -= uv[i];
cumulative_surpluses.addValues(cumulative_poitns, level_points, level_surps);
cumulative_poitns += level_points;
}
surpluses = Data2D<double>(num_outputs, points.getNumIndexes(), cumulative_surpluses.release());
}
void GridLocalPolynomial::evaluateGpuMixed(const double x[], int num_x, double y[]) const{
loadGpuSurpluses<double>();
std::vector<int> sindx, spntr;
std::vector<double> svals;
if (num_x > 1){
buildSpareBasisMatrix(x, num_x, 32, spntr, sindx, svals);
}else{
walkTree<2>(points, x, sindx, svals, nullptr);
#ifdef Tasmanian_ENABLE_DPCPP
// CUDA and HIP have methods for sparse-vector times dense matrix or vector
// therefore, CUDA/HIP do not use spntr when num_x is equal to 1, but DPC++ needs to set it too
spntr = {0, static_cast<int>(sindx.size())};
#endif
}
TasGpu::sparseMultiplyMixed(acceleration, num_outputs, num_x, points.getNumIndexes(), 1.0, gpu_cache->surpluses, spntr, sindx, svals, y);
}
template<typename T> void GridLocalPolynomial::evaluateBatchGPUtempl(const T gpu_x[], int cpu_num_x, T gpu_y[]) const{
if ((order == -1) || (order > 2)) throw std::runtime_error("ERROR: GPU evaluations are availabe only for local polynomial grid with order 0, 1, and 2");
loadGpuSurpluses<T>();
int num_points = points.getNumIndexes();
if (acceleration->algorithm_select == AccelerationContext::algorithm_dense){
GpuVector<T> gpu_basis(acceleration, cpu_num_x, num_points);
evaluateHierarchicalFunctionsGPU(gpu_x, cpu_num_x, gpu_basis.data());
TasGpu::denseMultiply(acceleration, num_outputs, cpu_num_x, num_points, 1.0, getGpuCache<T>()->surpluses, gpu_basis, 0.0, gpu_y);
}else{
GpuVector<int> gpu_spntr, gpu_sindx;
GpuVector<T> gpu_svals;
buildSparseBasisMatrixGPU(gpu_x, cpu_num_x, gpu_spntr, gpu_sindx, gpu_svals);
TasGpu::sparseMultiply(acceleration, num_outputs, cpu_num_x, num_points, 1.0, getGpuCache<T>()->surpluses, gpu_spntr, gpu_sindx, gpu_svals, gpu_y);
}
}
void GridLocalPolynomial::evaluateBatchGPU(const double gpu_x[], int cpu_num_x, double gpu_y[]) const{
evaluateBatchGPUtempl(gpu_x, cpu_num_x, gpu_y);
}
void GridLocalPolynomial::evaluateBatchGPU(const float gpu_x[], int cpu_num_x, float gpu_y[]) const{
evaluateBatchGPUtempl(gpu_x, cpu_num_x, gpu_y);
}
void GridLocalPolynomial::evaluateHierarchicalFunctionsGPU(const double gpu_x[], int cpu_num_x, double *gpu_y) const{
loadGpuBasis<double>();
TasGpu::devalpwpoly(acceleration, order, RuleLocal::getRule(effective_rule), num_dimensions, cpu_num_x, getNumPoints(), gpu_x, gpu_cache->nodes.data(), gpu_cache->support.data(), gpu_y);
}
void GridLocalPolynomial::buildSparseBasisMatrixGPU(const double gpu_x[], int cpu_num_x, GpuVector<int> &gpu_spntr, GpuVector<int> &gpu_sindx, GpuVector<double> &gpu_svals) const{
loadGpuBasis<double>();
loadGpuHierarchy<double>();
TasGpu::devalpwpoly_sparse(acceleration, order, RuleLocal::getRule(effective_rule), num_dimensions, cpu_num_x, gpu_x,
gpu_cache->nodes, gpu_cache->support,
gpu_cache->hpntr, gpu_cache->hindx, gpu_cache->hroots, gpu_spntr, gpu_sindx, gpu_svals);
}
void GridLocalPolynomial::evaluateHierarchicalFunctionsGPU(const float gpu_x[], int cpu_num_x, float *gpu_y) const{
loadGpuBasis<float>();
TasGpu::devalpwpoly(acceleration, order, RuleLocal::getRule(effective_rule), num_dimensions, cpu_num_x, getNumPoints(), gpu_x, gpu_cachef->nodes.data(), gpu_cachef->support.data(), gpu_y);
}
void GridLocalPolynomial::buildSparseBasisMatrixGPU(const float gpu_x[], int cpu_num_x, GpuVector<int> &gpu_spntr, GpuVector<int> &gpu_sindx, GpuVector<float> &gpu_svals) const{
loadGpuBasis<float>();
loadGpuHierarchy<float>();
TasGpu::devalpwpoly_sparse(acceleration, order, RuleLocal::getRule(effective_rule), num_dimensions, cpu_num_x, gpu_x,
gpu_cachef->nodes, gpu_cachef->support,
gpu_cachef->hpntr, gpu_cachef->hindx, gpu_cachef->hroots, gpu_spntr, gpu_sindx, gpu_svals);
}
template<typename T> void GridLocalPolynomial::loadGpuBasis() const{
auto& ccache = getGpuCache<T>();
if (!ccache) ccache = Utils::make_unique<CudaLocalPolynomialData<T>>();
if (!ccache->nodes.empty()) return;
Data2D<double> cpu_nodes(num_dimensions, getNumPoints());
getPoints(cpu_nodes.getStrip(0));
ccache->nodes.load(acceleration, cpu_nodes.begin(), cpu_nodes.end());
Data2D<T> cpu_support = [&](void)->Data2D<T>{
const MultiIndexSet &work = (points.empty()) ? needed : points;
switch(effective_rule) {
case RuleLocal::erule::pwc:
return encodeSupportForGPU<0, rule_localp, T>(work);
case RuleLocal::erule::localp:
return (order == 1) ? encodeSupportForGPU<1, rule_localp, T>(work)
: encodeSupportForGPU<2, rule_localp, T>(work);
case RuleLocal::erule::semilocalp:
return (order == 1) ? encodeSupportForGPU<1, rule_semilocalp, T>(work)
: encodeSupportForGPU<2, rule_semilocalp, T>(work);
case RuleLocal::erule::localp0:
return (order == 1) ? encodeSupportForGPU<1, rule_localp0, T>(work)
: encodeSupportForGPU<2, rule_localp0, T>(work);
default: // case RuleLocal::erule::localpb:
return (order == 1) ? encodeSupportForGPU<1, rule_localpb, T>(work)
: encodeSupportForGPU<2, rule_localpb, T>(work);
};
}();
ccache->support.load(acceleration, cpu_support.begin(), cpu_support.end());
}
void GridLocalPolynomial::clearGpuBasisHierarchy(){
if (gpu_cache) gpu_cache->clearBasisHierarchy();
if (gpu_cachef) gpu_cachef->clearBasisHierarchy();
}
template<typename T> void GridLocalPolynomial::loadGpuHierarchy() const{
auto& ccache = getGpuCache<T>();
if (!ccache) ccache = Utils::make_unique<CudaLocalPolynomialData<T>>();
if (!ccache->hpntr.empty()) return;
ccache->hpntr.load(acceleration, pntr);
ccache->hindx.load(acceleration, indx);
ccache->hroots.load(acceleration, roots);
}
template<typename T> void GridLocalPolynomial::loadGpuSurpluses() const{
auto& ccache = getGpuCache<T>();
if (!ccache) ccache = Utils::make_unique<CudaLocalPolynomialData<T>>();
if (ccache->surpluses.size() != 0) return;
ccache->surpluses.load(acceleration, surpluses.begin(), surpluses.end());
}
void GridLocalPolynomial::clearGpuSurpluses(){
if (gpu_cache) gpu_cache->surpluses.clear();
if (gpu_cachef) gpu_cachef->surpluses.clear();
}
void GridLocalPolynomial::updateValues(double const *vals){
clearGpuSurpluses();
if (needed.empty()){
values.setValues(vals);
}else{
clearGpuBasisHierarchy();
if (points.empty()){ // initial grid, just relabel needed as points (loaded)
values.setValues(vals);
points = std::move(needed);
needed = MultiIndexSet();
}else{ // merge needed and points
values.addValues(points, needed, vals);
points += needed;
needed = MultiIndexSet();
buildTree();
}
}
}
void GridLocalPolynomial::loadNeededValues(const double *vals){
#ifdef Tasmanian_ENABLE_GPU
if (acceleration->on_gpu()){
acceleration->setDevice();
loadNeededValuesGPU(vals);
return;
}
#endif
updateValues(vals);
recomputeSurpluses();
}
void GridLocalPolynomial::mergeRefinement(){
if (needed.empty()) return; // nothing to do
clearGpuSurpluses();
int num_all_points = getNumLoaded() + getNumNeeded();
values.setValues(std::vector<double>(Utils::size_mult(num_all_points, num_outputs), 0.0));
if (points.empty()){
points = std::move(needed);
needed = MultiIndexSet();
}else{
points += needed;
needed = MultiIndexSet();
buildTree();
}
surpluses = Data2D<double>(num_outputs, num_all_points);
}
void GridLocalPolynomial::beginConstruction(){
dynamic_values = Utils::make_unique<SimpleConstructData>();
if (points.empty()){
dynamic_values->initial_points = std::move(needed);
needed = MultiIndexSet();
roots.clear();
pntr.clear();
indx.clear();
}
}
void GridLocalPolynomial::writeConstructionData(std::ostream &os, bool iomode) const{
if (iomode == mode_ascii) dynamic_values->write<mode_ascii>(os); else dynamic_values->write<mode_binary>(os);
}
void GridLocalPolynomial::readConstructionData(std::istream &is, bool iomode){
if (iomode == mode_ascii)
dynamic_values = Utils::make_unique<SimpleConstructData>(is, num_dimensions, num_outputs, IO::mode_ascii_type());
else
dynamic_values = Utils::make_unique<SimpleConstructData>(is, num_dimensions, num_outputs, IO::mode_binary_type());
}
template<RuleLocal::erule effrule>
std::vector<double> GridLocalPolynomial::getCandidateConstructionPoints(double tolerance, TypeRefinement criteria, int output,
std::vector<int> const &level_limits, double const *scale_correction){
// combine the initial points with negative weights and the refinement candidates with surplus weights (no need to normalize, the sort uses relative values)
MultiIndexSet refine_candidates = getRefinementCanidates<effrule>(tolerance, criteria, output, level_limits, scale_correction);
MultiIndexSet new_points = (dynamic_values->initial_points.empty()) ? std::move(refine_candidates) : refine_candidates - dynamic_values->initial_points;
// compute the weights for the new_points points
std::vector<double> norm = getNormalization();
int active_outputs = (output == -1) ? num_outputs : 1;
Utils::Wrapper2D<double const> scale(active_outputs, scale_correction);
std::vector<double> default_scale;
if (scale_correction == nullptr){ // if no scale provided, assume default 1.0
default_scale = std::vector<double>(Utils::size_mult(active_outputs, points.getNumIndexes()), 1.0);
scale = Utils::Wrapper2D<double const>(active_outputs, default_scale.data());
}
auto getDominantSurplus = [&](int i)-> double{
double dominant = 0.0;
const double *s = surpluses.getStrip(i);
const double *c = scale.getStrip(i);
if (output == -1){
for(int k=0; k<num_outputs; k++) dominant = std::max(dominant, c[k] * std::abs(s[k]) / norm[k]);
}else{
dominant = c[0] * std::abs(s[output]) / norm[output];
}
return dominant;
};
std::vector<double> refine_weights(new_points.getNumIndexes());
#pragma omp parallel for
for(int i=0; i<new_points.getNumIndexes(); i++){
double weight = 0.0;
std::vector<int> p = new_points.copyIndex(i);
HierarchyManipulations::touchAllImmediateRelatives<effrule>(p, points,
[&](int relative)->void{ weight = std::max(weight, getDominantSurplus(relative)); });
refine_weights[i] = weight; // those will be inverted
}
// if using stable refinement, ensure the weight of the parents is never less than the children
if (!new_points.empty() && ((criteria == refine_parents_first) || (criteria == refine_fds))){
auto rlevels = HierarchyManipulations::computeLevels<effrule>(new_points);
auto split = HierarchyManipulations::splitByLevels(new_points, rlevels);
for(auto is = split.rbegin(); is != split.rend(); is++){
for(int i=0; i<is->getNumStrips(); i++){
std::vector<int> parent(is->getStrip(i), is->getStrip(i) + num_dimensions);
double correction = refine_weights[new_points.getSlot(parent)]; // will never be missing
for(auto &p : parent){
int r = p;
p = RuleLocal::getParent<effrule>(r);
int ip = (p == -1) ? -1 : new_points.getSlot(parent); // if parent is among the refined
if (ip != -1) refine_weights[ip] += correction;
p = RuleLocal::getStepParent<effrule>(r);
ip = (p == -1) ? -1 : new_points.getSlot(parent); // if parent is among the refined
if (ip != -1) refine_weights[ip] += correction;
p = r;
}
}
}
}else if (!new_points.empty() && (criteria == refine_stable)){
// stable refinement, ensure that if level[i] < level[j] then weight[i] > weight[j]
auto rlevels = HierarchyManipulations::computeLevels<effrule>(new_points);
auto split = HierarchyManipulations::splitByLevels(new_points, rlevels);
double max_weight = 0.0;
for(auto is = split.rbegin(); is != split.rend(); is++){ // loop backwards in levels
double correction = max_weight;
for(int i=0; i<is->getNumStrips(); i++){
int idx = new_points.getSlot(std::vector<int>(is->getStrip(i), is->getStrip(i) + num_dimensions));
refine_weights[idx] += correction;
max_weight = std::max(max_weight, refine_weights[idx]);
}
}
}
// compute the weights for the initial points
std::vector<int> initial_levels = HierarchyManipulations::computeLevels<effrule>(dynamic_values->initial_points);
std::forward_list<NodeData> weighted_points;
for(int i=0; i<dynamic_values->initial_points.getNumIndexes(); i++)
weighted_points.push_front({dynamic_values->initial_points.copyIndex(i), {-1.0 / ((double) initial_levels[i])}});
for(int i=0; i<new_points.getNumIndexes(); i++)
weighted_points.push_front({new_points.copyIndex(i), {1.0 / refine_weights[i]}});
// sort and return the sorted list
weighted_points.sort([&](const NodeData &a, const NodeData &b)->bool{ return (a.value[0] < b.value[0]); });
return listToLocalNodes(weighted_points, num_dimensions, [&](int i)->double{ return RuleLocal::getNode<effrule>(i); });
}
std::vector<double> GridLocalPolynomial::getCandidateConstructionPoints(double tolerance, TypeRefinement criteria, int output,
std::vector<int> const &level_limits, double const *scale_correction) {
switch(effective_rule) {
case RuleLocal::erule::pwc:
return getCandidateConstructionPoints<RuleLocal::erule::pwc>(tolerance, criteria, output, level_limits, scale_correction);
case RuleLocal::erule::localp:
return getCandidateConstructionPoints<RuleLocal::erule::localp>(tolerance, criteria, output, level_limits, scale_correction);
case RuleLocal::erule::semilocalp:
return getCandidateConstructionPoints<RuleLocal::erule::semilocalp>(tolerance, criteria, output, level_limits, scale_correction);
case RuleLocal::erule::localp0:
return getCandidateConstructionPoints<RuleLocal::erule::localp0>(tolerance, criteria, output, level_limits, scale_correction);
default: // case RuleLocal::erule::localpb:
return getCandidateConstructionPoints<RuleLocal::erule::localpb>(tolerance, criteria, output, level_limits, scale_correction);
};
}
template<RuleLocal::erule effrule>
std::vector<int> GridLocalPolynomial::getMultiIndex(const double x[]){
std::vector<int> p(num_dimensions); // convert x to p, maybe expensive
for(int j=0; j<num_dimensions; j++){
int i = 0;
while(std::abs(RuleLocal::getNode<effrule>(i) - x[j]) > Maths::num_tol) i++;
p[j] = i;
}
return p;
}
template<RuleLocal::erule effrule>
void GridLocalPolynomial::loadConstructedPoint(const double x[], const std::vector<double> &y){
auto p = getMultiIndex<effrule>(x);
dynamic_values->initial_points.removeIndex(p);
bool isConnected = false;
HierarchyManipulations::touchAllImmediateRelatives<effrule>(p, points, [&](int)->void{ isConnected = true; });
int lvl = RuleLocal::getLevel<effrule>(p[0]);
for(int j=1; j<num_dimensions; j++) lvl += RuleLocal::getLevel<effrule>(p[j]);
if (isConnected || (lvl == 0)){
expandGrid<effrule>(p, y);
loadConstructedPoints<effrule>();
}else{
dynamic_values->data.push_front({p, y});
}
}
void GridLocalPolynomial::loadConstructedPoint(const double x[], const std::vector<double> &y){
switch(effective_rule) {
case RuleLocal::erule::pwc:
return loadConstructedPoint<RuleLocal::erule::pwc>(x, y);
case RuleLocal::erule::localp:
return loadConstructedPoint<RuleLocal::erule::localp>(x, y);
case RuleLocal::erule::semilocalp:
return loadConstructedPoint<RuleLocal::erule::semilocalp>(x, y);
case RuleLocal::erule::localp0:
return loadConstructedPoint<RuleLocal::erule::localp0>(x, y);
default: // case RuleLocal::erule::localpb:
return loadConstructedPoint<RuleLocal::erule::localpb>(x, y);
};
}
template<RuleLocal::erule effrule>
void GridLocalPolynomial::expandGrid(const std::vector<int> &point, const std::vector<double> &value){
if (points.empty()){ // only one point
points = MultiIndexSet((size_t) num_dimensions, std::vector<int>(point));
values = StorageSet(num_outputs, 1, std::vector<double>(value));
surpluses = Data2D<double>(num_outputs, 1, std::vector<double>(value)); // one value is its own surplus
}else{ // merge with existing points
// compute the surplus for the point
std::vector<double> xnode(num_dimensions);
for(int j=0; j<num_dimensions; j++)
xnode[j] = RuleLocal::getNode<effrule>(point[j]);
std::vector<double> approximation(num_outputs), surp(num_outputs);
evaluate(xnode.data(), approximation.data());
std::transform(approximation.begin(), approximation.end(), value.begin(), surp.begin(), [&](double e, double v)->double{ return v - e; });
std::vector<int> graph = getSubGraph<effrule>(point); // get the descendant nodes that must be updated later
values.addValues(points, MultiIndexSet(num_dimensions, std::vector<int>(point)), value.data()); // added the value
points.addSortedIndexes(point); // add the point
int newindex = points.getSlot(point);
surpluses.appendStrip(newindex, surp); // find the index of the new point
for(auto &g : graph) if (g >= newindex) g++; // all points belowe the newindex have been shifted down by one spot
std::vector<int> levels(points.getNumIndexes(), 0); // compute the levels, but only for the new indexes
for(auto &g : graph){
int const *pnt = points.getIndex(g);
int l = RuleLocal::getLevel<effrule>(pnt[0]);
for(int j=1; j<num_dimensions; j++) l += RuleLocal::getLevel<effrule>(pnt[j]);
levels[g] = l;
std::copy_n(values.getValues(g), num_outputs, surpluses.getStrip(g)); // reset the surpluses to the values (will be updated)
}
// compute the current DAG and update the surplused for the descendants
updateSurpluses<effrule>(points, top_level + 1, levels, HierarchyManipulations::computeDAGup<effrule>(points));
}
buildTree(); // the tree is needed for evaluate(), must be rebuild every time the points set is updated
}
template<RuleLocal::erule effrule>
void GridLocalPolynomial::loadConstructedPoint(const double x[], int numx, const double y[]){
Utils::Wrapper2D<const double> wrapx(num_dimensions, x);
std::vector<std::vector<int>> pnts(numx);
#pragma omp parallel for
for(int i=0; i<numx; i++)
pnts[i] = getMultiIndex<effrule>(wrapx.getStrip(i));
if (!dynamic_values->initial_points.empty()){
Data2D<int> combined_pnts(num_dimensions, numx);
for(int i=0; i<numx; i++)
std::copy_n(pnts[i].begin(), num_dimensions, combined_pnts.getIStrip(i));
dynamic_values->initial_points = dynamic_values->initial_points - combined_pnts;
}
Utils::Wrapper2D<const double> wrapy(num_outputs, y);
for(int i=0; i<numx; i++)
dynamic_values->data.push_front({std::move(pnts[i]), std::vector<double>(wrapy.getStrip(i), wrapy.getStrip(i) + num_outputs)});
loadConstructedPoints<effrule>();
}
void GridLocalPolynomial::loadConstructedPoint(const double x[], int numx, const double y[]){
switch(effective_rule) {
case RuleLocal::erule::pwc:
return loadConstructedPoint<RuleLocal::erule::pwc>(x, numx, y);
case RuleLocal::erule::localp:
return loadConstructedPoint<RuleLocal::erule::localp>(x, numx, y);
case RuleLocal::erule::semilocalp:
return loadConstructedPoint<RuleLocal::erule::semilocalp>(x, numx, y);
case RuleLocal::erule::localp0:
return loadConstructedPoint<RuleLocal::erule::localp0>(x, numx, y);
default: // case RuleLocal::erule::localpb:
return loadConstructedPoint<RuleLocal::erule::localpb>(x, numx, y);
};
}
template<RuleLocal::erule effrule>
void GridLocalPolynomial::loadConstructedPoints(){
Data2D<int> candidates(num_dimensions, (int) std::distance(dynamic_values->data.begin(), dynamic_values->data.end()));
for(struct{ int i; std::forward_list<NodeData>::iterator d; } p = {0, dynamic_values->data.begin()};
p.d != dynamic_values->data.end(); p.i++, p.d++){
std::copy_n(p.d->point.begin(), num_dimensions, candidates.getIStrip(p.i));
}
auto new_points = HierarchyManipulations::getLargestConnected<effrule>(points, MultiIndexSet(candidates));
if (new_points.empty()) return;
clearGpuBasisHierarchy(); // the points will change, clear the cache
clearGpuSurpluses();
auto vals = dynamic_values->extractValues(new_points);
if (points.empty()){
points = std::move(new_points);
values.setValues(std::move(vals));
}else{
values.addValues(points, new_points, vals.data());
points += new_points;
}
buildTree();
recomputeSurpluses<effrule>(); // costly, but the only option under the circumstances
}
void GridLocalPolynomial::finishConstruction(){ dynamic_values.reset(); }
template<RuleLocal::erule effrule>
std::vector<int> GridLocalPolynomial::getSubGraph(std::vector<int> const &point) const{
std::vector<int> graph, p = point;
std::vector<bool> used(points.getNumIndexes(), false);
int max_1d_kids = RuleLocal::getMaxNumKids<effrule>();
int max_kids = max_1d_kids * num_dimensions;
std::vector<int> monkey_count(1, 0), monkey_tail;
while(monkey_count[0] < max_kids){
if (monkey_count.back() < max_kids){
int dim = monkey_count.back() / max_1d_kids;
monkey_tail.push_back(p[dim]);
p[dim] = RuleLocal::getKid<effrule>(monkey_tail.back(), monkey_count.back() % max_1d_kids);
int slot = points.getSlot(p);
if ((slot == -1) || used[slot]){ // this kid is missing
p[dim] = monkey_tail.back();
monkey_tail.pop_back();
monkey_count.back()++;
}else{ // found kid, go deeper in the graph
graph.push_back(slot);
used[slot] = true;
monkey_count.push_back(0);
}
}else{
monkey_count.pop_back();
int dim = monkey_count.back() / max_1d_kids;
p[dim] = monkey_tail.back();
monkey_tail.pop_back();
monkey_count.back()++;
}
}
return graph;
}
void GridLocalPolynomial::getInterpolationWeights(const double x[], double weights[]) const{
const MultiIndexSet &work = (points.empty()) ? needed : points;
std::vector<int> active_points;
std::vector<double> hbasis_values;
std::fill_n(weights, work.getNumIndexes(), 0.0);
// construct a sparse vector and apply transpose surplus transformation
walkTree<1>(work, x, active_points, hbasis_values, nullptr);
auto ibasis = hbasis_values.begin();
for(auto i : active_points) weights[i] = *ibasis++;
applyTransformationTransposed<0>(weights, work, active_points);
}
void GridLocalPolynomial::getDifferentiationWeights(const double x[], double weights[]) const {
// Based on GridLocalPolynomial::getInterpolationWeights().
const MultiIndexSet &work = (points.empty()) ? needed : points;
std::vector<int> active_points;
std::vector<double> diff_hbasis_values;
std::fill_n(weights, work.getNumIndexes(), 0.0);
walkTree<4>(work, x, active_points, diff_hbasis_values, nullptr);
auto ibasis = diff_hbasis_values.begin();
for(auto i : active_points)
for (int d=0; d<num_dimensions; d++)
weights[i * num_dimensions + d] = *ibasis++;
applyTransformationTransposed<1>(weights, work, active_points);
}
void GridLocalPolynomial::evaluateHierarchicalFunctions(const double x[], int num_x, double y[]) const{
const MultiIndexSet &work = (points.empty()) ? needed : points;
int num_points = work.getNumIndexes();
Utils::Wrapper2D<double const> xwrap(num_dimensions, x);
Utils::Wrapper2D<double> ywrap(num_points, y);
switch(effective_rule) {
case RuleLocal::erule::pwc:
#pragma omp parallel for
for(int i=0; i<num_x; i++){
double const *this_x = xwrap.getStrip(i);
double *this_y = ywrap.getStrip(i);
bool dummy;
for(int j=0; j<num_points; j++)
this_y[j] = evalBasisSupported<RuleLocal::erule::pwc>(work.getIndex(j), this_x, dummy);
}
break;
case RuleLocal::erule::localp:
#pragma omp parallel for
for(int i=0; i<num_x; i++){
double const *this_x = xwrap.getStrip(i);
double *this_y = ywrap.getStrip(i);
bool dummy;
for(int j=0; j<num_points; j++)
this_y[j] = evalBasisSupported<RuleLocal::erule::localp>(work.getIndex(j), this_x, dummy);
}
break;
case RuleLocal::erule::semilocalp:
#pragma omp parallel for
for(int i=0; i<num_x; i++){
double const *this_x = xwrap.getStrip(i);
double *this_y = ywrap.getStrip(i);
bool dummy;
for(int j=0; j<num_points; j++)
this_y[j] = evalBasisSupported<RuleLocal::erule::semilocalp>(work.getIndex(j), this_x, dummy);
}
break;
case RuleLocal::erule::localp0:
#pragma omp parallel for
for(int i=0; i<num_x; i++){
double const *this_x = xwrap.getStrip(i);
double *this_y = ywrap.getStrip(i);
bool dummy;
for(int j=0; j<num_points; j++)
this_y[j] = evalBasisSupported<RuleLocal::erule::localp0>(work.getIndex(j), this_x, dummy);
}
break;
default: // case RuleLocal::erule::localpb:
#pragma omp parallel for
for(int i=0; i<num_x; i++){
double const *this_x = xwrap.getStrip(i);
double *this_y = ywrap.getStrip(i);
bool dummy;
for(int j=0; j<num_points; j++)
this_y[j] = evalBasisSupported<RuleLocal::erule::localpb>(work.getIndex(j), this_x, dummy);
}
break;
};
}
template<RuleLocal::erule effrule>
void GridLocalPolynomial::recomputeSurpluses() {
surpluses = Data2D<double>(num_outputs, points.getNumIndexes(), std::vector<double>(values.begin(), values.end()));
// There are two available algorithms here:
// - global sparse Kronecker (kron), implemented here in recomputeSurpluses()
// - sparse matrix in matrix-free form (mat), implemented in updateSurpluses()
//
// (kron) has the additional restriction that it will only work when the hierarchy is complete
// i.e., all point (multi-indexes) have all of their parents
// this is guaranteed for a full-tensor grid, non-adaptive grid, or a grid adapted with the stable refinement strategy
// other refinement strategies or using dynamic refinement (even with a stable refinement strategy)
// may yield a hierarchy-complete grid, but this is not mathematically guaranteed
//
// computing the dagUp allows us to check (at runtime) if the grid is_complete, and exclude (kron) if incomplete
// the completeness check can be done on the fly but it does incur cost
//
// approximate computational cost, let n be the number of points and d be the number of dimensions
// (kron) d n n^(1/d) due to standard Kronecker reasons, except it is hard to find the "effective" n due to sparsity
// (mat) d^2 n log(n) since there are d log(n) ancestors and basis functions are product of d one dimensional functions
// naturally, there are constants and those also depend on the system, e.g., number of threads, thread scheduling, cache ...
// (mat) has a more even load per thread and parallelizes better
//
// for d = 1, the algorithms are the same, except (kron) explicitly forms the matrix and the matrix free (mat) version is much better
// for d = 2, the (mat) algorithm is still faster
// for d = 3, and sufficiently large size the (mat) algorithm still wins
// the breaking point depends on n, the order and system
// for d = 4 and above, the (kron) algorithm is much faster
// it is possible that for sufficiently large n (mat) will win again
// but tested on 12 cores CPUs (Intel and AMD) up to n = 3.5 million, the (kron) method is over 2x faster
// higher dimensions will favor (kron) even more
if (num_dimensions <= 2 or (num_dimensions == 3 and points.getNumIndexes() > 2000000)) {
Data2D<int> dagUp = HierarchyManipulations::computeDAGup<effrule>(points);
std::vector<int> level = HierarchyManipulations::computeLevels<effrule>(points);
updateSurpluses<effrule>(points, top_level, level, dagUp);
return;
}
bool is_complete = true;
Data2D<int> dagUp = HierarchyManipulations::computeDAGup<effrule>(points, is_complete);
if (not is_complete) {
// incomplete hierarchy, must use the slow algorithm
std::vector<int> level = HierarchyManipulations::computeLevels<effrule>(points);
updateSurpluses<effrule>(points, top_level, level, dagUp);
return;
}
int num_nodes = 1 + *std::max_element(points.begin(), points.end());
std::vector<int> vpntr, vindx;
std::vector<double> vvals;
RuleLocal::van_matrix<effrule>(order, num_nodes, vpntr, vindx, vvals);
std::vector<std::vector<int>> map;
std::vector<std::vector<int>> lines1d;
MultiIndexManipulations::resortIndexes(points, map, lines1d);
for(int d=num_dimensions-1; d>=0; d--) {
#pragma omp parallel for schedule(dynamic)
for(int job = 0; job < static_cast<int>(lines1d[d].size() - 1); job++) {
for(int i=lines1d[d][job]+1; i<lines1d[d][job+1]; i++) {
double *row_strip = surpluses.getStrip(map[d][i]);
int row = points.getIndex(map[d][i])[d];
int im = vpntr[row];
int ijx = lines1d[d][job];
int ix = points.getIndex(map[d][ijx])[d];
while(vindx[im] < row or ix < row) {
if (vindx[im] < ix) {
++im; // move the index of the matrix pattern (missing entry)
} else if (ix < vindx[im]) {
// entry not connected, move to the next one
++ijx;
ix = points.getIndex(map[d][ijx])[d];
} else {
double const *col_strip = surpluses.getStrip(map[d][ijx]);
double const v = vvals[im];
for(int k=0; k<num_outputs; k++)
row_strip[k] -= v * col_strip[k];
++im;
++ijx;
ix = points.getIndex(map[d][ijx])[d];
}
}
}
}
}
}
void GridLocalPolynomial::recomputeSurpluses() {
switch(effective_rule) {
case RuleLocal::erule::pwc:
recomputeSurpluses<RuleLocal::erule::pwc>();
break;
case RuleLocal::erule::localp:
recomputeSurpluses<RuleLocal::erule::localp>();
break;
case RuleLocal::erule::semilocalp:
recomputeSurpluses<RuleLocal::erule::semilocalp>();
break;
case RuleLocal::erule::localp0:
recomputeSurpluses<RuleLocal::erule::localp0>();
break;
default: // case RuleLocal::erule::localpb:
recomputeSurpluses<RuleLocal::erule::localpb>();
break;
};
}