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

openmc-dev / openmc / 22322317452

pending completion
22322317452

Pull #3808

github

web-flow
Merge 0e9eea39a into 83a30f686
Pull Request #3808: Add properties to settings w/ documentation, c++ loading of filename, and python round-trip test

16820 of 23482 branches covered (71.63%)

Branch coverage included in aggregate %.

76 of 92 new or added lines in 8 files covered. (82.61%)

724 existing lines in 14 files now uncovered.

56900 of 66807 relevant lines covered (85.17%)

43125827.06 hits per line

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

74.34
/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 "openmc/tensor.h"
12

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

31
namespace openmc {
32

33
//==============================================================================
34
// Global variables
35
//==============================================================================
36

37
namespace model {
38

39
std::unordered_map<int32_t, int32_t> material_map;
40
vector<unique_ptr<Material>> materials;
41

42
} // namespace model
43

44
//==============================================================================
45
// Material implementation
46
//==============================================================================
47

48
Material::Material(pugi::xml_node node)
12,398✔
49
{
50
  index_ = model::materials.size(); // Avoids warning about narrowing
12,398✔
51

52
  if (check_for_node(node, "id")) {
12,398!
53
    this->set_id(std::stoi(get_node_value(node, "id")));
12,398✔
54
  } else {
55
    fatal_error("Must specify id of material in materials XML file.");
×
56
  }
57

58
  if (check_for_node(node, "name")) {
12,398✔
59
    name_ = get_node_value(node, "name");
6,180✔
60
  }
61

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

69
  if (check_for_node(node, "depletable")) {
12,398✔
70
    depletable_ = get_node_value_bool(node, "depletable");
4,459✔
71
  }
72

73
  bool sum_density {false};
12,398✔
74
  pugi::xml_node density_node = node.child("density");
12,398✔
75
  std::string units;
12,398✔
76
  if (density_node) {
12,398!
77
    units = get_node_value(density_node, "units");
12,398✔
78
    if (units == "sum") {
12,398✔
79
      sum_density = true;
1,958✔
80
    } else if (units == "macro") {
10,440✔
81
      if (check_for_node(density_node, "value")) {
2,142!
82
        density_ = std::stod(get_node_value(density_node, "value"));
2,142✔
83
      } else {
84
        density_ = 1.0;
×
85
      }
86
    } else {
87
      double val = std::stod(get_node_value(density_node, "value"));
8,298✔
88
      if (val <= 0.0) {
8,298!
89
        fatal_error("Need to specify a positive density on material " +
×
90
                    std::to_string(id_) + ".");
×
91
      }
92

93
      if (units == "g/cc" || units == "g/cm3") {
8,298✔
94
        density_ = -val;
8,030✔
95
      } else if (units == "kg/m3") {
268✔
96
        density_ = -1.0e-3 * val;
12✔
97
      } else if (units == "atom/b-cm") {
256✔
98
        density_ = val;
244✔
99
      } else if (units == "atom/cc" || units == "atom/cm3") {
12!
100
        density_ = 1.0e-24 * val;
12✔
101
      } else {
102
        fatal_error("Unknown units '" + units + "' specified on material " +
×
103
                    std::to_string(id_) + ".");
×
104
      }
105
    }
106
  } else {
107
    fatal_error("Must specify <density> element in material " +
×
108
                std::to_string(id_) + ".");
×
109
  }
110

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

119
  // =======================================================================
120
  // READ AND PARSE <nuclide> TAGS
121

122
  // Check to ensure material has at least one nuclide
123
  if (!check_for_node(node, "nuclide") &&
14,540!
124
      !check_for_node(node, "macroscopic")) {
2,142!
125
    fatal_error("No macroscopic data or nuclides specified on material " +
×
126
                std::to_string(id_));
×
127
  }
128

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

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

147
    // Check for empty name on nuclide
148
    if (!check_for_node(node_nuc, "name")) {
2,142!
149
      fatal_error("No name specified on macroscopic data in material " +
×
150
                  std::to_string(id_));
×
151
    }
152

153
    // store nuclide name
154
    std::string name = get_node_value(node_nuc, "name", false, true);
2,142✔
155
    names.push_back(name);
2,142✔
156

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

172
      // store nuclide name
173
      std::string name = get_node_value(node_nuc, "name", false, true);
39,839✔
174
      names.push_back(name);
39,839✔
175

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

184
        if (!has_ao && !has_wo) {
39,839!
185
          fatal_error(
×
186
            "No atom or weight percent specified for nuclide: " + name);
×
187
        } else if (has_ao && has_wo) {
39,839!
188
          fatal_error("Cannot specify both atom and weight percents for a "
×
189
                      "nuclide: " +
×
190
                      name);
191
        }
192

193
        // Copy atom/weight percents
194
        if (has_ao) {
39,839✔
195
          densities.push_back(std::stod(get_node_value(node_nuc, "ao")));
33,422✔
196
        } else {
197
          densities.push_back(-std::stod(get_node_value(node_nuc, "wo")));
6,417✔
198
        }
199
      }
200
    }
39,839✔
201
  }
202

203
  // =======================================================================
204
  // READ AND PARSE <isotropic> element
205

206
  vector<std::string> iso_lab;
12,398✔
207
  if (check_for_node(node, "isotropic")) {
12,398✔
208
    iso_lab = get_node_array<std::string>(node, "isotropic");
144✔
209
  }
210

211
  // ========================================================================
212
  // COPY NUCLIDES TO ARRAYS IN MATERIAL
213

214
  // allocate arrays in Material object
215
  auto n = names.size();
12,398✔
216
  nuclide_.reserve(n);
12,398✔
217
  atom_density_ = tensor::Tensor<double>({n});
12,398✔
218
  if (settings::photon_transport)
12,398✔
219
    element_.reserve(n);
249✔
220

221
  for (int i = 0; i < n; ++i) {
54,379✔
222
    const auto& name {names[i]};
41,981✔
223

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

235
    // If this nuclide hasn't been encountered yet, we need to add its name
236
    // and alias to the nuclide_dict
237
    if (data::nuclide_map.find(name) == data::nuclide_map.end()) {
41,981✔
238
      int index = data::nuclide_map.size();
25,038✔
239
      data::nuclide_map[name] = index;
25,038✔
240
      nuclide_.push_back(index);
25,038✔
241
    } else {
242
      nuclide_.push_back(data::nuclide_map[name]);
16,943✔
243
    }
244

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

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

259
      if (data::element_map.find(element) == data::element_map.end()) {
1,068✔
260
        int index = data::element_map.size();
549✔
261
        data::element_map[element] = index;
549✔
262
        element_.push_back(index);
549✔
263
      } else {
264
        element_.push_back(data::element_map[element]);
519✔
265
      }
266
    }
1,068✔
267

