• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmc-dev / openmc / 13591584831

28 Feb 2025 03:46PM UTC coverage: 85.051% (+0.3%) from 84.722%
13591584831

Pull #3067

github

web-flow
Merge 08055e996 into c26fde666
Pull Request #3067: Implement user-configurable random number stride

36 of 44 new or added lines in 8 files covered. (81.82%)

3588 existing lines in 111 files now uncovered.

51062 of 60037 relevant lines covered (85.05%)

32650986.73 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.24
/src/material.cpp
1
#include "openmc/material.h"
2

3
#include <algorithm> // for min, max, sort, fill
4
#include <cassert>
5
#include <cmath>
6
#include <iterator>
7
#include <sstream>
8
#include <string>
9
#include <unordered_set>
10

11
#include "xtensor/xbuilder.hpp"
12
#include "xtensor/xoperation.hpp"
13
#include "xtensor/xview.hpp"
14

15
#include "openmc/capi.h"
16
#include "openmc/container_util.h"
17
#include "openmc/cross_sections.h"
18
#include "openmc/error.h"
19
#include "openmc/file_utils.h"
20
#include "openmc/hdf5_interface.h"
21
#include "openmc/math_functions.h"
22
#include "openmc/message_passing.h"
23
#include "openmc/mgxs_interface.h"
24
#include "openmc/nuclide.h"
25
#include "openmc/photon.h"
26
#include "openmc/search.h"
27
#include "openmc/settings.h"
28
#include "openmc/simulation.h"
29
#include "openmc/string_utils.h"
30
#include "openmc/thermal.h"
31
#include "openmc/xml_interface.h"
32

