-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgrid.cc
2562 lines (2152 loc) · 98.4 KB
/
grid.cc
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
#include "grid.h"
#include <mpi.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <optional>
#include <span>
#include <sstream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "artisoptions.h"
#include "atomic.h"
#include "constants.h"
#include "decay.h"
#include "globals.h"
#include "input.h"
#include "nltepop.h"
#include "nonthermal.h"
#include "packet.h"
#include "radfield.h"
#include "rpkt.h"
#include "sn3d.h"
#include "vectors.h"
namespace grid {
namespace {
struct ModelGridCellInput {
float rhoinit = -1.;
float ffegrp = 0.;
float initial_radial_pos_sum = 0.;
float initelectronfrac = -1; // Ye: electrons (or protons) per nucleon
float initenergyq = 0.; // q: energy in the model at tmin to use with USE_MODEL_INITIAL_ENERGY [erg/g]
};
std::array<char, 3> coordlabel{'?', '?', '?'};
std::array<int, 3> ncoordgrid{0}; // propagation grid dimensions
auto model_type = GridType::SPHERICAL1D;
ptrdiff_t npts_model = 0; // number of model grid cells
ptrdiff_t nonempty_npts_model = 0; // number of allocated non-empty model grid cells
double t_model = -1.; // time at which densities in input model are correct.
std::vector<double> vout_model{};
std::array<int, 3> ncoord_model{0}; // the model.txt input grid dimensions
double min_den; // minimum model density
double mfegroup = 0.; // Total mass of Fe group elements in ejecta
int first_cellindex = -1; // auto-determine first cell index in model.txt (usually 1 or 0)
// Initial co-ordinates of inner most corner of cell.
std::vector<std::array<double, 3>> propcell_pos_min{};
// associate each propagation cell with a model grid cell, or not, if the cell is empty (or doesn't get mapped to
// anything such as 1D/2D to 3D)
std::vector<int> propcell_mgi;
std::vector<int> propcell_nonemptymgi;
std::vector<int> modelgrid_numpropcells;
std::vector<int> nonemptymgi_of_mgi;
std::vector<int> mgi_of_nonemptymgi;
std::span<double> totmassradionuclide{}; // total mass of each radionuclide in the ejecta
MPI_Win win_nltepops_allcells = MPI_WIN_NULL;
MPI_Win win_initnucmassfrac_allcells = MPI_WIN_NULL;
float *initnucmassfrac_allcells{};
float *initmassfracuntrackedstable_allcells{};
int *elements_uppermost_ion_allcells{}; // Highest ion index that has a significant population
std::vector<int> ranks_nstart;
std::vector<int> ranks_nstart_nonempty;
std::vector<int> ranks_ndo;
std::vector<int> ranks_ndo_nonempty;
inline std::span<ModelGridCellInput> modelgrid_input{};
// Get number of dimensions
constexpr auto get_ndim(const GridType gridtype) -> int {
switch (gridtype) {
case GridType::SPHERICAL1D:
return 1;
case GridType::CYLINDRICAL2D:
return 2;
case GridType::CARTESIAN3D:
return 3;
default:
assert_always(false);
return -1;
}
}
void set_rho_tmin(const int modelgridindex, const float x) { modelgrid_input[modelgridindex].rhoinit = x; }
void set_initelectronfrac(const int modelgridindex, const double electronfrac) {
modelgrid_input[modelgridindex].initelectronfrac = electronfrac;
}
void read_possible_yefile() {
if (!std::filesystem::exists("Ye.txt")) {
printout("Ye.txt not found\n");
return;
}
FILE *filein = fopen_required("Ye.txt", "r");
int nlines_in = 0;
assert_always(fscanf(filein, "%d", &nlines_in) == 1);
for (int n = 0; n < nlines_in; n++) {
int mgiplusone = -1;
double initelecfrac = 0.;
assert_always(fscanf(filein, "%d %lg", &mgiplusone, &initelecfrac) == 2);
const int mgi = mgiplusone - 1;
if (mgi >= 0 && mgi < get_npts_model()) {
set_initelectronfrac(mgi, initelecfrac);
}
}
fclose(filein);
}
void allocate_initradiobund() {
assert_always(npts_model > 0);
const ptrdiff_t num_nuclides = decay::get_num_nuclides();
const size_t totalradioabundcount = (npts_model + 1) * num_nuclides;
std::tie(initnucmassfrac_allcells, win_initnucmassfrac_allcells) =
MPI_shared_malloc_keepwin<float>(totalradioabundcount);
printout(
"[info] mem_usage: radioabundance data for %td nuclides for %td cells occupies %.3f MB (node shared memory)\n",
num_nuclides, npts_model, static_cast<double>(totalradioabundcount * sizeof(float)) / 1024. / 1024.);
MPI_Barrier(globals::mpi_comm_node);
assert_always(initnucmassfrac_allcells != nullptr);
for (ptrdiff_t mgi = 0; mgi < (npts_model + 1); mgi++) {
if (mgi % static_cast<ptrdiff_t>(globals::node_nprocs) == globals::rank_in_node) {
std::fill_n(&initnucmassfrac_allcells[mgi * num_nuclides], num_nuclides, 0.);
}
}
MPI_Barrier(globals::mpi_comm_node);
}
auto get_cell_r_inner(const int cellindex) -> double {
if constexpr (GRID_TYPE == GridType::SPHERICAL1D) {
return get_cellcoordmin(cellindex, 0);
}
if constexpr (GRID_TYPE == GridType::CYLINDRICAL2D) {
const auto rcyl_inner = get_cellcoordmin(cellindex, 0);
const auto z_inner = std::min(std::abs(get_cellcoordmin(cellindex, 1)), std::abs(get_cellcoordmax(cellindex, 1)));
return std::sqrt(std::pow(rcyl_inner, 2) + std::pow(z_inner, 2));
}
if constexpr (GRID_TYPE == GridType::CARTESIAN3D) {
const auto x_inner = std::min(std::abs(get_cellcoordmin(cellindex, 0)), std::abs(get_cellcoordmax(cellindex, 0)));
const auto y_inner = std::min(std::abs(get_cellcoordmin(cellindex, 1)), std::abs(get_cellcoordmax(cellindex, 1)));
const auto z_inner = std::min(std::abs(get_cellcoordmin(cellindex, 2)), std::abs(get_cellcoordmax(cellindex, 2)));
return std::sqrt(std::pow(x_inner, 2) + std::pow(y_inner, 2) + std::pow(z_inner, 2));
}
assert_always(false);
return NAN;
}
void set_ffegrp(const int modelgridindex, float x) {
if (!(x >= 0.)) {
printout("WARNING: Fe-group mass fraction %g is negative in cell %d\n", x, modelgridindex);
assert_always(x > -1e-6);
x = 0.;
}
assert_always(x >= 0);
assert_always(x <= 1.001);
modelgrid_input[modelgridindex].ffegrp = x;
}
void set_propcell_modelgridindex(const int cellindex, const int new_modelgridindex) {
assert_testmodeonly(cellindex >= 0);
assert_testmodeonly(cellindex < ngrid);
assert_testmodeonly(new_modelgridindex >= 0);
assert_testmodeonly(new_modelgridindex <= get_npts_model());
propcell_mgi[cellindex] = new_modelgridindex;
}
void set_modelinitnucmassfrac(const int modelgridindex, const int nucindex, float abund) {
// set the mass fraction of a nuclide in a model grid cell at t=t_model by nuclide index
// initnucmassfrac array is in node shared memory
assert_always(nucindex >= 0);
if (!(abund >= 0.)) {
printout("WARNING: nuclear mass fraction for nucindex %d = %g is negative in cell %d\n", nucindex, abund,
modelgridindex);
assert_always(abund > -1e-6);
abund = 0.;
}
assert_always(abund >= 0.);
assert_always(abund <= 1.);
const ptrdiff_t num_nuclides = decay::get_num_nuclides();
initnucmassfrac_allcells[(modelgridindex * num_nuclides) + nucindex] = abund;
}
void set_initenergyq(const int modelgridindex, const double initenergyq) {
modelgrid_input[modelgridindex].initenergyq = initenergyq;
}
void set_elem_untrackedstable_abund_from_total(const int nonemptymgi, const int element, const float elemabundance) {
// set the stable mass fraction of an element from the total element mass fraction
// by subtracting the abundances of radioactive isotopes.
// if the element Z=anumber has no specific stable abundance variable then the function does nothing
const int atomic_number = get_atomicnumber(element);
const int mgi = get_mgi_of_nonemptymgi(nonemptymgi);
double isofracsum = 0.; // mass fraction sum of radioactive isotopes
for (int nucindex = 0; nucindex < decay::get_num_nuclides(); nucindex++) {
if (decay::get_nuc_z(nucindex) == atomic_number) {
// radioactive isotope of this element
isofracsum += get_modelinitnucmassfrac(mgi, nucindex);
}
}
double massfrac_untrackedstable = elemabundance - isofracsum;
if (massfrac_untrackedstable < 0.) {
// allow some roundoff error before we complain
if ((isofracsum - elemabundance - 1.) > 1e-4 && std::abs(isofracsum - elemabundance) > 1e-6) {
printout("WARNING: cell %d Z=%d element abundance is less than the sum of its radioisotope abundances\n", mgi,
atomic_number);
printout(" massfrac(Z) %g massfrac_radioisotopes(Z) %g\n", elemabundance, isofracsum);
printout(" increasing elemental abundance to %g and setting stable isotopic abundance to zero\n", isofracsum);
}
// result is allowed to be slightly negative due to roundoff error
assert_always(massfrac_untrackedstable >= -1e-2);
massfrac_untrackedstable = 0.; // bring up to zero if negative
}
// if (globals::rank_in_node == 0)
{
initmassfracuntrackedstable_allcells[(nonemptymgi * get_nelements()) + element] = massfrac_untrackedstable;
}
// (isofracsum + massfracstable) might not exactly match elemabundance if we had to boost it to reach isofracsum
set_elem_abundance(nonemptymgi, element, isofracsum + massfrac_untrackedstable);
}
void allocate_nonemptycells_composition_cooling()
// Initialise composition dependent cell data for the given cell
{
const ptrdiff_t nonempty_npts_model_ptrdifft = get_nonempty_npts_model();
const auto nelements = get_nelements();
initmassfracuntrackedstable_allcells = MPI_shared_malloc<float>(nonempty_npts_model_ptrdifft * nelements);
elem_meanweight_allcells = MPI_shared_malloc<float>(nonempty_npts_model_ptrdifft * nelements);
elements_uppermost_ion_allcells = MPI_shared_malloc<int>(nonempty_npts_model_ptrdifft * nelements);
elem_massfracs_allcells = MPI_shared_malloc<float>(nonempty_npts_model_ptrdifft * nelements);
ion_groundlevelpops_allcells = MPI_shared_malloc<float>(nonempty_npts_model_ptrdifft * get_includedions());
ion_partfuncts_allcells = MPI_shared_malloc<float>(nonempty_npts_model_ptrdifft * get_includedions());
ion_cooling_contribs_allcells = MPI_shared_malloc<double>(nonempty_npts_model_ptrdifft * get_includedions());
if (globals::total_nlte_levels > 0) {
std::tie(nltepops_allcells, win_nltepops_allcells) =
MPI_shared_malloc_keepwin<double>(nonempty_npts_model_ptrdifft * globals::total_nlte_levels);
assert_always(nltepops_allcells != nullptr);
} else {
nltepops_allcells = nullptr;
}
if (globals::rank_in_node == 0) {
std::fill_n(initmassfracuntrackedstable_allcells, nonempty_npts_model_ptrdifft * nelements, -1.);
std::fill_n(elem_meanweight_allcells, nonempty_npts_model_ptrdifft * nelements, -1.);
std::fill_n(elements_uppermost_ion_allcells, nonempty_npts_model_ptrdifft * nelements, -1);
std::fill_n(elem_massfracs_allcells, nonempty_npts_model_ptrdifft * nelements, -1.);
// -1 indicates that there is currently no information on the nlte populations
std::ranges::fill_n(grid::nltepops_allcells, nonempty_npts_model_ptrdifft * globals::total_nlte_levels, -1.);
}
}
void allocate_nonemptymodelcells() {
// Determine the number of simulation cells associated with the model cells
std::ranges::fill(modelgrid_numpropcells, 0);
if (globals::rank_in_node == 0) {
for (int mgi = 0; mgi < (get_npts_model() + 1); mgi++) {
modelgrid_input[mgi].initial_radial_pos_sum = 0.;
}
}
for (int cellindex = 0; cellindex < ngrid; cellindex++) {
const auto radial_pos_mid = get_cellradialposmid(cellindex);
if (FORCE_SPHERICAL_ESCAPE_SURFACE && radial_pos_mid > globals::vmax * globals::tmin) {
// for 1D models, the final shell outer v should already be at vmax
assert_always(model_type != GridType::SPHERICAL1D || propcell_mgi[cellindex] == get_npts_model());
set_propcell_modelgridindex(cellindex, get_npts_model());
}
const int mgi = get_propcell_modelgridindex(cellindex);
assert_always(!(get_model_type() == GridType::CARTESIAN3D) || (get_rho_tmin(mgi) > 0) || (mgi == get_npts_model()));
modelgrid_numpropcells[mgi] += 1;
if (globals::rank_in_node == 0) {
modelgrid_input[mgi].initial_radial_pos_sum += radial_pos_mid;
}
assert_always(!(get_model_type() == GridType::CARTESIAN3D) || (modelgrid_numpropcells[mgi] == 1) ||
(mgi == get_npts_model()));
}
MPI_Barrier(MPI_COMM_WORLD);
// find number of non-empty cells and allocate nonempty list
nonempty_npts_model = 0;
for (int mgi = 0; mgi < get_npts_model(); mgi++) {
if (get_numpropcells(mgi) > 0) {
nonempty_npts_model++;
}
}
assert_always(nonempty_npts_model > 0);
mgi_of_nonemptymgi.resize(nonempty_npts_model, -2);
propcell_nonemptymgi.resize(ngrid, -1);
int nonemptymgi = 0; // index within list of non-empty modelgrid cells
for (int mgi = 0; mgi < get_npts_model(); mgi++) {
if (get_numpropcells(mgi) > 0) {
assert_always(get_rho_tmin(mgi) >= 0);
nonemptymgi_of_mgi[mgi] = nonemptymgi;
mgi_of_nonemptymgi[nonemptymgi] = mgi;
nonemptymgi++;
} else {
nonemptymgi_of_mgi[mgi] = -1;
set_rho_tmin(mgi, 0.);
for (int nucindex = 0; nucindex < decay::get_num_nuclides(); nucindex++) {
set_modelinitnucmassfrac(mgi, nucindex, 0.);
}
}
}
MPI_Barrier(MPI_COMM_WORLD);
for (int cellindex = 0; cellindex < ngrid; cellindex++) {
const int mgi = get_propcell_modelgridindex(cellindex);
if (mgi >= get_npts_model()) {
propcell_nonemptymgi[cellindex] = -1;
} else {
propcell_nonemptymgi[cellindex] = get_nonemptymgi_of_mgi(mgi);
}
}
assert_always(modelgrid.data() == nullptr);
modelgrid = MPI_shared_malloc_span<ModelGridCell>(nonempty_npts_model);
std::ranges::fill(modelgrid, ModelGridCell{});
MPI_Barrier(MPI_COMM_WORLD);
allocate_nonemptycells_composition_cooling();
if constexpr (EXPANSIONOPACITIES_ON || RPKT_BOUNDBOUND_THERMALISATION_PROBABILITY > 0.) {
allocate_expansionopacities();
}
globals::dep_estimator_gamma.resize(nonempty_npts_model, 0.);
globals::dep_estimator_positron.resize(nonempty_npts_model, 0.);
globals::dep_estimator_electron.resize(nonempty_npts_model, 0.);
globals::dep_estimator_alpha.resize(nonempty_npts_model, 0.);
const auto ionestimcount = nonempty_npts_model * globals::nbfcontinua_ground;
const auto ionestimsize = ionestimcount * sizeof(double);
if (ionestimsize > 0) {
std::tie(globals::corrphotoionrenorm, globals::win_corrphotoionrenorm) =
MPI_shared_malloc_keepwin<double>(ionestimcount);
globals::gammaestimator.resize(ionestimcount, 0.);
#ifdef DO_TITER
globals::gammaestimator_save.resize(nonempty_npts_model, 0.);
#endif
} else {
globals::corrphotoionrenorm = nullptr;
globals::gammaestimator.clear();
#ifdef DO_TITER
globals::gammaestimator_save.clear();
#endif
}
if (USE_LUT_BFHEATING && ionestimsize > 0) {
globals::bfheatingestimator.resize(ionestimcount, 0.);
#ifdef DO_TITER
globals::bfheatingestimator_save.resize(nonempty_npts_model, 0.);
#endif
} else {
globals::bfheatingestimator.clear();
#ifdef DO_TITER
globals::bfheatingestimator_save.clear();
#endif
}
globals::ffheatingestimator.resize(nonempty_npts_model, 0.);
globals::colheatingestimator.resize(nonempty_npts_model, 0.);
#ifdef DO_TITER
globals::ffheatingestimator_save.resize(nonempty_npts_model, 0.);
globals::colheatingestimator_save.resize(nonempty_npts_model, 0.);
#endif
// barrier to make sure node master has set abundance values to node shared memory
MPI_Barrier(MPI_COMM_WORLD);
printout("[info] mem_usage: the modelgrid array occupies %.3f MB\n",
(get_npts_model() + 1) * sizeof(modelgrid[0]) / 1024. / 1024.);
printout("There are %td modelgrid cells with associated propagation cells (nonempty_npts_model)\n",
nonempty_npts_model);
printout(
"[info] mem_usage: NLTE populations for all allocated cells occupy a total of %.3f MB (node shared memory)\n",
get_nonempty_npts_model() * globals::total_nlte_levels * sizeof(double) / 1024. / 1024.);
}
void map_1dmodelto3dgrid()
// Map 1D spherical model grid onto propagation grid
{
for (int cellindex = 0; cellindex < ngrid; cellindex++) {
const double cellvmid = get_cellradialposmid(cellindex) / globals::tmin;
const int mgi = static_cast<int>(std::ranges::lower_bound(vout_model, cellvmid) - vout_model.begin());
if (mgi < get_npts_model() && modelgrid_input[mgi].rhoinit > 0) {
set_propcell_modelgridindex(cellindex, mgi);
assert_always(vout_model[mgi] >= cellvmid);
assert_always((mgi > 0 ? vout_model[mgi - 1] : 0.0) <= cellvmid);
} else {
// corner cells outside of the outermost model shell are empty
// and so are any shells with zero density
set_propcell_modelgridindex(cellindex, get_npts_model());
}
}
}
void map_2dmodelto3dgrid()
// Map 2D cylindrical model onto propagation grid
{
for (int cellindex = 0; cellindex < ngrid; cellindex++) {
// map to 3D Cartesian grid
const auto pos_mid = std::array<double, 3>{get_cellcoordmin(cellindex, 0) + (0.5 * wid_init(cellindex, 0)),
get_cellcoordmin(cellindex, 1) + (0.5 * wid_init(cellindex, 1)),
get_cellcoordmin(cellindex, 2) + (0.5 * wid_init(cellindex, 2))};
const double rcylindrical = std::sqrt(std::pow(pos_mid[0], 2) + std::pow(pos_mid[1], 2));
// 2D grid is uniform so rcyl and z indices can be calculated with no lookup
const int n_rcyl = static_cast<int>(rcylindrical / globals::tmin / globals::vmax * ncoord_model[0]);
const int n_z =
static_cast<int>((pos_mid[2] / globals::tmin + globals::vmax) / (2 * globals::vmax) * ncoord_model[1]);
if (n_rcyl >= 0 && n_rcyl < ncoord_model[0] && n_z >= 0 && n_z < ncoord_model[1]) {
const int mgi = (n_z * ncoord_model[0]) + n_rcyl;
if (modelgrid_input[mgi].rhoinit > 0) {
set_propcell_modelgridindex(cellindex, mgi);
} else {
set_propcell_modelgridindex(cellindex, get_npts_model());
}
} else {
set_propcell_modelgridindex(cellindex, get_npts_model());
}
}
}
// mgi and cellindex are interchangeable in this mode (except for empty cells that associated with mgi ==
// get_npts_model())
void map_modeltogrid_direct() {
for (int cellindex = 0; cellindex < ngrid; cellindex++) {
const int mgi = (modelgrid_input[cellindex].rhoinit > 0) ? cellindex : get_npts_model();
set_propcell_modelgridindex(cellindex, mgi);
}
}
void abundances_read() {
// barrier to make sure node master has set values in node shared memory
MPI_Barrier(MPI_COMM_WORLD);
printout("reading abundances.txt...");
const bool threedimensional = (get_model_type() == GridType::CARTESIAN3D);
// Open the abundances file
auto abundance_file = fstream_required("abundances.txt", std::ios::in);
// and process through the grid to read in the abundances per cell
// The abundance file should only contain information for non-empty
// cells. Its format must be cellnumber (integer), abundance for
// element Z=1 (float) up to abundance for element Z=30 (float)
// i.e. in total one integer and 30 floats.
// loop over propagation cells for 3D models, or modelgrid cells
for (int mgi = 0; mgi < get_npts_model(); mgi++) {
std::string line;
assert_always(get_noncommentline(abundance_file, line));
std::istringstream ssline(line);
int cellnumberinput = -1;
assert_always(ssline >> cellnumberinput);
assert_always(cellnumberinput == mgi + first_cellindex);
// the abundances.txt file specifies the elemental mass fractions for each model cell
// (or proportial to mass frac, e.g. element densities because they will be normalised anyway)
// The abundances begin with hydrogen, helium, etc, going as far up the atomic numbers as required
double normfactor = 0.;
float abundances_in[150] = {0.};
double abund_in = 0.;
for (int anumber = 1; anumber <= 150; anumber++) {
abundances_in[anumber - 1] = 0.;
if (!(ssline >> abund_in)) {
// at least one element (hydrogen) should have been specified for nonempty cells
assert_always(anumber > 1 || get_numpropcells(mgi) == 0);
break;
}
if (abund_in < 0. || abund_in < std::numeric_limits<float>::min()) {
assert_always(abund_in > -1e-6);
abund_in = 0.;
}
abundances_in[anumber - 1] = static_cast<float>(abund_in);
normfactor += abundances_in[anumber - 1];
}
if (get_numpropcells(mgi) > 0) {
if (threedimensional || normfactor <= 0.) {
normfactor = 1.;
}
const int nonemptymgi = get_nonemptymgi_of_mgi(mgi);
for (int element = 0; element < get_nelements(); element++) {
// now set the abundances (by mass) of included elements, i.e.
// read out the abundances specified in the atomic data file
const int anumber = get_atomicnumber(element);
const float elemabundance = abundances_in[anumber - 1] / normfactor;
assert_always(elemabundance >= 0.);
// radioactive nuclide abundances should have already been set by read_??_model
set_elem_untrackedstable_abund_from_total(nonemptymgi, element, elemabundance);
}
}
}
// barrier to make sure node master has set values in node shared memory
MPI_Barrier(MPI_COMM_WORLD);
printout("done.\n");
}
void parse_model_headerline(const std::string &line, std::vector<int> &zlist, std::vector<int> &alist,
std::vector<std::string> &colnames) {
// custom header line
std::istringstream iss(line);
std::string token;
int columnindex = -1;
while (std::getline(iss, token, ' ')) {
if (std::ranges::all_of(token, isspace)) { // skip whitespace tokens
continue;
}
columnindex++;
if (token == "#inputcellid") {
assert_always(columnindex == 0);
} else if (token == "velocity_outer") {
assert_always(columnindex == 1);
} else if (token == "vel_r_max_kmps") {
assert_always(columnindex == 1);
} else if (token.starts_with("pos_")) {
continue;
} else if (token == "logrho") {
// 1D models have log10(rho [g/cm3])
assert_always(columnindex == 2);
assert_always(get_model_type() == GridType::SPHERICAL1D);
} else if (token == "rho") {
// 2D and 3D models have rho [g/cm3]
assert_always(get_model_type() != GridType::SPHERICAL1D);
assert_always((columnindex == 4 && get_model_type() == GridType::CARTESIAN3D) ||
(columnindex == 3 && get_model_type() == GridType::CYLINDRICAL2D));
continue;
} else if (token.starts_with("X_") && token != "X_Fegroup") {
colnames.push_back(token);
const int z = decay::get_nucstring_z(token.substr(2)); // + 2 skips the 'X_'
const int a = decay::get_nucstring_a(token.substr(2));
assert_always(z >= 0);
assert_always(a >= 0);
// printout("Custom column: '%s' Z %d A %d\n", token.c_str(), z, a);
zlist.push_back(z);
alist.push_back(a);
} else {
// printout("Custom column: '%s' Z %d A %d\n", token.c_str(), -1, -1);
colnames.push_back(token);
zlist.push_back(-1);
alist.push_back(-1);
}
}
}
auto get_token_count(std::string &line) -> int {
std::string token;
int abundcolcount = 0;
auto ssline = std::istringstream(line);
while (std::getline(ssline, token, ' ')) {
if (!std::ranges::all_of(token, isspace)) { // skip whitespace tokens
abundcolcount++;
}
}
return abundcolcount;
}
void read_model_radioabundances(std::fstream &fmodel, std::istringstream &ssline_in, const int mgi, const bool keepcell,
const std::vector<std::string> &colnames, const std::vector<int> &nucindexlist,
const bool one_line_per_cell) {
std::string line;
if (!one_line_per_cell) {
assert_always(std::getline(fmodel, line));
}
auto ssline = one_line_per_cell ? std::move(ssline_in) : std::istringstream(line);
if (!keepcell) {
return;
}
for (ptrdiff_t i = 0; i < std::ssize(colnames); i++) {
double valuein = 0.;
assert_always(ssline >> valuein); // usually a mass fraction, but now can be anything
if (nucindexlist[i] >= 0) {
assert_testmodeonly(valuein <= 1.);
set_modelinitnucmassfrac(mgi, nucindexlist[i], valuein);
} else if (colnames[i] == "X_Fegroup") {
set_ffegrp(mgi, valuein);
} else if (colnames[i] == "cellYe") {
set_initelectronfrac(mgi, valuein);
} else if (colnames[i] == "q") {
// use value for t_model and adjust to tmin with expansion factor
set_initenergyq(mgi, valuein * t_model / globals::tmin);
} else if (colnames[i] == "tracercount") {
;
} else {
if (mgi == 0) {
printout("WARNING: ignoring column '%s' nucindex %d valuein[mgi=0] %lg\n", colnames[i].c_str(), nucindexlist[i],
valuein);
}
}
}
double valuein = 0.;
assert_always(!(ssline >> valuein)); // should be no tokens left!
}
auto read_model_columns(std::fstream &fmodel) -> std::tuple<std::vector<std::string>, std::vector<int>, bool> {
auto pos_data_start = fmodel.tellg(); // get position in case we need to undo getline
std::vector<int> zlist;
std::vector<int> alist;
std::vector<std::string> colnames;
std::string line;
std::getline(fmodel, line);
std::string headerline;
const bool header_specified = lineiscommentonly(line);
if (header_specified) {
// line is the header
headerline = line;
pos_data_start = fmodel.tellg();
std::getline(fmodel, line);
} else {
// line is not a comment, so it must be the first line of data
// add a default header for unlabelled columns
switch (model_type) {
case GridType::SPHERICAL1D:
headerline = std::string("#inputcellid vel_r_max_kmps logrho");
break;
case GridType::CYLINDRICAL2D:
headerline = std::string("#inputcellid pos_rcyl_mid pos_z_mid rho");
break;
case GridType::CARTESIAN3D:
headerline = std::string("#inputcellid pos_x_min pos_y_min pos_z_min rho");
break;
}
headerline += std::string(" X_Fegroup X_Ni56 X_Co56 X_Fe52 X_Cr48");
}
int colcount = get_token_count(line);
const bool one_line_per_cell = (colcount >= get_token_count(headerline));
printout("model.txt has %s line per cell format\n", one_line_per_cell ? "one" : "two");
if (!one_line_per_cell) { // add columns from the second line
std::getline(fmodel, line);
colcount += get_token_count(line);
}
if (!header_specified && colcount > get_token_count(headerline)) {
headerline += " X_Ni57 X_Co57";
}
assert_always(colcount == get_token_count(headerline));
fmodel.seekg(pos_data_start); // get back to start of data
if (header_specified) {
printout("model.txt has header line: %s\n", headerline.c_str());
} else {
printout("model.txt has no header line. Using default: %s\n", headerline.c_str());
}
parse_model_headerline(headerline, zlist, alist, colnames);
decay::init_nuclides(zlist, alist);
std::vector<int> nucindexlist(zlist.size());
for (ptrdiff_t i = 0; i < std::ssize(zlist); i++) {
nucindexlist[i] = (zlist[i] > 0) ? decay::get_nucindex(zlist[i], alist[i]) : -1;
}
allocate_initradiobund();
return {colnames, nucindexlist, one_line_per_cell};
}
auto get_inputcellvolume(const int mgi) -> double {
if (get_model_type() == GridType::SPHERICAL1D) {
const double v_inner = (mgi == 0) ? 0. : vout_model[mgi - 1];
// mass_in_shell = rho_model[mgi] * (pow(vout_model[mgi], 3) - pow(v_inner, 3)) * 4 * PI * pow(t_model, 3) / 3.;
return (pow(vout_model[mgi], 3) - pow(v_inner, 3)) * 4 * PI * pow(globals::tmin, 3) / 3.;
}
if (get_model_type() == GridType::CYLINDRICAL2D) {
const int n_r = mgi % ncoord_model[0];
const double dcoord_rcyl = globals::vmax * t_model / ncoord_model[0]; // dr 2D for input model
const double dcoord_z = 2. * globals::vmax * t_model / ncoord_model[1]; // dz 2D for input model
return pow(globals::tmin / t_model, 3) * dcoord_z * PI *
(pow((n_r + 1) * dcoord_rcyl, 2.) - pow(n_r * dcoord_rcyl, 2.));
}
if (get_model_type() == GridType::CARTESIAN3D) {
// Assumes cells are cubes here - all same volume.
return pow((2 * globals::vmax * globals::tmin), 3.) / (ncoordgrid[0] * ncoordgrid[1] * ncoordgrid[2]);
}
assert_always(false);
return NAN;
}
void calc_modelinit_totmassradionuclides() {
mtot_input = 0.;
mfegroup = 0.;
assert_always(totmassradionuclide.data() == nullptr);
totmassradionuclide =
std::span(static_cast<double *>(malloc(decay::get_num_nuclides() * sizeof(double))), decay::get_num_nuclides());
assert_always(totmassradionuclide.data() != nullptr);
for (int nucindex = 0; nucindex < decay::get_num_nuclides(); nucindex++) {
totmassradionuclide[nucindex] = 0.;
}
for (int mgi = 0; mgi < get_npts_model(); mgi++) {
const double mass_in_shell = get_rho_tmin(mgi) * get_inputcellvolume(mgi);
if (mass_in_shell > 0) {
mtot_input += mass_in_shell;
for (int nucindex = 0; nucindex < decay::get_num_nuclides(); nucindex++) {
totmassradionuclide[nucindex] += mass_in_shell * get_modelinitnucmassfrac(mgi, nucindex);
}
mfegroup += mass_in_shell * get_ffegrp(mgi);
}
}
}
void read_grid_restart_data(const int timestep) {
char filename[MAXFILENAMELENGTH];
snprintf(filename, MAXFILENAMELENGTH, "gridsave_ts%d.tmp", timestep);
printout("READIN GRID SNAPSHOT from %s\n", filename);
FILE *gridsave_file = fopen_required(filename, "r");
int ntimesteps_in = -1;
assert_always(fscanf(gridsave_file, "%d ", &ntimesteps_in) == 1);
assert_always(ntimesteps_in == globals::ntimesteps);
int nprocs_in = -1;
assert_always(fscanf(gridsave_file, "%d ", &nprocs_in) == 1);
assert_always(nprocs_in == globals::nprocs);
for (int nts = 0; nts < globals::ntimesteps; nts++) {
int pellet_decays = 0.;
assert_always(fscanf(gridsave_file,
"%la %la %la %la %la %la %la %la %la %la %la %la %la %la %la %la %la %la %la %d ",
&globals::timesteps[nts].gamma_dep, &globals::timesteps[nts].gamma_dep_discrete,
&globals::timesteps[nts].positron_dep, &globals::timesteps[nts].positron_dep_discrete,
&globals::timesteps[nts].positron_emission, &globals::timesteps[nts].eps_positron_ana_power,
&globals::timesteps[nts].electron_dep, &globals::timesteps[nts].electron_dep_discrete,
&globals::timesteps[nts].electron_emission, &globals::timesteps[nts].eps_electron_ana_power,
&globals::timesteps[nts].alpha_dep, &globals::timesteps[nts].alpha_dep_discrete,
&globals::timesteps[nts].alpha_emission, &globals::timesteps[nts].eps_alpha_ana_power,
&globals::timesteps[nts].qdot_betaminus, &globals::timesteps[nts].qdot_alpha,
&globals::timesteps[nts].qdot_total, &globals::timesteps[nts].gamma_emission,
&globals::timesteps[nts].cmf_lum, &pellet_decays) == 20);
globals::timesteps[nts].pellet_decays = pellet_decays;
}
int timestep_in = 0;
assert_always(fscanf(gridsave_file, "%d ", ×tep_in) == 1);
assert_always(timestep_in == timestep);
for (int nonemptymgi = 0; nonemptymgi < get_nonempty_npts_model(); nonemptymgi++) {
const int mgi = grid::get_mgi_of_nonemptymgi(nonemptymgi);
int mgi_in = -1;
float T_R = 0.;
float T_e = 0.;
float W = 0.;
float T_J = 0.;
int thick = 0;
assert_always(fscanf(gridsave_file, "%d %a %a %a %a %d %la %la %la %la %a %a", &mgi_in, &T_R, &T_e, &W, &T_J,
&thick, &globals::dep_estimator_gamma[nonemptymgi],
&globals::dep_estimator_positron[nonemptymgi], &globals::dep_estimator_electron[nonemptymgi],
&globals::dep_estimator_alpha[nonemptymgi], &modelgrid[nonemptymgi].nne,
&modelgrid[nonemptymgi].nnetot) == 12);
if (mgi_in != mgi) {
printout("[fatal] read_grid_restart_data: cell mismatch in reading input gridsave.dat ... abort\n");
printout("[fatal] read_grid_restart_data: read cellnumber %d, expected cellnumber %d\n", mgi_in, mgi);
assert_always(mgi_in == mgi);
}
assert_always(T_R >= 0.);
assert_always(T_e >= 0.);
assert_always(W >= 0.);
assert_always(T_J >= 0.);
assert_always(globals::dep_estimator_gamma[nonemptymgi] >= 0.);
assert_always(globals::dep_estimator_positron[nonemptymgi] >= 0.);
assert_always(globals::dep_estimator_electron[nonemptymgi] >= 0.);
assert_always(globals::dep_estimator_alpha[nonemptymgi] >= 0.);
set_TR(nonemptymgi, T_R);
set_Te(nonemptymgi, T_e);
set_W(nonemptymgi, W);
set_TJ(nonemptymgi, T_J);
modelgrid[nonemptymgi].thick = thick;
if constexpr (USE_LUT_PHOTOION) {
for (int i = 0; i < globals::nbfcontinua_ground; i++) {
const int estimindex = (nonemptymgi * globals::nbfcontinua_ground) + i;
assert_always(fscanf(gridsave_file, " %la %la", &globals::corrphotoionrenorm[estimindex],
&globals::gammaestimator[estimindex]) == 2);
}
}
}
// the order of these calls is very important!
radfield::read_restart_data(gridsave_file);
if (globals::rank_in_node == 0) {
// all data is shared on the node
nonthermal::read_restart_data(gridsave_file);
nltepop_read_restart_data(gridsave_file);
}
MPI_Barrier(globals::mpi_comm_node);
fclose(gridsave_file);
}
// Assign temperatures to the grid cells at the start of the simulation
void assign_initial_temperatures() {
MPI_Barrier(MPI_COMM_WORLD); // For a simulation started from scratch we estimate the initial temperatures
// We assume that for early times the material is so optically thick, that
// all the radiation is trapped in the cell it originates from. This
// means furthermore LTE, so that both temperatures can be evaluated
// according to the local energy density resulting from the 56Ni decay.
// The dilution factor is W=1 in LTE.
printout("Assigning initial temperatures...\n");
const double tstart = globals::timesteps[0].mid;
int cells_below_mintemp = 0;
int cells_above_maxtemp = 0;
for (int nonemptymgi = 0; nonemptymgi < get_nonempty_npts_model(); nonemptymgi++) {
const int mgi = get_mgi_of_nonemptymgi(nonemptymgi);
double decayedenergy_per_mass = decay::get_endecay_per_ejectamass_t0_to_time_withexpansion(nonemptymgi, tstart);
if constexpr (INITIAL_PACKETS_ON && USE_MODEL_INITIAL_ENERGY) {
decayedenergy_per_mass += get_initenergyq(mgi);
}
double T_initial =
pow(CLIGHT / 4 / STEBO * pow(globals::tmin / tstart, 3) * get_rho_tmin(mgi) * decayedenergy_per_mass, 1. / 4.);
if (T_initial < MINTEMP) {
// printout("mgi %d: T_initial of %g is below MINTEMP %g K, setting to MINTEMP.\n", mgi, T_initial, MINTEMP);
T_initial = MINTEMP;
cells_below_mintemp++;
} else if (T_initial > MAXTEMP) {
// printout("mgi %d: T_initial of %g is above MAXTEMP %g K, setting to MAXTEMP.\n", mgi, T_initial, MAXTEMP);
T_initial = MAXTEMP;
cells_above_maxtemp++;
} else if (!std::isfinite(T_initial)) {
printout("mgi %d: T_initial of %g is infinite!\n", mgi, T_initial);
}
assert_always(std::isfinite(T_initial));
set_Te(nonemptymgi, T_initial);
set_TJ(nonemptymgi, T_initial);
set_TR(nonemptymgi, T_initial);
set_W(nonemptymgi, 1.);
modelgrid[nonemptymgi].thick = 0;
}
printout(" cells below MINTEMP %g: %d\n", MINTEMP, cells_below_mintemp);
printout(" cells above MAXTEMP %g: %d\n", MAXTEMP, cells_above_maxtemp);
}
// start at mgi_start and find the next non-empty cell, or return -1 if none found
[[nodiscard]] auto get_next_nonemptymgi(const int mgi_start) -> int {
for (int mgi = mgi_start; mgi < get_npts_model(); mgi++) {
if (get_numpropcells(mgi) > 0) {
return nonemptymgi_of_mgi[mgi];
}
}
return -1;
}
void setup_nstart_ndo() {
const int nprocesses = globals::nprocs;
assert_always(nonempty_npts_model > 0);
const int min_nonempty_perproc =
nonempty_npts_model / nprocesses; // integer division, minimum non-empty cells per process
const int n_remainder = nonempty_npts_model % nprocesses;
ranks_nstart.resize(nprocesses, -1);
ranks_nstart_nonempty.resize(nprocesses, -1);
ranks_ndo.resize(nprocesses, 0);
ranks_ndo_nonempty.resize(nprocesses, 0);
// begin with no cell assignments
std::ranges::fill(ranks_nstart, 0);
std::ranges::fill(ranks_nstart_nonempty, 0);
std::ranges::fill(ranks_ndo, 0);
std::ranges::fill(ranks_ndo_nonempty, 0);
if (nprocesses >= get_npts_model()) {
// for convenience, rank == mgi when there is at least one rank per cell
for (int rank = 0; rank < nprocesses; rank++) {
if (rank < get_npts_model()) {
const int mgi = rank;
ranks_nstart[rank] = mgi;
ranks_ndo[rank] = 1;
ranks_nstart_nonempty[rank] = (get_numpropcells(mgi) > 0) ? get_nonemptymgi_of_mgi(mgi) : 0;
ranks_ndo_nonempty[rank] = (get_numpropcells(mgi) > 0) ? 1 : 0;
}
}
} else {
// evenly divide up the non-empty cells among the ranks
int rank = 0;
for (int mgi = 0; mgi < get_npts_model(); mgi++) {
const int target_nonempty_thisrank = (rank < n_remainder) ? min_nonempty_perproc + 1 : min_nonempty_perproc;
if ((rank < (nprocesses - 1)) && (ranks_ndo_nonempty[rank] >= target_nonempty_thisrank)) {
// current rank has enough non-empty cells, so start assigning cells to the next rank
rank++;
ranks_nstart[rank] = mgi;
ranks_nstart_nonempty[rank] = get_next_nonemptymgi(mgi);
assert_always(ranks_nstart_nonempty[rank] >= 0);
}
ranks_ndo[rank]++;
if (get_numpropcells(mgi) > 0) {
ranks_ndo_nonempty[rank]++;
}
}
}
int npts_assigned = 0;
int nonempty_npts_model_assigned = 0;
for (int r = 0; r < nprocesses; r++) {
npts_assigned += ranks_ndo[r];
nonempty_npts_model_assigned += ranks_ndo_nonempty[r];
}
assert_always(npts_assigned == get_npts_model());