268
    // Copy atom/weight percent
269
    atom_density_(i) = densities[i];
41,981✔
270
  }
271

272
  if (settings::run_CE) {
12,398✔
273
    // By default, isotropic-in-lab is not used
274
    if (iso_lab.size() > 0) {
10,100✔
275
      p0_.resize(n);
144✔
276

277
      // Apply isotropic-in-lab treatment to specified nuclides
278
      for (int j = 0; j < n; ++j) {
1,356✔
279
        for (const auto& nuc : iso_lab) {
6,300!
280
          if (names[j] == nuc) {
6,300✔
281
            p0_[j] = true;
1,212✔
282
            break;
1,212✔
283
          }
284
        }
285
      }
286
    }
287
  }
288

289
  // Check to make sure either all atom percents or all weight percents are
290
  // given
291
  if (!((atom_density_ >= 0.0).all() || (atom_density_ <= 0.0).all())) {
12,398!
292
    fatal_error(
×
293
      "Cannot mix atom and weight percents in material " + std::to_string(id_));
×
294
  }
295

296
  // Determine density if it is a sum value
297
  if (sum_density)
12,398✔
298
    density_ = atom_density_.sum();
1,958✔
299

300
  if (check_for_node(node, "temperature")) {
12,398✔
301
    temperature_ = std::stod(get_node_value(node, "temperature"));
1,536✔
302
  }
303

304
  if (check_for_node(node, "volume")) {
12,398✔
305
    volume_ = std::stod(get_node_value(node, "volume"));
1,599✔
306
  }
307

308
  // =======================================================================
309
  // READ AND PARSE <sab> TAG FOR THERMAL SCATTERING DATA