33
namespace openmc {
34

35
//==============================================================================
36
// Global variables
37
//==============================================================================
38

39
namespace model {
40

41
std::unordered_map<int32_t, int32_t> material_map;
42
vector<unique_ptr<Material>> materials;
43

44
} // namespace model
45

46
//==============================================================================
47
// Material implementation
48
//==============================================================================
49

50
Material::Material(pugi::xml_node node)
14,015✔
51
{
52
  index_ = model::materials.size(); // Avoids warning about narrowing
14,015✔
53

54
  if (check_for_node(node, "id")) {
14,015✔
55
    this->set_id(std::stoi(get_node_value(node, "id")));
14,015✔
56
  } else {
UNCOV
57
    fatal_error("Must specify id of material in materials XML file.");
×
58
  }
59

60
  if (check_for_node(node, "name")) {
14,015✔
61
    name_ = get_node_value(node, "name");
6,261✔
62
  }
63

64
  if (check_for_node(node, "cfg")) {
14,015✔
65
    auto cfg = get_node_value(node, "cfg");
1✔
66
    write_message(
1✔
67
      5, "NCrystal config string for material #{}: '{}'", this->id(), cfg);
1✔
68
    ncrystal_mat_ = NCrystalMat(cfg);
1✔
69
  }
1✔
70

71
  if (check_for_node(node, "depletable")) {
14,015✔
72
    depletable_ = get_node_value_bool(node, "depletable");
5,282✔
73
  }
74

75
  bool sum_density {false};
14,015✔
76
  pugi::xml_node density_node = node.child("density");
14,015✔
77
  std::string units;
14,015✔
78
  if (density_node) {
14,015✔
79
    units = get_node_value(density_node, "units");
14,015✔
80
    if (units == "sum") {
14,015✔
81
      sum_density = true;
2,667✔
82
    } else if (units == "macro") {
11,348✔
83
      if (check_for_node(density_node, "value")) {
1,789✔
84
        density_ = std::stod(get_node_value(density_node, "value"));
1,789✔
85
      } else {
UNCOV
86
        density_ = 1.0;
×
87
      }
88
    } else {
89
      double val = std::stod(get_node_value(density_node, "value"));
9,559✔
90
      if (val <= 0.0) {
9,559✔
91
        fatal_error("Need to specify a positive density on material " +
×
UNCOV
92
                    std::to_string(id_) + ".");
×
93
      }
94

95
      if (units == "g/cc" || units == "g/cm3") {
9,559✔
96
        density_ = -val;
9,097✔
97
      } else if (units == "kg/m3") {
462✔
98
        density_ = -1.0e-3 * val;
17✔
99
      } else if (units == "atom/b-cm") {
445✔
100
        density_ = val;
428✔
101
      } else if (units == "atom/cc" || units == "atom/cm3") {
17✔
102
        density_ = 1.0e-24 * val;
17✔
103
      } else {
104
        fatal_error("Unknown units '" + units + "' specified on material " +
×
UNCOV
105
                    std::to_string(id_) + ".");
×
106
      }
107
    }
108
  } else {
109
    fatal_error("Must specify <density> element in material " +
×
UNCOV
110
                std::to_string(id_) + ".");
×
111
  }
112

113
  if (node.child("element")) {
14,015✔
114
    fatal_error(
×
UNCOV
115
      "Unable to add an element to material " + std::to_string(id_) +
×
116
      " since the element option has been removed from the xml input. "
117
      "Elements can only be added via the Python API, which will expand "
118
      "elements into their natural nuclides.");
119
  }
120

121
  // =======================================================================
122
  // READ AND PARSE <nuclide> TAGS
123

124
  // Check to ensure material has at least one nuclide
125
  if (!check_for_node(node, "nuclide") &&
15,804✔
126
      !check_for_node(node, "macroscopic")) {
1,789✔
127
    fatal_error("No macroscopic data or nuclides specified on material " +
×
UNCOV
128
                std::to_string(id_));
×
129
  }
130

131
  // Create list of macroscopic x/s based on those specified, just treat
132
  // them as nuclides. This is all really a facade so the user thinks they
133
  // are entering in macroscopic data but the code treats them the same
134
  // as nuclides internally.
135
  // Get pointer list of XML <macroscopic>
136
  auto node_macros = node.children("macroscopic");
14,015✔
137
  int num_macros = std::distance(node_macros.begin(), node_macros.end());
14,015✔
138

139
  vector<std::string> names;
14,015✔
140
  vector<double> densities;
14,015✔
141
  if (settings::run_CE && num_macros > 0) {
14,015✔
UNCOV
142
    fatal_error("Macroscopic can not be used in continuous-energy mode.");
×
143
  } else if (num_macros > 1) {
14,015✔
144
    fatal_error("Only one macroscopic object permitted per material, " +
×
UNCOV
145
                std::to_string(id_));
×
146
  } else if (num_macros == 1) {
14,015✔
147
    pugi::xml_node node_nuc = *node_macros.begin();
1,789✔
148

149
    // Check for empty name on nuclide
150
    if (!check_for_node(node_nuc, "name")) {
1,789✔
151
      fatal_error("No name specified on macroscopic data in material " +
×
UNCOV
152
                  std::to_string(id_));
×
153
    }
154

155
    // store nuclide name
156
    std::string name = get_node_value(node_nuc, "name", false, true);
1,789✔
157
    names.push_back(name);
1,789✔
158

159
    // Set density for macroscopic data
160
    if (units == "macro") {
1,789✔
161
      densities.push_back(density_);
1,789✔
162
    } else {
UNCOV
163
      fatal_error("Units can only be macro for macroscopic data " + name);
×
164
    }
165
  } else {
1,789✔
166
    // Create list of nuclides based on those specified
167
    for (auto node_nuc : node.children("nuclide")) {
64,507✔
168
      // Check for empty name on nuclide
169
      if (!check_for_node(node_nuc, "name")) {
52,281✔
170
        fatal_error(
×
UNCOV
171
          "No name specified on nuclide in material " + std::to_string(id_));
×
172
      }
173

174
      // store nuclide name
175
      std::string name = get_node_value(node_nuc, "name", false, true);
52,281✔
176
      names.push_back(name);
52,281✔
177

178
      // Check if no atom/weight percents were specified or if both atom and
179
      // weight percents were specified
180
      if (units == "macro") {
52,281✔
UNCOV
181
        densities.push_back(density_);
×
182
      } else {
183
        bool has_ao = check_for_node(node_nuc, "ao");
52,281✔
184
        bool has_wo = check_for_node(node_nuc, "wo");
52,281✔
185

186
        if (!has_ao && !has_wo) {
52,281✔
187
          fatal_error(
×
UNCOV
188
            "No atom or weight percent specified for nuclide: " + name);
×
189
        } else if (has_ao && has_wo) {
52,281✔
190
          fatal_error("Cannot specify both atom and weight percents for a "
×
UNCOV
191
                      "nuclide: " +
×
192
                      name);
193
        }
194

195
        // Copy atom/weight percents
196
        if (has_ao) {
52,281✔
197
          densities.push_back(std::stod(get_node_value(node_nuc, "ao")));
43,167✔
198
        } else {
199
          densities.push_back(-std::stod(get_node_value(node_nuc, "wo")));
9,114✔
200
        }
201
      }
202
    }
52,281✔
203
  }
204

205
  // =======================================================================
206
  // READ AND PARSE <isotropic> element
207

208
  vector<std::string> iso_lab;
14,015✔
209
  if (check_for_node(node, "isotropic")) {
14,015✔
210
    iso_lab = get_node_array<std::string>(node, "isotropic");
204✔
211
  }
212

213
  // ========================================================================
214
  // COPY NUCLIDES TO ARRAYS IN MATERIAL
215

216
  // allocate arrays in Material object
217
  auto n = names.size();
14,015✔
218
  nuclide_.reserve(n);
14,015✔
219
  atom_density_ = xt::empty<double>({n});
14,015✔
220
  if (settings::photon_transport)
14,015✔
221
    element_.reserve(n);
278✔
222

223
  for (int i = 0; i < n; ++i) {
68,085✔
224
    const auto& name {names[i]};
54,070✔
225

226
    // Check that this nuclide is listed in the nuclear data library
227
    // (cross_sections.xml for CE and the MGXS HDF5 for MG)
228
    if (settings::run_mode != RunMode::PLOTTING) {
54,070✔
229
      LibraryKey key {Library::Type::neutron, name};
52,608✔
230
      if (data::library_map.find(key) == data::library_map.end()) {
52,608✔
UNCOV
231
        fatal_error("Could not find nuclide " + name +
×
232
                    " in the "
233
                    "nuclear data library.");
234
      }
235
    }
52,608✔
236

237
    // If this nuclide hasn't been encountered yet, we need to add its name
238
    // and alias to the nuclide_dict
239
    if (data::nuclide_map.find(name) == data::nuclide_map.end()) {
54,070✔
240
      int index = data::nuclide_map.size();
28,751✔
241
      data::nuclide_map[name] = index;
28,751✔
242
      nuclide_.push_back(index);
28,751✔
243
    } else {
244
      nuclide_.push_back(data::nuclide_map[name]);
25,319✔
245
    }
246

247
    // If the corresponding element hasn't been encountered yet and photon
248
    // transport will be used, we need to add its symbol to the element_dict
249
    if (settings::photon_transport) {
54,070✔
250
      std::string element = to_element(name);
1,389✔
251

252
      // Make sure photon cross section data is available
253
      if (settings::run_mode != RunMode::PLOTTING) {
1,389✔
254
        LibraryKey key {Library::Type::photon, element};
1,389✔
255
        if (data::library_map.find(key) == data::library_map.end()) {
1,389✔
256
          fatal_error(
×
UNCOV
257
            "Could not find element " + element + " in cross_sections.xml.");
×
258
        }
259
      }
1,389✔
260

261
      if (data::element_map.find(element) == data::element_map.end()) {
1,389✔
262
        int index = data::element_map.size();
659✔
263
        data::element_map[element] = index;
659✔
264
        element_.push_back(index);
659✔
265
      } else {
266
        element_.push_back(data::element_map[element]);
730✔
267
      }
268
    }
1,389✔
269

270
    // Copy atom/weight percent
271
    atom_density_(i) = densities[i];
54,070✔
272
  }
273

274
  if (settings::run_CE) {
14,015✔
275
    // By default, isotropic-in-lab is not used
276
    if (iso_lab.size() > 0) {
12,005✔
277
      p0_.resize(n);
204✔
278

279
      // Apply isotropic-in-lab treatment to specified nuclides
280
      for (int j = 0; j < n; ++j) {
1,921✔
281
        for (const auto& nuc : iso_lab) {
8,925✔
282
          if (names[j] == nuc) {
8,925✔
283
            p0_[j] = true;
1,717✔
284
            break;
1,717✔
285
          }
286
        }
287
      }
288
    }
289
  }
290

291
  // Check to make sure either all atom percents or all weight percents are
292
  // given
293
  if (!(xt::all(atom_density_ >= 0.0) || xt::all(atom_density_ <= 0.0))) {
14,015✔
294
    fatal_error(
×
UNCOV
295
      "Cannot mix atom and weight percents in material " + std::to_string(id_));
×
296
  }
297

298
  // Determine density if it is a sum value
299
  if (sum_density)
14,015✔
300
    density_ = xt::sum(atom_density_)();
2,667✔
301

302
  if (check_for_node(node, "temperature")) {
14,015✔
303
    temperature_ = std::stod(get_node_value(node, "temperature"));
2,064✔
304
  }
305

306
  if (check_for_node(node, "volume")) {
14,015✔
307
    volume_ = std::stod(get_node_value(node, "volume"));
2,401✔
308
  }
309

310
  // =======================================================================
311
  // READ AND PARSE <sab> TAG FOR THERMAL SCATTERING DATA
312
  if (settings::run_CE) {
14,015✔
313
    // Loop over <sab> elements
314

315
    vector<std::string> sab_names;
12,005✔
316
    for (auto node_sab : node.children("sab")) {
13,935✔
317
      // Determine name of thermal scattering table
318
      if (!check_for_node(node_sab, "name")) {
1,930✔
UNCOV
319
        fatal_error("Need to specify <name> for thermal scattering table.");
×
320
      }
321
      std::string name = get_node_value(node_sab, "name");
1,930✔
322
      sab_names.push_back(name);
1,930✔
323

324
      // Read the fraction of nuclei affected by this thermal scattering table
325
      double fraction = 1.0;
1,930✔
326
      if (check_for_node(node_sab, "fraction")) {
1,930✔
327
        fraction = std::stod(get_node_value(node_sab, "fraction"));
17✔
328
      }
329

330
      // Check that the thermal scattering table is listed in the
331
      // cross_sections.xml file
332
      if (settings::run_mode != RunMode::PLOTTING) {
1,930✔
333
        LibraryKey key {Library::Type::thermal, name};
1,836✔
334
        if (data::library_map.find(key) == data::library_map.end()) {
1,836✔
UNCOV
335
          fatal_error("Could not find thermal scattering data " + name +
×
336
                      " in cross_sections.xml file.");
337
        }
338
      }
1,836✔
339

340
      // Determine index of thermal scattering data in global
341
      // data::thermal_scatt array
342
      int index_table;
343
      if (data::thermal_scatt_map.find(name) == data::thermal_scatt_map.end()) {
1,930✔
344
        index_table = data::thermal_scatt_map.size();
1,171✔
345
        data::thermal_scatt_map[name] = index_table;
1,171✔
346
      } else {
347
        index_table = data::thermal_scatt_map[name];
759✔
348
      }
349

350
      // Add entry to thermal tables vector. For now, we put the nuclide index
351
      // as zero since we don't know which nuclides the table is being applied
352
      // to yet (this is assigned in init_thermal)
353
      thermal_tables_.push_back({index_table, 0, fraction});
1,930✔
354
    }
1,930✔
355
  }
12,005✔
356
}
14,015✔
357

358
Material::~Material()
14,063✔
359
{
360
  model::material_map.erase(id_);
14,063✔
361
}
14,063✔
362

UNCOV
363
Material& Material::clone()
×
364
{
UNCOV
365
  std::unique_ptr<Material> mat = std::make_unique<Material>();
×
366

367
  // set all other parameters to whatever the calling Material has
368
  mat->name_ = name_;
×
369
  mat->nuclide_ = nuclide_;
×
370
  mat->element_ = element_;
×
371
  mat->ncrystal_mat_ = ncrystal_mat_;
×
372
  mat->atom_density_ = atom_density_;
×
373
  mat->density_ = density_;
×
374
  mat->density_gpcc_ = density_gpcc_;
×
375
  mat->volume_ = volume_;
×
376
  mat->fissionable() = fissionable_;
×
377
  mat->depletable() = depletable_;
×
378
  mat->p0_ = p0_;
×
379
  mat->mat_nuclide_index_ = mat_nuclide_index_;
×
380
  mat->thermal_tables_ = thermal_tables_;
×
UNCOV
381
  mat->temperature_ = temperature_;
×
382

383
  if (ttb_)
×
UNCOV
384
    mat->ttb_ = std::make_unique<Bremsstrahlung>(*ttb_);
×
385

386
  mat->index_ = model::materials.size();
×
387
  mat->set_id(C_NONE);
×
388
  model::materials.push_back(std::move(mat));
×
UNCOV
389
  return *model::materials.back();
×
390
}
391

392
void Material::finalize()
13,543✔
393
{
394
  // Set fissionable if any nuclide is fissionable
395
  if (settings::run_CE) {
13,543✔
396
    for (const auto& i_nuc : nuclide_) {
43,972✔
397
      if (data::nuclides[i_nuc]->fissionable_) {
38,004✔
398
        fissionable_ = true;
5,565✔
399
        break;
5,565✔
400
      }
401
    }
402

403
    // Generate material bremsstrahlung data for electrons and positrons
404
    if (settings::photon_transport &&
11,533✔
405
        settings::electron_treatment == ElectronTreatment::TTB) {
278✔
406
      this->init_bremsstrahlung();
266✔
407
    }
408

409
    // Assign thermal scattering tables
410
    this->init_thermal();
11,533✔
411
  }
412

413
  // Normalize density
414
  this->normalize_density();
13,543✔
415
}
13,543✔
416

417
void Material::normalize_density()
13,543✔
418
{
419
  bool percent_in_atom = (atom_density_(0) >= 0.0);
13,543✔
420
  bool density_in_atom = (density_ >= 0.0);
13,543✔
421

422
  for (int i = 0; i < nuclide_.size(); ++i) {
66,154✔
423
    // determine atomic weight ratio
424
    int i_nuc = nuclide_[i];
52,611✔
425
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
55,029✔
426
                                  : data::mg.nuclides_[i_nuc].awr;
2,418✔
427

428
    // if given weight percent, convert all values so that they are divided
429
    // by awr. thus, when a sum is done over the values, it's actually
430
    // sum(w/awr)
431
    if (!percent_in_atom)
52,611✔
432
      atom_density_(i) = -atom_density_(i) / awr;
9,114✔
433
  }
434

435
  // determine normalized atom percents. if given atom percents, this is
436
  // straightforward. if given weight percents, the value is w/awr and is
437
  // divided by sum(w/awr)
438
  atom_density_ /= xt::sum(atom_density_)();
13,543✔
439

440
  // Change density in g/cm^3 to atom/b-cm. Since all values are now in
441
  // atom percent, the sum needs to be re-evaluated as 1/sum(x*awr)
442
  if (!density_in_atom) {
13,543✔
443
    double sum_percent = 0.0;
8,638✔
444
    for (int i = 0; i < nuclide_.size(); ++i) {
38,847✔
445
      int i_nuc = nuclide_[i];
30,209✔
446
      double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
30,294✔
447
                                    : data::mg.nuclides_[i_nuc].awr;
85✔
448
      sum_percent += atom_density_(i) * awr;
30,209✔
449
    }
450
    sum_percent = 1.0 / sum_percent;
8,638✔
451
    density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent;
8,638✔
452
  }
453

454
  // Calculate nuclide atom densities
455
  atom_density_ *= density_;
13,543✔
456

457
  // Calculate density in g/cm^3.
458
  density_gpcc_ = 0.0;
13,543✔
459
  for (int i = 0; i < nuclide_.size(); ++i) {
66,154✔
460
    int i_nuc = nuclide_[i];
52,611✔
461
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_ : 1.0;
52,611✔
462
    density_gpcc_ += atom_density_(i) * awr * MASS_NEUTRON / N_AVOGADRO;
52,611✔
463
  }
464
}
13,543✔
465

466
void Material::init_thermal()
19,264✔
467
{
468
  vector<ThermalTable> tables;
19,264✔
469

470
  std::unordered_set<int> already_checked;
19,264✔
471
  for (const auto& table : thermal_tables_) {
21,113✔
472
    // Make sure each S(a,b) table only gets checked once
473
    if (already_checked.find(table.index_table) != already_checked.end()) {
1,849✔
UNCOV
474
      continue;
×
475
    }
476
    already_checked.insert(table.index_table);
1,849✔
477

478
    // In order to know which nuclide the S(a,b) table applies to, we need
479
    // to search through the list of nuclides for one which has a matching
480
    // name
481
    bool found = false;
1,849✔
482
    for (int j = 0; j < nuclide_.size(); ++j) {
12,587✔
483
      const auto& name {data::nuclides[nuclide_[j]]->name_};
10,738✔
484
      if (contains(data::thermal_scatt[table.index_table]->nuclides_, name)) {
10,738✔
485
        tables.push_back({table.index_table, j, table.fraction});
1,917✔
486
        found = true;
1,917✔
487
      }
488
    }
489

490
    // Check to make sure thermal scattering table matched a nuclide
491
    if (!found) {
1,849✔
492
      fatal_error("Thermal scattering table " +
×
493
                  data::thermal_scatt[table.index_table]->name_ +
×
494
                  " did not match any nuclide on material " +
×
UNCOV
495
                  std::to_string(id_));
×
496
    }
497
  }
498

499
  // Make sure each nuclide only appears in one table.
500
  for (int j = 0; j < tables.size(); ++j) {
21,181✔
501
    for (int k = j + 1; k < tables.size(); ++k) {
2,189✔
502
      if (tables[j].index_nuclide == tables[k].index_nuclide) {
272✔
503
        int index = nuclide_[tables[j].index_nuclide];
×
504
        auto name = data::nuclides[index]->name_;
×
505
        fatal_error(
×
UNCOV
506
          name + " in material " + std::to_string(id_) +
×
507
          " was found "
508
          "in multiple thermal scattering tables. Each nuclide can appear in "
509
          "only one table per material.");
UNCOV
510
      }
×
511
    }
512
  }
513

514
  // If there are multiple S(a,b) tables, we need to make sure that the
515
  // entries in i_sab_nuclides are sorted or else they won't be applied
516
  // correctly in the cross_section module.
517
  std::sort(tables.begin(), tables.end(), [](ThermalTable a, ThermalTable b) {
19,264✔
518
    return a.index_nuclide < b.index_nuclide;
187✔
519
  });
520

521
  // Update the list of thermal tables
522
  thermal_tables_ = tables;
19,264✔
523
}
19,264✔
524

525
void Material::collision_stopping_power(double* s_col, bool positron)
532✔
526
{
527
  // Average electron number and average atomic weight
528
  double electron_density = 0.0;
532✔
529
  double mass_density = 0.0;
532✔
530

531
  // Log of the mean excitation energy of the material
532
  double log_I = 0.0;
532✔
533

534
  // Effective number of conduction electrons in the material
535
  double n_conduction = 0.0;
532✔
536

537
  // Oscillator strength and square of the binding energy for each oscillator
538
  // in material
539
  vector<double> f;
532✔
540
  vector<double> e_b_sq;
532✔
541

542
  for (int i = 0; i < element_.size(); ++i) {
2,854✔
543
    const auto& elm = *data::elements[element_[i]];
2,322✔
544
    double awr = data::nuclides[nuclide_[i]]->awr_;
2,322✔
545

546
    // Get atomic density of nuclide given atom/weight percent
547
    double atom_density =
548
      (atom_density_[0] > 0.0) ? atom_density_[i] : -atom_density_[i] / awr;
2,322✔
549

550
    electron_density += atom_density * elm.Z_;
2,322✔
551
    mass_density += atom_density * awr * MASS_NEUTRON;
2,322✔
552
    log_I += atom_density * elm.Z_ * std::log(elm.I_);
2,322✔
553

554
    for (int j = 0; j < elm.n_electrons_.size(); ++j) {
18,992✔
555
      if (elm.n_electrons_[j] < 0) {
16,670✔
556
        n_conduction -= elm.n_electrons_[j] * atom_density;
1,694✔
557
        continue;
1,694✔
558
      }
559
      e_b_sq.push_back(elm.ionization_energy_[j] * elm.ionization_energy_[j]);
14,976✔
560
      f.push_back(elm.n_electrons_[j] * atom_density);
14,976✔
561
    }
562
  }
563
  log_I /= electron_density;
532✔
564
  n_conduction /= electron_density;
532✔
565
  for (auto& f_i : f)
15,508✔
566
    f_i /= electron_density;
14,976✔
567

568
  // Get density in g/cm^3 if it is given in atom/b-cm
569
  double density = (density_ < 0.0) ? -density_ : mass_density / N_AVOGADRO;
532✔
570

571
  // Calculate the square of the plasma energy
572
  double e_p_sq =
532✔
573
    PLANCK_C * PLANCK_C * PLANCK_C * N_AVOGADRO * electron_density * density /
532✔
574
    (2.0 * PI * PI * FINE_STRUCTURE * MASS_ELECTRON_EV * mass_density);
532✔
575

576
  // Get the Sternheimer adjustment factor
577
  double rho =
578
    sternheimer_adjustment(f, e_b_sq, e_p_sq, n_conduction, log_I, 1.0e-6, 100);
532✔
579

580
  // Classical electron radius in cm
581
  constexpr double CM_PER_ANGSTROM {1.0e-8};
532✔
582
  constexpr double r_e =
532✔
583
    CM_PER_ANGSTROM * PLANCK_C / (2.0 * PI * FINE_STRUCTURE * MASS_ELECTRON_EV);
584

585
  // Constant in expression for collision stopping power
586
  constexpr double BARN_PER_CM_SQ {1.0e24};
532✔
587
  double c =
532✔
588
    BARN_PER_CM_SQ * 2.0 * PI * r_e * r_e * MASS_ELECTRON_EV * electron_density;
589

590
  // Loop over incident charged particle energies
591
  for (int i = 0; i < data::ttb_e_grid.size(); ++i) {
106,620✔
592
    double E = data::ttb_e_grid(i);
106,088✔
593

594
    // Get the density effect correction
595
    double delta =
596
      density_effect(f, e_b_sq, e_p_sq, n_conduction, rho, E, 1.0e-6, 100);
106,088✔
597

598
    // Square of the ratio of the speed of light to the velocity of the charged
599
    // particle
600
    double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) /
106,088✔
601
                     ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV));
