forked from fmihpc/vlasiator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spatial_cell.cpp
1479 lines (1274 loc) · 67.7 KB
/
spatial_cell.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
/*
* This file is part of Vlasiator.
* Copyright 2010-2016 Finnish Meteorological Institute
*
* For details of usage, see the COPYING file and read the "Rules of the Road"
* at http://www.physics.helsinki.fi/vlasiator/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <unordered_set>
#include "spatial_cell.hpp"
#include "velocity_blocks.h"
#include "object_wrapper.h"
#ifndef NDEBUG
#define DEBUG_SPATIAL_CELL
#endif
using namespace std;
namespace spatial_cell {
int SpatialCell::activePopID = 0;
uint64_t SpatialCell::mpi_transfer_type = 0;
bool SpatialCell::mpiTransferAtSysBoundaries = false;
bool SpatialCell::mpiTransferInAMRTranslation = false;
int SpatialCell::mpiTransferXYZTranslation = 0;
SpatialCell::SpatialCell() {
// Block list and cache always have room for all blocks
this->sysBoundaryLayer=0; // Default value, layer not yet initialized
for (unsigned int i=0; i<WID3; ++i) null_block_data[i] = 0.0;
// reset spatial cell parameters
for (unsigned int i = 0; i < CellParams::N_SPATIAL_CELL_PARAMS; i++) {
this->parameters[i]=0.0;
}
// reset BVOL derivatives
for (unsigned int i = 0; i < bvolderivatives::N_BVOL_DERIVATIVES; i++) {
this->derivativesBVOL[i]=0;
}
for (unsigned int i = 0; i < MAX_NEIGHBORS_PER_DIM; ++i) {
this->neighbor_number_of_blocks[i] = 0;
this->neighbor_block_data[i] = NULL;
}
//is transferred by default
this->mpiTransferEnabled=true;
// Set correct number of populations
populations.resize(getObjectWrapper().particleSpecies.size());
// Set velocity meshes
for (uint popID=0; popID<populations.size(); ++popID) {
const species::Species& spec = getObjectWrapper().particleSpecies[popID];
populations[popID].vmesh.initialize(spec.velocityMesh);
populations[popID].velocityBlockMinValue = spec.sparseMinValue;
populations[popID].N_blocks = 0;
}
}
/** Adds "important" and removes "unimportant" velocity blocks
* to/from this cell.
*
* velocity_block_with_content_list needs to be up to date in local and remote cells.
* velocity_block_with_no_content_list needs to be up to date in local cells.
*
* update_velocity_block_with_content_lists() should have
* been called with the current distribution function values, and then the contetn list transferred.
*
* Removes all velocity blocks from this spatial cell which don't
* have content and don't have spatial or velocity neighbors with
* content. Adds neighbors for all velocity blocks which do have
* content (including spatial neighbors). All cells in
* spatial_neighbors are assumed to be neighbors of this cell.
*
* This function is thread-safe when called for different cells
* per thread. We need the block_has_content vector from
* neighbouring cells, but these are not written to here. We only
* modify local cell.
*
* NOTE: The VAMR mesh must be valid, otherwise this function will
* remove some blocks that should not be removed.*/
#ifndef VAMR
void SpatialCell::adjust_velocity_blocks(const std::vector<SpatialCell*>& spatial_neighbors,
const uint popID,bool doDeleteEmptyBlocks) {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
// This set contains all those cellids which have neighbors in any
// of the 6-dimensions Actually, we would only need to add
// local blocks with no content here, as blocks with content
// do not need to be created and also will not be removed as
// we only check for removal for blocks with no content
std::unordered_set<vmesh::GlobalID> neighbors_have_content;
//add neighbor content info for velocity space neighbors to map. We loop over blocks
//with content and raise the neighbors_have_content for
//itself, and for all its neighbors
for (vmesh::LocalID block_index=0; block_index<velocity_block_with_content_list.size(); ++block_index) {
vmesh::GlobalID block = velocity_block_with_content_list[block_index];
const uint8_t refLevel=0;
const velocity_block_indices_t indices = SpatialCell::get_velocity_block_indices(popID,block);
neighbors_have_content.insert(block); //also add the cell itself
int addWidthV = getObjectWrapper().particleSpecies[popID].sparseBlockAddWidthV;
for (int offset_vx=-addWidthV;offset_vx<=addWidthV;offset_vx++) {
for (int offset_vy=-addWidthV;offset_vy<=addWidthV;offset_vy++) {
for (int offset_vz=-addWidthV;offset_vz<=addWidthV;offset_vz++) {
const vmesh::GlobalID neighbor_block
= get_velocity_block(popID,{{indices[0]+offset_vx,indices[1]+offset_vy,indices[2]+offset_vz}},refLevel);
neighbors_have_content.insert(neighbor_block); //add all potential ngbrs of this block with content
}
}
}
}
//add neighbor content info for spatial space neighbors to map. We loop over
//neighbor cell lists with existing blocks, and raise the
//flag for the local block with same block id
for (std::vector<SpatialCell*>::const_iterator neighbor=spatial_neighbors.begin();
neighbor != spatial_neighbors.end(); ++neighbor) {
for (vmesh::LocalID block_index=0; block_index<(*neighbor)->velocity_block_with_content_list.size(); ++block_index) {
vmesh::GlobalID block = (*neighbor)->velocity_block_with_content_list[block_index];
neighbors_have_content.insert(block);
}
}
// REMOVE all blocks in this cell without content + without neighbors with content
// better to do it in the reverse order, as then blocks at the
// end are removed first, and we may avoid copying extra data.
if (doDeleteEmptyBlocks) {
for (int block_index= this->velocity_block_with_no_content_list.size()-1; block_index>=0; --block_index) {
const vmesh::GlobalID blockGID = velocity_block_with_no_content_list[block_index];
#ifdef DEBUG_SPATIAL_CELL
if (blockGID == invalid_global_id()) {
cerr << "Got invalid block at " << __FILE__ << ' ' << __LINE__ << endl;
exit(1);
}
#endif
const vmesh::LocalID blockLID = get_velocity_block_local_id(blockGID,popID);
#ifdef DEBUG_SPATIAL_CELL
if (blockLID == invalid_local_id()) {
cerr << "Could not find block in " << __FILE__ << ' ' << __LINE__ << endl;
exit(1);
}
#endif
bool removeBlock = false;
std::unordered_set<vmesh::GlobalID>::iterator it = neighbors_have_content.find(blockGID);
if (it == neighbors_have_content.end()) removeBlock = true;
if (removeBlock == true) {
//No content, and also no neighbor have content -> remove
//and increment rho loss counters
const Real* block_parameters = get_block_parameters(popID)+blockLID*BlockParams::N_VELOCITY_BLOCK_PARAMS;
const Real DV3 = block_parameters[BlockParams::DVX]
* block_parameters[BlockParams::DVY]
* block_parameters[BlockParams::DVZ];
Real sum=0;
for (unsigned int i=0; i<WID3; ++i) sum += get_data(popID)[blockLID*SIZE_VELBLOCK+i];
this->populations[popID].RHOLOSSADJUST += DV3*sum;
// and finally remove block
this->remove_velocity_block(blockGID,popID);
}
}
}
// ADD all blocks with neighbors in spatial or velocity space (if it exists then the block is unchanged)
for (std::unordered_set<vmesh::GlobalID>::iterator it=neighbors_have_content.begin(); it != neighbors_have_content.end(); ++it) {
this->add_velocity_block(*it,popID);
}
}
#else // VAMR version
void SpatialCell::adjust_velocity_blocks(const std::vector<SpatialCell*>& spatial_neighbors,
const uint popID,bool doDeleteEmptyBlocks) {
// This set contains all those cell ids which have neighbors in any
// of the 6-dimensions Actually, we would only need to add
// local blocks with no content here, as blocks with content
// do not need to be created and also will not be removed as
// we only check for removal for blocks with no content
std::unordered_set<vmesh::GlobalID> neighbors_have_content;
for (vmesh::LocalID block_index=0; block_index<velocity_block_with_content_list.size(); ++block_index) {
vmesh::GlobalID blockGID = velocity_block_with_content_list[block_index];
vector<vmesh::GlobalID> neighborGIDs;
populations[popID].vmesh.getNeighborsExistingAtSameLevel(blockGID,neighborGIDs);
neighbors_have_content.insert(neighborGIDs.begin(),neighborGIDs.end());
neighbors_have_content.insert(blockGID);
}
//add neighbor content info for spatial space neighbors to map. We loop over
//neighbor cell lists with existing blocks, and raise the
//flag for the local block with same block id
unordered_set<vmesh::GlobalID> spat_nbr_has_content;
for (std::vector<SpatialCell*>::const_iterator neighbor=spatial_neighbors.begin();
neighbor != spatial_neighbors.end(); ++neighbor) {
for (vmesh::LocalID block_index=0; block_index<(*neighbor)->velocity_block_with_content_list.size(); ++block_index) {
vmesh::GlobalID block = (*neighbor)->velocity_block_with_content_list[block_index];
spat_nbr_has_content.insert(block);
}
}
// REMOVE all blocks in this cell without content + without neighbors with content
// better to do it in the reverse order, as then blocks at the
// end are removed first, and we may avoid copying extra data.
if (doDeleteEmptyBlocks) {
for (int block_index= this->velocity_block_with_no_content_list.size()-1; block_index>=0; --block_index) {
const vmesh::GlobalID blockGID = this->velocity_block_with_no_content_list[block_index];
#ifdef DEBUG_SPATIAL_CELL
if (blockGID == invalid_global_id()) {
cerr << "Got invalid block at " << __FILE__ << ' ' << __LINE__ << endl;
exit(1);
}
#endif
const vmesh::LocalID blockLID = get_velocity_block_local_id(blockGID,popID);
#ifdef DEBUG_SPATIAL_CELL
if (blockLID == invalid_local_id()) {
cerr << "Could not find block in " << __FILE__ << ' ' << __LINE__ << endl;
exit(1);
}
#endif
bool removeBlock = false;
// Check this block in the neighbor cells
if (neighbors_have_content.find(blockGID) != neighbors_have_content.end()) continue;
// Check the parent of this block in the neighbor cells
if (neighbors_have_content.find(populations[popID].vmesh.getParent(blockGID)) != neighbors_have_content.end()) continue;
// Check all the children of this block in the neighbor cells
std::vector<vmesh::GlobalID> children;
populations[popID].vmesh.getChildren(blockGID,children);
int counter = 0;
for (size_t c=0; c<children.size(); ++c) {
if (neighbors_have_content.find(children[c]) != neighbors_have_content.end()) ++counter;
}
if (counter > 0) continue;
// It is safe to remove this block
removeBlock = true;
if (removeBlock == true) {
//No content, and also no neighbor have content -> remove
//and increment rho loss counters
const Real* block_parameters = get_block_parameters(popID)+blockLID*BlockParams::N_VELOCITY_BLOCK_PARAMS;
const Real DV3 = block_parameters[BlockParams::DVX]
* block_parameters[BlockParams::DVY]
* block_parameters[BlockParams::DVZ];
Real sum=0;
for (unsigned int i=0; i<WID3; ++i) sum += get_data(popID)[blockLID*SIZE_VELBLOCK+i];
this->populations[popID].RHOLOSSADJUST += DV3*sum;
// and finally remove block
this->remove_velocity_block(blockGID,popID);
}
}
}
// Filter the spat_nbr_has_content list so that it doesn't
// contain overlapping blocks
unordered_set<vmesh::GlobalID> ghostBlockList;
vector<vector<vmesh::GlobalID> > sorted(populations[popID].vmesh.getMaxAllowedRefinementLevel()+1);
// First sort the list according to refinement levels. This allows
// us to skip checking the existence of children and grandchildren below.
for (unordered_set<vmesh::GlobalID>::const_iterator it=spat_nbr_has_content.begin();
it!=spat_nbr_has_content.end(); ++it) {
sorted[populations[popID].vmesh.getRefinementLevel(*it)].push_back(*it);
}
// Iterate through the sorted block list, and determine the no-content
// blocks and their correct refinement levels that must exist
for (int r=sorted.size()-1; r >= 0; --r) {
for (size_t b=0; b<sorted[r].size(); ++b) {
// If parent exists, all siblings must exist
if (r > 0) {
if (spat_nbr_has_content.find(populations[popID].vmesh.getParent(sorted[r][b])) != spat_nbr_has_content.end()) {
vector<vmesh::GlobalID> siblings;
populations[popID].vmesh.getSiblings(sorted[r][b],siblings);
ghostBlockList.insert(siblings.begin(),siblings.end());
continue;
}
}
// If grandparent exists, parent octant must exist
if (r > 1) {
vmesh::GlobalID grandParentGID = populations[popID].vmesh.getParent(populations[popID].vmesh.getParent(sorted[r][b]));
if (spat_nbr_has_content.find(grandParentGID) != spat_nbr_has_content.end()) {
vector<vmesh::GlobalID> siblings;
populations[popID].vmesh.getSiblings(populations[popID].vmesh.getParent(sorted[r][b]),siblings);
ghostBlockList.insert(siblings.begin(),siblings.end());
continue;
}
}
// Parent or grandparent does not exist, add this block
ghostBlockList.insert(sorted[r][b]);
}
}
// Add missing no-content blocks
for (unordered_set<vmesh::GlobalID>::const_iterator it=ghostBlockList.begin();
it != ghostBlockList.end(); ++it) {
// Parent already exists
if (populations[popID].vmesh.getLocalID(populations[popID].vmesh.getParent(*it)) != vmesh::VelocityMesh<vmesh::GlobalID,vmesh::LocalID>::invalidLocalID()) continue;
// If any children exist, make sure they all exist
std::vector<vmesh::GlobalID> children;
populations[popID].vmesh.getChildren(*it,children);
bool childrensExist = false;
for (size_t c=0; c<children.size(); ++c) {
if (populations[popID].vmesh.getLocalID(children[c]) != vmesh::VelocityMesh<vmesh::GlobalID,vmesh::LocalID>::invalidLocalID()) {
childrensExist = true;
break;
}
}
if (childrensExist == true) {
// Attempt to add all children, only succeeds if the
// children does not exist
for (size_t c=0; c<children.size(); ++c) add_velocity_block(children[c],popID);
continue;
}
add_velocity_block(*it,popID);
}
}
#endif
void SpatialCell::adjustSingleCellVelocityBlocks(const uint popID) {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
//neighbor_ptrs is empty as we do not have any consistent
//data in neighbours yet, adjustments done only based on velocity
//space. TODO: should this delete blocks or not? Now not
std::vector<SpatialCell*> neighbor_ptrs;
update_velocity_block_content_lists(popID);
adjust_velocity_blocks(neighbor_ptrs,popID,false);
}
void SpatialCell::coarsen_block(const vmesh::GlobalID& parent,const std::vector<vmesh::GlobalID>& children,const uint popID) {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
// First create the parent (coarse) block and grab pointer to its data.
// add_velocity_block initializes data to zero values.
if (add_velocity_block(parent,popID) == false) return;
vmesh::LocalID parentLID = populations[popID].vmesh.getLocalID(parent);
Realf* parent_data = get_data(popID)+parentLID*SIZE_VELBLOCK;
// Calculate children (fine) block local IDs, some of the children may not exist
for (size_t c=0; c<children.size(); ++c) {
vmesh::LocalID childrenLID = populations[popID].vmesh.getLocalID(children[c]);
if (childrenLID == SpatialCell::invalid_local_id()) continue;
Realf* data = get_data(popID)+childrenLID*SIZE_VELBLOCK;
const int i_oct = c % 2;
const int j_oct = (c/2) % 2;
const int k_oct = c / 4;
/*for (int k=0; k<WID; k+=2) for (int j=0; j<WID; j+=2) for (int i=0; i<WID; i+=2) {
cerr << "\t" << i_oct*2+i/2 << ' ' << j_oct*2+j/2 << ' ' << k_oct*2+k/2 << " gets values from" << endl;
// Sum the values in 8 cells that correspond to the same call in parent block
Realf sum = 0;
for (int kk=0; kk<2; ++kk) for (int jj=0; jj<2; ++jj) for (int ii=0; ii<2; ++ii) {
cerr << "\t\t" << i+ii << ' ' << j+jj << ' ' << k+kk << endl;
sum += data[vblock::index(i+ii,j+jj,k+kk)];
}
parent_data[vblock::index(i_oct*2+i/2,j_oct*2+j/2,k_oct*2+k/2)] = sum/8;
}*/
for (uint k=0; k<WID; ++k) for (uint j=0; j<WID; ++j) for (uint i=0; i<WID; ++i) {
parent_data[vblock::index(i_oct*2+i/2,j_oct*2+j/2,k_oct*2+k/2)] += data[vblock::index(i,j,k)]/8.0;
}
}
// Remove the children
for (size_t c=0; c<children.size(); ++c) {
remove_velocity_block(children[c],popID);
}
}
void SpatialCell::coarsen_blocks(vamr_ref_criteria::Base* refCriterion,const uint popID) {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
// Sort blocks according to their refinement levels
vector<vector<vmesh::GlobalID> > blocks(populations[popID].vmesh.getMaxAllowedRefinementLevel()+1);
for (vmesh::LocalID blockLID=0; blockLID<get_number_of_velocity_blocks(popID); ++blockLID) {
vmesh::GlobalID blockGID = populations[popID].vmesh.getGlobalID(blockLID);
uint8_t r = populations[popID].vmesh.getRefinementLevel(blockGID);
blocks[r].push_back(blockGID);
}
// This is how much neighbor data we use when evaluating refinement criteria
const int PAD=1;
Realf array[(WID+2*PAD)*(WID+2*PAD)*(WID+2*PAD)];
// Evaluate refinement criterion for velocity blocks, starting from
// the highest refinement level blocks
for (size_t r=blocks.size()-1; r>=1; --r) {
// List of blocks that can be coarsened
//vector<vmesh::GlobalID> coarsenList;
unordered_set<vmesh::GlobalID> coarsenList;
// Evaluate refinement criterion for all blocks
for (size_t b=0; b<blocks[r].size(); ++b) {
const vmesh::GlobalID blockGID = blocks[r][b];
fetch_data<1>(blockGID,populations[popID].vmesh,get_data(popID),array);
if (refCriterion->evaluate(array,popID) < Parameters::vamrCoarsenLimit) coarsenList.insert(blockGID);
}
// List of blocks created and removed during the coarsening. The first element (=key)
// is the global ID of the parent block that is created, the vector (=value) contains
// the global IDs of the children that will be removed
unordered_map<vmesh::GlobalID,vector<vmesh::GlobalID> > allowCoarsen;
// A block can refined only if all blocks in the octant allow it,
// and only if the octant (in which the block belongs to) neighbors
// do not have children
for (unordered_set<vmesh::GlobalID>::const_iterator it=coarsenList.begin(); it!=coarsenList.end(); ++it) {
vector<vmesh::GlobalID> siblings;
populations[popID].vmesh.getSiblings(*it,siblings);
bool allows=true;
for (size_t s=0; s<siblings.size(); ++s) {
// Skip non-existing blocks
if (populations[popID].vmesh.getLocalID(siblings[s]) == invalid_local_id()) {
continue;
}
// Check that the sibling allows coarsening
if (coarsenList.find(siblings[s]) == coarsenList.end()) {
allows = false;
break;
}
}
// Check that the mesh structure allows coarsening
if (populations[popID].vmesh.coarsenAllowed(*it) == false) continue;
// If all siblings allow coarsening, add block to coarsen list
if (allows == true) {
allowCoarsen.insert(make_pair(populations[popID].vmesh.getParent(*it),siblings));
}
}
cerr << "ref level " << r << " has " << allowCoarsen.size() << " blocks for coarsening" << endl;
for (unordered_map<vmesh::GlobalID,vector<vmesh::GlobalID> >::const_iterator it=allowCoarsen.begin(); it!=allowCoarsen.end(); ++it) {
coarsen_block(it->first,it->second,popID);
}
}
}
/*!
Returns true if given velocity block has enough of a distribution function.
Returns false if the value of the distribution function is too low in every
sense in given block.
Also returns false if given block doesn't exist or is an error block.
*/
bool SpatialCell::compute_block_has_content(const vmesh::GlobalID& blockGID,const uint popID) const {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
if (blockGID == invalid_global_id()) return false;
const vmesh::LocalID blockLID = get_velocity_block_local_id(blockGID,popID);
if (blockLID == invalid_local_id()) return false;
bool has_content = false;
const Real velocity_block_min_value = getVelocityBlockMinValue(popID);
const Realf* block_data = populations[popID].blockContainer.getData(blockLID);
for (unsigned int i=0; i<VELOCITY_BLOCK_LENGTH; ++i) {
if (block_data[i] >= velocity_block_min_value) {
has_content = true;
break;
}
}
return has_content;
}
/** Get maximum translation timestep for the given species.
* @param popID ID of the particle species.
* @return Maximum timestep calculated by the Vlasov translation.*/
const Real& SpatialCell::get_max_r_dt(const uint popID) const {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
return populations[popID].max_dt[species::MAXRDT];
}
/** Get maximum acceleration timestep for the given species.
* @param popID ID of the particle species.
* @return Maximum timestep calculated by Vlasov acceleration.*/
const Real& SpatialCell::get_max_v_dt(const uint popID) const {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
return populations[popID].max_dt[species::MAXVDT];
}
/** Get MPI datatype for sending the cell data.
* @param cellID Spatial cell (dccrg) ID.
* @param sender_rank Rank of the MPI process sending data from this cell.
* @param receiver_rank Rank of the MPI process receiving data to this cell.
* @param receiving If true, this process is receiving data.
* @param neighborhood Neighborhood ID.
* @return MPI datatype that transfers the requested data.*/
std::tuple<void*, int, MPI_Datatype> SpatialCell::get_mpi_datatype(
const CellID cellID,
const int sender_rank,
const int receiver_rank,
const bool receiving,
const int neighborhood
) {
std::vector<MPI_Aint> displacements;
std::vector<int> block_lengths;
// create datatype for actual data if we are in the first two
// layers around a boundary, or if we send for the whole system
// in AMR translation, only send the necessary cells
if (this->mpiTransferEnabled && ((SpatialCell::mpiTransferAtSysBoundaries==false && SpatialCell::mpiTransferInAMRTranslation==false) ||
(SpatialCell::mpiTransferAtSysBoundaries==true && (this->sysBoundaryLayer ==1 || this->sysBoundaryLayer ==2)) ||
(SpatialCell::mpiTransferInAMRTranslation==true &&
this->parameters[CellParams::AMR_TRANSLATE_COMM_X+SpatialCell::mpiTransferXYZTranslation]==true ))) {
//add data to send/recv to displacement and block length lists
if ((SpatialCell::mpi_transfer_type & Transfer::VEL_BLOCK_LIST_STAGE1) != 0) {
//first copy values in case this is the send operation
populations[activePopID].N_blocks = populations[activePopID].blockContainer.size();
// send velocity block list size
displacements.push_back((uint8_t*) &(populations[activePopID].N_blocks) - (uint8_t*) this);
block_lengths.push_back(sizeof(vmesh::LocalID));
}
if ((SpatialCell::mpi_transfer_type & Transfer::VEL_BLOCK_LIST_STAGE2) != 0) {
// STAGE1 should have been done, otherwise we have problems...
if (receiving) {
//mpi_number_of_blocks transferred earlier
populations[activePopID].vmesh.setNewSize(populations[activePopID].N_blocks);
} else {
//resize to correct size (it will avoid reallocation if it is big enough, I assume)
populations[activePopID].N_blocks = populations[activePopID].blockContainer.size();
}
// send velocity block list
displacements.push_back((uint8_t*) &(populations[activePopID].vmesh.getGrid()[0]) - (uint8_t*) this);
block_lengths.push_back(sizeof(vmesh::GlobalID) * populations[activePopID].vmesh.size());
}
if ((SpatialCell::mpi_transfer_type & Transfer::VEL_BLOCK_WITH_CONTENT_STAGE1) !=0) {
//Communicate size of list so that buffers can be allocated on receiving side
if (!receiving) this->velocity_block_with_content_list_size = this->velocity_block_with_content_list.size();
displacements.push_back((uint8_t*) &(this->velocity_block_with_content_list_size) - (uint8_t*) this);
block_lengths.push_back(sizeof(vmesh::LocalID));
}
if ((SpatialCell::mpi_transfer_type & Transfer::VEL_BLOCK_WITH_CONTENT_STAGE2) !=0) {
if (receiving) {
this->velocity_block_with_content_list.resize(this->velocity_block_with_content_list_size);
}
//velocity_block_with_content_list_size should first be updated, before this can be done (STAGE1)
displacements.push_back((uint8_t*) &(this->velocity_block_with_content_list[0]) - (uint8_t*) this);
block_lengths.push_back(sizeof(vmesh::GlobalID)*this->velocity_block_with_content_list_size);
}
if ((SpatialCell::mpi_transfer_type & Transfer::VEL_BLOCK_DATA) !=0) {
displacements.push_back((uint8_t*) get_data(activePopID) - (uint8_t*) this);
block_lengths.push_back(sizeof(Realf) * VELOCITY_BLOCK_LENGTH * populations[activePopID].blockContainer.size());
}
if ((SpatialCell::mpi_transfer_type & Transfer::NEIGHBOR_VEL_BLOCK_DATA) != 0) {
/*We are actually transferring the data of a
* neighbor. The values of neighbor_block_data
* and neighbor_number_of_blocks should be set in
* solver.*/
// Send this data only to ranks that contain face neighbors
// this->neighbor_number_of_blocks has been initialized to 0, on other ranks it can stay that way.
const set<int>& ranks = this->face_neighbor_ranks[neighborhood];
if ( P::amrMaxSpatialRefLevel == 0 || receiving || ranks.find(receiver_rank) != ranks.end()) {
for ( int i = 0; i < MAX_NEIGHBORS_PER_DIM; ++i) {
displacements.push_back((uint8_t*) this->neighbor_block_data[i] - (uint8_t*) this);
block_lengths.push_back(sizeof(Realf) * VELOCITY_BLOCK_LENGTH * this->neighbor_number_of_blocks[i]);
}
}
}
// send spatial cell parameters
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_PARAMETERS)!=0){
displacements.push_back((uint8_t*) &(this->parameters[0]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * CellParams::N_SPATIAL_CELL_PARAMS);
}
// send spatial cell dimensions and coordinates
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_DIMENSIONS)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::XCRD]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 6);
}
// send BGBXVOL BGBYVOL BGBZVOL PERBXVOL PERBYVOL PERBZVOL
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_BVOL)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::BGBXVOL]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 6);
}
// send RHOM, VX, VY, VZ
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_RHOM_V)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::RHOM]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 4);
}
// send RHOM_DT2, VX_DT2, VY_DT2, VZ_DT2
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_RHOMDT2_VDT2)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::RHOM_DT2]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 4);
}
// send RHOQ
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_RHOQ)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::RHOQ]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real));
}
// send RHOQ_DT2
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_RHOQDT2)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::RHOQ_DT2]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real));
}
// send spatial cell BVOL derivatives
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_BVOL_DERIVATIVES)!=0){
displacements.push_back((uint8_t*) &(this->derivativesBVOL[0]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * bvolderivatives::N_BVOL_DERIVATIVES);
}
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_IOLOCALCELLID)!=0){
displacements.push_back((uint8_t*) &(this->ioLocalCellId) - (uint8_t*) this);
block_lengths.push_back(sizeof(uint64_t));
}
// send electron pressure gradient term components
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_GRADPE_TERM)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::EXGRADPE]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 3);
}
// send P tensor diagonal components
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_P)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::P_11]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 3);
}
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_PDT2)!=0){
displacements.push_back((uint8_t*) &(this->parameters[CellParams::P_11_DT2]) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * 3);
}
// send sysBoundaryFlag
if ((SpatialCell::mpi_transfer_type & Transfer::CELL_SYSBOUNDARYFLAG)!=0){
displacements.push_back((uint8_t*) &(this->sysBoundaryFlag) - (uint8_t*) this);
block_lengths.push_back(sizeof(uint));
displacements.push_back((uint8_t*) &(this->sysBoundaryLayer) - (uint8_t*) this);
block_lengths.push_back(sizeof(uint));
}
if ((SpatialCell::mpi_transfer_type & Transfer::VEL_BLOCK_PARAMETERS) !=0) {
displacements.push_back((uint8_t*) get_block_parameters(activePopID) - (uint8_t*) this);
block_lengths.push_back(sizeof(Real) * size(activePopID) * BlockParams::N_VELOCITY_BLOCK_PARAMS);
}
// Copy particle species metadata
if ((SpatialCell::mpi_transfer_type & Transfer::POP_METADATA) != 0) {
for (uint popID=0; popID<populations.size(); ++popID) {
displacements.push_back((uint8_t*) &(populations[popID].RHO) - (uint8_t*)this);
block_lengths.push_back(offsetof(spatial_cell::Population, N_blocks));
}
}
// Refinement parameters
if ((SpatialCell::mpi_transfer_type & Transfer::REFINEMENT_PARAMETERS)){
displacements.push_back(reinterpret_cast<uint8_t*>(this->parameters.data() + CellParams::AMR_ALPHA) - reinterpret_cast<uint8_t*>(this));
block_lengths.push_back(sizeof(Real) * (CellParams::AMR_JPERB - CellParams::AMR_ALPHA + 1)); // This is just 2, but let's be explicit
}
// Copy random number generator state variables
//if ((SpatialCell::mpi_transfer_type & Transfer::RANDOMGEN) != 0) {
// displacements.push_back((uint8_t*)get_rng_state_buffer() - (uint8_t*)this);
// block_lengths.push_back(256/8);
// displacements.push_back((uint8_t*)get_rng_data_buffer() - (uint8_t*)this);
// block_lengths.push_back(sizeof(random_data));
//}
}
void* address = this;
int count;
MPI_Datatype datatype;
if (displacements.size() > 0) {
count = 1;
MPI_Type_create_hindexed(
displacements.size(),
&block_lengths[0],
&displacements[0],
MPI_BYTE,
&datatype
);
} else {
count = 0;
datatype = MPI_BYTE;
}
const bool printMpiDatatype = false;
if(printMpiDatatype) {
int mpiSize;
int myRank;
MPI_Type_size(datatype,&mpiSize);
MPI_Comm_rank(MPI_COMM_WORLD,&myRank);
cout << myRank << " get_mpi_datatype: " << cellID << " " << sender_rank << " " << receiver_rank << " " << mpiSize << ", Nblocks = " << populations[activePopID].N_blocks << ", nbr Nblocks =";
for (uint i = 0; i < MAX_NEIGHBORS_PER_DIM; ++i) {
const set<int>& ranks = this->face_neighbor_ranks[neighborhood];
if ( receiving || ranks.find(receiver_rank) != ranks.end()) {
cout << " " << this->neighbor_number_of_blocks[i];
} else {
cout << " " << 0;
}
}
cout << " face_neighbor_ranks =";
for (const auto& rank : this->face_neighbor_ranks[neighborhood]) {
cout << " " << rank;
}
cout << endl;
}
return std::make_tuple(address,count,datatype);
}
/** Get random number generator data buffer.
* @return Random number generator data buffer.*/
//random_data* SpatialCell::get_rng_data_buffer() {
// return &rngDataBuffer;
//}
/** Get random number generator state buffer.
* @return Random number generator state buffer.*/
//char* SpatialCell::get_rng_state_buffer() {
// return rngStateBuffer;
//}
/**< Minimum value of distribution function in any phase space cell
* of a velocity block for the block to be considered to have content.
* @param popID ID of the particle species.
* @return Sparse min value for this species.*/
Real SpatialCell::getVelocityBlockMinValue(const uint popID) const {
return populations[popID].velocityBlockMinValue;
}
void SpatialCell::merge_values_recursive(const uint popID,vmesh::GlobalID parentGID,vmesh::GlobalID blockGID,
uint8_t refLevel,bool recursive,const Realf* data,
std::set<vmesh::GlobalID>& blockRemovalList) {
#ifdef DEBUG_SPATIAL_CELL
if (blockGID == invalid_global_id()) {
cerr << "merge_values_recursive called for GID=" << blockGID << " at r=" << (int)refLevel << " parent=" << parentGID << endl;
}
#endif
// Get all possible children:
vector<vmesh::GlobalID> childrenGIDs;
populations[popID].vmesh.getChildren(blockGID,childrenGIDs);
#ifdef VAMR
#warning FIXME activePopID is not correct here (VAMR, hence TBD)
#endif
// Check if any of block's children exist:
bool hasChildren = false;
for (size_t c=0; c<childrenGIDs.size(); ++c) {
if (populations[activePopID].vmesh.getLocalID(childrenGIDs[c]) != invalid_local_id()) {
hasChildren = true;
break;
}
}
/* // TEST
for (size_t c=0; c<childrenGIDs.size(); ++c) {
bool hasGrandChildren=false;
vector<vmesh::GlobalID> grandChildren;
if (vmesh.getLocalID(childrenGIDs[c]) != vmesh.invalidLocalID()) continue;
vmesh::VelocityMesh<vmesh::GlobalID,vmesh::LocalID>::getChildren(childrenGIDs[c],grandChildren);
for (size_t cc=0; cc<grandChildren.size(); ++cc) {
if (vmesh.getLocalID(grandChildren[cc]) != vmesh.invalidLocalID()) {
hasGrandChildren = true;
break;
}
}
if (hasGrandChildren==true) {
std::cerr << "block at r=" << (int)refLevel << " has lost grand children" << std::endl;
}
}
// END TEST */
// No children, try to merge values to this block:
if (hasChildren == false) {
vmesh::LocalID blockLID = populations[activePopID].vmesh.getLocalID(blockGID);
#ifdef DEBUG_SPATIAL_CELL
if (blockLID == invalid_local_id()) {
cerr << "ERROR: Failed to merge values, block does not exist!" << endl;
cerr << "\t exiting from " << __FILE__ << ':' << __LINE__ << endl;
exit(1);
}
#endif
Realf* myData = populations[activePopID].blockContainer.getData(blockLID);
if (parentGID == blockGID) {
// If we enter here, the block is at the lowest refinement level.
// If the block does not have enough content, flag it for removal
//#warning REMOVED for debugging
/*for (unsigned int i=0; i<WID3; ++i) {
if (myData[i] >= SpatialCell::velocity_block_min_value) return;
}
blockRemovalList.insert(blockGID);*/
} else {
// Merge values to this block
for (uint i=0; i<WID3; ++i) myData[i] += data[i];
}
return;
}
// Iterate over all octants, each octant corresponds to a different child:
for (int k_oct=0; k_oct<2; ++k_oct) for (int j_oct=0; j_oct<2; ++j_oct) for (int i_oct=0; i_oct<2; ++i_oct) {
// Copy data belonging to the octant to a temporary array:
Realf array[WID3];
for (uint k=0; k<WID; ++k) for (uint j=0; j<WID; ++j) for (uint i=0; i<WID; ++i) {
array[vblock::index(i,j,k)] = data[vblock::index(i_oct*2+i/2,j_oct*2+j/2,k_oct*2+k/2)];
}
// Send the data to the child:
const int octant = k_oct*4 + j_oct*2 + i_oct;
merge_values_recursive(popID,blockGID,childrenGIDs[octant],refLevel+1,true,array,blockRemovalList);
}
// Data merged to children, block can be removed
blockRemovalList.insert(blockGID);
}
void SpatialCell::merge_values(const uint popID) {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
const uint8_t maxRefLevel = populations[popID].vmesh.getMaxAllowedRefinementLevel();
for (uint i=0; i<WID3; ++i) null_block_data[i] = 0;
// Sort blocks according to their refinement levels:
vector<vector<vmesh::GlobalID> > blocks(maxRefLevel+1);
for (vmesh::LocalID blockLID=0; blockLID<get_number_of_velocity_blocks(popID); ++blockLID) {
const vmesh::GlobalID blockGID = populations[popID].vmesh.getGlobalID(blockLID);
if (blockGID == SpatialCell::invalid_global_id()) {
cerr << "got invalid global id from mesh!" << endl;
continue;
}
uint8_t refLevel = populations[popID].vmesh.getRefinementLevel(blockGID);
blocks[refLevel].push_back(blockGID);
}
set<vmesh::GlobalID> blockRemovalList;
for (uint8_t refLevel=0; refLevel<blocks.size()-1; ++refLevel) {
for (size_t b=0; b<blocks[refLevel].size(); ++b) {
const vmesh::GlobalID blockGID = blocks[refLevel][b];
const vmesh::LocalID blockLID = populations[popID].vmesh.getLocalID(blockGID);
if (blockLID == invalid_local_id()) continue;
const Realf* data = populations[popID].blockContainer.getData(blockLID);
merge_values_recursive(popID,blockGID,blockGID,refLevel,true,data,blockRemovalList);
}
}
cerr << "should remove " << blockRemovalList.size() << " blocks" << endl;
for (set<vmesh::GlobalID>::const_iterator it=blockRemovalList.begin(); it!=blockRemovalList.end(); ++it) {
//remove_velocity_block(*it);
}
}
void SpatialCell::add_values(const vmesh::GlobalID& targetGID,
std::unordered_map<vmesh::GlobalID,Realf[(WID+2)*(WID+2)*(WID+2)]>& sourceData,
const uint popID) {
#ifdef DEBUG_SPATIAL_CELL
if (popID >= populations.size()) {
std::cerr << "ERROR, popID " << popID << " exceeds populations.size() " << populations.size() << " in ";
std::cerr << __FILE__ << ":" << __LINE__ << std::endl;
exit(1);
}
#endif
vmesh::LocalID targetLID = get_velocity_block_local_id(targetGID,popID);
if (targetLID == SpatialCell::invalid_local_id()) {
std::cerr << "error has occurred" << std::endl;
return;
}
Realf* targetData = get_data(popID)+targetLID*SIZE_VELBLOCK;
// Add data from all same level blocks
vector<vmesh::GlobalID> neighborIDs;
populations[popID].vmesh.getNeighborsAtSameLevel(targetGID,neighborIDs);
std::unordered_map<vmesh::GlobalID,Realf[(WID+2)*(WID+2)*(WID+2)]>::iterator it;
it = sourceData.find(neighborIDs[vblock::nbrIndex( 0, 0, 0)]); // This block
if (it != sourceData.end()) {
Realf* source = it->second;
for (uint k=0; k<WID; ++k) for (uint j=0; j<WID; ++j) for (uint i=0; i<WID; ++i) {
targetData[vblock::index(i,j,k)] += source[vblock::padIndex<1>(i+1,j+1,k+1)];
}
}
// ***** face neighbors ***** //
for (int i_off=-1; i_off<2; i_off+=2) {
it = sourceData.find(neighborIDs[vblock::nbrIndex(i_off,0,0)]);
if (it == sourceData.end()) continue;
uint i_trgt = 0;
uint i_src = WID+1;
if (i_off > 0) {i_trgt = WID-1; i_src=0;}
Realf* source = it->second;
for (uint k=0; k<WID; ++k) for (uint j=0; j<WID; ++j) {
targetData[vblock::index(i_trgt,j,k)] += source[vblock::padIndex<1>(i_src,j+1,k+1)];
}
}