310
  if (settings::run_CE) {
12,398✔
311
    // Loop over <sab> elements
312

313
    vector<std::string> sab_names;
10,100✔
314
    for (auto node_sab : node.children("sab")) {
11,721✔
315
      // Determine name of thermal scattering table
316
      if (!check_for_node(node_sab, "name")) {
1,621!
317
        fatal_error("Need to specify <name> for thermal scattering table.");
×
318
      }
319
      std::string name = get_node_value(node_sab, "name");
1,621✔
320
      sab_names.push_back(name);
1,621✔
321

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

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

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

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

356
Material::~Material()
12,434✔
357
{
358
  model::material_map.erase(id_);
12,434✔
359
}
12,434✔
360

361
Material& Material::clone()
×
362
{
363
  std::unique_ptr<Material> mat = std::make_unique<Material>();
×
364

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

381
  if (ttb_)
×
382
    mat->ttb_ = std::make_unique<Bremsstrahlung>(*ttb_);
×
383

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

390
void Material::finalize()
12,161✔
391
{
392
  // Set fissionable if any nuclide is fissionable
393
  if (settings::run_CE) {
12,161✔
394
    for (const auto& i_nuc : nuclide_) {
34,937✔
395
      if (data::nuclides[i_nuc]->fissionable_) {
29,544✔
396
        fissionable_ = true;
4,470✔
397
        break;
4,470✔
398
      }
399
    }
400

401
    // Generate material bremsstrahlung data for electrons and positrons
402
    if (settings::photon_transport &&
9,863✔
403
        settings::electron_treatment == ElectronTreatment::TTB) {
249✔
404
      this->init_bremsstrahlung();
213✔
405
    }
406

407
    // Assign thermal scattering tables
408
    this->init_thermal();
9,863✔
409
  }
410

411
  // Normalize density
412
  this->normalize_density();
12,161✔
413
}
12,161✔
414

415
void Material::normalize_density()
12,161✔
416
{
417
  bool percent_in_atom = (atom_density_(0) >= 0.0);
12,161✔
418
  bool density_in_atom = (density_ >= 0.0);
12,161✔
419

420
  for (int i = 0; i < nuclide_.size(); ++i) {
53,439✔
421
    // determine atomic weight ratio
422
    int i_nuc = nuclide_[i];
41,278✔
423
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
43,864✔
424
                                  : data::mg.nuclides_[i_nuc].awr;
2,586✔
425

426
    // if given weight percent, convert all values so that they are divided
427
    // by awr. thus, when a sum is done over the values, it's actually
428
    // sum(w/awr)
429
    if (!percent_in_atom)
41,278✔
430
      atom_density_(i) = -atom_density_(i) / awr;
6,417✔
431
  }
432

433
  // determine normalized atom percents. if given atom percents, this is
434
  // straightforward. if given weight percents, the value is w/awr and is
435
  // divided by sum(w/awr)
436
  atom_density_ /= atom_density_.sum();
12,161✔
437

438
  // Change density in g/cm^3 to atom/b-cm. Since all values are now in
439
  // atom percent, the sum needs to be re-evaluated as 1/sum(x*awr)
440
  if (!density_in_atom) {
12,161✔
441
    double sum_percent = 0.0;
7,805✔
442
    for (int i = 0; i < nuclide_.size(); ++i) {
34,232✔
443
      int i_nuc = nuclide_[i];
26,427✔
444
      double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
26,487✔
445
                                    : data::mg.nuclides_[i_nuc].awr;
60✔
446
      sum_percent += atom_density_(i) * awr;
26,427✔
447
    }
448
    sum_percent = 1.0 / sum_percent;
7,805✔
449
    density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent;
7,805✔
450
  }
451

452
  // Calculate nuclide atom densities
453
  atom_density_ *= density_;
12,161✔
454

455
  // Calculate density in [g/cm^3] and charge density in [e/b-cm]
456
  density_gpcc_ = 0.0;
12,161✔
457
  charge_density_ = 0.0;
12,161✔
458
  for (int i = 0; i < nuclide_.size(); ++i) {
53,439✔
459
    int i_nuc = nuclide_[i];
41,278✔
460
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_ : 1.0;
41,278✔
461
    int z = settings::run_CE ? data::nuclides[i_nuc]->Z_ : 0.0;
41,278✔
462
    density_gpcc_ += atom_density_(i) * awr * MASS_NEUTRON / N_AVOGADRO;
41,278✔
463
    charge_density_ += atom_density_(i) * z;
41,278✔
464
  }
465
}
12,161✔
466

467
void Material::init_thermal()
14,903✔
468
{
469
  vector<ThermalTable> tables;
14,903✔
470

471
  std::unordered_set<int> already_checked;
14,903✔
472
  for (const auto& table : thermal_tables_) {
16,490✔
473
    // Make sure each S(a,b) table only gets checked once
474
    if (already_checked.find(table.index_table) != already_checked.end()) {
1,587!
475
      continue;
×
476
    }
477
    already_checked.insert(table.index_table);
1,587✔
478

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

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

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

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

522
  // Update the list of thermal tables
523
  thermal_tables_ = tables;
14,903✔
524
}
14,903✔
525

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

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

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

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

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

547
    // Get atomic density of nuclide given atom/weight percent
548
    double atom_density =
549
      (atom_density_[0] > 0.0) ? atom_density_[i] : -atom_density_[i] / awr;
1,632!
550

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

555
    for (int j = 0; j < elm.n_electrons_.size(); ++j) {
12,894✔
556
      if (elm.n_electrons_[j] < 0) {
11,262✔
557
        n_conduction -= elm.n_electrons_[j] * atom_density;
1,152✔
558
        continue;
1,152✔
559
      }
560
      e_b_sq.push_back(elm.ionization_energy_[j] * elm.ionization_energy_[j]);
10,110✔
561
      f.push_back(elm.n_electrons_[j] * atom_density);
10,110✔
562
    }
563
  }
564
  log_I /= electron_density;
426✔
565
  n_conduction /= electron_density;
426✔
566
  for (auto& f_i : f)
10,536✔
567
    f_i /= electron_density;
10,110✔
568

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

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

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

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

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

591
  // Loop over incident charged particle energies
592
  for (int i = 0; i < data::ttb_e_grid.size(); ++i) {
85,366✔
593
    double E = data::ttb_e_grid(i);
84,940✔
594

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

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

604
    double tau = E / MASS_ELECTRON_EV;
84,940✔
605

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

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

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

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

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

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

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

646
    // Allocate temporary arrays
647
    auto stopping_power_collision = tensor::zeros<double>({n_e});
426✔
648
    auto stopping_power_radiative = tensor::zeros<double>({n_e});
426✔
649
    auto dcs = tensor::zeros<double>({n_e, n_k});
426✔
650

651
    double Z_eq_sq = 0.0;
426✔
652
    double sum_density = 0.0;
426✔
653

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

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

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

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

673
      // Accumulate material DCS
674
      dcs += (atom_density * elm.Z_ * elm.Z_) * elm.dcs_;
1,632✔
675

676
      // Accumulate material radiative stopping power
677
      stopping_power_radiative += atom_density * elm.stopping_power_radiative_;
1,632✔
678
    }
679
    Z_eq_sq /= sum_density;
426✔
680

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

704
    // Total material stopping power
705
    tensor::Tensor<double> stopping_power =
706
      stopping_power_collision + stopping_power_radiative;
426✔
707

708
    // Loop over photon energies
709
    auto f = tensor::zeros<double>({n_e});
426✔
710
    auto z = tensor::zeros<double>({n_e});
426✔
711
    for (int i = 0; i < n_e - 1; ++i) {
84,940✔
712
      double w = data::ttb_e_grid(i);
84,514✔
713

714
      // Loop over incident particle energies
715
      for (int j = i; j < n_e; ++j) {
8,596,854✔
716
        double e = data::ttb_e_grid(j);
8,512,340✔
717

718
        // Reduced photon energy
719
        double k = w / e;
8,512,340✔
720

721
        // Find the lower bounding index of the reduced photon energy
722
        int i_k = lower_bound_index(
8,512,340✔
723
          data::ttb_k_grid.cbegin(), data::ttb_k_grid.cend(), k);
8,512,340✔
724

725
        // Get the interpolation bounds
726
        double k_l = data::ttb_k_grid(i_k);
8,512,340✔
727
        double k_r = data::ttb_k_grid(i_k + 1);
8,512,340✔
728
        double x_l = dcs(j, i_k);
8,512,340✔
729
        double x_r = dcs(j, i_k + 1);
8,512,340✔
730

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

735
        // Square of the ratio of the speed of light to the velocity of the
736
        // charged particle
737
        double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) /
8,512,340✔
738
                         ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV));
8,512,340✔
739

740
        // Compute the integrand of the PDF
741
        f(j) = x / (beta_sq * stopping_power(j) * w);
8,512,340✔
742
      }
743

744
      // Number of points to integrate
745
      int n = n_e - i;
84,514✔
746

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

752
        double c = 0.0;
84,088✔
753
        for (int j = i; j < n_e - 1; ++j) {
8,511,488✔
754
          c += spline_integrate(n, &data::ttb_e_grid(i), &f(i), &z(i),
8,427,400✔
755
            data::ttb_e_grid(j), data::ttb_e_grid(j + 1));
8,427,400✔
756

757
          ttb->pdf(j + 1, i) = c;
8,427,400✔
758
        }
759

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

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

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

778
      // Loop over photon energies
779
      double c = 0.0;
84,514✔
780
      for (int i = 0; i < j; ++i) {
8,512,340✔
781
        // Integrate the CDF from the PDF using the fact that the PDF is linear
782
        // in log-log space
783
        double w_l = std::log(data::ttb_e_grid(i));
8,427,826✔
784
        double w_r = std::log(data::ttb_e_grid(i + 1));
8,427,826✔
785
        double x_l = std::log(ttb->pdf(j, i));
8,427,826✔
786
        double x_r = std::log(ttb->pdf(j, i + 1));
8,427,826✔
787
        double beta = (x_r - x_l) / (w_r - w_l);
8,427,826✔
788
        double a = beta + 1.0;
8,427,826✔
789
        c += std::exp(w_l + x_l) / a * std::expm1(a * (w_r - w_l));
8,427,826✔
790
        ttb->cdf(j, i + 1) = c;
8,427,826✔
791
      }
792

793
      // Set photon number yield
794
      ttb->yield(j) = c;
84,514✔
795
    }
796

797
    // Use logarithm of number yield since it is log-log interpolated
798
    ttb->yield =
799
      tensor::where(ttb->yield > 0.0, tensor::log(ttb->yield), -500.0);
426✔
800
  }
426✔
801
}
213✔
802

803
void Material::init_nuclide_index()
15,048✔
804
{
805
  int n = settings::run_CE ? data::nuclides.size() : data::mg.nuclides_.size();
15,048✔
806
  mat_nuclide_index_.resize(n);
15,048✔
807
  std::fill(mat_nuclide_index_.begin(), mat_nuclide_index_.end(), C_NONE);
15,048✔
808
  for (int i = 0; i < nuclide_.size(); ++i) {
91,757✔
809
    mat_nuclide_index_[nuclide_[i]] = i;
76,709✔
810
  }
811
}
15,048✔
812

813
void Material::calculate_xs(Particle& p) const
1,449,953,494✔
814
{
815
  // Set all material macroscopic cross sections to zero
816
  p.macro_xs().total = 0.0;
1,449,953,494✔
817
  p.macro_xs().absorption = 0.0;
1,449,953,494✔
818
  p.macro_xs().fission = 0.0;
1,449,953,494✔
819
  p.macro_xs().nu_fission = 0.0;
1,449,953,494✔
820

821
  if (p.type().is_neutron()) {
1,449,953,494✔
822
    this->calculate_neutron_xs(p);
1,391,025,706✔
823
  } else if (p.type().is_photon()) {
58,927,788✔
824
    this->calculate_photon_xs(p);
14,810,142✔
825
  }
826
}
1,449,953,494✔
827