106,088✔
602

603
    double tau = E / MASS_ELECTRON_EV;
106,088✔
604

605
    double F;
606
    if (positron) {
106,088✔
607
      double t = tau + 2.0;
53,044✔
608
      F = std::log(4.0) - (beta_sq / 12.0) * (23.0 + 14.0 / t + 10.0 / (t * t) +
53,044✔
609
                                               4.0 / (t * t * t));
53,044✔
610
    } else {
611
      F = (1.0 - beta_sq) *
53,044✔
612
          (1.0 + tau * tau / 8.0 - (2.0 * tau + 1.0) * std::log(2.0));
53,044✔
613
    }
614

615
    // Calculate the collision stopping power for this energy
616
    s_col[i] =
106,088✔
617
      c / beta_sq *
106,088✔
618
      (2.0 * (std::log(E) - log_I) + std::log(1.0 + tau / 2.0) + F - delta);
106,088✔
619
  }
620
}
532✔
621

622
void Material::init_bremsstrahlung()
266✔
623
{
624
  // Create new object
625
  ttb_ = make_unique<Bremsstrahlung>();
266✔
626

627
  // Get the size of the energy grids
628
  auto n_k = data::ttb_k_grid.size();
266✔
629
  auto n_e = data::ttb_e_grid.size();
266✔
630

631
  // Determine number of elements
632
  int n = element_.size();
266✔
633

634
  for (int particle = 0; particle < 2; ++particle) {
798✔
635
    // Loop over logic twice, once for electron, once for positron
636
    BremsstrahlungData* ttb =
637
      (particle == 0) ? &ttb_->electron : &ttb_->positron;
532✔
638
    bool positron = (particle == 1);
532✔
639

640
    // Allocate arrays for TTB data
641
    ttb->pdf = xt::zeros<double>({n_e, n_e});
532✔
642
    ttb->cdf = xt::zeros<double>({n_e, n_e});
532✔
643
    ttb->yield = xt::empty<double>({n_e});
532✔
644

645
    // Allocate temporary arrays
646
    xt::xtensor<double, 1> stopping_power_collision({n_e}, 0.0);
532✔
647
    xt::xtensor<double, 1> stopping_power_radiative({n_e}, 0.0);
532✔
648
    xt::xtensor<double, 2> dcs({n_e, n_k}, 0.0);
532✔
649

650
    double Z_eq_sq = 0.0;
532✔
651
    double sum_density = 0.0;
532✔
652

653
    // Get the collision stopping power of the material
654
    this->collision_stopping_power(stopping_power_collision.data(), positron);
532✔
655

656
    // Calculate the molecular DCS and the molecular radiative stopping power
657
    // using Bragg's additivity rule.
658
    for (int i = 0; i < n; ++i) {
2,854✔
659
      // Get pointer to current element
660
      const auto& elm = *data::elements[element_[i]];
2,322✔
661
      double awr = data::nuclides[nuclide_[i]]->awr_;
2,322✔
662

663
      // Get atomic density and mass density of nuclide given atom/weight
664
      // percent
665
      double atom_density =
666
        (atom_density_[0] > 0.0) ? atom_density_[i] : -atom_density_[i] / awr;
2,322✔
667

668
      // Calculate the "equivalent" atomic number Zeq of the material
669
      Z_eq_sq += atom_density * elm.Z_ * elm.Z_;
2,322✔
670
      sum_density += atom_density;
2,322✔
671

672
      // Accumulate material DCS
673
      dcs += (atom_density * elm.Z_ * elm.Z_) * elm.dcs_;
2,322✔
674

675
      // Accumulate material radiative stopping power
676
      stopping_power_radiative += atom_density * elm.stopping_power_radiative_;
2,322✔
677
    }
678
    Z_eq_sq /= sum_density;
532✔
679

680
    // Calculate the positron DCS and radiative stopping power. These are
681
    // obtained by multiplying the electron DCS and radiative stopping powers by
682
    // a factor r, which is a numerical approximation of the ratio of the
683
    // radiative stopping powers for positrons and electrons. Source: F. Salvat,
684
    // J. M. Fernández-Varea, and J. Sempau, "PENELOPE-2011: A Code System for
685
    // Monte Carlo Simulation of Electron and Photon Transport," OECD-NEA,
686
    // Issy-les-Moulineaux, France (2011).
687
    if (positron) {
532✔
688
      for (int i = 0; i < n_e; ++i) {
53,310✔
689
        double t = std::log(
53,044✔
690
          1.0 + 1.0e6 * data::ttb_e_grid(i) / (Z_eq_sq * MASS_ELECTRON_EV));
53,044✔
691
        double r =
692
          1.0 -
53,044✔
693
          std::exp(-1.2359e-1 * t + 6.1274e-2 * std::pow(t, 2) -
53,044✔
694
                   3.1516e-2 * std::pow(t, 3) + 7.7446e-3 * std::pow(t, 4) -
53,044✔
695
                   1.0595e-3 * std::pow(t, 5) + 7.0568e-5 * std::pow(t, 6) -
53,044✔
696
                   1.808e-6 * std::pow(t, 7));
53,044✔
697
        stopping_power_radiative(i) *= r;
53,044✔
698
        auto dcs_i = xt::view(dcs, i, xt::all());
53,044✔
699
        dcs_i *= r;
53,044✔
700
      }
53,044✔
701
    }
702

703
    // Total material stopping power
704
    xt::xtensor<double, 1> stopping_power =
705
      stopping_power_collision + stopping_power_radiative;
532✔
706

707
    // Loop over photon energies
708
    xt::xtensor<double, 1> f({n_e}, 0.0);
532✔
709
    xt::xtensor<double, 1> z({n_e}, 0.0);
532✔
710
    for (int i = 0; i < n_e - 1; ++i) {
106,088✔
711
      double w = data::ttb_e_grid(i);
105,556✔
712

713
      // Loop over incident particle energies
714
      for (int j = i; j < n_e; ++j) {
10,737,696✔
715
        double e = data::ttb_e_grid(j);
10,632,140✔
716

717
        // Reduced photon energy
718
        double k = w / e;
10,632,140✔
719

720
        // Find the lower bounding index of the reduced photon energy
721
        int i_k = lower_bound_index(
10,632,140✔
722
          data::ttb_k_grid.cbegin(), data::ttb_k_grid.cend(), k);
10,632,140✔
723

724
        // Get the interpolation bounds
725
        double k_l = data::ttb_k_grid(i_k);
10,632,140✔
726
        double k_r = data::ttb_k_grid(i_k + 1);
10,632,140✔
727
        double x_l = dcs(j, i_k);
10,632,140✔
728
        double x_r = dcs(j, i_k + 1);
10,632,140✔
729

730
        // Find the value of the DCS using linear interpolation in reduced
731
        // photon energy k
732
        double x = x_l + (k - k_l) * (x_r - x_l) / (k_r - k_l);
10,632,140✔
733

734
        // Square of the ratio of the speed of light to the velocity of the
735
        // charged particle
736
        double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) /
10,632,140✔
737
                         ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV));
10,632,140✔
738

739
        // Compute the integrand of the PDF
740
        f(j) = x / (beta_sq * stopping_power(j) * w);
10,632,140✔
741
      }
