-
Notifications
You must be signed in to change notification settings - Fork 8
/
input.cc
2005 lines (1714 loc) · 84.6 KB
/
input.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 "input.h"
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <mpi.h>
#include <algorithm>
#include <array>
#include <cinttypes>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <functional>
#include <ios>
#include <iterator>
#ifndef GPU_ON
#include <random>
#endif
#include <span>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include "artisoptions.h"
#include "atomic.h"
#include "constants.h"
#include "decay.h"
#include "globals.h"
#include "grid.h"
#include "kpkt.h"
#include "packet.h"
#include "ratecoeff.h"
#include "sn3d.h"
#include "vpkt.h"
namespace {
const int groundstate_index_in = 1; // starting level index in the input files
struct Transition {
int lower;
int upper;
float A;
float coll_str;
bool forbidden;
}; // only used temporarily during input
constexpr std::array<std::string_view, 24> inputlinecomments = {
" 0: pre_zseed: specific random number seed if > 0 or random if negative",
" 1: ntimesteps: number of timesteps",
" 2: timestep_start timestep_finish: timestep number range start (inclusive) and stop (not inclusive)",
" 3: tmin_days tmax_days: start and end times [day]",
" 4: UNUSED nusyn_min_mev nusyn_max_mev: lowest and highest frequency to synthesise [MeV]",
" 5: UNUSED nsyn_time: number of times for synthesis",
" 6: UNUSED start and end times for synthesis",
" 7: model_type: number of dimensions (1, 2, or 3)",
" 8: UNUSED compute r-light curve (1: no estimators, 2: thin cells, 3: thick cells, 4: gamma-ray heating)",
" 9: UNUSED n_out_it: number of iterations",
"10: UNUSED: change speed of light by some factor. Change constants.h CLIGHT_PROP instead",
"11: gamma_kappagrey: if >0: use grey opacity for gammas, if <0: use detailed opacity",
"12: syn_dir: x, y, and z components of unit vector (will be normalised after input or randomised if zero length)",
"13: opacity_case: opacity choice",
"14: rho_crit_para: free parameter for calculation of rho_crit",
"15: UNUSED debug_packet: (>=0: activate debug output for packet id, <0: ignore)",
"16: simulation_continued_from_saved: (0: start new simulation, 1: continue from gridsave and packets files)",
"17: UNUSED rfcut_angstroms: wavelength (in Angstroms) at which the parameterisation of the radiation field "
"switches from the nebular approximation to LTE.",
"18: num_lte_timesteps",
"19: cell_is_optically_thick num_grey_timesteps",
"20: UNUSED max_bf_continua: (>0: max bound-free continua per ion, <0 unlimited)",
"21: nprocs_exspec: extract spectra for n MPI tasks. sn3d will set this on start of new sim.",
"22: do_emission_res: Extract line-of-sight dependent information of last emission for spectrum_res (1: yes, 0: "
"no)",
"23: kpktdiffusion_timescale n_kpktdiffusion_timesteps: kpkts diffuse x of a time step's length for the first y "
"time steps"};
CellCachePhixsTargets *chphixstargetsblock{};
void read_phixs_data_table(std::fstream &phixsfile, const int nphixspoints_inputtable, const int element,
const int lowerion, const int lowerlevel, const int upperion, int upperlevel_in,
std::vector<float> &tmpallphixs, size_t *mem_usage_phixs, const int phixs_file_version) {
std::string phixsline;
assert_always(globals::elements[element].ions[lowerion].levels[lowerlevel].phixstargetstart == -1);
globals::elements[element].ions[lowerion].levels[lowerlevel].phixstargetstart =
static_cast<int>(globals::allphixstargets.size());
if (upperlevel_in >= 0) { // file gives photoionisation to a single target state only
int upperlevel = upperlevel_in - groundstate_index_in;
assert_always(upperlevel >= 0);
assert_always(globals::elements[element].ions[lowerion].levels[lowerlevel].nphixstargets == 0);
globals::elements[element].ions[lowerion].levels[lowerlevel].nphixstargets = 1;
*mem_usage_phixs += sizeof(PhotoionTarget);
if (single_level_top_ion && (upperion == get_nions(element) - 1)) {
// top ion has only one level, so send it to that level
upperlevel = 0;
}
globals::allphixstargets.push_back({.probability = 1., .levelindex = upperlevel});
} else { // upperlevel < 0, indicating that a table of upper levels and their probabilities will follow
int in_nphixstargets = 0;
assert_always(get_noncommentline(phixsfile, phixsline));
assert_always(std::stringstream(phixsline) >> in_nphixstargets);
assert_always(in_nphixstargets > 0);
// read in a table of target states and probabilities and store them
if (!single_level_top_ion || upperion < get_nions(element) - 1) // in case the top ion has nlevelsmax = 1
{
globals::elements[element].ions[lowerion].levels[lowerlevel].nphixstargets = in_nphixstargets;
*mem_usage_phixs += in_nphixstargets * sizeof(PhotoionTarget);
double probability_sum = 0.;
for (int i = 0; i < in_nphixstargets; i++) {
double phixstargetprobability{NAN};
assert_always(get_noncommentline(phixsfile, phixsline));
assert_always(std::stringstream(phixsline) >> upperlevel_in >> phixstargetprobability);
const int upperlevel = upperlevel_in - groundstate_index_in;
assert_always(upperlevel >= 0);
assert_always(phixstargetprobability > 0);
globals::allphixstargets.push_back({.probability = phixstargetprobability, .levelindex = upperlevel});
probability_sum += phixstargetprobability;
}
if (fabs(probability_sum - 1.0) > 0.01) {
printout("WARNING: photoionisation table for Z=%d ionstage %d has probabilities that sum to %g",
get_atomicnumber(element), get_ionstage(element, lowerion), probability_sum);
}
} else { // file has table of target states and probabilities but our top ion is limited to one level
globals::elements[element].ions[lowerion].levels[lowerlevel].nphixstargets = 1;
*mem_usage_phixs += sizeof(PhotoionTarget);
for (int i = 0; i < in_nphixstargets; i++) {
assert_always(get_noncommentline(phixsfile, phixsline));
}
// send it to the ground state of the top ion
globals::allphixstargets.push_back({.probability = 1., .levelindex = 0});
}
}
// The level contributes to the ionisinglevels if its energy
// is below the ionisation potential and the level doesn't
// belong to the topmost ion included.
// Rate coefficients are only available for ionising levels.
// also need (levelenergy < ionpot && ...)?
if (lowerion < get_nions(element) - 1) {
for (int phixstargetindex = 0; phixstargetindex < get_nphixstargets(element, lowerion, lowerlevel);
phixstargetindex++) {
const int upperlevel =
globals::allphixstargets[globals::elements[element].ions[lowerion].levels[lowerlevel].phixstargetstart +
phixstargetindex]
.levelindex;
if (upperlevel > get_maxrecombininglevel(element, lowerion + 1)) {
globals::elements[element].ions[lowerion + 1].maxrecombininglevel = upperlevel;
}
}
}
*mem_usage_phixs += globals::NPHIXSPOINTS * sizeof(float);
assert_always(tmpallphixs.size() % globals::NPHIXSPOINTS == 0);
const auto tmpphixsstart = tmpallphixs.size();
globals::elements[element].ions[lowerion].levels[lowerlevel].phixsstart = tmpphixsstart / globals::NPHIXSPOINTS;
tmpallphixs.resize(tmpallphixs.size() + globals::NPHIXSPOINTS);
auto *levelphixstable = &tmpallphixs[tmpphixsstart];
if (phixs_file_version == 1) {
assert_always(get_nphixstargets(element, lowerion, lowerlevel) == 1);
assert_always(get_phixsupperlevel(element, lowerion, lowerlevel, 0) == 0);
const double nu_edge = (epsilon(element, upperion, 0) - epsilon(element, lowerion, lowerlevel)) / H;
auto nugrid_in = std::vector<double>(nphixspoints_inputtable);
auto phixs_in = std::vector<double>(nphixspoints_inputtable);
for (int i = 0; i < nphixspoints_inputtable; i++) {
double energy = -1.;
double phixs = -1.;
assert_always(get_noncommentline(phixsfile, phixsline));
assert_always(std::stringstream(phixsline) >> energy >> phixs);
assert_always(energy >= 0);
assert_always(phixs >= 0);
nugrid_in[i] = nu_edge + (energy * 13.6 * EV) / H;
// the photoionisation cross-sections in the database are given in Mbarn=1e6 * 1e-28m^2
// to convert to cgs units multiply by 1e-18
phixs_in[i] = phixs * 1e-18;
}
const double nu_max = nugrid_in.back();
// Now interpolate these cross-sections
levelphixstable[0] = phixs_in[0];
gsl_interp_accel *acc = gsl_interp_accel_alloc();
gsl_spline *spline = gsl_spline_alloc(gsl_interp_linear, nphixspoints_inputtable);
gsl_spline_init(spline, nugrid_in.data(), phixs_in.data(), nphixspoints_inputtable);
for (int i = 1; i < globals::NPHIXSPOINTS; i++) {
const double nu = nu_edge * (1. + i * globals::NPHIXSNUINCREMENT);
if (nu > nu_max) {
levelphixstable[i] = phixs_in[nphixspoints_inputtable - 1] * pow(nu_max / nu, 3);
} else {
levelphixstable[i] = gsl_spline_eval(spline, nu, acc);
}
}
gsl_spline_free(spline);
gsl_interp_accel_free(acc);
} else {
for (int i = 0; i < globals::NPHIXSPOINTS; i++) {
float phixs{NAN};
assert_always(phixsfile >> phixs);
assert_always(phixs >= 0);
// the photoionisation cross-sections in the database are given in Mbarn = 1e6 * 1e-28m^2
// to convert to cgs units multiply by 1e-18
levelphixstable[i] = phixs * 1e-18;
}
}
globals::nbfcontinua += get_nphixstargets(element, lowerion, lowerlevel);
if (lowerlevel == 0 && get_nphixstargets(element, lowerion, lowerlevel) > 0) {
globals::nbfcontinua_ground++;
}
}
void read_phixs_file(const int phixs_file_version, std::vector<float> &tmpallphixs) {
size_t mem_usage_phixs = 0;
printout("readin phixs data from %s\n", phixsdata_filenames[phixs_file_version]);
auto phixsfile = fstream_required(phixsdata_filenames[phixs_file_version], std::ios::in);
std::string phixsline;
if (phixs_file_version == 1 && phixs_file_version_exists[2]) {
printout(
"using NPHIXSPOINTS = %d and NPHIXSNUINCREMENT = %lg from phixsdata_v2.txt to interpolate "
"phixsdata.txt data\n",
globals::NPHIXSPOINTS, globals::NPHIXSNUINCREMENT);
last_phixs_nuovernuedge = (1.0 + globals::NPHIXSNUINCREMENT * (globals::NPHIXSPOINTS - 1));
} else if (phixs_file_version == 1) {
globals::NPHIXSPOINTS = 100;
globals::NPHIXSNUINCREMENT = .1;
// not exactly where the last point is, but classic integrals go from nu_edge to 10*nu_edge
last_phixs_nuovernuedge = 10;
printout("using NPHIXSPOINTS = %d and NPHIXSNUINCREMENT = %lg set in input.cc\n", globals::NPHIXSPOINTS,
globals::NPHIXSNUINCREMENT);
} else {
assert_always(phixsfile >> globals::NPHIXSPOINTS);
assert_always(globals::NPHIXSPOINTS > 0);
assert_always(phixsfile >> globals::NPHIXSNUINCREMENT);
assert_always(globals::NPHIXSNUINCREMENT > 0.);
last_phixs_nuovernuedge = (1.0 + globals::NPHIXSNUINCREMENT * (globals::NPHIXSPOINTS - 1));
}
int Z = -1;
int upperionstage = -1;
int upperlevel_in = -1;
int lowerionstage = -1;
int lowerlevel_in = -1;
double phixs_threshold_ev = -1; // currently just ignored, and epilson is used instead
while (true) {
int nphixspoints_inputtable = 0;
if (!get_noncommentline(phixsfile, phixsline)) {
break;
}
if (phixs_file_version == 1) {
assert_always(std::istringstream(phixsline) >> Z >> upperionstage >> upperlevel_in >> lowerionstage >>
lowerlevel_in >> nphixspoints_inputtable);
} else {
assert_always(std::istringstream(phixsline) >> Z >> upperionstage >> upperlevel_in >> lowerionstage >>
lowerlevel_in >> phixs_threshold_ev);
nphixspoints_inputtable = globals::NPHIXSPOINTS;
}
assert_always(Z > 0);
assert_always(upperionstage >= 2);
assert_always(lowerionstage >= 1);
const int element = get_elementindex(Z);
// store only photoionization crosssections for elements that are part of the current model atom
bool skip_this_phixs_table = true; // will be set to false for good data
if (element >= 0 && get_nions(element) > 0) {
// translate readin ionstages to ion indices
const int upperion = upperionstage - get_ionstage(element, 0);
const int lowerion = lowerionstage - get_ionstage(element, 0);
const int lowerlevel = lowerlevel_in - groundstate_index_in;
assert_always(lowerionstage >= 0);
assert_always(lowerlevel >= 0);
// store only photoionization crosssections for ions that are part of the current model atom
if (lowerion >= 0 && upperion < get_nions(element) && lowerlevel < get_nlevels_ionising(element, lowerion)) {
read_phixs_data_table(phixsfile, nphixspoints_inputtable, element, lowerion, lowerlevel, upperion,
upperlevel_in, tmpallphixs, &mem_usage_phixs, phixs_file_version);
skip_this_phixs_table = false;
}
}
if (skip_this_phixs_table) { // for ions or elements that are not part of the current model atom, proceed through
// the table and throw away the data
if (upperlevel_in < 0) { // a table of target states and probabilities will follow, so read past those lines
int nphixstargets = 0;
assert_always(get_noncommentline(phixsfile, phixsline));
assert_always(std::stringstream(phixsline) >> nphixstargets);
for (int i = 0; i < nphixstargets; i++) {
assert_always(get_noncommentline(phixsfile, phixsline));
}
}
// skip through cross section list
for (int i = 0; i < nphixspoints_inputtable; i++) {
if (phixs_file_version == 1) {
assert_always(get_noncommentline(phixsfile, phixsline));
} else {
// one day we might want to put all of the cross section points onto a single line,
// so don't use getline here
float phixs = 0;
assert_always(phixsfile >> phixs);
}
}
}
}
printout("[info] mem_usage: photoionisation tables occupy %.3f MB\n", mem_usage_phixs / 1024. / 1024.);
}
constexpr auto downtranslevelstart(const int level) {
// each level index is associated with a block of size levelindex spanning all possible down transitions.
// so use the formula for the sum of 1 + 2 + 3 + 4 + ... + level
return level * (level + 1) / 2;
}
void read_ion_levels(std::fstream &adata, const int element, const int ion, const int nions, const int nlevels,
int nlevelsmax, const double energyoffset, const double ionpot) {
for (int level = 0; level < nlevels; level++) {
int levelindex_in = 0;
double levelenergy{NAN};
double statweight{NAN};
int ntransitions = 0;
std::string line;
assert_always(get_noncommentline(adata, line));
assert_always(std::istringstream(line) >> levelindex_in >> levelenergy >> statweight >> ntransitions);
assert_always(levelindex_in == level + groundstate_index_in);
if (level < nlevelsmax) {
const double currentlevelenergy = (energyoffset + levelenergy) * EV;
globals::elements[element].ions[ion].levels[level].nphixstargets = 0;
globals::elements[element].ions[ion].levels[level].phixsstart = -1;
globals::elements[element].ions[ion].levels[level].phixstargetstart = -1;
globals::elements[element].ions[ion].levels[level].epsilon = currentlevelenergy;
globals::elements[element].ions[ion].levels[level].stat_weight = statweight;
assert_always(statweight > 0.);
// The level contributes to the ionisinglevels if its energy
// is below the ionization potential and the level doesn't
// belong to the topmost ion included.
// Rate coefficients are only available for ionising levels.
if (levelenergy < ionpot && ion < nions - 1) {
globals::elements[element].ions[ion].ionisinglevels++;
}
set_ndowntrans(element, ion, level, 0);
set_nuptrans(element, ion, level, 0);
} else {
// globals::elements[element].ions[ion].levels[nlevelsmax - 1].stat_weight += statweight;
}
}
}
void read_ion_transitions(std::fstream &ftransitiondata, const int tottransitions_in_file, int &tottransitions,
std::vector<Transition> &iontransitiontable, const int nlevels_requiretransitions,
const int nlevels_requiretransitions_upperlevels) {
iontransitiontable.clear();
iontransitiontable.reserve(tottransitions);
std::string line;
if (tottransitions == 0) {
// we will not read in any transitions, just skip past these lines in the file
for (int i = 0; i < tottransitions_in_file; i++) {
assert_always(getline(ftransitiondata, line));
}
} else {
// will be autodetected from first table row. old format had an index column and no collstr or forbidden columns
bool oldtransitionformat = false;
int prev_upper = -1;
int prev_lower = 0;
for (int i = 0; i < tottransitions_in_file; i++) {
int lower_in = -1;
int upper_in = -1;
float A = 0;
float coll_str = -1.;
int intforbidden = 0;
assert_always(getline(ftransitiondata, line));
if (i == 0) {
std::istringstream ss(line);
std::string word;
int column_count = 0;
while (ss >> word) {
column_count++;
}
assert_always(column_count == 4 || column_count == 5);
oldtransitionformat = (column_count == 4);
}
if (!oldtransitionformat) {
assert_always(std::istringstream(line) >> lower_in >> upper_in >> A >> coll_str >> intforbidden);
} else {
int transindex = 0; // not used
assert_always(std::istringstream(line) >> transindex >> lower_in >> upper_in >> A);
}
const int lower = lower_in - groundstate_index_in;
const int upper = upper_in - groundstate_index_in;
assert_always(lower >= 0);
assert_always(upper > lower);
assert_always(lower >= prev_lower);
assert_always(upper >= prev_upper || lower > prev_lower);
// this entire block can be removed if we don't want to add in extra collisonal
// transitions between levels
if (prev_lower < nlevels_requiretransitions) {
assert_always(prev_lower >= 0);
int stoplevel = 0;
if (lower == prev_lower && upper > prev_upper + 1) {
// same lower level, but some upper levels were skipped over
stoplevel = upper - 1;
if (stoplevel >= nlevels_requiretransitions_upperlevels) {
stoplevel = nlevels_requiretransitions_upperlevels - 1;
}
} else if ((lower > prev_lower) && prev_upper < (nlevels_requiretransitions_upperlevels - 1)) {
// we've moved onto another lower level, but the previous one was missing some required transitions
stoplevel = nlevels_requiretransitions_upperlevels - 1;
} else {
stoplevel = -1;
}
for (int tmplevel = prev_upper + 1; tmplevel <= stoplevel; tmplevel++) {
if (tmplevel == prev_lower) {
continue;
}
tottransitions++;
assert_always(tmplevel >= 0);
iontransitiontable.push_back(
{.lower = prev_lower, .upper = tmplevel, .A = 0., .coll_str = -2., .forbidden = true});
}
}
iontransitiontable.push_back(
{.lower = lower, .upper = upper, .A = A, .coll_str = coll_str, .forbidden = (intforbidden == 1)});
prev_lower = lower;
prev_upper = upper;
}
}
}
void add_transitions_to_unsorted_linelist(const int element, const int ion, const int nlevelsmax,
const std::vector<Transition> &transitiontable,
std::vector<int> &iondowntranstmplineindicies, int &lineindex,
std::vector<TransitionLine> &temp_linelist,
std::vector<LevelTransition> &temp_alltranslist,
size_t &temp_alltranslist_size) {
const int lineindex_initial = lineindex;
ptrdiff_t totupdowntrans = 0;
// pass 0 to get transition counts of each level
// pass 1 to allocate and fill transition arrays
for (int pass = 0; pass < 2; pass++) {
lineindex = lineindex_initial;
if (pass == 1) {
int alltransindex = temp_alltranslist_size;
temp_alltranslist_size += totupdowntrans;
if (globals::rank_in_node == 0) {
resize_exactly(temp_alltranslist, temp_alltranslist_size);
assert_always(temp_alltranslist_size >= temp_linelist.size());
temp_linelist.reserve(temp_alltranslist_size);
}
for (int level = 0; level < nlevelsmax; level++) {
globals::elements[element].ions[ion].levels[level].alltrans_startdown = alltransindex;
alltransindex += get_ndowntrans(element, ion, level);
alltransindex += get_nuptrans(element, ion, level);
set_ndowntrans(element, ion, level, 0);
set_nuptrans(element, ion, level, 0);
}
}
std::ranges::fill(iondowntranstmplineindicies, -99);
totupdowntrans = 0;
for (const auto &transition : transitiontable) {
const int level = transition.upper;
const int lowerlevel = transition.lower;
if (pass == 0) {
assert_always(lowerlevel >= 0);
assert_always(level > lowerlevel);
}
if ((lowerlevel >= nlevelsmax) || (level >= nlevelsmax)) {
continue;
}
const double nu_trans = (epsilon(element, ion, level) - epsilon(element, ion, lowerlevel)) / H;
if (!(nu_trans > 0)) {
continue;
}
// Make sure that we don't allow duplicate. In that case take only the lines
// first occurrence
int &downtranslineindex = iondowntranstmplineindicies[downtranslevelstart(level) + lowerlevel];
// negative means that the transition hasn't been seen yet
if (downtranslineindex < 0) {
downtranslineindex = lineindex++;
const int nupperdowntrans = get_ndowntrans(element, ion, level) + 1;
set_ndowntrans(element, ion, level, nupperdowntrans);
const int nloweruptrans = get_nuptrans(element, ion, lowerlevel) + 1;
set_nuptrans(element, ion, lowerlevel, nloweruptrans);
totupdowntrans += 2;
if (pass == 1 && globals::rank_in_node == 0) {
const auto g_ratio = stat_weight(element, ion, level) / stat_weight(element, ion, lowerlevel);
const float f_ul = g_ratio * ME * pow(CLIGHT, 3) / (8 * pow(QE * nu_trans * PI, 2)) * transition.A;
assert_always(std::isfinite(f_ul));
temp_linelist.push_back({
.nu = nu_trans,
.einstein_A = transition.A,
.elementindex = element,
.ionindex = ion,
.upperlevelindex = level,
.lowerlevelindex = lowerlevel,
});
// the line list has not been sorted yet, so the store the level index for now and
// the index into the sorted line list will be set later
temp_alltranslist[globals::elements[element].ions[ion].levels[level].alltrans_startdown + nupperdowntrans -
1] = {.lineindex = -1,
.targetlevelindex = lowerlevel,
.einstein_A = transition.A,
.coll_str = transition.coll_str,
.osc_strength = f_ul,
.forbidden = transition.forbidden};
const auto lowerstartup = globals::elements[element].ions[ion].levels[lowerlevel].alltrans_startdown +
get_ndowntrans(element, ion, lowerlevel);
temp_alltranslist[lowerstartup + nloweruptrans - 1] = {.lineindex = -1,
.targetlevelindex = level,
.einstein_A = transition.A,
.coll_str = transition.coll_str,
.osc_strength = f_ul,
.forbidden = transition.forbidden};
}
} else if (pass == 1 && globals::rank_in_node == 0) {
// This is a new branch to deal with lines that have different types of transition. It should trip after a
// transition is already known.
if ((temp_linelist[downtranslineindex].elementindex != element) ||
(temp_linelist[downtranslineindex].ionindex != ion) ||
(temp_linelist[downtranslineindex].upperlevelindex != level) ||
(temp_linelist[downtranslineindex].lowerlevelindex != lowerlevel)) {
printout("[input] Failure to identify level pair for duplicate bb-transition ... going to abort now\n");
printout("[input] element %d ion %d targetlevel %d level %d\n", element, ion, lowerlevel, level);
printout("[input] transitions[level].to[targetlevel]=lineindex %d\n", downtranslineindex);
printout("[input] A_ul %g, coll_str %g\n", transition.A, transition.coll_str);
printout(
"[input] globals::linelist[lineindex].elementindex %d, "
"globals::linelist[lineindex].ionindex %d, globals::linelist[lineindex].upperlevelindex "
"%d, globals::linelist[lineindex].lowerlevelindex %d\n",
temp_linelist[downtranslineindex].elementindex, temp_linelist[downtranslineindex].ionindex,
temp_linelist[downtranslineindex].upperlevelindex, temp_linelist[downtranslineindex].lowerlevelindex);
std::abort();
}
const auto g_ratio = stat_weight(element, ion, level) / stat_weight(element, ion, lowerlevel);
const float f_ul = g_ratio * ME * pow(CLIGHT, 3) / (8 * pow(QE * nu_trans * PI, 2)) * transition.A;
const int nupperdowntrans = get_ndowntrans(element, ion, level);
auto &downtransition = temp_alltranslist[globals::elements[element].ions[ion].levels[level].alltrans_startdown +
nupperdowntrans - 1];
assert_always(downtransition.targetlevelindex == lowerlevel);
downtransition.einstein_A += transition.A;
downtransition.osc_strength += f_ul;
downtransition.coll_str = std::max(downtransition.coll_str, transition.coll_str);
const int nloweruptrans = get_nuptrans(element, ion, lowerlevel);
const auto lowerstartup = globals::elements[element].ions[ion].levels[lowerlevel].alltrans_startdown +
get_ndowntrans(element, ion, lowerlevel);
auto &uptransition = temp_alltranslist[lowerstartup + nloweruptrans - 1];
// as above, the downtrans list should be searched to find the correct index instead of using the last one.
// assert_always(uptransition.targetlevelindex == level);
uptransition.einstein_A += transition.A;
uptransition.osc_strength += f_ul;
uptransition.coll_str = std::max(uptransition.coll_str, transition.coll_str);
}
}
}
MPI_Barrier(MPI_COMM_WORLD);
}
auto calculate_nlevels_groundterm(const int element, const int ion) -> int {
const int nlevels = get_nlevels(element, ion);
if (nlevels == 1) {
return 1;
}
int nlevels_groundterm = 1;
// detect single-level ground term
const double endiff10 = epsilon(element, ion, 1) - epsilon(element, ion, 0);
const double endiff21 = epsilon(element, ion, 2) - epsilon(element, ion, 1);
if (endiff10 > 2. * endiff21) {
nlevels_groundterm = 1;
} else {
for (int level = 1; level < nlevels - 2; level++) {
const double endiff1 = epsilon(element, ion, level) - epsilon(element, ion, level - 1);
const double endiff2 = epsilon(element, ion, level + 1) - epsilon(element, ion, level);
if (endiff2 > 2. * endiff1) {
nlevels_groundterm = level + 1;
break;
}
}
}
// there should be no duplicate stat weights within the ground term
// limit the ground multiplet to nnnnlowest levels below the first duplicated stat weight
for (int level_a = 1; level_a < nlevels_groundterm; level_a++) {
const float g_a = stat_weight(element, ion, level_a);
for (int level_b = 0; level_b < level_a; level_b++) {
const float g_b = stat_weight(element, ion, level_b);
if (fabs(g_a - g_b) < 0.4) {
// level_a is outside the ground term because of duplicate stat weight
// highest ground level index is level_a - 1, so nlevels_groundterm == level_a
return level_a;
}
}
}
return nlevels_groundterm;
}
auto search_groundphixslist(const double nu_edge, const int element_in, const int ion_in, const int level_in) -> int
// Return the closest ground level continuum index to the given edge
// frequency. If the given edge frequency is redder than the reddest
// continuum return -1.
// NB: groundphixslist must be in ascending order.
{
assert_always((USE_LUT_PHOTOION || USE_LUT_BFHEATING));
if (nu_edge < globals::groundcont[0].nu_edge) {
return -1;
}
int i = 1;
for (i = 1; i < globals::nbfcontinua_ground; i++) {
if (nu_edge < globals::groundcont[i].nu_edge) {
break;
}
}
if (i == globals::nbfcontinua_ground) {
const int element = globals::groundcont[i - 1].element;
const int ion = globals::groundcont[i - 1].ion;
if (element == element_in && ion == ion_in && level_in == 0) {
return i - 1;
}
printout(
"[fatal] search_groundphixslist: element %d, ion %d, level %d has edge_frequency %g equal to the "
"bluest ground-level continuum\n",
element_in, ion_in, level_in, nu_edge);
printout(
"[fatal] search_groundphixslist: bluest ground level continuum is element %d, ion %d at "
"nu_edge %g\n",
element, ion, globals::groundcont[i - 1].nu_edge);
printout("[fatal] search_groundphixslist: i %d, nbfcontinua_ground %d\n", i, globals::nbfcontinua_ground);
printout(
"[fatal] This shouldn't happen, is hoewever possible if there are multiple levels in the adata file at "
"energy=0\n");
for (int looplevels = 0; looplevels < get_nlevels(element_in, ion_in); looplevels++) {
printout("[fatal] element %d, ion %d, level %d, energy %g\n", element_in, ion_in, looplevels,
epsilon(element_in, ion_in, looplevels));
}
printout("[fatal] Abort omitted ... MAKE SURE ATOMIC DATA ARE CONSISTENT\n");
return i - 1;
// abort();
}
const double left_diff = nu_edge - globals::groundcont[i - 1].nu_edge;
const double right_diff = globals::groundcont[i].nu_edge - nu_edge;
return (left_diff <= right_diff) ? i - 1 : i;
}
// set up the photoionisation transition lists
// and temporary gamma/kappa lists for each thread
void setup_phixs_list() {
printout("[info] read_atomicdata: number of bfcontinua %d\n", globals::nbfcontinua);
printout("[info] read_atomicdata: number of ground-level bfcontinua %d\n", globals::nbfcontinua_ground);
globals::groundcont.resize(globals::nbfcontinua_ground);
int nextgroundcontindex = 0;
for (int element = 0; element < get_nelements(); element++) {
const int nions = get_nions(element);
for (int ion = 0; ion < nions - 1; ion++) {
const int level = 0;
const int nphixstargets = get_nphixstargets(element, ion, level);
if (nphixstargets == 0) {
continue;
}
const double E_threshold = get_phixs_threshold(element, ion, level, 0);
const double nu_edge = E_threshold / H;
assert_always(nextgroundcontindex < globals::nbfcontinua_ground);
globals::groundcont[nextgroundcontindex] = {.nu_edge = nu_edge, .element = element, .ion = ion};
nextgroundcontindex++;
}
}
assert_always(nextgroundcontindex == globals::nbfcontinua_ground);
std::ranges::SORT_OR_STABLE_SORT(globals::groundcont, std::ranges::less{}, &GroundPhotoion::nu_edge);
auto *nonconstallcont =
static_cast<FullPhotoionTransition *>(malloc(globals::nbfcontinua * sizeof(FullPhotoionTransition)));
printout("[info] mem_usage: photoionisation list occupies %.3f MB\n",
globals::nbfcontinua * (sizeof(FullPhotoionTransition)) / 1024. / 1024.);
int allcontindex = 0;
for (int element = 0; element < get_nelements(); element++) {
const int nions = get_nions(element);
for (int ion = 0; ion < nions - 1; ion++) {
globals::elements[element].ions[ion].groundcontindex =
static_cast<int>(std::ranges::find_if(globals::groundcont,
[=](const auto &groundcont) {
return (groundcont.element == element) && (groundcont.ion == ion);
}) -
globals::groundcont.begin());
if (globals::elements[element].ions[ion].groundcontindex >= globals::nbfcontinua_ground) {
globals::elements[element].ions[ion].groundcontindex = -1;
}
const int nlevels = get_nlevels_ionising(element, ion);
for (int level = 0; level < nlevels; level++) {
const int nphixstargets = get_nphixstargets(element, ion, level);
for (int phixstargetindex = 0; phixstargetindex < nphixstargets; phixstargetindex++) {
const double nu_edge = get_phixs_threshold(element, ion, level, phixstargetindex) / H;
assert_always(allcontindex < globals::nbfcontinua);
nonconstallcont[allcontindex].nu_edge = nu_edge;
nonconstallcont[allcontindex].element = element;
nonconstallcont[allcontindex].ion = ion;
nonconstallcont[allcontindex].level = level;
nonconstallcont[allcontindex].phixstargetindex = phixstargetindex;
nonconstallcont[allcontindex].probability = get_phixsprobability(element, ion, level, phixstargetindex);
nonconstallcont[allcontindex].upperlevel = get_phixsupperlevel(element, ion, level, phixstargetindex);
if constexpr (USE_LUT_PHOTOION || USE_LUT_BFHEATING) {
const double nu_edge_target0 = get_phixs_threshold(element, ion, level, 0) / H;
const auto groundcontindex = search_groundphixslist(nu_edge_target0, element, ion, level);
nonconstallcont[allcontindex].index_in_groundphixslist = groundcontindex;
globals::elements[element].ions[ion].levels[level].closestgroundlevelcont = groundcontindex;
}
allcontindex++;
}
}
}
}
assert_always(allcontindex == globals::nbfcontinua);
assert_always(globals::nbfcontinua >= 0); // was initialised as -1 before startup
const auto nbfcontinua =
globals::nbfcontinua; // so that clang-tidy doesn't throw errors on the assumption that nbfcontinua is changing
globals::bfestimcount = 0;
if (nbfcontinua > 0) {
// indices above were temporary only. continuum index should be to the sorted list
std::ranges::SORT_OR_STABLE_SORT(std::span(nonconstallcont, nbfcontinua), std::ranges::less{},
&FullPhotoionTransition::nu_edge);
globals::bfestim_nu_edge.clear();
for (int i = 0; i < nbfcontinua; i++) {
auto &cont = nonconstallcont[i];
if (DETAILED_BF_ESTIMATORS_ON &&
LEVEL_HAS_BFEST(get_atomicnumber(cont.element), get_ionstage(cont.element, cont.ion), cont.level)) {
cont.bfestimindex = globals::bfestimcount;
globals::bfestim_nu_edge.push_back(cont.nu_edge);
globals::bfestimcount++;
} else {
cont.bfestimindex = -1;
}
}
globals::allcont_nu_edge.resize(nbfcontinua, 0.);
globals::bfestim_nu_edge.shrink_to_fit();
assert_always(globals::bfestimcount == std::ssize(globals::bfestim_nu_edge));
for (int i = 0; i < nbfcontinua; i++) {
globals::allcont_nu_edge[i] = nonconstallcont[i].nu_edge;
}
setup_photoion_luts();
for (int i = 0; i < nbfcontinua; i++) {
const int element = nonconstallcont[i].element;
const int ion = nonconstallcont[i].ion;
const int level = nonconstallcont[i].level;
nonconstallcont[i].photoion_xs = get_phixs_table(element, ion, level);
assert_always(nonconstallcont[i].photoion_xs != nullptr);
}
}
printout("[info] bound-free estimators track bfestimcount %d photoionisation transitions\n", globals::bfestimcount);
globals::allcont = nonconstallcont;
nonconstallcont = nullptr;
}
void read_phixs_data() {
globals::nbfcontinua_ground = 0;
globals::nbfcontinua = 0;
std::vector<float> tmpallphixs;
globals::allphixstargets.clear();
// read in photoionisation cross sections
phixs_file_version_exists[0] = false;
phixs_file_version_exists[1] = std::filesystem::exists(phixsdata_filenames[1]);
phixs_file_version_exists[2] = std::filesystem::exists(phixsdata_filenames[2]);
// just in case the file system was faulty and the ranks disagree on the existence of the files
MPI_Allreduce(MPI_IN_PLACE, phixs_file_version_exists.data(), 3, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);
assert_always(phixs_file_version_exists[1] || phixs_file_version_exists[2]); // at least one must exist
if (phixs_file_version_exists[1] && phixs_file_version_exists[2]) {
printout(
"Reading two phixs files: Reading phixsdata_v2.txt first so we use NPHIXSPOINTS and NPHIXSNUINCREMENT "
"from phixsdata_v2.txt to interpolate the phixsdata.txt data\n");
}
if (phixs_file_version_exists[2]) {
read_phixs_file(2, tmpallphixs);
}
if (phixs_file_version_exists[1]) {
read_phixs_file(1, tmpallphixs);
}
int cont_index = 0;
ptrdiff_t nbftables = 0;
for (int element = 0; element < get_nelements(); element++) {
const int nions = get_nions(element);
for (int ion = 0; ion < nions; ion++) {
const int nlevels = get_nlevels(element, ion);
for (int level = 0; level < nlevels; level++) {
const int nphixstargets = get_nphixstargets(element, ion, level);
globals::elements[element].ions[ion].levels[level].cont_index = (nphixstargets > 0) ? cont_index : -1;
cont_index += nphixstargets;
if (nphixstargets > 0) {
nbftables++;
}
}
// below is just an extra warning consistency check
const int nlevels_groundterm = globals::elements[element].ions[ion].nlevels_groundterm;
// all levels in the ground term should be photoionisation targets from the lower ground state
if (ion > 0 && ion < get_nions(element) - 1) {
const int nphixstargets = get_nphixstargets(element, ion - 1, 0);
if (nphixstargets > 0 && get_phixsupperlevel(element, ion - 1, 0, 0) == 0) {
const int phixstargetlevels = get_phixsupperlevel(element, ion - 1, 0, nphixstargets - 1) + 1;
if (nlevels_groundterm != phixstargetlevels) {
printout("WARNING: Z=%d ionstage %d nlevels_groundterm %d phixstargetlevels(ion-1) %d.\n",
get_atomicnumber(element), get_ionstage(element, ion), nlevels_groundterm, phixstargetlevels);
// if (nlevels_groundterm < phixstargetlevels)
// {
// printout(" -> setting to %d\n", phixstargetlevels);
// globals::elements[element].ions[ion].nlevels_groundterm = phixstargetlevels;
// }
}
}
}
}
}
printout("cont_index %d\n", cont_index);
if (!tmpallphixs.empty()) {
assert_always((nbftables * globals::NPHIXSPOINTS) == std::ssize(tmpallphixs));
// copy the photoionisation tables into one contiguous block of memory
globals::allphixs = MPI_shared_malloc<float>(tmpallphixs.size());
assert_always(globals::allphixs != nullptr);
std::copy_n(tmpallphixs.cbegin(), tmpallphixs.size(), globals::allphixs);
MPI_Barrier(MPI_COMM_WORLD);
tmpallphixs.clear();
tmpallphixs.shrink_to_fit();
}
globals::allphixstargets.shrink_to_fit();
assert_always(cont_index == std::ssize(globals::allphixstargets));
setup_phixs_list();
}
void read_atomicdata_files() {
int totaluptrans = 0;
int totaldowntrans = 0;
auto compositiondata = fstream_required("compositiondata.txt", std::ios::in);
auto adata = fstream_required("adata.txt", std::ios::in);
printout("single_level_top_ion: %s\n", single_level_top_ion ? "true" : "false");
printout("single_ground_level: %s\n", single_ground_level ? "true" : "false");
// initialize atomic data structure to number of elements
int nelements_in = 0;
assert_always(compositiondata >> nelements_in);
globals::elements.resize(nelements_in);
std::vector<TransitionLine> temp_linelist;
std::vector<LevelTransition> temp_alltranslist;
size_t temp_alltranslist_size = 0; // keep size separate because the vector is only resized on rank_in_node == 0
std::vector<Transition> iontransitiontable;
std::vector<int> iondowntranstmplineindicies;
// temperature to determine relevant ionstages
int T_preset = 0;
assert_always(compositiondata >> T_preset);
assert_always(T_preset == 0); // no longer in use
int homogeneous_abundances = 0;
assert_always(compositiondata >> homogeneous_abundances);
assert_always(homogeneous_abundances == 0); // no longer in use
// open transition data file
auto ftransitiondata = fstream_required("transitiondata.txt", std::ios::in);
int lineindex = 0; // counter to determine the total number of lines
int uniqueionindex = 0; // index into list of all ions of all elements
int uniquelevelindex = 0; // index into list of all levels of all ions of all elements
int nbfcheck = 0;
for (int element = 0; element < get_nelements(); element++) {
// read information about the next element which should be stored to memory
int Z = 0;
int nions = 0;
int lowermost_ionstage = 0;
int uppermost_ionstage = 0;
int nlevelsmax_readin = 0;
double uniformabundance{NAN}; // no longer in use mode for setting uniform abundances
double mass_amu{NAN};
assert_always(compositiondata >> Z >> nions >> lowermost_ionstage >> uppermost_ionstage >> nlevelsmax_readin >>
uniformabundance >> mass_amu);
printout("readin compositiondata: next element Z %d, nions %d, lowermost %d, uppermost %d, nlevelsmax %d\n", Z,
nions, lowermost_ionstage, uppermost_ionstage, nlevelsmax_readin);
assert_always(Z > 0);
assert_always(nions >= 0);
assert_always(nions == 0 || (nions == uppermost_ionstage - lowermost_ionstage + 1));
assert_always(uniformabundance >= 0);
assert_always(mass_amu >= 0);
// write this element's data to memory
globals::elements[element].anumber = Z;
globals::elements[element].nions = nions;
globals::elements[element].initstablemeannucmass = mass_amu * MH;
globals::elements[element].uniqueionindexstart = uniqueionindex;
// Initialize the elements ionlist
globals::elements[element].ions = static_cast<Ion *>(malloc(nions * sizeof(Ion)));
assert_always(globals::elements[element].ions != nullptr);
// now read in data for all ions of the current element. before doing so initialize
// energy scale for the current element (all level energies are stored relative to
// the ground level of the neutral ion)
double energyoffset = 0.;
double ionpot = 0.;
for (int ion = 0; ion < nions; ion++) {
int nlevelsmax = nlevelsmax_readin;
// calculate the current levels ground level energy
assert_always(ionpot >= 0);
energyoffset += ionpot;
// read information for the elements next ionstage
int adata_Z_in = -1;
int ionstage = -1;
int nlevels = 0;
while (adata_Z_in != Z || ionstage != lowermost_ionstage + ion) // skip over this ion block
{
if (adata_Z_in == Z) {
printout("increasing energyoffset by ionpot %g\n", ionpot);
energyoffset += ionpot;
}
for (int i = 0; i < nlevels; i++) {
double levelenergy{NAN};