828
void Material::calculate_neutron_xs(Particle& p) const
1,391,025,706✔
829
{
830
  // Find energy index on energy grid
831
  int neutron = ParticleType::neutron().transport_index();
1,391,025,706✔
832
  int i_grid =
833
    std::log(p.E() / data::energy_min[neutron]) / simulation::log_spacing;
1,391,025,706✔
834

835
  // Determine if this material has S(a,b) tables
836
  bool check_sab = (thermal_tables_.size() > 0);
1,391,025,706✔
837

838
  // Initialize position in i_sab_nuclides
839
  int j = 0;
1,391,025,706✔
840

841
  // Calculate NCrystal cross section
842
  double ncrystal_xs = -1.0;
1,391,025,706✔
843
  if (ncrystal_mat_ && p.E() < NCRYSTAL_MAX_ENERGY) {
1,391,025,706!
844
    ncrystal_xs = ncrystal_mat_.xs(p);
9,129,951✔
845
  }
846

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

852
    int i_sab = C_NONE;
2,147,483,647✔
853
    double sab_frac = 0.0;
2,147,483,647✔
854

855
    // Check if this nuclide matches one of the S(a,b) tables specified.
856
    // This relies on thermal_tables_ being sorted by .index_nuclide
857
    if (check_sab) {
2,147,483,647✔
858
      const auto& sab {thermal_tables_[j]};
678,486,765✔
859
      if (i == sab.index_nuclide) {
678,486,765✔
860
        // Get index in sab_tables
861
        i_sab = sab.index_table;
342,400,125✔
862
        sab_frac = sab.fraction;
342,400,125✔
863

864
        // If particle energy is greater than the highest energy for the
865
        // S(a,b) table, then don't use the S(a,b) table
866
        if (p.E() > data::thermal_scatt[i_sab]->energy_max_)
342,400,125✔
867
          i_sab = C_NONE;
204,245,055✔
868

869
        // Increment position in thermal_tables_
870
        ++j;
342,400,125✔
871

872
        // Don't check for S(a,b) tables if there are no more left
873
        if (j == thermal_tables_.size())
342,400,125✔
874
          check_sab = false;
342,209,046✔
875
      }
876
    }
877

878
    // ======================================================================
879
    // CALCULATE MICROSCOPIC CROSS SECTION
880

881
    // Get nuclide index
882
    int i_nuclide = nuclide_[i];
2,147,483,647✔
883

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

888
    // ======================================================================
889
    // ADD TO MACROSCOPIC CROSS SECTION
890

891
    // Copy atom density of nuclide in material
892
    double atom_density = this->atom_density(i, p.density_mult());
2,147,483,647✔
893

894
    // Add contributions to cross sections
895
    p.macro_xs().total += atom_density * micro.total;
2,147,483,647✔
896
    p.macro_xs().absorption += atom_density * micro.absorption;
2,147,483,647✔
897
    p.macro_xs().fission += atom_density * micro.fission;
2,147,483,647✔
898
    p.macro_xs().nu_fission += atom_density * micro.nu_fission;
2,147,483,647✔
899
  }
900
}
1,391,025,706✔
901

902
void Material::calculate_photon_xs(Particle& p) const
14,810,142✔
903
{
904
  p.macro_xs().coherent = 0.0;
14,810,142✔
905
  p.macro_xs().incoherent = 0.0;
14,810,142✔
906
  p.macro_xs().photoelectric = 0.0;
14,810,142✔
907
  p.macro_xs().pair_production = 0.0;
14,810,142✔
908

909
  // Add contribution from each nuclide in material
910
  for (int i = 0; i < nuclide_.size(); ++i) {
80,545,973✔
911
    // ========================================================================
912
    // CALCULATE MICROSCOPIC CROSS SECTION
913

914
    // Determine microscopic cross sections for this nuclide
915
    int i_element = element_[i];
65,735,831✔
916

917
    // Calculate microscopic cross section for this nuclide
918
    const auto& micro {p.photon_xs(i_element)};
65,735,831✔
919
    if (p.E() != micro.last_E) {
65,735,831✔
920
      data::elements[i_element]->calculate_xs(p);
35,135,183✔
921
    }
922

923
    // ========================================================================
924
    // ADD TO MACROSCOPIC CROSS SECTION
925

926
    // Copy atom density of nuclide in material
927
    double atom_density = this->atom_density(i, p.density_mult());
65,735,831✔
928

929
    // Add contributions to material macroscopic cross sections
930
    p.macro_xs().total += atom_density * micro.total;
65,735,831✔
931
    p.macro_xs().coherent += atom_density * micro.coherent;
65,735,831✔
932
    p.macro_xs().incoherent += atom_density * micro.incoherent;
65,735,831✔
933
    p.macro_xs().photoelectric += atom_density * micro.photoelectric;
65,735,831✔
934
    p.macro_xs().pair_production += atom_density * micro.pair_production;
65,735,831✔
935
  }
936
}
14,810,142✔
937

938
void Material::set_id(int32_t id)
12,434✔
939
{
940
  assert(id >= 0 || id == C_NONE);
9,496!
941

942
  // Clear entry in material map if an ID was already assigned before
943
  if (id_ != C_NONE) {
12,434!
944
    model::material_map.erase(id_);
×
945
    id_ = C_NONE;
×
946
  }
947

948
  // Make sure no other material has same ID
949
  if (model::material_map.find(id) != model::material_map.end()) {
12,434!
950
    throw std::runtime_error {
×
951
      "Two materials have the same ID: " + std::to_string(id)};
×
952
  }
953

954
  // If no ID specified, auto-assign next ID in sequence
955
  if (id == C_NONE) {
12,434!
956
    id = 0;
×
957
    for (const auto& m : model::materials) {
×
958
      id = std::max(id, m->id_);
×
959
    }
960
    ++id;
×
961
  }
962

963
  // Update ID and entry in material map
964
  id_ = id;
12,434✔
965
  model::material_map[id] = index_;
12,434✔
966
}
12,434✔
967