742

743
      // Number of points to integrate
744
      int n = n_e - i;
105,556✔
745

746
      // Integrate the PDF using cubic spline integration over the incident
747
      // particle energy
748
      if (n > 2) {
105,556✔
749
        spline(n, &data::ttb_e_grid(i), &f(i), &z(i));
105,024✔
750

751
        double c = 0.0;
105,024✔
752
        for (int j = i; j < n_e - 1; ++j) {
10,631,076✔
753
          c += spline_integrate(n, &data::ttb_e_grid(i), &f(i), &z(i),
10,526,052✔
754
            data::ttb_e_grid(j), data::ttb_e_grid(j + 1));
10,526,052✔
755

756
          ttb->pdf(j + 1, i) = c;
10,526,052✔
757
        }
758

759
        // Integrate the last two points using trapezoidal rule in log-log space
760
      } else {
761
        double e_l = std::log(data::ttb_e_grid(i));
532✔
762
        double e_r = std::log(data::ttb_e_grid(i + 1));
532✔
763
        double x_l = std::log(f(i));
532✔
764
        double x_r = std::log(f(i + 1));
532✔
765

766
        ttb->pdf(i + 1, i) =
532✔
767
          0.5 * (e_r - e_l) * (std::exp(e_l + x_l) + std::exp(e_r + x_r));
532✔
768
      }
769
    }
770

771
    // Loop over incident particle energies
