-
Notifications
You must be signed in to change notification settings - Fork 40
/
grid.cpp
1565 lines (1345 loc) · 58.8 KB
/
grid.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 <cstdlib>
#include <iostream>
#include <iomanip> // for setprecision()
#include <cmath>
#include <vector>
#include <sstream>
#include <ctime>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "grid.h"
#include "vlasovmover.h"
#include "definitions.h"
#include "mpiconversion.h"
#include "logger.h"
#include "parameters.h"
#include "datareduction/datareducer.h"
#include "sysboundary/sysboundary.h"
#include "fieldsolver/fs_common.h"
#include "fieldsolver/gridGlue.hpp"
#include "fieldsolver/derivatives.hpp"
#include "vlasovsolver/cpu_trans_pencils.hpp"
#include "projects/project.h"
#include "iowrite.h"
#include "ioread.h"
#include "object_wrapper.h"
#ifdef PAPI_MEM
#include "papi.h"
#endif
#ifndef NDEBUG
#ifdef VAMR
#define DEBUG_VAMR_VALIDATE
#endif
#endif
using namespace std;
int globalflags::AMRstencilWidth = VLASOV_STENCIL_WIDTH;
extern Logger logFile, diagnostic;
void initVelocityGridGeometry(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid);
void initSpatialCellCoordinates(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid);
void initializeStencils(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid);
void writeVelMesh(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid) {
const vector<CellID>& cells = getLocalCells();
static int counter=0;
stringstream fname;
fname << "VelMesh.";
fname.width(3);
fname.fill(0);
fname << counter << ".vlsv";
vlsv::Writer vlsvWriter;
vlsvWriter.open(fname.str(),MPI_COMM_WORLD,0,MPI_INFO_NULL);
writeVelocityDistributionData(vlsvWriter,mpiGrid,cells,MPI_COMM_WORLD);
vlsvWriter.close();
++counter;
}
void initializeGrids(
int argn,
char **argc,
dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid,
FsGrid< std::array<Real, fsgrids::bfield::N_BFIELD>, FS_STENCIL_WIDTH> & perBGrid,
FsGrid< std::array<Real, fsgrids::bgbfield::N_BGB>, FS_STENCIL_WIDTH> & BgBGrid,
FsGrid< std::array<Real, fsgrids::moments::N_MOMENTS>, FS_STENCIL_WIDTH> & momentsGrid,
FsGrid< std::array<Real, fsgrids::moments::N_MOMENTS>, FS_STENCIL_WIDTH> & momentsDt2Grid,
FsGrid< std::array<Real, fsgrids::efield::N_EFIELD>, FS_STENCIL_WIDTH> & EGrid,
FsGrid< std::array<Real, fsgrids::egradpe::N_EGRADPE>, FS_STENCIL_WIDTH> & EGradPeGrid,
FsGrid< std::array<Real, fsgrids::volfields::N_VOL>, FS_STENCIL_WIDTH> & volGrid,
FsGrid< fsgrids::technical, FS_STENCIL_WIDTH> & technicalGrid,
SysBoundary& sysBoundaries,
Project& project
) {
int myRank;
MPI_Comm_rank(MPI_COMM_WORLD,&myRank);
// Init Zoltan:
float zoltanVersion;
if (Zoltan_Initialize(argn,argc,&zoltanVersion) != ZOLTAN_OK) {
if(myRank == MASTER_RANK) cerr << "\t ERROR: Zoltan initialization failed." << endl;
exit(1);
} else {
logFile << "\t Zoltan " << zoltanVersion << " initialized successfully" << std::endl << writeVerbose;
}
MPI_Comm comm = MPI_COMM_WORLD;
int neighborhood_size = VLASOV_STENCIL_WIDTH;
if (P::amrMaxSpatialRefLevel > 0) {
switch (VLASOV_STENCIL_WIDTH) {
case 1:
// Required cells will be included already
break;
case 2:
// looking from high to low refinement: stencil 2 will only give 1 cell, so need to add 1
neighborhood_size = VLASOV_STENCIL_WIDTH+1;
break;
case 3:
// looking from high to low refinement: stencil 3 will only give 2 cells, so need to add 2
// to reach surely into the third low-refinement neighbour
neighborhood_size = VLASOV_STENCIL_WIDTH+2;
break;
default:
std::cerr<<"Warning: unrecognized VLASOV_STENCIL_WIDTH in grid.cpp"<<std::endl;
}
}
globalflags::AMRstencilWidth = neighborhood_size;
const std::array<uint64_t, 3> grid_length = {{P::xcells_ini, P::ycells_ini, P::zcells_ini}};
dccrg::Cartesian_Geometry::Parameters geom_params;
geom_params.start[0] = P::xmin;
geom_params.start[1] = P::ymin;
geom_params.start[2] = P::zmin;
geom_params.level_0_cell_length[0] = P::dx_ini;
geom_params.level_0_cell_length[1] = P::dy_ini;
geom_params.level_0_cell_length[2] = P::dz_ini;
mpiGrid.set_initial_length(grid_length)
.set_load_balancing_method(&P::loadBalanceAlgorithm[0])
.set_neighborhood_length(neighborhood_size)
.set_maximum_refinement_level(P::amrMaxSpatialRefLevel)
.set_periodic(sysBoundaries.isPeriodic(0),
sysBoundaries.isPeriodic(1),
sysBoundaries.isPeriodic(2))
.initialize(comm)
.set_geometry(geom_params);
phiprof::Timer refineTimer {"Refine spatial cells"};
// We need this first as well
recalculateLocalCellsCache();
if (!P::isRestart) {
if (P::amrMaxSpatialRefLevel > 0 && project.refineSpatialCells(mpiGrid)) {
mpiGrid.balance_load();
recalculateLocalCellsCache();
mapRefinement(mpiGrid, technicalGrid);
}
} else {
if (readFileCells(mpiGrid, P::restartFileName)) {
mpiGrid.balance_load();
recalculateLocalCellsCache();
mapRefinement(mpiGrid, technicalGrid);
}
}
refineTimer.stop();
// Init velocity mesh on all cells
initVelocityGridGeometry(mpiGrid);
initializeStencils(mpiGrid);
for (const auto& [key, value] : P::loadBalanceOptions) {
mpiGrid.set_partitioning_option(key, value);
}
phiprof::Timer initialLBTimer {"Initial load-balancing"};
if (myRank == MASTER_RANK) logFile << "(INIT): Starting initial load balance." << endl << writeVerbose;
mpiGrid.balance_load(); // Direct DCCRG call, recalculate cache afterwards
recalculateLocalCellsCache();
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_DATA);
mpiGrid.update_copies_of_remote_neighbors(NEAREST_NEIGHBORHOOD_ID);
if(P::amrMaxSpatialRefLevel > 0) {
setFaceNeighborRanks( mpiGrid );
}
const vector<CellID>& cells = getLocalCells();
initialLBTimer.stop();
if (myRank == MASTER_RANK) {
logFile << "(INIT): Set initial state." << endl << writeVerbose;
}
phiprof::Timer initialStateTimer {"Set initial state"};
phiprof::Timer setCoordsTimer {"Set spatial cell coordinates"};
initSpatialCellCoordinates(mpiGrid);
setCoordsTimer.stop();
phiprof::Timer initBoundaryTimer {"Initialize system boundary conditions"};
sysBoundaries.initSysBoundaries(project, P::t_min);
initBoundaryTimer.stop();
SpatialCell::set_mpi_transfer_type(Transfer::CELL_DIMENSIONS);
mpiGrid.update_copies_of_remote_neighbors(SYSBOUNDARIES_NEIGHBORHOOD_ID);
// We want this before restart refinement
phiprof::Timer classifyTimer {"Classify cells (sys boundary conditions)"};
sysBoundaries.classifyCells(mpiGrid,technicalGrid);
classifyTimer.stop();
if (P::isRestart) {
logFile << "Restart from "<< P::restartFileName << std::endl << writeVerbose;
phiprof::Timer restartReadTimer {"Read restart"};
if (readGrid(mpiGrid,perBGrid,EGrid,technicalGrid,P::restartFileName) == false) {
logFile << "(MAIN) ERROR: restarting failed" << endl;
exit(1);
}
restartReadTimer.stop();
if (P::forceRefinement) {
// Adapt refinement to match new static refinement parameters
phiprof::Timer timer {"Restart refinement"};
for (int i = 0; i < P::amrMaxSpatialRefLevel; ++i) {
// (un)Refinement is done one level at a time so we don't blow up memory
if (!adaptRefinement(mpiGrid, technicalGrid, sysBoundaries, project, i)) {
cerr << "(MAIN) ERROR: Forcing refinement takes too much memory" << endl;
exit(1);
}
balanceLoad(mpiGrid, sysBoundaries);
}
} else if (P::refineOnRestart) {
// Considered deprecated
phiprof::Timer timer {"Restart refinement"};
// Get good load balancing for refinement
balanceLoad(mpiGrid, sysBoundaries);
adaptRefinement(mpiGrid, technicalGrid, sysBoundaries, project);
balanceLoad(mpiGrid, sysBoundaries);
}
}
// Check refined cells do not touch boundary cells
phiprof::Timer boundaryCheckTimer {"Check boundary refinement"};
sysBoundaries.checkRefinement(mpiGrid);
boundaryCheckTimer.stop();
if (P::isRestart) {
//initial state for sys-boundary cells, will skip those not set to be reapplied at restart
phiprof::Timer timer {"Apply system boundary conditions state"};
sysBoundaries.applyInitialState(mpiGrid, technicalGrid, perBGrid, BgBGrid, project);
}
// Update technicalGrid
technicalGrid.updateGhostCells(); // This needs to be done at some point
if (!P::isRestart && !P::writeFullBGB) {
// If we are starting a new regular simulation, we need to prepare all cells with their initial state.
// If we're only after writing out the full BGB we don't need all this shebang EXCEPT the weights!
//Initial state based on project, background field in all cells
//and other initial values in non-sysboundary cells
phiprof::Timer applyInitialTimer {"Apply initial state"};
// Go through every cell on this node and initialize the
// -Background field on all cells
// -Perturbed fields and ion distribution function in non-sysboundary cells
// Each initialization has to be independent to avoid threading problems
// Allow the project to set up data structures for it's setCell calls
project.setupBeforeSetCell(cells);
phiprof::Timer setCellTimer {"setCell"};
#pragma omp parallel for schedule(dynamic)
for (size_t i=0; i<cells.size(); ++i) {
SpatialCell* cell = mpiGrid[cells[i]];
if (cell->sysBoundaryFlag == sysboundarytype::NOT_SYSBOUNDARY) {
project.setCell(cell);
}
}
setCellTimer.stop();
// Initial state for sys-boundary cells
applyInitialTimer.stop();
phiprof::Timer applyBCTimer {"Apply system boundary conditions state"};
sysBoundaries.applyInitialState(mpiGrid, technicalGrid, perBGrid, BgBGrid, project);
applyBCTimer.stop();
#pragma omp parallel for schedule(static)
for (size_t i=0; i<cells.size(); ++i) {
mpiGrid[cells[i]]->parameters[CellParams::LBWEIGHTCOUNTER] = 0;
}
for (uint popID=0; popID<getObjectWrapper().particleSpecies.size(); ++popID) {
adjustVelocityBlocks(mpiGrid,cells,true,popID);
#ifdef DEBUG_VAMR_VALIDATE
writeVelMesh(mpiGrid);
validateMesh(mpiGrid,popID);
#endif
// set initial LB metric based on number of blocks, all others
// will be based on time spent in acceleration
#pragma omp parallel for schedule(static)
for (size_t i=0; i<cells.size(); ++i) {
mpiGrid[cells[i]]->parameters[CellParams::LBWEIGHTCOUNTER] += mpiGrid[cells[i]]->get_number_of_velocity_blocks(popID);
}
}
shrink_to_fit_grid_data(mpiGrid); //get rid of excess data already here
/*
// Apply boundary conditions so that we get correct initial moments
sysBoundaries.applySysBoundaryVlasovConditions(mpiGrid,Parameters::t);
//compute moments, and set them in RHO* and RHO_*_DT2. If restart, they are already read in
phiprof::Timer initMomentsTimer {"Init moments"};
calculateInitialVelocityMoments(mpiGrid);
initMomentsTimer.stop();
*/
} else if (P::writeFullBGB) {
// If, instead of starting a regular simulation, we are only writing out the background field, it is enough to set a dummy load balance value of 1 here.
for (size_t i=0; i<cells.size(); ++i) {
mpiGrid[cells[i]]->parameters[CellParams::LBWEIGHTCOUNTER] = 1;
}
}
// Balance load before we transfer all data below
balanceLoad(mpiGrid, sysBoundaries);
// Function includes re-calculation of local cells cache
phiprof::Timer fetchNeighbourTimer {"Fetch Neighbour data", {"MPI"}};
// update complete cell spatial data for full stencil (
SpatialCell::set_mpi_transfer_type(Transfer::ALL_SPATIAL_DATA);
mpiGrid.update_copies_of_remote_neighbors(FULL_NEIGHBORHOOD_ID);
fetchNeighbourTimer.stop();
phiprof::Timer setBTimer {"project.setProjectBField"};
project.setProjectBField(perBGrid, BgBGrid, technicalGrid);
setBTimer.stop();
phiprof::Timer fsGridGhostTimer {"fsgrid-ghost-updates"};
perBGrid.updateGhostCells();
BgBGrid.updateGhostCells();
EGrid.updateGhostCells();
// This will only have the BGB set up properly at this stage but we need the BGBvol for the Vlasov boundaries below.
volGrid.updateGhostCells();
fsGridGhostTimer.stop();
phiprof::Timer getFieldsTimer {"getFieldsFromFsGrid"};
getFieldsFromFsGrid(volGrid, BgBGrid, EGradPeGrid, technicalGrid, mpiGrid, cells);
getFieldsTimer.stop();
setBTimer.stop();
// If we only want the full BGB for writeout, we have it now and we can return early.
if(P::writeFullBGB == true) {
return;
}
if (P::isRestart == false) {
// Apply boundary conditions so that we get correct initial moments
sysBoundaries.applySysBoundaryVlasovConditions(mpiGrid,Parameters::t, true); // It doesn't matter here whether we put _R or _V moments
//compute moments, and set them in RHO* and RHO_*_DT2. If restart, they are already read in
phiprof::Timer timer {"Init moments"};
calculateInitialVelocityMoments(mpiGrid);
} else {
phiprof::Timer timer {"Init moments"};
for (size_t i=0; i<cells.size(); ++i) {
calculateCellMoments(mpiGrid[cells[i]], true, true);
}
}
phiprof::Timer finishFSGridTimer {"Finish fsgrid setup"};
feedMomentsIntoFsGrid(mpiGrid, cells, momentsGrid,technicalGrid, false);
if(!P::isRestart) {
// WARNING this means moments and dt2 moments are the same here at t=0, which is a feature so far.
feedMomentsIntoFsGrid(mpiGrid, cells, momentsDt2Grid, technicalGrid, false);
} else {
feedMomentsIntoFsGrid(mpiGrid, cells, momentsDt2Grid, technicalGrid, true);
}
momentsGrid.updateGhostCells();
momentsDt2Grid.updateGhostCells();
finishFSGridTimer.stop();
// Set this so CFL doesn't break
if(P::refineOnRestart) {
// Half-step acceleration
if( P::propagateVlasovAcceleration ) {
calculateAcceleration(mpiGrid, -0.5*P::dt + 0.5*P::bailout_min_dt);
} else {
calculateAcceleration(mpiGrid, 0.0);
}
P::dt = P::bailout_min_dt;
}
initialStateTimer.stop();
}
// initialize velocity grid of spatial cells before creating cells in dccrg.initialize
void initVelocityGridGeometry(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid){
// Velocity mesh(es) are created in parameters.cpp, here we just
// trigger the initialization of static variables in vmesh::VelocityMesh class.
SpatialCell dummy;
dummy.initialize_mesh();
}
void initSpatialCellCoordinates(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid) {
vector<CellID> cells = mpiGrid.get_cells();
#pragma omp parallel for
for (size_t i=0; i<cells.size(); ++i) {
std::array<double, 3> cell_min = mpiGrid.geometry.get_min(cells[i]);
std::array<double, 3> cell_length = mpiGrid.geometry.get_length(cells[i]);
mpiGrid[cells[i]]->parameters[CellParams::XCRD] = cell_min[0];
mpiGrid[cells[i]]->parameters[CellParams::YCRD] = cell_min[1];
mpiGrid[cells[i]]->parameters[CellParams::ZCRD] = cell_min[2];
mpiGrid[cells[i]]->parameters[CellParams::DX ] = cell_length[0];
mpiGrid[cells[i]]->parameters[CellParams::DY ] = cell_length[1];
mpiGrid[cells[i]]->parameters[CellParams::DZ ] = cell_length[2];
mpiGrid[cells[i]]->parameters[CellParams::CELLID] = cells[i];
mpiGrid[cells[i]]->parameters[CellParams::REFINEMENT_LEVEL] = mpiGrid.get_refinement_level(cells[i]);
}
}
/*
Record for each cell which processes own one or more of its face neighbors
*/
void setFaceNeighborRanks( dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid ) {
const vector<CellID>& cells = getLocalCells();
// TODO: Try a #pragma omp parallel for
for (const auto& cellid : cells) {
if (cellid == INVALID_CELLID) continue;
SpatialCell* cell = mpiGrid[cellid];
if (!cell) continue;
cell->face_neighbor_ranks.clear();
for (const auto& [neighbor, dir] : mpiGrid.get_face_neighbors_of(cellid)) {
int neighborhood;
// We store rank numbers into a map that has neighborhood ids as its key values.
switch (dir) {
case -3:
neighborhood = SHIFT_M_Z_NEIGHBORHOOD_ID;
break;
case -2:
neighborhood = SHIFT_M_Y_NEIGHBORHOOD_ID;
break;
case -1:
neighborhood = SHIFT_M_X_NEIGHBORHOOD_ID;
break;
case +1:
neighborhood = SHIFT_P_X_NEIGHBORHOOD_ID;
break;
case +2:
neighborhood = SHIFT_P_Y_NEIGHBORHOOD_ID;
break;
case +3:
neighborhood = SHIFT_P_Z_NEIGHBORHOOD_ID;
break;
default:
cerr << "Invalid face neighbor dimension: " << dir << " in " << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
cell->face_neighbor_ranks[neighborhood].insert(mpiGrid.get_process(neighbor));
}
}
}
void balanceLoad(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid, SysBoundary& sysBoundaries){
// Invalidate cached cell lists
Parameters::meshRepartitioned = true;
// tell other processes which velocity blocks exist in remote spatial cells
phiprof::Timer balanceLoadTimer {"Balancing load", {"Load balance"}};
phiprof::Timer deallocTimer {"deallocate boundary data"};
//deallocate blocks in remote cells to decrease memory load
deallocateRemoteCellBlocks(mpiGrid);
deallocTimer.stop();
//set weights based on each cells LB weight counter
const vector<CellID>& cells = getLocalCells();
for (size_t i=0; i<cells.size(); ++i){
// Set cell weight. We could use different counters or number of blocks if different solvers are active.
// if (P::propagateVlasovAcceleration)
// When using the FS-SPLIT functionality, Jaro Hokkanen reported issues with using the regular
// CellParams::LBWEIGHTCOUNTER, so use of blockscounts + 1 might be required.
mpiGrid.set_cell_weight(cells[i], (Real)1 + mpiGrid[cells[i]]->parameters[CellParams::LBWEIGHTCOUNTER]);
}
phiprof::Timer initLBTimer {"dccrg.initialize_balance_load"};
mpiGrid.initialize_balance_load(true);
initLBTimer.stop();
const std::unordered_set<CellID>& incoming_cells = mpiGrid.get_cells_added_by_balance_load();
std::vector<CellID> incoming_cells_list (incoming_cells.begin(),incoming_cells.end());
const std::unordered_set<CellID>& outgoing_cells = mpiGrid.get_cells_removed_by_balance_load();
std::vector<CellID> outgoing_cells_list (outgoing_cells.begin(),outgoing_cells.end());
/*transfer cells in parts to preserve memory*/
phiprof::Timer transfersTimer {"Data transfers"};
const uint64_t num_part_transfers=5;
for (uint64_t transfer_part=0; transfer_part<num_part_transfers; transfer_part++) {
//Set transfers on/off for the incoming cells in this transfer set and prepare for receive
for (unsigned int i=0;i<incoming_cells_list.size();i++){
CellID cell_id=incoming_cells_list[i];
SpatialCell* cell = mpiGrid[cell_id];
if (cell_id%num_part_transfers!=transfer_part) {
cell->set_mpi_transfer_enabled(false);
} else {
cell->set_mpi_transfer_enabled(true);
}
}
//Set transfers on/off for the outgoing cells in this transfer set
for (unsigned int i=0; i<outgoing_cells_list.size(); i++) {
CellID cell_id=outgoing_cells_list[i];
SpatialCell* cell = mpiGrid[cell_id];
if (cell_id%num_part_transfers!=transfer_part) {
cell->set_mpi_transfer_enabled(false);
} else {
cell->set_mpi_transfer_enabled(true);
}
}
for (size_t p=0; p<getObjectWrapper().particleSpecies.size(); ++p) {
// Set active population
SpatialCell::setCommunicatedSpecies(p);
//Transfer velocity block list
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_LIST_STAGE1);
mpiGrid.continue_balance_load();
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_LIST_STAGE2);
mpiGrid.continue_balance_load();
int prepareReceives {phiprof::initializeTimer("Preparing receives")};
int receives = 0;
for (unsigned int i=0; i<incoming_cells_list.size(); i++) {
CellID cell_id=incoming_cells_list[i];
SpatialCell* cell = mpiGrid[cell_id];
if (cell_id % num_part_transfers == transfer_part) {
receives++;
// reserve space for velocity block data in arriving remote cells
phiprof::Timer timer {prepareReceives};
cell->prepare_to_receive_blocks(p);
timer.stop(1, "Spatial cells");
}
}
if(receives == 0) {
//empty phiprof timer, to avoid unneccessary divergence in unique
//profiles (keep order same)
phiprof::Timer timer {prepareReceives};
timer.stop(0, "Spatial cells");
}
//do the actual transfer of data for the set of cells to be transferred
phiprof::Timer transferTimer {"transfer_all_data"};
SpatialCell::set_mpi_transfer_type(Transfer::ALL_DATA);
mpiGrid.continue_balance_load();
transferTimer.stop();
// Free memory for cells that have been sent (the block data)
for (unsigned int i=0;i<outgoing_cells_list.size();i++){
CellID cell_id=outgoing_cells_list[i];
SpatialCell* cell = mpiGrid[cell_id];
// Free memory of this cell as it has already been transferred,
// it will not be used anymore. NOTE: Only clears memory allocated
// to the active population.
if (cell_id % num_part_transfers == transfer_part) cell->clear(p);
}
} // for-loop over populations
} // for-loop over transfer parts
transfersTimer.stop();
//finish up load balancing
phiprof::Timer finishLBTimer {"dccrg.finish_balance_load"};
mpiGrid.finish_balance_load();
finishLBTimer.stop();
//Make sure transfers are enabled for all cells
recalculateLocalCellsCache();
#pragma omp parallel for
for (uint i=0; i<cells.size(); ++i) {
mpiGrid[cells[i]]->set_mpi_transfer_enabled(true);
}
// flag transfers if AMR
phiprof::Timer computeTransferTimer {"compute_amr_transfer_flags"};
flagSpatialCellsForAmrCommunication(mpiGrid,cells);
computeTransferTimer.stop();
// Communicate all spatial data for FULL neighborhood, which
// includes all data with the exception of dist function data
SpatialCell::set_mpi_transfer_type(Transfer::ALL_SPATIAL_DATA);
mpiGrid.update_copies_of_remote_neighbors(FULL_NEIGHBORHOOD_ID);
phiprof::Timer updateBlocksTimer {"update block lists"};
//new partition, re/initialize blocklists of remote cells.
for (uint popID=0; popID<getObjectWrapper().particleSpecies.size(); ++popID) {
updateRemoteVelocityBlockLists(mpiGrid,popID);
}
updateBlocksTimer.stop();
phiprof::Timer updateBoundariesTimer {"update sysboundaries"};
sysBoundaries.updateSysBoundariesAfterLoadBalance( mpiGrid );
updateBoundariesTimer.stop();
phiprof::Timer initSolversTimer {"Init solvers"};
// Initialize field propagator (only if in use):
if (Parameters::propagateField == true) {
if (initializeFieldPropagatorAfterRebalance() == false) {
logFile << "(MAIN): Field propagator did not initialize correctly!" << endl << writeVerbose;
exit(1);
}
}
initSolversTimer.stop();
// Record ranks of face neighbors
if(P::amrMaxSpatialRefLevel > 0) {
phiprof::Timer timer {"set face neighbor ranks"};
setFaceNeighborRanks( mpiGrid );
}
// Prepare cellIDs and pencils for AMR translation
if(P::amrMaxSpatialRefLevel > 0) {
prepareSeedIdsAndPencils(mpiGrid);
}
}
/*
Adjust sparse velocity space to make it consistent in all 6 dimensions.
Further documentation in grid.h
*/
bool adjustVelocityBlocks(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid,
const vector<CellID>& cellsToAdjust,
bool doPrepareToReceiveBlocks,
const uint popID) {
phiprof::Timer readjustBlocksTimer {"re-adjust blocks", {"Block adjustment"}};
SpatialCell::setCommunicatedSpecies(popID);
const vector<CellID>& cells = getLocalCells();
phiprof::Timer computeTimer {"Compute with_content_list"};
#pragma omp parallel for
for (uint i=0; i<cells.size(); ++i) {
mpiGrid[cells[i]]->updateSparseMinValue(popID);
mpiGrid[cells[i]]->update_velocity_block_content_lists(popID);
}
computeTimer.stop();
if (doPrepareToReceiveBlocks) {
// We are in the last substep of acceleration, so need to account for neighbours
phiprof::Timer transferTimer {"Transfer with_content_list", {"MPI"}};
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_WITH_CONTENT_STAGE1 );
mpiGrid.update_copies_of_remote_neighbors(NEAREST_NEIGHBORHOOD_ID);
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_WITH_CONTENT_STAGE2 );
mpiGrid.update_copies_of_remote_neighbors(NEAREST_NEIGHBORHOOD_ID);
transferTimer.stop();
}
//Adjusts velocity blocks in local spatial cells, doesn't adjust velocity blocks in remote cells.
phiprof::Timer adjustimer {"Adjusting blocks"};
#pragma omp parallel for schedule(dynamic)
for (size_t i=0; i<cellsToAdjust.size(); ++i) {
Real density_pre_adjust=0.0;
Real density_post_adjust=0.0;
CellID cell_id=cellsToAdjust[i];
SpatialCell* cell = mpiGrid[cell_id];
vector<SpatialCell*> neighbor_ptrs;
if (doPrepareToReceiveBlocks) {
// gather spatial neighbor list and gather vector with pointers to cells
// If we are within an acceleration substep prior to the last one,
// it's enough to adjust blocks based on local data only, and in
// that case we simply pass an empty list of pointers.
const auto* neighbors = mpiGrid.get_neighbors_of(cell_id, NEAREST_NEIGHBORHOOD_ID);
// Note: at AMR refinement boundaries this can cause blocks to propagate further
// than absolutely required. Face neighbours, however, are not enough as we must
// account for diagonal propagation.
neighbor_ptrs.reserve(neighbors->size());
for ( const auto& [neighbor_id, dir] : *neighbors) {
if (neighbor_id != 0) {
neighbor_ptrs.push_back(mpiGrid[neighbor_id]);
}
}
}
if (getObjectWrapper().particleSpecies[popID].sparse_conserve_mass) {
for (size_t i=0; i<cell->get_number_of_velocity_blocks(popID)*WID3; ++i) {
density_pre_adjust += cell->get_data(popID)[i];
}
}
cell->adjust_velocity_blocks(neighbor_ptrs,popID);
if (getObjectWrapper().particleSpecies[popID].sparse_conserve_mass) {
for (size_t i=0; i<cell->get_number_of_velocity_blocks(popID)*WID3; ++i) {
density_post_adjust += cell->get_data(popID)[i];
}
if (density_post_adjust != 0.0) {
for (size_t i=0; i<cell->get_number_of_velocity_blocks(popID)*WID3; ++i) {
cell->get_data(popID)[i] *= density_pre_adjust/density_post_adjust;
}
}
}
}
adjustimer.stop();
//Updated newly adjusted velocity block lists on remote cells, and
//prepare to receive block data
if (doPrepareToReceiveBlocks) {
updateRemoteVelocityBlockLists(mpiGrid,popID);
}
return true;
}
/*! Shrink to fit velocity space data to save memory.
* \param mpiGrid Spatial grid
*/
void shrink_to_fit_grid_data(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid) {
const std::vector<CellID>& cells = getLocalCells();
const std::vector<CellID>& remote_cells = mpiGrid.get_remote_cells_on_process_boundary(FULL_NEIGHBORHOOD_ID);
#pragma omp parallel for
for(size_t i=0; i<cells.size() + remote_cells.size(); ++i) {
if(i < cells.size()){
SpatialCell* target= mpiGrid[cells[i]];
if (target!=nullptr){
target->shrink_to_fit();
}
}else{
SpatialCell* target= mpiGrid[remote_cells[i - cells.size()]];
if (target!=nullptr){
target->shrink_to_fit();
}
}
}
}
/*! Estimates memory consumption and writes it into logfile. Collective operation on MPI_COMM_WORLD
* \param mpiGrid Spatial grid
*/
void report_grid_memory_consumption(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid) {
/*now report memory consumption into logfile*/
const vector<CellID>& cells = getLocalCells();
const std::vector<CellID> remote_cells = mpiGrid.get_remote_cells_on_process_boundary();
int rank,n_procs;
MPI_Comm_size(MPI_COMM_WORLD, &n_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* Compute memory statistics of the memory consumption of the spatial cells.
* Internally we use double as MPI does
* not define proper uint64_t datatypes for MAXLOCNot Real, as we
* want double here not to loose accuracy.
*/
/*report data for memory needed by blocks*/
double mem[6] = {0};
double sum_mem[6];
for(unsigned int i=0;i<cells.size();i++){
mem[0] += mpiGrid[cells[i]]->get_cell_memory_size();
mem[3] += mpiGrid[cells[i]]->get_cell_memory_capacity();
}
for(unsigned int i=0;i<remote_cells.size();i++){
mem[1] += mpiGrid[remote_cells[i]]->get_cell_memory_size();
mem[4] += mpiGrid[remote_cells[i]]->get_cell_memory_capacity();
}
mem[2] = mem[0] + mem[1];//total meory according to size()
mem[5] = mem[3] + mem[4];//total memory according to capacity()
MPI_Reduce(mem, sum_mem, 6, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
logFile << "(MEM) Total size: " << sum_mem[2] << endl;
logFile << "(MEM) Total capacity " << sum_mem[5] << endl;
struct {
double val;
int rank;
} max_mem[3],mem_usage_loc[3],min_mem[3];
for(uint i = 0; i<3; i++){
mem_usage_loc[i].val = mem[i + 3]; //report on capacity numbers (6: local cells, 7: remote cells, 8: all cells)
mem_usage_loc[i].rank = rank;
}
MPI_Reduce(mem_usage_loc, max_mem, 3, MPI_DOUBLE_INT, MPI_MAXLOC, 0, MPI_COMM_WORLD);
MPI_Reduce(mem_usage_loc, min_mem, 3, MPI_DOUBLE_INT, MPI_MINLOC, 0, MPI_COMM_WORLD);
logFile << "(MEM) Average capacity: " << sum_mem[5]/n_procs << " local cells " << sum_mem[3]/n_procs << " remote cells " << sum_mem[4]/n_procs << endl;
logFile << "(MEM) Max capacity: " << max_mem[2].val << " on process " << max_mem[2].rank << endl;
logFile << "(MEM) Min capacity: " << min_mem[2].val << " on process " << min_mem[2].rank << endl;
logFile << writeVerbose;
}
/*! Deallocates all block data in remote cells in order to save
* memory
* \param mpiGrid Spatial grid
*/
void deallocateRemoteCellBlocks(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid) {
const std::vector<uint64_t> incoming_cells
= mpiGrid.get_remote_cells_on_process_boundary(VLASOV_SOLVER_NEIGHBORHOOD_ID);
for(unsigned int i=0;i<incoming_cells.size();i++){
uint64_t cell_id=incoming_cells[i];
SpatialCell* cell = mpiGrid[cell_id];
if (cell != NULL) {
for (uint popID=0; popID<getObjectWrapper().particleSpecies.size(); ++popID)
cell->clear(popID);
}
}
}
/*
Updates velocity block lists between remote neighbors and prepares local
copies of remote neighbors for receiving velocity block data.
*/
void updateRemoteVelocityBlockLists(
dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid,
const uint popID,
const uint neighborhood/*=DIST_FUNC_NEIGHBORHOOD_ID default*/
)
{
SpatialCell::setCommunicatedSpecies(popID);
// update velocity block lists For small velocity spaces it is
// faster to do it in one operation, and not by first sending size,
// then list. For large we do it in two steps
phiprof::Timer updateTimer {"Velocity block list update", {"MPI"}};
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_LIST_STAGE1);
mpiGrid.update_copies_of_remote_neighbors(neighborhood);
SpatialCell::set_mpi_transfer_type(Transfer::VEL_BLOCK_LIST_STAGE2);
mpiGrid.update_copies_of_remote_neighbors(neighborhood);
updateTimer.stop();
// Prepare spatial cells for receiving velocity block data
phiprof::Timer receivesTimer {"Preparing receives"};
const std::vector<uint64_t> incoming_cells = mpiGrid.get_remote_cells_on_process_boundary(neighborhood);
#pragma omp parallel for
for (unsigned int i=0; i<incoming_cells.size(); ++i) {
uint64_t cell_id = incoming_cells[i];
SpatialCell* cell = mpiGrid[cell_id];
if (cell == NULL) {
//for (const auto& cell: mpiGrid.local_cells()) {
for (const auto& cell: mpiGrid.local_cells) {
if (cell.id == cell_id) {
cerr << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
for (const auto& neighbor: cell.neighbors_of) {
if (neighbor.id == cell_id) {
cerr << __FILE__ << ":" << __LINE__ << std::endl;
abort();
}
}
}
continue;
}
cell->prepare_to_receive_blocks(popID);
}
receivesTimer.stop(incoming_cells.size(), "SpatialCells");
}
/*
Set stencils. These are the stencils (in 2D, real ones in 3D of
course). x are stencil neighbor to cell local cell o:
NEAREST SYSBOUNDARIES (nearest neighbor)
-----------
xxx
xox
xxx
-----------
EXTENDED_SYSBOUNDARIES (second nearest neighbor, also in diagonal)
-----------
xxxxx
xxxxx
xxoxx
xxxxx
xxxxx
-----------
VLASOV
-----------
x
x
xxoxx
x
x
-----------
VLASOV_{XYZ}
-----------
xxoxxx
-----------
VLASOV_TARGET_{XYZ}
-----------
xox
-----------
DIST_FUNC (Includes all cells which should know about each others blocks and have space for them. VLASOV + SYSBOUNDARIES.
-----------
x
xxx
xxoxx
xxx
x
-----------
FULL (Includes all possible communication, possible AMR extension)
-----------
A
xxxxx
xxxxx
AxxoxxA
xxxxx
xxxxx
A
-----------
SHIFT_M_X ox
SHIFT_P_X xo
Y, Z in the same way
*/
void initializeStencils(dccrg::Dccrg<SpatialCell,dccrg::Cartesian_Geometry>& mpiGrid){
// set reduced neighborhoods
typedef dccrg::Types<3>::neighborhood_item_t neigh_t;
// set a reduced neighborhood for nearest neighbours
std::vector<neigh_t> neighborhood;
for (int z = -1; z <= 1; z++) {
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if (x == 0 && y == 0 && z == 0) {
continue;
}
neigh_t offsets = {{x, y, z}};
neighborhood.push_back(offsets);
}
}
}
//mpiGrid.add_neighborhood(FIELD_SOLVER_NEIGHBORHOOD_ID, neighborhood);
if (!mpiGrid.add_neighborhood(NEAREST_NEIGHBORHOOD_ID, neighborhood)){
std::cerr << "Failed to add neighborhood NEAREST_NEIGHBORHOOD_ID \n";
abort();
}
if (!mpiGrid.add_neighborhood(SYSBOUNDARIES_NEIGHBORHOOD_ID, neighborhood)){
std::cerr << "Failed to add neighborhood SYSBOUNDARIES_NEIGHBORHOOD_ID \n";
abort();
}
neighborhood.clear();
for (int z = -2; z <= 2; z++) {
for (int y = -2; y <= 2; y++) {
for (int x = -2; x <= 2; x++) {
if (x == 0 && y == 0 && z == 0) {
continue;
}
neigh_t offsets = {{x, y, z}};
neighborhood.push_back(offsets);
}
}
}
if (!mpiGrid.add_neighborhood(SYSBOUNDARIES_EXTENDED_NEIGHBORHOOD_ID, neighborhood)){
std::cerr << "Failed to add neighborhood SYSBOUNDARIES_EXTENDED_NEIGHBORHOOD_ID \n";
abort();
}
// In spatial AMR using DCCRG, the neighbors are considered relative to a given cell's size.
// To get two coarse neighbors from a fine cell at interfaces, the stencil size needs to be increased by one.
int addStencilDepth = 0;
if (P::amrMaxSpatialRefLevel > 0) {
switch (VLASOV_STENCIL_WIDTH) {
case 1:
// Required cells will be included already