968
void Material::set_density(double density, const std::string& units)
5,202✔
969
{
970
  assert(density >= 0.0);
4,142!
971

972
  if (nuclide_.empty()) {
5,202!
973
    throw std::runtime_error {"No nuclides exist in material yet."};
×
974
  }
975

976
  if (units == "atom/b-cm") {
5,202✔
977
    // Set total density based on value provided
978
    density_ = density;
5,166✔
979

980
    // Determine normalized atom percents
981
    double sum_percent = atom_density_.sum();
5,166✔
982
    atom_density_ /= sum_percent;
5,166✔
983

984
    // Recalculate nuclide atom densities based on given density
985
    atom_density_ *= density;
5,166✔
986

987
    // Calculate density in g/cm^3 and charge density in [e/b-cm]
988
    density_gpcc_ = 0.0;
5,166✔
989
    charge_density_ = 0.0;
5,166✔
990
    for (int i = 0; i < nuclide_.size(); ++i) {
53,475✔
991
      int i_nuc = nuclide_[i];
48,309✔
992
      double awr = data::nuclides[i_nuc]->awr_;
48,309✔
993
      int z = settings::run_CE ? data::nuclides[i_nuc]->Z_ : 0.0;
48,309!
994
      density_gpcc_ += atom_density_(i) * awr * MASS_NEUTRON / N_AVOGADRO;
48,309✔
995
      charge_density_ += atom_density_(i) * z;
48,309✔
996
    }
997
  } else if (units == "g/cm3" || units == "g/cc") {
36!
998
    // Determine factor by which to change densities
999
    double previous_density_gpcc = density_gpcc_;
27✔
1000
    double f = density / previous_density_gpcc;
27✔
1001

1002
    // Update densities
1003
    density_gpcc_ = density;
27✔
1004
    density_ *= f;
27✔
1005
    atom_density_ *= f;
27✔
1006
    charge_density_ *= f;
27✔
1007
  } else {
1008
    throw std::invalid_argument {
9✔
1009
      "Invalid units '" + std::string(units.data()) + "' specified."};
18✔
1010
  }
1011
}
5,193✔
1012

1013
void Material::set_densities(
5,040✔
1014
  const vector<std::string>& name, const vector<double>& density)
1015
{
1016
  auto n = name.size();
5,040✔
1017
  assert(n > 0);
4,016!
1018
  assert(n == density.size());
4,016!
1019

1020
  if (n != nuclide_.size()) {
5,040✔
1021
    nuclide_.resize(n);
1,188✔
1022
    atom_density_ = tensor::zeros<double>({n});
1,188✔
1023
    if (settings::photon_transport)
1,188!
1024
      element_.resize(n);
×
1025
  }
1026

1027
  double sum_density = 0.0;
5,040✔
1028
  for (int64_t i = 0; i < n; ++i) {
52,791✔
1029
    const auto& nuc {name[i]};
47,751✔
1030
    if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) {
47,751!
1031
      int err = openmc_load_nuclide(nuc.c_str(), nullptr, 0);
×
1032
      if (err < 0)
×
1033
        throw std::runtime_error {openmc_err_msg};
×
1034
    }
1035

1036
    nuclide_[i] = data::nuclide_map.at(nuc);
47,751✔
1037
    assert(density[i] > 0.0);
38,121!
1038
    atom_density_(i) = density[i];
47,751✔
1039
    sum_density += density[i];
47,751✔
1040

1041
    if (settings::photon_transport) {
47,751!
1042
      auto element_name = to_element(nuc);
×
1043
      element_[i] = data::element_map.at(element_name);
×
1044
    }
×
1045
  }
1046

1047
  // Set total density to the sum of the vector
1048
  this->set_density(sum_density, "atom/b-cm");
5,040✔
1049

1050
  // Generate material bremsstrahlung data for electrons and positrons
1051
  if (settings::photon_transport &&
5,040!
1052
      settings::electron_treatment == ElectronTreatment::TTB) {
×
1053
    this->init_bremsstrahlung();
×
1054
  }
1055

1056
  // Assign S(a,b) tables
1057
  this->init_thermal();
5,040✔
1058
}
5,040✔
1059

1060
double Material::volume() const
45✔
1061
{
1062
  if (volume_ < 0.0) {
45✔
1063
    throw std::runtime_error {
9✔
1064
      "Volume for material with ID=" + std::to_string(id_) + " not set."};
18✔
1065
  }
1066
  return volume_;
36✔
1067
}
1068

1069
double Material::temperature() const
15,488✔
1070
{
1071
  // If material doesn't have an assigned temperature, use global default
1072
  return temperature_ >= 0 ? temperature_ : settings::temperature_default;
15,488✔
1073
}
1074

1075
void Material::to_hdf5(hid_t group) const
10,380✔
1076
{
1077
  hid_t material_group = create_group(group, "material " + std::to_string(id_));
10,380✔
1078

1079
  write_attribute(material_group, "depletable", static_cast<int>(depletable()));
10,380✔
1080
  if (volume_ > 0.0) {
10,380✔
1081
    write_attribute(material_group, "volume", volume_);
1,590✔
1082
  }
1083
  if (temperature_ > 0.0) {
10,380✔
1084
    write_attribute(material_group, "temperature", temperature_);
1,500✔
1085
  }
1086
  write_dataset(material_group, "name", name_);
10,380✔
1087
  write_dataset(material_group, "atom_density", density_);
10,380✔
1088

1089
  // Copy nuclide/macro name for each nuclide to vector
1090
  vector<std::string> nuc_names;
10,380✔
1091
  vector<std::string> macro_names;
10,380✔
1092
  vector<double> nuc_densities;
10,380✔
1093
  if (settings::run_CE) {
10,380✔
1094
    for (int i = 0; i < nuclide_.size(); ++i) {
43,915✔
1095
      int i_nuc = nuclide_[i];
35,047✔
1096
      nuc_names.push_back(data::nuclides[i_nuc]->name_);
35,047✔
1097
      nuc_densities.push_back(atom_density_(i));
35,047✔
1098
    }
1099
  } else {
1100
    for (int i = 0; i < nuclide_.size(); ++i) {
3,051✔
1101
      int i_nuc = nuclide_[i];
1,539✔
1102
      if (data::mg.nuclides_[i_nuc].awr != MACROSCOPIC_AWR) {
1,539✔
1103
        nuc_names.push_back(data::mg.nuclides_[i_nuc].name);
72✔
1104
        nuc_densities.push_back(atom_density_(i));
72✔
1105
      } else {
1106
        macro_names.push_back(data::mg.nuclides_[i_nuc].name);
1,467✔
1107
      }
1108
    }
1109
  }
1110

1111
  // Write vector to 'nuclides'
1112
  if (!nuc_names.empty()) {
10,380✔
1113
    write_dataset(material_group, "nuclides", nuc_names);
8,913✔
1114
    write_dataset(material_group, "nuclide_densities", nuc_densities);
8,913✔
1115
  }
1116

1117
  // Write vector to 'macroscopics'
1118
  if (!macro_names.empty()) {
10,380✔
1119
    write_dataset(material_group, "macroscopics", macro_names);
1,467✔
1120
  }
1121

1122
  if (!thermal_tables_.empty()) {
10,380✔
1123
    vector<std::string> sab_names;
1,290✔
1124
    for (const auto& table : thermal_tables_) {
2,634✔
1125
      sab_names.push_back(data::thermal_scatt[table.index_table]->name_);
1,344✔
1126
    }
1127
    write_dataset(material_group, "sab_names", sab_names);
1,290✔
1128
  }
1,290✔
1129

1130
  close_group(material_group);
10,380✔
1131
}
10,380✔
1132