772
    for (int j = 1; j < n_e; ++j) {
106,088✔
773
      // Set last element of PDF to small non-zero value to enable log-log
774
      // interpolation
775
      ttb->pdf(j, j) = std::exp(-500.0);
105,556✔
776

777
      // Loop over photon energies
778
      double c = 0.0;
105,556✔
779
      for (int i = 0; i < j; ++i) {
10,632,140✔
780
        // Integrate the CDF from the PDF using the trapezoidal rule in log-log
781
        // space
782
        double w_l = std::log(data::ttb_e_grid(i));
10,526,584✔
783
        double w_r = std::log(data::ttb_e_grid(i + 1));
10,526,584✔
784
        double x_l = std::log(ttb->pdf(j, i));
10,526,584✔
785
        double x_r = std::log(ttb->pdf(j, i + 1));
10,526,584✔
786

787
        c += 0.5 * (w_r - w_l) * (std::exp(w_l + x_l) + std::exp(w_r + x_r));
10,526,584✔
788
        ttb->cdf(j, i + 1) = c;
10,526,584✔
789
      }
790

791
      // Set photon number yield
792
      ttb->yield(j) = c;
105,556✔
793
    }
794

795
    // Use logarithm of number yield since it is log-log interpolated
796
    ttb->yield = xt::where(ttb->yield > 0.0, xt::log(ttb->yield), -500.0);
532✔
797
  }
532✔
798
}
266✔
799

800
void Material::init_nuclide_index()
18,692✔
801
{
802
  int n = settings::run_CE ? data::nuclides.size() : data::mg.nuclides_.size();
18,692✔
803
  mat_nuclide_index_.resize(n);
18,692✔
804
  std::fill(mat_nuclide_index_.begin(), mat_nuclide_index_.end(), C_NONE);
18,692✔
805
  for (int i = 0; i < nuclide_.size(); ++i) {
129,128✔
806
    mat_nuclide_index_[nuclide_[i]] = i;
110,436✔
807
  }
808
}
18,692✔
809

810
void Material::calculate_xs(Particle& p) const
1,362,586,344✔
811
{
812
  // Set all material macroscopic cross sections to zero
813
  p.macro_xs().total = 0.0;
1,362,586,344✔
814
  p.macro_xs().absorption = 0.0;
1,362,586,344✔
815
  p.macro_xs().fission = 0.0;
1,362,586,344✔
816
  p.macro_xs().nu_fission = 0.0;
1,362,586,344✔
817

818
  if (p.type() == ParticleType::neutron) {
1,362,586,344✔
819
    this->calculate_neutron_xs(p);
1,294,170,841✔
820
  } else if (p.type() == ParticleType::photon) {
68,415,503✔
821
    this->calculate_photon_xs(p);
15,152,362✔
822
  }
823
}
1,362,586,344✔
824

825
void Material::calculate_neutron_xs(Particle& p) const
1,294,170,841✔
826
{
827
  // Find energy index on energy grid
828
  int neutron = static_cast<int>(ParticleType::neutron);
1,294,170,841✔
829
  int i_grid =
830
    std::log(p.E() / data::energy_min[neutron]) / simulation::log_spacing;
1,294,170,841✔
831

832
  // Determine if this material has S(a,b) tables
833
  bool check_sab = (thermal_tables_.size() > 0);
1,294,170,841✔
834

835
  // Initialize position in i_sab_nuclides
836
  int j = 0;
1,294,170,841✔
837

838
  // Calculate NCrystal cross section
839
  double ncrystal_xs = -1.0;
1,294,170,841✔
840
  if (ncrystal_mat_ && p.E() < NCRYSTAL_MAX_ENERGY) {
1,294,170,841✔
841
    ncrystal_xs = ncrystal_mat_.xs(p);
1,014,439✔
842
  }
843

844
  // Add contribution from each nuclide in material
845
  for (int i = 0; i < nuclide_.size(); ++i) {
2,147,483,647✔
846
    // ======================================================================
847
    // CHECK FOR S(A,B) TABLE
848

849
    int i_sab = C_NONE;
2,147,483,647✔
850
    double sab_frac = 0.0;
2,147,483,647✔
851

852
    // Check if this nuclide matches one of the S(a,b) tables specified.
853
    // This relies on thermal_tables_ being sorted by .index_nuclide
854
    if (check_sab) {
2,147,483,647✔
855
      const auto& sab {thermal_tables_[j]};
784,465,113✔
856
      if (i == sab.index_nuclide) {
784,465,113✔
857
        // Get index in sab_tables
858
        i_sab = sab.index_table;
314,301,687✔
859
        sab_frac = sab.fraction;
314,301,687✔
860

861
        // If particle energy is greater than the highest energy for the
862
        // S(a,b) table, then don't use the S(a,b) table
863
        if (p.E() > data::thermal_scatt[i_sab]->energy_max_)
314,301,687✔
864
          i_sab = C_NONE;
206,392,819✔
865

866
        // Increment position in thermal_tables_
867
        ++j;
314,301,687✔
868

869
        // Don't check for S(a,b) tables if there are no more left
870
        if (j == thermal_tables_.size())
314,301,687✔
871
          check_sab = false;
314,045,739✔
872
      }
873
    }
874

875
    // ======================================================================
876
    // CALCULATE MICROSCOPIC CROSS SECTION
877

878
    // Get nuclide index
879
    int i_nuclide = nuclide_[i];
2,147,483,647✔
880

881
    // Update microscopic cross section for this nuclide
882
    p.update_neutron_xs(i_nuclide, i_grid, i_sab, sab_frac, ncrystal_xs);
2,147,483,647✔
883
    auto& micro = p.neutron_xs(i_nuclide);
2,147,483,647✔
884

885
    // ======================================================================
886
    // ADD TO MACROSCOPIC CROSS SECTION
887

888
    // Copy atom density of nuclide in material
889
    double atom_density = atom_density_(i);
2,147,483,647✔
890

891
    // Add contributions to cross sections
892
    p.macro_xs().total += atom_density * micro.total;
2,147,483,647✔
893
    p.macro_xs().absorption += atom_density * micro.absorption;
2,147,483,647✔
894
    p.macro_xs().fission += atom_density * micro.fission;
2,147,483,647✔
895
    p.macro_xs().nu_fission += atom_density * micro.nu_fission;
2,147,483,647✔
896
  }
897
}
1,294,170,841✔
898

899
void Material::calculate_photon_xs(Particle& p) const
15,152,362✔
900
{
901
  p.macro_xs().coherent = 0.0;
15,152,362✔
902
  p.macro_xs().incoherent = 0.0;
15,152,362✔
903
  p.macro_xs().photoelectric = 0.0;
15,152,362✔
904
  p.macro_xs().pair_production = 0.0;
15,152,362✔
905

906
  // Add contribution from each nuclide in material
907
  for (int i = 0; i < nuclide_.size(); ++i) {
97,753,146✔
908
    // ========================================================================
909
    // CALCULATE MICROSCOPIC CROSS SECTION
910

911
    // Determine microscopic cross sections for this nuclide
912
    int i_element = element_[i];
82,600,784✔
913

914
    // Calculate microscopic cross section for this nuclide
915
    const auto& micro {p.photon_xs(i_element)};
82,600,784✔
916
    if (p.E() != micro.last_E) {
82,600,784✔
917
      data::elements[i_element]->calculate_xs(p);
38,161,198✔
918
    }
919

920
    // ========================================================================
921
    // ADD TO MACROSCOPIC CROSS SECTION
922

923
    // Copy atom density of nuclide in material
924
    double atom_density = atom_density_(i);
82,600,784✔
925

926
    // Add contributions to material macroscopic cross sections
927
    p.macro_xs().total += atom_density * micro.total;
82,600,784✔
928
    p.macro_xs().coherent += atom_density * micro.coherent;
82,600,784✔
929
    p.macro_xs().incoherent += atom_density * micro.incoherent;
82,600,784✔
930
    p.macro_xs().photoelectric += atom_density * micro.photoelectric;
82,600,784✔
931
    p.macro_xs().pair_production += atom_density * micro.pair_production;
82,600,784✔
932
  }
933
}
15,152,362✔
934

935
void Material::set_id(int32_t id)
14,063✔
936
{
937
  assert(id >= 0 || id == C_NONE);
11,548✔
938

939
  // Clear entry in material map if an ID was already assigned before
940
  if (id_ != C_NONE) {
14,063✔
941
    model::material_map.erase(id_);
×
UNCOV
942
    id_ = C_NONE;
×
943
  }
944

945
  // Make sure no other material has same ID
946
  if (model::material_map.find(id) != model::material_map.end()) {
14,063✔
947
    throw std::runtime_error {
×
UNCOV
948
      "Two materials have the same ID: " + std::to_string(id)};
×
949
  }
950

951
  // If no ID specified, auto-assign next ID in sequence
952
  if (id == C_NONE) {
14,063✔
953
    id = 0;
×
954
    for (const auto& m : model::materials) {
×
UNCOV
955
      id = std::max(id, m->id_);
×
956
    }
UNCOV
957
    ++id;
×
958
  }
959

960
  // Update ID and entry in material map
961
  id_ = id;
14,063✔
962
  model::material_map[id] = index_;
14,063✔
963
}
14,063✔
964