1133
void Material::export_properties_hdf5(hid_t group) const
108✔
1134
{
1135
  hid_t material_group = create_group(group, "material " + std::to_string(id_));
108✔
1136
  write_attribute(material_group, "atom_density", density_);
108✔
1137
  write_attribute(material_group, "mass_density", density_gpcc_);
108✔
1138
  close_group(material_group);
108✔
1139
}
108✔
1140

1141
void Material::import_properties_hdf5(hid_t group, bool read_densities)
81✔
1142
{
1143
  if (!read_densities)
81!
NEW
1144
    return;
×
1145

1146
  hid_t material_group = open_group(group, "material " + std::to_string(id_));
81✔
1147
  double density;
1148
  read_attribute(material_group, "atom_density", density);
81✔
1149
  this->set_density(density, "atom/b-cm");
81✔
1150
  close_group(material_group);
81✔
1151
}
1152

1153
void Material::add_nuclide(const std::string& name, double density)
9✔
1154
{
1155
  // Check if nuclide is already in material
1156
  for (int i = 0; i < nuclide_.size(); ++i) {
45✔
1157
    int i_nuc = nuclide_[i];
36✔
1158
    if (data::nuclides[i_nuc]->name_ == name) {
36!
1159
      double awr = data::nuclides[i_nuc]->awr_;
×
1160
      density_ += density - atom_density_(i);
×
1161
      density_gpcc_ +=
×
1162
        (density - atom_density_(i)) * awr * MASS_NEUTRON / N_AVOGADRO;
×
1163
      atom_density_(i) = density;
×
1164
      return;
×
1165
    }
1166
  }
1167

1168
  // If nuclide wasn't found, extend nuclide/density arrays
1169
  int err = openmc_load_nuclide(name.c_str(), nullptr, 0);
9✔
1170
  if (err < 0)
9!
1171
    throw std::runtime_error {openmc_err_msg};
×
1172

1173
  // Append new nuclide/density
1174
  int i_nuc = data::nuclide_map[name];
9✔
1175
  nuclide_.push_back(i_nuc);
9✔
1176

1177
  // Append new element if photon transport is on
1178
  if (settings::photon_transport) {
9!
1179
    int i_elem = data::element_map[to_element(name)];
×
1180
    element_.push_back(i_elem);
×
1181
  }
1182

1183
  auto n = nuclide_.size();
9✔
1184

1185
  // Create copy of atom_density_ array with one extra entry
1186
  tensor::Tensor<double> atom_density = tensor::zeros<double>({n});
9✔
1187
  atom_density.slice(tensor::range(0, n - 1)) = atom_density_;
9✔
1188
  atom_density(n - 1) = density;
9✔
1189
  atom_density_ = atom_density;
9✔
1190

1191
  density_ += density;
9✔
1192
  density_gpcc_ +=
9✔
1193
    density * data::nuclides[i_nuc]->awr_ * MASS_NEUTRON / N_AVOGADRO;
9✔
1194
}
9✔
1195

1196
//==============================================================================
1197
// Non-method functions
1198
//==============================================================================
1199

1200
double sternheimer_adjustment(const vector<double>& f,
426✔
1201
  const vector<double>& e_b_sq, double e_p_sq, double n_conduction,
1202
  double log_I, double tol, int max_iter)
1203
{
1204
  // Get the total number of oscillators
1205
  int n = f.size();
426✔
1206

1207
  // Calculate the Sternheimer adjustment factor using Newton's method
1208
  double rho = 2.0;
426✔
1209
  int iter;
1210
  for (iter = 0; iter < max_iter; ++iter) {
1,704!
1211
    double rho_0 = rho;
1,704✔
1212

1213
    // Function to find the root of and its derivative
1214
    double g = 0.0;
1,704✔
1215
    double gp = 0.0;
1,704✔
1216

1217
    for (int i = 0; i < n; ++i) {
42,576✔
1218
      // Square of resonance energy of a bound-shell oscillator
1219
      double e_r_sq = e_b_sq[i] * rho * rho + 2.0 / 3.0 * f[i] * e_p_sq;
40,872✔
1220
      g += f[i] * std::log(e_r_sq);
40,872✔
1221
      gp += e_b_sq[i] * f[i] * rho / e_r_sq;
40,872✔
1222
    }
1223
    // Include conduction electrons
1224
    if (n_conduction > 0.0) {
1,704✔
1225
      g += n_conduction * std::log(n_conduction * e_p_sq);
1,410✔
1226
    }
1227

1228
    // Set the next guess: rho_n+1 = rho_n - g(rho_n)/g'(rho_n)
1229
    rho -= (g - 2.0 * log_I) / (2.0 * gp);
1,704✔
1230

1231
    // If the initial guess is too large, rho can be negative
1232
    if (rho < 0.0)
1,704!
1233
      rho = rho_0 / 2.0;
×
1234

1235
    // Check for convergence
1236
    if (std::abs(rho - rho_0) / rho_0 < tol)
1,704✔
1237
      break;
426✔
1238
  }
1239
  // Did not converge
1240
  if (iter >= max_iter) {
426!
1241
    warning("Maximum Newton-Raphson iterations exceeded.");
×
1242
    rho = 1.0e-6;
×
1243
  }
1244
  return rho;
426✔
1245
}
1246

1247
double density_effect(const vector<double>& f, const vector<double>& e_b_sq,
84,940✔
1248
  double e_p_sq, double n_conduction, double rho, double E, double tol,
1249
  int max_iter)
1250
{
1251
  // Get the total number of oscillators
1252
  int n = f.size();
84,940✔
1253

1254
  // Square of the ratio of the speed of light to the velocity of the charged
1255
  // particle
1256
  double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) /
84,940✔
1257
                   ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV));
84,940✔
1258

1259
  // For nonmetals, delta = 0 for beta < beta_0, where beta_0 is obtained by
1260
  // setting the frequency w = 0.
1261
  double beta_0_sq = 0.0;
84,940✔
1262
  if (n_conduction == 0.0) {
84,940✔
1263
    for (int i = 0; i < n; ++i) {
110,400✔
1264
      beta_0_sq += f[i] * e_p_sq / (e_b_sq[i] * rho * rho);
93,600✔
1265
    }
1266
    beta_0_sq = 1.0 / (1.0 + beta_0_sq);
16,800✔
1267
  }
1268
  double delta = 0.0;
84,940✔
1269
  if (beta_sq < beta_0_sq)
84,940✔
1270
    return delta;
8,682✔
1271

1272
  // Compute the square of the frequency w^2 using Newton's method, with the
1273
  // initial guess of w^2 equal to beta^2 * gamma^2
1274
  double w_sq = E / MASS_ELECTRON_EV * (E / MASS_ELECTRON_EV + 2);
76,258✔
1275
  int iter;
1276
  for (iter = 0; iter < max_iter; ++iter) {
511,130!
1277
    double w_sq_0 = w_sq;
511,130✔
1278

1279
    // Function to find the root of and its derivative
1280
    double g = 0.0;
511,130✔
1281
    double gp = 0.0;
511,130✔
1282

1283
    for (int i = 0; i < n; ++i) {
14,967,290✔
1284
      double c = e_b_sq[i] * rho * rho / e_p_sq + w_sq;
14,456,160✔
1285
      g += f[i] / c;
14,456,160✔
1286
      gp -= f[i] / (c * c);
14,456,160✔
1287
    }
1288
    // Include conduction electrons
1289
    g += n_conduction / w_sq;
511,130✔
1290
    gp -= n_conduction / (w_sq * w_sq);
511,130✔
1291

1292
    // Set the next guess: w_n+1 = w_n - g(w_n)/g'(w_n)
1293
    w_sq -= (g + 1.0 - 1.0 / beta_sq) / gp;
511,130✔
1294

1295
    // If the initial guess is too large, w can be negative
1296
    if (w_sq < 0.0)
511,130✔
1297
      w_sq = w_sq_0 / 2.0;
109,056✔
1298

1299
    // Check for convergence
1300
    if (std::abs(w_sq - w_sq_0) / w_sq_0 < tol)
511,130✔
1301
      break;
76,258✔
1302
  }
1303
  // Did not converge
1304
  if (iter >= max_iter) {
76,258!
1305
    warning("Maximum Newton-Raphson iterations exceeded: setting density "
×
1306
            "effect correction to zero.");
1307
    return delta;
×
1308
  }
1309

1310
  // Solve for the density effect correction
1311
  for (int i = 0; i < n; ++i) {
2,046,118✔
1312
    double l_sq = e_b_sq[i] * rho * rho / e_p_sq + 2.0 / 3.0 * f[i];
1,969,860✔
1313
    delta += f[i] * std::log((l_sq + w_sq) / l_sq);
1,969,860✔
1314
  }
1315
  // Include conduction electrons
1316
  if (n_conduction > 0.0) {
76,258✔
1317
    delta += n_conduction * std::log((n_conduction + w_sq) / n_conduction);
68,140✔
1318
  }
1319

1320
  return delta - w_sq * (1.0 - beta_sq);
76,258✔
1321
}
1322

1323
void read_materials_xml()
1,072✔
1324
{
1325
  write_message("Reading materials XML file...", 5);
1,072✔
1326

1327
  pugi::xml_document doc;
1,072✔
1328

1329
  // Check if materials.xml exists
1330
  std::string filename = settings::path_input + "materials.xml";
1,072✔
1331
  if (!file_exists(filename)) {
1,072!
1332
    fatal_error("Material XML file '" + filename + "' does not exist!");
×
1333
  }
1334

1335
  // Parse materials.xml file and get root element
1336
  doc.load_file(filename.c_str());
1,072✔
1337

1338
  // Loop over XML material elements and populate the array.
1339
  pugi::xml_node root = doc.document_element();
1,072✔
1340

1341
  read_materials_xml(root);
1,072✔
1342
}
1,072✔
1343

1344
void read_materials_xml(pugi::xml_node root)
6,475✔
1345
{
1346
  for (pugi::xml_node material_node : root.children("material")) {
18,873✔
1347
    model::materials.push_back(make_unique<Material>(material_node));
12,398✔
1348
  }
1349
  model::materials.shrink_to_fit();
6,475✔
1350
}
6,475✔
1351

1352
void free_memory_material()
6,576✔
1353
{
1354
  model::materials.clear();
6,576✔
1355
  model::material_map.clear();
6,576✔
1356
}
6,576✔
1357

1358
//==============================================================================
1359
// C API
1360
//==============================================================================
1361

1362
extern "C" int openmc_get_material_index(int32_t id, int32_t* index)
6,705✔
1363
{
1364
  auto it = model::material_map.find(id);
6,705✔
1365
  if (it == model::material_map.end()) {
6,705✔
1366
    set_errmsg("No material exists with ID=" + std::to_string(id) + ".");
9✔
1367
    return OPENMC_E_INVALID_ID;
9✔
1368
  } else {
1369
    *index = it->second;
6,696✔
1370
    return 0;
6,696✔
1371
  }
1372
}
1373

1374
extern "C" int openmc_material_add_nuclide(
9✔
1375
  int32_t index, const char* name, double density)
1376
{
1377
  int err = 0;
9✔
1378
  if (index >= 0 && index < model::materials.size()) {
9!
1379
    try {
1380
      model::materials[index]->add_nuclide(name, density);
9✔
1381
    } catch (const std::runtime_error& e) {
×
1382
      return OPENMC_E_DATA;
×
1383
    }
×
1384
  } else {
1385
    set_errmsg("Index in materials array is out of bounds.");
×
1386
    return OPENMC_E_OUT_OF_BOUNDS;
×
1387
  }
1388
  return err;
9✔
1389
}
1390

1391
extern "C" int openmc_material_get_densities(
135✔
1392
  int32_t index, const int** nuclides, const double** densities, int* n)
1393
{
1394
  if (index >= 0 && index < model::materials.size()) {
135!
1395
    auto& mat = model::materials[index];
135✔
1396
    if (!mat->nuclides().empty()) {
135!
1397
      *nuclides = mat->nuclides().data();
135✔
1398
      *densities = mat->densities().data();
135✔
1399
      *n = mat->nuclides().size();
135✔
1400
      return 0;
135✔
1401
    } else {
1402
      set_errmsg("Material atom density array has not been allocated.");
×
1403
      return OPENMC_E_ALLOCATE;
×
1404
    }
1405
  } else {
1406
    set_errmsg("Index in materials array is out of bounds.");
×
1407
    return OPENMC_E_OUT_OF_BOUNDS;
×
1408
  }
1409
}
1410

1411
extern "C" int openmc_material_get_density(int32_t index, double* density)
27✔
1412
{
1413
  if (index >= 0 && index < model::materials.size()) {
27!
1414
    auto& mat = model::materials[index];
27✔
1415
    *density = mat->density_gpcc();
27✔
1416
    return 0;
27✔
1417
  } else {
1418
    set_errmsg("Index in materials array is out of bounds.");
×
1419
    return OPENMC_E_OUT_OF_BOUNDS;
×
1420
  }
1421
}
1422

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