965
void Material::set_density(double density, const std::string& units)
7,911✔
966
{
967
  assert(density >= 0.0);
6,450✔
968

969
  if (nuclide_.empty()) {
7,911✔
UNCOV
970
    throw std::runtime_error {"No nuclides exist in material yet."};
×
971
  }
972

973
  if (units == "atom/b-cm") {
7,911✔
974
    // Set total density based on value provided
975
    density_ = density;
7,863✔
976

977
    // Determine normalized atom percents
978
    double sum_percent = xt::sum(atom_density_)();
7,863✔
979
    atom_density_ /= sum_percent;
7,863✔
980

981
    // Recalculate nuclide atom densities based on given density
982
    atom_density_ *= density;
7,863✔
983

984
    // Calculate density in g/cm^3.
985
    density_gpcc_ = 0.0;
7,863✔
986
    for (int i = 0; i < nuclide_.size(); ++i) {
83,566✔
987
      int i_nuc = nuclide_[i];
75,703✔
988
      double awr = data::nuclides[i_nuc]->awr_;
75,703✔
989
      density_gpcc_ += atom_density_(i) * awr * MASS_NEUTRON / N_AVOGADRO;
75,703✔
990
    }
991
  } else if (units == "g/cm3" || units == "g/cc") {
48✔
992
    // Determine factor by which to change densities
993
    double previous_density_gpcc = density_gpcc_;
36✔
994
    double f = density / previous_density_gpcc;
36✔
995

996
    // Update densities
997
    density_gpcc_ = density;
36✔
998
    density_ *= f;
36✔
999
    atom_density_ *= f;
36✔
1000
  } else {
1001
    throw std::invalid_argument {
12✔
1002
      "Invalid units '" + std::string(units.data()) + "' specified."};
24✔
1003
  }
1004
}
7,899✔
1005

1006
void Material::set_densities(
7,731✔
1007
  const vector<std::string>& name, const vector<double>& density)
1008
{
1009
  auto n = name.size();
7,731✔
1010
  assert(n > 0);
6,300✔
1011
  assert(n == density.size());
6,300✔
1012

1013
  if (n != nuclide_.size()) {
7,731✔
1014
    nuclide_.resize(n);
1,889✔
1015
    atom_density_ = xt::zeros<double>({n});
1,889✔
1016
    if (settings::photon_transport)
1,889✔
UNCOV
1017
      element_.resize(n);
×
1018
  }
1019

1020
  double sum_density = 0.0;
7,731✔
1021
  for (int64_t i = 0; i < n; ++i) {
82,846✔
1022
    const auto& nuc {name[i]};
75,115✔
1023
    if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) {
75,115✔
1024
      int err = openmc_load_nuclide(nuc.c_str(), nullptr, 0);
×
1025
      if (err < 0)
×
UNCOV
1026
        throw std::runtime_error {openmc_err_msg};
×
1027
    }
1028

1029
    nuclide_[i] = data::nuclide_map.at(nuc);
75,115✔
1030
    assert(density[i] > 0.0);
61,300✔
1031
    atom_density_(i) = density[i];
75,115✔
1032
    sum_density += density[i];
75,115✔
1033

1034
    if (settings::photon_transport) {
75,115✔
1035
      auto element_name = to_element(nuc);
×
UNCOV
1036
      element_[i] = data::element_map.at(element_name);
×
1037
    }
1038
  }
1039

1040
  // Set total density to the sum of the vector
1041
  this->set_density(sum_density, "atom/b-cm");
7,731✔
1042

1043
  // Generate material bremsstrahlung data for electrons and positrons
1044
  if (settings::photon_transport &&
7,731✔
1045
      settings::electron_treatment == ElectronTreatment::TTB) {
×
UNCOV
1046
    this->init_bremsstrahlung();
×
1047
  }
1048

1049
  // Assign S(a,b) tables
1050
  this->init_thermal();
7,731✔
1051
}
7,731✔
1052

1053
double Material::volume() const
60✔
1054
{
1055
  if (volume_ < 0.0) {
60✔
1056
    throw std::runtime_error {
12✔
1057
      "Volume for material with ID=" + std::to_string(id_) + " not set."};
24✔
1058
  }
1059
  return volume_;
48✔
1060
}
1061

1062
double Material::temperature() const
17,946✔
1063
{
1064
  // If material doesn't have an assigned temperature, use global default
1065
  return temperature_ >= 0 ? temperature_ : settings::temperature_default;
17,946✔
1066
}
1067

1068
void Material::to_hdf5(hid_t group) const
11,133✔
1069
{
1070
  hid_t material_group = create_group(group, "material " + std::to_string(id_));
11,133✔
1071

1072
  write_attribute(material_group, "depletable", static_cast<int>(depletable()));
11,133✔
1073
  if (volume_ > 0.0) {
11,133✔
1074
    write_attribute(material_group, "volume", volume_);
2,389✔
1075
  }
1076
  if (temperature_ > 0.0) {
11,133✔
1077
    write_attribute(material_group, "temperature", temperature_);
2,054✔
1078
  }
1079
  write_dataset(material_group, "name", name_);
11,133✔
1080
  write_dataset(material_group, "atom_density", density_);
11,133✔
1081

1082
  // Copy nuclide/macro name for each nuclide to vector
1083
  vector<std::string> nuc_names;
11,133✔
1084
  vector<std::string> macro_names;
11,133✔
1085
  vector<double> nuc_densities;
11,133✔
1086
  if (settings::run_CE) {
11,133✔
1087
    for (int i = 0; i < nuclide_.size(); ++i) {
53,959✔
1088
      int i_nuc = nuclide_[i];
43,954✔
1089
      nuc_names.push_back(data::nuclides[i_nuc]->name_);
43,954✔
1090
      nuc_densities.push_back(atom_density_(i));
43,954✔
1091
    }
1092
  } else {
1093
    for (int i = 0; i < nuclide_.size(); ++i) {
2,292✔
1094
      int i_nuc = nuclide_[i];
1,164✔
1095
      if (data::mg.nuclides_[i_nuc].awr != MACROSCOPIC_AWR) {
1,164✔
1096
        nuc_names.push_back(data::mg.nuclides_[i_nuc].name);
96✔
1097
        nuc_densities.push_back(atom_density_(i));
96✔
1098
      } else {
1099
        macro_names.push_back(data::mg.nuclides_[i_nuc].name);
1,068✔
1100
      }
1101
    }
1102
  }
1103

1104
  // Write vector to 'nuclides'
1105
  if (!nuc_names.empty()) {
11,133✔
1106
    write_dataset(material_group, "nuclides", nuc_names);
10,065✔
1107
    write_dataset(material_group, "nuclide_densities", nuc_densities);
10,065✔
1108
  }
1109

1110
  // Write vector to 'macroscopics'
1111
  if (!macro_names.empty()) {
11,133✔
1112
    write_dataset(material_group, "macroscopics", macro_names);
1,068✔
1113
  }
1114

1115
  if (!thermal_tables_.empty()) {
11,133✔
1116
    vector<std::string> sab_names;
1,402✔
1117
    for (const auto& table : thermal_tables_) {
2,876✔
1118
      sab_names.push_back(data::thermal_scatt[table.index_table]->name_);
1,474✔
1119
    }
1120
    write_dataset(material_group, "sab_names", sab_names);
1,402✔
1121
  }
1,402✔
1122

1123
  close_group(material_group);
11,133✔
1124
}
11,133✔
1125

1126
void Material::export_properties_hdf5(hid_t group) const
108✔
1127
{
1128
  hid_t material_group = create_group(group, "material " + std::to_string(id_));
108✔
1129
  write_attribute(material_group, "atom_density", density_);
108✔
1130
  write_attribute(material_group, "mass_density", density_gpcc_);
108✔
1131
  close_group(material_group);
108✔
1132
}
108✔
1133

1134
void Material::import_properties_hdf5(hid_t group)
72✔
1135
{
1136
  hid_t material_group = open_group(group, "material " + std::to_string(id_));
72✔
1137
  double density;
1138
  read_attribute(material_group, "atom_density", density);
72✔
1139
  this->set_density(density, "atom/b-cm");
72✔
1140
  close_group(material_group);
72✔
1141
}
72✔
1142

1143
void Material::add_nuclide(const std::string& name, double density)
12✔
1144
{
1145
  // Check if nuclide is already in material
1146
  for (int i = 0; i < nuclide_.size(); ++i) {
60✔
1147
    int i_nuc = nuclide_[i];
48✔
1148
    if (data::nuclides[i_nuc]->name_ == name) {
48✔
1149
      double awr = data::nuclides[i_nuc]->awr_;
×
1150
      density_ += density - atom_density_(i);
×
1151
      density_gpcc_ +=
×
1152
        (density - atom_density_(i)) * awr * MASS_NEUTRON / N_AVOGADRO;
×
1153
      atom_density_(i) = density;
×
UNCOV
1154
      return;
×
1155
    }
1156
  }
1157

1158
  // If nuclide wasn't found, extend nuclide/density arrays
1159
  int err = openmc_load_nuclide(name.c_str(), nullptr, 0);
12✔
1160
  if (err < 0)
12✔
UNCOV
1161
    throw std::runtime_error {openmc_err_msg};
×
1162

1163
  // Append new nuclide/density
1164
  int i_nuc = data::nuclide_map[name];
12✔
1165
  nuclide_.push_back(i_nuc);
12✔
1166

1167
  // Append new element if photon transport is on
1168
  if (settings::photon_transport) {
12✔
1169
    int i_elem = data::element_map[to_element(name)];
×
UNCOV
1170
    element_.push_back(i_elem);
×
1171
  }
1172

1173
  auto n = nuclide_.size();
12✔
1174

1175
  // Create copy of atom_density_ array with one extra entry
1176
  xt::xtensor<double, 1> atom_density = xt::zeros<double>({n});
12✔
1177
  xt::view(atom_density, xt::range(0, n - 1)) = atom_density_;
12✔
1178
  atom_density(n - 1) = density;
12✔
1179
  atom_density_ = atom_density;
12✔
1180

1181
  density_ += density;
12✔
1182
  density_gpcc_ +=
12✔
1183
    density * data::nuclides[i_nuc]->awr_ * MASS_NEUTRON / N_AVOGADRO;
12✔
1184
}
12✔
1185