1434
extern "C" int openmc_material_get_id(int32_t index, int32_t* id)
7,497✔
1435
{
1436
  if (index >= 0 && index < model::materials.size()) {
7,497!
1437
    *id = model::materials[index]->id();
7,497✔
1438
    return 0;
7,497✔
1439
  } else {
1440
    set_errmsg("Index in materials array is out of bounds.");
×
1441
    return OPENMC_E_OUT_OF_BOUNDS;
×
1442
  }
1443
}
1444

1445
extern "C" int openmc_material_get_temperature(
54✔
1446
  int32_t index, double* temperature)
1447
{
1448
  if (index < 0 || index >= model::materials.size()) {
54!
1449
    set_errmsg("Index in materials array is out of bounds.");
×
1450
    return OPENMC_E_OUT_OF_BOUNDS;
×
1451
  }
1452
  *temperature = model::materials[index]->temperature();
54✔
1453
  return 0;
54✔
1454
}
1455

1456
extern "C" int openmc_material_get_volume(int32_t index, double* volume)
45✔
1457
{
1458
  if (index >= 0 && index < model::materials.size()) {
45!
1459
    try {
1460
      *volume = model::materials[index]->volume();
45✔
1461
    } catch (const std::exception& e) {
9!
1462
      set_errmsg(e.what());
9✔
1463
      return OPENMC_E_UNASSIGNED;
9✔
1464
    }
9✔
1465
    return 0;
36✔
1466
  } else {
1467
    set_errmsg("Index in materials array is out of bounds.");
×
1468
    return OPENMC_E_OUT_OF_BOUNDS;
×
1469
  }
1470
}
1471

1472
extern "C" int openmc_material_set_density(
81✔
1473
  int32_t index, double density, const char* units)
1474
{
1475
  if (index >= 0 && index < model::materials.size()) {
81!
1476
    try {
1477
      model::materials[index]->set_density(density, units);
99✔
1478
    } catch (const std::exception& e) {
9!
1479
      set_errmsg(e.what());
9✔
1480
      return OPENMC_E_UNASSIGNED;
9✔
1481
    }
9✔
1482
  } else {
1483
    set_errmsg("Index in materials array is out of bounds.");
×
1484
    return OPENMC_E_OUT_OF_BOUNDS;
×
1485
  }
1486
  return 0;
72✔
1487
}
1488

1489
extern "C" int openmc_material_set_densities(
5,040✔
1490
  int32_t index, int n, const char** name, const double* density)
1491
{
1492
  if (index >= 0 && index < model::materials.size()) {
5,040!
1493
    try {
1494
      model::materials[index]->set_densities(
15,120✔
1495
        {name, name + n}, {density, density + n});
10,080✔
1496
    } catch (const std::exception& e) {
×
1497
      set_errmsg(e.what());
×
1498
      return OPENMC_E_UNASSIGNED;
×
1499
    }
×
1500
  } else {
1501
    set_errmsg("Index in materials array is out of bounds.");
×
1502
    return OPENMC_E_OUT_OF_BOUNDS;
×
1503
  }
1504
  return 0;
5,040✔
1505
}
1506

1507
extern "C" int openmc_material_set_id(int32_t index, int32_t id)
36✔
1508
{
1509
  if (index >= 0 && index < model::materials.size()) {
36!
1510
    try {
1511
      model::materials.at(index)->set_id(id);
36✔
1512
    } catch (const std::exception& e) {
×
1513
      set_errmsg(e.what());
×
1514
      return OPENMC_E_UNASSIGNED;
×
1515
    }
×
1516
  } else {
1517
    set_errmsg("Index in materials array is out of bounds.");
×
1518
    return OPENMC_E_OUT_OF_BOUNDS;
×
1519
  }
1520
  return 0;
36✔
1521
}
1522

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

1530
  *name = model::materials[index]->name().data();
27✔
1531

1532
  return 0;
27✔
1533
}
1534

1535
extern "C" int openmc_material_set_name(int32_t index, const char* name)
9✔
1536
{
1537
  if (index < 0 || index >= model::materials.size()) {
9!
1538
    set_errmsg("Index in materials array is out of bounds.");
×
1539
    return OPENMC_E_OUT_OF_BOUNDS;
×
1540
  }
1541

1542
  model::materials[index]->set_name(name);
9✔
1543

1544
  return 0;
9✔
1545
}
1546

1547
extern "C" int openmc_material_set_volume(int32_t index, double volume)
27✔
1548
{
1549
  if (index >= 0 && index < model::materials.size()) {
27!
1550
    auto& m {model::materials[index]};
27✔
1551
    if (volume >= 0.0) {
27!
1552
      m->volume_ = volume;
27✔
1553
      return 0;
27✔
1554
    } else {
1555
      set_errmsg("Volume must be non-negative");
×
1556
      return OPENMC_E_INVALID_ARGUMENT;
×
1557
    }
1558
  } else {
1559
    set_errmsg("Index in materials array is out of bounds.");
×
1560
    return OPENMC_E_OUT_OF_BOUNDS;
×
1561
  }
1562
}
1563

1564
extern "C" int openmc_material_get_depletable(int32_t index, bool* depletable)
18✔
1565
{
1566
  if (index < 0 || index >= model::materials.size()) {
18!
1567
    set_errmsg("Index in materials array is out of bounds.");
×
1568
    return OPENMC_E_OUT_OF_BOUNDS;
×
1569
  }
1570

1571
  *depletable = model::materials[index]->depletable();
18✔
1572

1573
  return 0;
18✔
1574
}
1575

1576
extern "C" int openmc_material_set_depletable(int32_t index, bool depletable)
9✔
1577
{
1578
  if (index < 0 || index >= model::materials.size()) {
9!
1579
    set_errmsg("Index in materials array is out of bounds.");
×
1580
    return OPENMC_E_OUT_OF_BOUNDS;
×
1581
  }
1582

1583
  model::materials[index]->depletable() = depletable;
9✔
1584

1585
  return 0;
9✔
1586
}
1587

1588
extern "C" int openmc_extend_materials(
36✔
1589
  int32_t n, int32_t* index_start, int32_t* index_end)
1590
{
1591
  if (index_start)
36!
1592
    *index_start = model::materials.size();
36✔
1593
  if (index_end)
36!
1594
    *index_end = model::materials.size() + n - 1;
×
1595
  for (int32_t i = 0; i < n; i++) {
72✔
1596
    model::materials.push_back(make_unique<Material>());
36✔
1597
  }
1598
  return 0;
36✔
1599
}
1600

1601
extern "C" size_t n_materials()
54✔
1602
{
1603
  return model::materials.size();
54✔
1604
}
1605

1606
} // 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

© 2026 Coveralls, Inc