1186
//==============================================================================
1187
// Non-method functions
1188
//==============================================================================
1189

1190
double sternheimer_adjustment(const vector<double>& f,
532✔
1191
  const vector<double>& e_b_sq, double e_p_sq, double n_conduction,
1192
  double log_I, double tol, int max_iter)
1193
{
1194
  // Get the total number of oscillators
1195
  int n = f.size();
532✔
1196

1197
  // Calculate the Sternheimer adjustment factor using Newton's method
1198
  double rho = 2.0;
532✔
1199
  int iter;
1200
  for (iter = 0; iter < max_iter; ++iter) {
2,138✔
1201
    double rho_0 = rho;
2,138✔
1202

1203
    // Function to find the root of and its derivative
1204
    double g = 0.0;
2,138✔
1205
    double gp = 0.0;
2,138✔
1206

1207
    for (int i = 0; i < n; ++i) {
62,748✔
1208
      // Square of resonance energy of a bound-shell oscillator
1209
      double e_r_sq = e_b_sq[i] * rho * rho + 2.0 / 3.0 * f[i] * e_p_sq;
60,610✔
1210
      g += f[i] * std::log(e_r_sq);
60,610✔
1211
      gp += e_b_sq[i] * f[i] * rho / e_r_sq;
60,610✔
1212
    }
1213
    // Include conduction electrons
1214
    if (n_conduction > 0.0) {
2,138✔
1215
      g += n_conduction * std::log(n_conduction * e_p_sq);
1,834✔
1216
    }
1217

1218
    // Set the next guess: rho_n+1 = rho_n - g(rho_n)/g'(rho_n)
1219
    rho -= (g - 2.0 * log_I) / (2.0 * gp);
2,138✔
1220

1221
    // If the initial guess is too large, rho can be negative
1222
    if (rho < 0.0)
2,138✔
UNCOV
1223
      rho = rho_0 / 2.0;
×
1224

1225
    // Check for convergence
1226
    if (std::abs(rho - rho_0) / rho_0 < tol)
2,138✔
1227
      break;
532✔
1228
  }
1229
  // Did not converge
1230
  if (iter >= max_iter) {
532✔
1231
    warning("Maximum Newton-Raphson iterations exceeded.");
×
UNCOV
1232
    rho = 1.0e-6;
×
1233
  }
1234
  return rho;
532✔
1235
}
1236

1237
double density_effect(const vector<double>& f, const vector<double>& e_b_sq,
106,088✔
1238
  double e_p_sq, double n_conduction, double rho, double E, double tol,
1239
  int max_iter)
1240
{
1241
  // Get the total number of oscillators
1242
  int n = f.size();
106,088✔
1243

1244
  // Square of the ratio of the speed of light to the velocity of the charged
1245
  // particle
1246
  double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) /
106,088✔
1247
                   ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV));
106,088✔
1248

1249
  // For nonmetals, delta = 0 for beta < beta_0, where beta_0 is obtained by
1250
  // setting the frequency w = 0.
1251
  double beta_0_sq = 0.0;
106,088✔
1252
  if (n_conduction == 0.0) {
106,088✔
1253
    for (int i = 0; i < n; ++i) {
118,800✔
1254
      beta_0_sq += f[i] * e_p_sq / (e_b_sq[i] * rho * rho);
102,400✔
1255
    }
1256
    beta_0_sq = 1.0 / (1.0 + beta_0_sq);
16,400✔
1257
  }
1258
  double delta = 0.0;
106,088✔
1259
  if (beta_sq < beta_0_sq)
106,088✔
1260
    return delta;
8,946✔
1261

1262
  // Compute the square of the frequency w^2 using Newton's method, with the
1263
  // initial guess of w^2 equal to beta^2 * gamma^2
1264
  double w_sq = E / MASS_ELECTRON_EV * (E / MASS_ELECTRON_EV + 2);
97,142✔
1265
  int iter;
1266
  for (iter = 0; iter < max_iter; ++iter) {
669,490✔
1267
    double w_sq_0 = w_sq;
669,490✔
1268

1269
    // Function to find the root of and its derivative
1270
    double g = 0.0;
669,490✔
1271
    double gp = 0.0;
669,490✔
1272

1273
    for (int i = 0; i < n; ++i) {
22,357,296✔
1274
      double c = e_b_sq[i] * rho * rho / e_p_sq + w_sq;
21,687,806✔
1275
      g += f[i] / c;
21,687,806✔
1276
      gp -= f[i] / (c * c);
21,687,806✔
1277
    }
1278
    // Include conduction electrons
1279
    g += n_conduction / w_sq;
669,490✔
1280
    gp -= n_conduction / (w_sq * w_sq);
669,490✔
1281

1282
    // Set the next guess: w_n+1 = w_n - g(w_n)/g'(w_n)
1283
    w_sq -= (g + 1.0 - 1.0 / beta_sq) / gp;
669,490✔
1284

1285
    // If the initial guess is too large, w can be negative
1286
    if (w_sq < 0.0)
669,490✔
1287
      w_sq = w_sq_0 / 2.0;
148,844✔
1288

1289
    // Check for convergence
1290
    if (std::abs(w_sq - w_sq_0) / w_sq_0 < tol)
669,490✔
1291
      break;
97,142✔
1292
  }
1293
  // Did not converge
1294
  if (iter >= max_iter) {
97,142✔
UNCOV
1295
    warning("Maximum Newton-Raphson iterations exceeded: setting density "
×
1296
            "effect correction to zero.");
UNCOV
1297
    return delta;
×
1298
  }
1299

1300
  // Solve for the density effect correction
1301
  for (int i = 0; i < n; ++i) {
3,033,014✔
1302
    double l_sq = e_b_sq[i] * rho * rho / e_p_sq + 2.0 / 3.0 * f[i];
2,935,872✔
1303
    delta += f[i] * std::log((l_sq + w_sq) / l_sq);
2,935,872✔
1304
  }
1305
  // Include conduction electrons
1306
  if (n_conduction > 0.0) {
97,142✔
1307
    delta += n_conduction * std::log((n_conduction + w_sq) / n_conduction);
89,688✔
1308
  }
1309

1310
  return delta - w_sq * (1.0 - beta_sq);
97,142✔
1311
}
1312

1313
void read_materials_xml()
1,421✔
1314
{
1315
  write_message("Reading materials XML file...", 5);
1,421✔
1316

1317
  pugi::xml_document doc;
1,421✔
1318

1319
  // Check if materials.xml exists
1320
  std::string filename = settings::path_input + "materials.xml";
1,421✔
1321
  if (!file_exists(filename)) {
1,421✔
UNCOV
1322
    fatal_error("Material XML file '" + filename + "' does not exist!");
×
1323
  }
1324

1325
  // Parse materials.xml file and get root element
1326
  doc.load_file(filename.c_str());
1,421✔
1327

1328
  // Loop over XML material elements and populate the array.
1329
  pugi::xml_node root = doc.document_element();
1,421✔
1330

1331
  read_materials_xml(root);
1,421✔
1332
}
1,421✔
1333

1334
void read_materials_xml(pugi::xml_node root)
6,748✔
1335
{
1336
  for (pugi::xml_node material_node : root.children("material")) {
20,755✔
1337
    model::materials.push_back(make_unique<Material>(material_node));
14,007✔
1338
  }
1339
  model::materials.shrink_to_fit();
6,748✔
1340
}
6,748✔
1341

1342
void free_memory_material()
6,880✔
1343
{
1344
  model::materials.clear();
6,880✔
1345
  model::material_map.clear();
6,880✔
1346
}
6,880✔
1347

1348
//==============================================================================
1349
// C API
1350
//==============================================================================
1351

1352
extern "C" int openmc_get_material_index(int32_t id, int32_t* index)
10,194✔
1353
{
1354
  auto it = model::material_map.find(id);
10,194✔
1355
  if (it == model::material_map.end()) {
10,194✔
1356
    set_errmsg("No material exists with ID=" + std::to_string(id) + ".");
12✔
1357
    return OPENMC_E_INVALID_ID;
12✔
1358
  } else {
1359
    *index = it->second;
10,182✔
1360
    return 0;
10,182✔
1361
  }
1362
}
1363

1364
extern "C" int openmc_material_add_nuclide(
12✔
1365
  int32_t index, const char* name, double density)
1366
{
1367
  int err = 0;
12✔
1368
  if (index >= 0 && index < model::materials.size()) {
12✔
1369
    try {
1370
      model::materials[index]->add_nuclide(name, density);
12✔
1371
    } catch (const std::runtime_error& e) {
×
1372
      return OPENMC_E_DATA;
×
UNCOV
1373
    }
×
1374
  } else {
1375
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1376
    return OPENMC_E_OUT_OF_BOUNDS;
×
1377
  }
1378
  return err;
12✔
1379
}
1380

1381
extern "C" int openmc_material_get_densities(
180✔
1382
  int32_t index, const int** nuclides, const double** densities, int* n)
1383
{
1384
  if (index >= 0 && index < model::materials.size()) {
180✔
1385
    auto& mat = model::materials[index];
180✔
1386
    if (!mat->nuclides().empty()) {
180✔
1387
      *nuclides = mat->nuclides().data();
180✔
1388
      *densities = mat->densities().data();
180✔
1389
      *n = mat->nuclides().size();
180✔
1390
      return 0;
180✔
1391
    } else {
1392
      set_errmsg("Material atom density array has not been allocated.");
×
UNCOV
1393
      return OPENMC_E_ALLOCATE;
×
1394
    }
1395
  } else {
1396
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1397
    return OPENMC_E_OUT_OF_BOUNDS;
×
1398
  }
1399
}
1400

1401
extern "C" int openmc_material_get_density(int32_t index, double* density)
36✔
1402
{
1403
  if (index >= 0 && index < model::materials.size()) {
36✔
1404
    auto& mat = model::materials[index];
36✔
1405
    *density = mat->density_gpcc();
36✔
1406
    return 0;
36✔
1407
  } else {
1408
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1409
    return OPENMC_E_OUT_OF_BOUNDS;
×
1410
  }
1411
}
1412

UNCOV
1413
extern "C" int openmc_material_get_fissionable(int32_t index, bool* fissionable)
×
1414
{
1415
  if (index >= 0 && index < model::materials.size()) {
×
1416
    *fissionable = model::materials[index]->fissionable();
×
UNCOV
1417
    return 0;
×
1418
  } else {
1419
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1420
    return OPENMC_E_OUT_OF_BOUNDS;
×
1421
  }
1422
}
1423

1424
extern "C" int openmc_material_get_id(int32_t index, int32_t* id)
11,358✔
1425
{
1426
  if (index >= 0 && index < model::materials.size()) {
11,358✔
1427
    *id = model::materials[index]->id();
11,358✔
1428
    return 0;
11,358✔
1429
  } else {
1430
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1431
    return OPENMC_E_OUT_OF_BOUNDS;
×
1432
  }
1433
}
1434

1435
extern "C" int openmc_material_get_temperature(
72✔
1436
  int32_t index, double* temperature)
1437
{
1438
  if (index < 0 || index >= model::materials.size()) {
72✔
1439
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1440
    return OPENMC_E_OUT_OF_BOUNDS;
×
1441
  }
1442
  *temperature = model::materials[index]->temperature();
72✔
1443
  return 0;
72✔
1444
}
1445

1446
extern "C" int openmc_material_get_volume(int32_t index, double* volume)
60✔
1447
{
1448
  if (index >= 0 && index < model::materials.size()) {
60✔
1449
    try {
1450
      *volume = model::materials[index]->volume();
60✔
1451
    } catch (const std::exception& e) {
12✔
1452
      set_errmsg(e.what());
12✔
1453
      return OPENMC_E_UNASSIGNED;
12✔
1454
    }
12✔
1455
    return 0;
48✔
1456
  } else {
1457
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1458
    return OPENMC_E_OUT_OF_BOUNDS;
×
1459
  }
1460
}
1461

1462
extern "C" int openmc_material_set_density(
108✔
1463
  int32_t index, double density, const char* units)
1464
{
1465
  if (index >= 0 && index < model::materials.size()) {
108✔
1466
    try {
1467
      model::materials[index]->set_density(density, units);
132✔
1468
    } catch (const std::exception& e) {
12✔
1469
      set_errmsg(e.what());
12✔
1470
      return OPENMC_E_UNASSIGNED;
12✔
1471
    }
12✔
1472
  } else {
1473
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1474
    return OPENMC_E_OUT_OF_BOUNDS;
×
1475
  }
1476
  return 0;
96✔
1477
}
1478

1479
extern "C" int openmc_material_set_densities(
7,731✔
1480
  int32_t index, int n, const char** name, const double* density)
1481
{
1482
  if (index >= 0 && index < model::materials.size()) {
7,731✔
1483
    try {
1484
      model::materials[index]->set_densities(
23,193✔
1485
        {name, name + n}, {density, density + n});
15,462✔
1486
    } catch (const std::exception& e) {
×
1487
      set_errmsg(e.what());
×
1488
      return OPENMC_E_UNASSIGNED;
×
UNCOV
1489
    }
×
1490
  } else {
1491
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1492
    return OPENMC_E_OUT_OF_BOUNDS;
×
1493
  }
1494
  return 0;
7,731✔
1495
}
1496

1497
extern "C" int openmc_material_set_id(int32_t index, int32_t id)
48✔
1498
{
1499
  if (index >= 0 && index < model::materials.size()) {
48✔
1500
    try {
1501
      model::materials.at(index)->set_id(id);
48✔
1502
    } catch (const std::exception& e) {
×
1503
      set_errmsg(e.what());
×
1504
      return OPENMC_E_UNASSIGNED;
×
UNCOV
1505
    }
×
1506
  } else {
1507
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1508
    return OPENMC_E_OUT_OF_BOUNDS;
×
1509
  }
1510
  return 0;
48✔
1511
}
1512

1513
extern "C" int openmc_material_get_name(int32_t index, const char** name)
36✔
1514
{
1515
  if (index < 0 || index >= model::materials.size()) {
36✔
1516
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1517
    return OPENMC_E_OUT_OF_BOUNDS;
×
1518
  }
1519

1520
  *name = model::materials[index]->name().data();
36✔
1521

1522
  return 0;
36✔
1523
}
1524

1525
extern "C" int openmc_material_set_name(int32_t index, const char* name)
12✔
1526
{
1527
  if (index < 0 || index >= model::materials.size()) {
12✔
1528
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1529
    return OPENMC_E_OUT_OF_BOUNDS;
×
1530
  }
1531

1532
  model::materials[index]->set_name(name);
12✔
1533

1534
  return 0;
12✔
1535
}
1536

1537
extern "C" int openmc_material_set_volume(int32_t index, double volume)
50✔
1538
{
1539
  if (index >= 0 && index < model::materials.size()) {
50✔
1540
    auto& m {model::materials[index]};
50✔
1541
    if (volume >= 0.0) {
50✔
1542
      m->volume_ = volume;
50✔
1543
      return 0;
50✔
1544
    } else {
1545
      set_errmsg("Volume must be non-negative");
×
UNCOV
1546
      return OPENMC_E_INVALID_ARGUMENT;
×
1547
    }
1548
  } else {
1549
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1550
    return OPENMC_E_OUT_OF_BOUNDS;
×
1551
  }
1552
}
1553

1554
extern "C" int openmc_material_get_depletable(int32_t index, bool* depletable)
24✔
1555
{
1556
  if (index < 0 || index >= model::materials.size()) {
24✔
1557
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1558
    return OPENMC_E_OUT_OF_BOUNDS;
×
1559
  }
1560

1561
  *depletable = model::materials[index]->depletable();
24✔
1562

1563
  return 0;
24✔
1564
}
1565

1566
extern "C" int openmc_material_set_depletable(int32_t index, bool depletable)
12✔
1567
{
1568
  if (index < 0 || index >= model::materials.size()) {
12✔
1569
    set_errmsg("Index in materials array is out of bounds.");
×
UNCOV
1570
    return OPENMC_E_OUT_OF_BOUNDS;
×
1571
  }
1572

1573
  model::materials[index]->depletable() = depletable;
12✔
1574

1575
  return 0;
12✔
1576
}
1577

1578
extern "C" int openmc_extend_materials(
48✔
1579
  int32_t n, int32_t* index_start, int32_t* index_end)
1580
{
1581
  if (index_start)
48✔
1582
    *index_start = model::materials.size();
48✔
1583
  if (index_end)
48✔
UNCOV
1584
    *index_end = model::materials.size() + n - 1;
×
1585
  for (int32_t i = 0; i < n; i++) {
96✔
1586
    model::materials.push_back(make_unique<Material>());
48✔
1587
  }
1588
  return 0;
48✔
1589
}
1590

1591
extern "C" size_t n_materials()
72✔
1592
{
1593
  return model::materials.size();
72✔
1594
}
1595

1596
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc