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

openmc-dev / openmc / 18299973882

07 Oct 2025 02:14AM UTC coverage: 81.92% (-3.3%) from 85.194%
18299973882

push

github

web-flow
Switch to using coveralls github action for reporting (#3594)

16586 of 23090 branches covered (71.83%)

Branch coverage included in aggregate %.

53703 of 62712 relevant lines covered (85.63%)

43428488.21 hits per line

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

74.84
/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)
15,881✔
51
{
52
  index_ = model::materials.size(); // Avoids warning about narrowing
15,881✔
53

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

60
  if (check_for_node(node, "name")) {
15,881✔
61
    name_ = get_node_value(node, "name");
7,577✔
62
  }
63

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

71
  if (check_for_node(node, "depletable")) {
15,881✔
72
    depletable_ = get_node_value_bool(node, "depletable");
6,058✔
73
  }
74

75
  bool sum_density {false};
15,881✔
76
  pugi::xml_node density_node = node.child("density");
15,881✔
77
  std::string units;
15,881✔
78
  if (density_node) {
15,881!
79
    units = get_node_value(density_node, "units");
15,881✔
80
    if (units == "sum") {
15,881✔
81
      sum_density = true;
2,758✔
82
    } else if (units == "macro") {
13,123✔
83
      if (check_for_node(density_node, "value")) {
2,195!
84
        density_ = std::stod(get_node_value(density_node, "value"));
2,195✔
85
      } else {
86
        density_ = 1.0;
×
87
      }
88
    } else {
89
      double val = std::stod(get_node_value(density_node, "value"));
10,928✔
90
      if (val <= 0.0) {
10,928!
91
        fatal_error("Need to specify a positive density on material " +
×
92
                    std::to_string(id_) + ".");
×
93
      }
94

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

113
  if (node.child("element")) {
15,881!
114
    fatal_error(
×
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") &&
18,076!
126
      !check_for_node(node, "macroscopic")) {
2,195!
127
    fatal_error("No macroscopic data or nuclides specified on material " +
×
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");
15,881✔
137
  int num_macros = std::distance(node_macros.begin(), node_macros.end());
15,881✔
138

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

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

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

159
    // Set density for macroscopic data
160
    if (units == "macro") {
2,195!
161
      densities.push_back(density_);
2,195✔
162
    } else {
163
      fatal_error("Units can only be macro for macroscopic data " + name);
×
164
    }
165
  } else {
2,195✔
166
    // Create list of nuclides based on those specified
167
    for (auto node_nuc : node.children("nuclide")) {
66,670✔
168
      // Check for empty name on nuclide
169
      if (!check_for_node(node_nuc, "name")) {
52,984!
170
        fatal_error(
×
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,984✔
176
      names.push_back(name);
52,984✔
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,984!
181
        densities.push_back(density_);
×
182
      } else {
183
        bool has_ao = check_for_node(node_nuc, "ao");
52,984✔
184
        bool has_wo = check_for_node(node_nuc, "wo");
52,984✔
185

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

195
        // Copy atom/weight percents
196
        if (has_ao) {
52,984✔
197
          densities.push_back(std::stod(get_node_value(node_nuc, "ao")));
44,335✔
198
        } else {
199
          densities.push_back(-std::stod(get_node_value(node_nuc, "wo")));
8,649✔
200
        }
201
      }
202
    }
52,984✔
203
  }
204

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

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

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

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

223
  for (int i = 0; i < n; ++i) {
71,060✔
224
    const auto& name {names[i]};
55,179✔
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) {
55,179✔
229
      LibraryKey key {Library::Type::neutron, name};
53,832✔
230
      if (data::library_map.find(key) == data::library_map.end()) {
53,832!
231
        fatal_error("Could not find nuclide " + name +
×
232
                    " in the "
233
                    "nuclear data library.");
234
      }
235
    }
53,832✔
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()) {
55,179✔
240
      int index = data::nuclide_map.size();
30,739✔
241
      data::nuclide_map[name] = index;
30,739✔
242
      nuclide_.push_back(index);
30,739✔
243
    } else {
244
      nuclide_.push_back(data::nuclide_map[name]);
24,440✔
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) {
55,179✔
250
      std::string element = to_element(name);
1,369✔
251

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

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

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

274
  if (settings::run_CE) {
15,881✔
275
    // By default, isotropic-in-lab is not used
276
    if (iso_lab.size() > 0) {
13,478✔
277
      p0_.resize(n);
192✔
278

279
      // Apply isotropic-in-lab treatment to specified nuclides
280
      for (int j = 0; j < n; ++j) {
1,808✔
281
        for (const auto& nuc : iso_lab) {
8,400!
282
          if (names[j] == nuc) {
8,400✔
283
            p0_[j] = true;
1,616✔
284
            break;
1,616✔
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))) {
15,881!
294
    fatal_error(
×
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)
15,881✔
300
    density_ = xt::sum(atom_density_)();
2,758✔
301

302
  if (check_for_node(node, "temperature")) {
15,881✔
303
    temperature_ = std::stod(get_node_value(node, "temperature"));
1,929✔
304
  }
305

306
  if (check_for_node(node, "volume")) {
15,881✔
307
    volume_ = std::stod(get_node_value(node, "volume"));
2,619✔
308
  }
309

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

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

324
      // Read the fraction of nuclei affected by this thermal scattering table
325
      double fraction = 1.0;
2,083✔
326
      if (check_for_node(node_sab, "fraction")) {
2,083✔
327
        fraction = std::stod(get_node_value(node_sab, "fraction"));
16✔
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) {
2,083✔
333
        LibraryKey key {Library::Type::thermal, name};
1,997✔
334
        if (data::library_map.find(key) == data::library_map.end()) {
1,997!
335
          fatal_error("Could not find thermal scattering data " + name +
×
336
                      " in cross_sections.xml file.");
337
        }
338
      }
1,997✔
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()) {
2,083✔
344
        index_table = data::thermal_scatt_map.size();
1,303✔
345
        data::thermal_scatt_map[name] = index_table;
1,303✔
346
      } else {
347
        index_table = data::thermal_scatt_map[name];
780✔
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});
2,083✔
354
    }
2,083✔
355
  }
13,478✔
356
}
15,881✔
357

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

363
Material& Material::clone()
×
364
{
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_.clone();
×
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_;
×
381
  mat->temperature_ = temperature_;
×
382

383
  if (ttb_)
×
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));
×
389
  return *model::materials.back();
×
390
}
×
391

392
void Material::finalize()
15,440✔
393
{
394
  // Set fissionable if any nuclide is fissionable
395
  if (settings::run_CE) {
15,440✔
396
    for (const auto& i_nuc : nuclide_) {
45,811✔
397
      if (data::nuclides[i_nuc]->fissionable_) {
38,791✔
398
        fissionable_ = true;
6,017✔
399
        break;
6,017✔
400
      }
401
    }
402

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

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

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

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

422
  for (int i = 0; i < nuclide_.size(); ++i) {
69,275✔
423
    // determine atomic weight ratio
424
    int i_nuc = nuclide_[i];
53,835✔
425
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
56,622✔
426
                                  : data::mg.nuclides_[i_nuc].awr;
2,787✔
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)
53,835✔
432
      atom_density_(i) = -atom_density_(i) / awr;
8,649✔
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_)();
15,440✔
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) {
15,440✔
443
    double sum_percent = 0.0;
10,134✔
444
    for (int i = 0; i < nuclide_.size(); ++i) {
42,877✔
445
      int i_nuc = nuclide_[i];
32,743✔
446
      double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
32,823✔
447
                                    : data::mg.nuclides_[i_nuc].awr;
80✔
448
      sum_percent += atom_density_(i) * awr;
32,743✔
449
    }
450
    sum_percent = 1.0 / sum_percent;
10,134✔
451
    density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent;
10,134✔
452
  }
453

454
  // Calculate nuclide atom densities
455
  atom_density_ *= density_;
15,440✔
456

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

469
void Material::init_thermal()
20,947✔
470
{
471
  vector<ThermalTable> tables;
20,947✔
472

473
  std::unordered_set<int> already_checked;
20,947✔
474
  for (const auto& table : thermal_tables_) {
22,960✔
475
    // Make sure each S(a,b) table only gets checked once
476
    if (already_checked.find(table.index_table) != already_checked.end()) {
2,013!
477
      continue;
×
478
    }
479
    already_checked.insert(table.index_table);
2,013✔
480

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

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

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

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

524
  // Update the list of thermal tables
525
  thermal_tables_ = tables;
20,947✔
526
}
20,947✔
527

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

534
  // Log of the mean excitation energy of the material
535
  double log_I = 0.0;
518✔
536

537
  // Effective number of conduction electrons in the material
538
  double n_conduction = 0.0;
518✔
539

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

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

549
    // Get atomic density of nuclide given atom/weight percent
550
    double atom_density =
551
      (atom_density_[0] > 0.0) ? atom_density_[i] : -atom_density_[i] / awr;
2,200!
552

553
    electron_density += atom_density * elm.Z_;
2,200✔
554
    mass_density += atom_density * awr * MASS_NEUTRON;
2,200✔
555
    log_I += atom_density * elm.Z_ * std::log(elm.I_);
2,200✔
556

557
    for (int j = 0; j < elm.n_electrons_.size(); ++j) {
17,778✔
558
      if (elm.n_electrons_[j] < 0) {
15,578✔
559
        n_conduction -= elm.n_electrons_[j] * atom_density;
1,616✔
560
        continue;
1,616✔
561
      }
562
      e_b_sq.push_back(elm.ionization_energy_[j] * elm.ionization_energy_[j]);
13,962✔
563
      f.push_back(elm.n_electrons_[j] * atom_density);
13,962✔
564
    }
565
  }
566
  log_I /= electron_density;
518✔
567
  n_conduction /= electron_density;
518✔
568
  for (auto& f_i : f)
14,480✔
569
    f_i /= electron_density;
13,962✔
570

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

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

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

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

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

593
  // Loop over incident charged particle energies
594
  for (int i = 0; i < data::ttb_e_grid.size(); ++i) {
103,796✔
595
    double E = data::ttb_e_grid(i);
103,278✔
596

597
    // Get the density effect correction
598
    double delta =
599
      density_effect(f, e_b_sq, e_p_sq, n_conduction, rho, E, 1.0e-6, 100);
103,278✔
600

601
    // Square of the ratio of the speed of light to the velocity of the charged
602
    // particle
603
    double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) /
103,278✔
604
                     ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV));
103,278✔
605

606
    double tau = E / MASS_ELECTRON_EV;
103,278✔
607

608
    double F;
609
    if (positron) {
103,278✔
610
      double t = tau + 2.0;
51,639✔
611
      F = std::log(4.0) - (beta_sq / 12.0) * (23.0 + 14.0 / t + 10.0 / (t * t) +
51,639✔
612
                                               4.0 / (t * t * t));
51,639✔
613
    } else {
614
      F = (1.0 - beta_sq) *
51,639✔
615
          (1.0 + tau * tau / 8.0 - (2.0 * tau + 1.0) * std::log(2.0));
51,639✔
616
    }
617

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

625
void Material::init_bremsstrahlung()
259✔
626
{
627
  // Create new object
628
  ttb_ = make_unique<Bremsstrahlung>();
259✔
629

630
  // Get the size of the energy grids
631
  auto n_k = data::ttb_k_grid.size();
259✔
632
  auto n_e = data::ttb_e_grid.size();
259✔
633

634
  // Determine number of elements
635
  int n = element_.size();
259✔
636

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

643
    // Allocate arrays for TTB data
644
    ttb->pdf = xt::zeros<double>({n_e, n_e});
518✔
645
    ttb->cdf = xt::zeros<double>({n_e, n_e});
518✔
646
    ttb->yield = xt::zeros<double>({n_e});
518✔
647

648
    // Allocate temporary arrays
649
    xt::xtensor<double, 1> stopping_power_collision({n_e}, 0.0);
518✔
650
    xt::xtensor<double, 1> stopping_power_radiative({n_e}, 0.0);
518✔
651
    xt::xtensor<double, 2> dcs({n_e, n_k}, 0.0);
518✔
652

653
    double Z_eq_sq = 0.0;
518✔
654
    double sum_density = 0.0;
518✔
655

656
    // Get the collision stopping power of the material
657
    this->collision_stopping_power(stopping_power_collision.data(), positron);
518✔
658

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

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

671
      // Calculate the "equivalent" atomic number Zeq of the material
672
      Z_eq_sq += atom_density * elm.Z_ * elm.Z_;
2,200✔
673
      sum_density += atom_density;
2,200✔
674

675
      // Accumulate material DCS
676
      dcs += (atom_density * elm.Z_ * elm.Z_) * elm.dcs_;
2,200✔
677

678
      // Accumulate material radiative stopping power
679
      stopping_power_radiative += atom_density * elm.stopping_power_radiative_;
2,200✔
680
    }
681
    Z_eq_sq /= sum_density;
518✔
682

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

706
    // Total material stopping power
707
    xt::xtensor<double, 1> stopping_power =
708
      stopping_power_collision + stopping_power_radiative;
518✔
709

710
    // Loop over photon energies
711
    xt::xtensor<double, 1> f({n_e}, 0.0);
518✔
712
    xt::xtensor<double, 1> z({n_e}, 0.0);
518✔
713
    for (int i = 0; i < n_e - 1; ++i) {
103,278✔
714
      double w = data::ttb_e_grid(i);
102,760✔
715

716
      // Loop over incident particle energies
717
      for (int j = i; j < n_e; ++j) {
10,452,144✔
718
        double e = data::ttb_e_grid(j);
10,349,384✔
719

720
        // Reduced photon energy
721
        double k = w / e;
10,349,384✔
722

723
        // Find the lower bounding index of the reduced photon energy
724
        int i_k = lower_bound_index(
10,349,384✔
725
          data::ttb_k_grid.cbegin(), data::ttb_k_grid.cend(), k);
10,349,384✔
726

727
        // Get the interpolation bounds
728
        double k_l = data::ttb_k_grid(i_k);
10,349,384✔
729
        double k_r = data::ttb_k_grid(i_k + 1);
10,349,384✔
730
        double x_l = dcs(j, i_k);
10,349,384✔
731
        double x_r = dcs(j, i_k + 1);
10,349,384✔
732

733
        // Find the value of the DCS using linear interpolation in reduced
734
        // photon energy k
735
        double x = x_l + (k - k_l) * (x_r - x_l) / (k_r - k_l);
10,349,384✔
736

737
        // Square of the ratio of the speed of light to the velocity of the
738
        // charged particle
739
        double beta_sq = e * (e + 2.0 * MASS_ELECTRON_EV) /
10,349,384✔
740
                         ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV));
10,349,384✔
741

742
        // Compute the integrand of the PDF
743
        f(j) = x / (beta_sq * stopping_power(j) * w);
10,349,384✔
744
      }
745

746
      // Number of points to integrate
747
      int n = n_e - i;
102,760✔
748

749
      // Integrate the PDF using cubic spline integration over the incident
750
      // particle energy
751
      if (n > 2) {
102,760✔
752
        spline(n, &data::ttb_e_grid(i), &f(i), &z(i));
102,242✔
753

754
        double c = 0.0;
102,242✔
755
        for (int j = i; j < n_e - 1; ++j) {
10,348,348✔
756
          c += spline_integrate(n, &data::ttb_e_grid(i), &f(i), &z(i),
10,246,106✔
757
            data::ttb_e_grid(j), data::ttb_e_grid(j + 1));
10,246,106✔
758

759
          ttb->pdf(j + 1, i) = c;
10,246,106✔
760
        }
761

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

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

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

780
      // Loop over photon energies
781
      double c = 0.0;
102,760✔
782
      for (int i = 0; i < j; ++i) {
10,349,384✔
783
        // Integrate the CDF from the PDF using the fact that the PDF is linear
784
        // in log-log space
785
        double w_l = std::log(data::ttb_e_grid(i));
10,246,624✔
786
        double w_r = std::log(data::ttb_e_grid(i + 1));
10,246,624✔
787
        double x_l = std::log(ttb->pdf(j, i));
10,246,624✔
788
        double x_r = std::log(ttb->pdf(j, i + 1));
10,246,624✔
789
        double beta = (x_r - x_l) / (w_r - w_l);
10,246,624✔
790
        double a = beta + 1.0;
10,246,624✔
791
        c += std::exp(w_l + x_l) / a * std::expm1(a * (w_r - w_l));
10,246,624✔
792
        ttb->cdf(j, i + 1) = c;
10,246,624✔
793
      }
794

795
      // Set photon number yield
796
      ttb->yield(j) = c;
102,760✔
797
    }
798

799
    // Use logarithm of number yield since it is log-log interpolated
800
    ttb->yield = xt::where(ttb->yield > 0.0, xt::log(ttb->yield), -500.0);
518✔
801
  }
518✔
802
}
259✔
803

804
void Material::init_nuclide_index()
19,352✔
805
{
806
  int n = settings::run_CE ? data::nuclides.size() : data::mg.nuclides_.size();
19,352✔
807
  mat_nuclide_index_.resize(n);
19,352✔
808
  std::fill(mat_nuclide_index_.begin(), mat_nuclide_index_.end(), C_NONE);
19,352✔
809
  for (int i = 0; i < nuclide_.size(); ++i) {
125,533✔
810
    mat_nuclide_index_[nuclide_[i]] = i;
106,181✔
811
  }
812
}
19,352✔
813

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

822
  if (p.type() == ParticleType::neutron) {
1,435,586,508✔
823
    this->calculate_neutron_xs(p);
1,366,968,854✔
824
  } else if (p.type() == ParticleType::photon) {
68,617,654✔
825
    this->calculate_photon_xs(p);
16,685,974✔
826
  }
827
}
1,435,586,508✔
828

829
void Material::calculate_neutron_xs(Particle& p) const
1,366,968,854✔
830
{
831
  // Find energy index on energy grid
832
  int neutron = static_cast<int>(ParticleType::neutron);
1,366,968,854✔
833
  int i_grid =
834
    std::log(p.E() / data::energy_min[neutron]) / simulation::log_spacing;
1,366,968,854✔
835

836
  // Determine if this material has S(a,b) tables
837
  bool check_sab = (thermal_tables_.size() > 0);
1,366,968,854✔
838

839
  // Initialize position in i_sab_nuclides
840
  int j = 0;
1,366,968,854✔
841

842
  // Calculate NCrystal cross section
843
  double ncrystal_xs = -1.0;
1,366,968,854✔
844
  if (ncrystal_mat_ && p.E() < NCRYSTAL_MAX_ENERGY) {
1,366,968,854!
845
    ncrystal_xs = ncrystal_mat_.xs(p);
11,158,829✔
846
  }
847

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

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

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

865
        // If particle energy is greater than the highest energy for the
866
        // S(a,b) table, then don't use the S(a,b) table
867
        if (p.E() > data::thermal_scatt[i_sab]->energy_max_)
330,332,048✔
868
          i_sab = C_NONE;
219,346,797✔
869

870
        // Increment position in thermal_tables_
871
        ++j;
330,332,048✔
872

873
        // Don't check for S(a,b) tables if there are no more left
874
        if (j == thermal_tables_.size())
330,332,048✔
875
          check_sab = false;
330,098,507✔
876
      }
877
    }
878

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

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

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

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

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

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

903
void Material::calculate_photon_xs(Particle& p) const
16,685,974✔
904
{
905
  p.macro_xs().coherent = 0.0;
16,685,974✔
906
  p.macro_xs().incoherent = 0.0;
16,685,974✔
907
  p.macro_xs().photoelectric = 0.0;
16,685,974✔
908
  p.macro_xs().pair_production = 0.0;
16,685,974✔
909

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

915
    // Determine microscopic cross sections for this nuclide
916
    int i_element = element_[i];
79,879,062✔
917

918
    // Calculate microscopic cross section for this nuclide
919
    const auto& micro {p.photon_xs(i_element)};
79,879,062✔
920
    if (p.E() != micro.last_E) {
79,879,062✔
921
      data::elements[i_element]->calculate_xs(p);
39,269,956✔
922
    }
923

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

927
    // Copy atom density of nuclide in material
928
    double atom_density = this->atom_density(i, p.density_mult());
79,879,062✔
929

930
    // Add contributions to material macroscopic cross sections
931
    p.macro_xs().total += atom_density * micro.total;
79,879,062✔
932
    p.macro_xs().coherent += atom_density * micro.coherent;
79,879,062✔
933
    p.macro_xs().incoherent += atom_density * micro.incoherent;
79,879,062✔
934
    p.macro_xs().photoelectric += atom_density * micro.photoelectric;
79,879,062✔
935
    p.macro_xs().pair_production += atom_density * micro.pair_production;
79,879,062✔
936
  }
937
}
16,685,974✔
938

939
void Material::set_id(int32_t id)
15,987✔
940
{
941
  assert(id >= 0 || id == C_NONE);
13,201!
942

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

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

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

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

969
void Material::set_density(double density, const std::string& units)
8,170✔
970
{
971
  assert(density >= 0.0);
6,770!
972

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

977
  if (units == "atom/b-cm") {
8,170✔
978
    // Set total density based on value provided
979
    density_ = density;
8,112✔
980

981
    // Determine normalized atom percents
982
    double sum_percent = xt::sum(atom_density_)();
8,112✔
983
    atom_density_ /= sum_percent;
8,112✔
984

985
    // Recalculate nuclide atom densities based on given density
986
    atom_density_ *= density;
8,112✔
987

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

1003
    // Update densities
1004
    density_gpcc_ = density;
43✔
1005
    density_ *= f;
43✔
1006
    atom_density_ *= f;
43✔
1007
    charge_density_ *= f;
43✔
1008
  } else {
1009
    throw std::invalid_argument {
15✔
1010
      "Invalid units '" + std::string(units.data()) + "' specified."};
30✔
1011
  }
1012
}
8,155✔
1013

1014
void Material::set_densities(
7,910✔
1015
  const vector<std::string>& name, const vector<double>& density)
1016
{
1017
  auto n = name.size();
7,910✔
1018
  assert(n > 0);
6,546!
1019
  assert(n == density.size());
6,546!
1020

1021
  if (n != nuclide_.size()) {
7,910✔
1022
    nuclide_.resize(n);
1,754✔
1023
    atom_density_ = xt::zeros<double>({n});
1,754✔
1024
    if (settings::photon_transport)
1,754!
1025
      element_.resize(n);
×
1026
  }
1027

1028
  double sum_density = 0.0;
7,910✔
1029
  for (int64_t i = 0; i < n; ++i) {
79,945✔
1030
    const auto& nuc {name[i]};
72,035✔
1031
    if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) {
72,035!
1032
      int err = openmc_load_nuclide(nuc.c_str(), nullptr, 0);
×
1033
      if (err < 0)
×
1034
        throw std::runtime_error {openmc_err_msg};
×
1035
    }
1036

1037
    nuclide_[i] = data::nuclide_map.at(nuc);
72,035✔
1038
    assert(density[i] > 0.0);
59,451!
1039
    atom_density_(i) = density[i];
72,035✔
1040
    sum_density += density[i];
72,035✔
1041

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

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

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

1057
  // Assign S(a,b) tables
1058
  this->init_thermal();
7,910✔
1059
}
7,910✔
1060

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

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

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

1080
  write_attribute(material_group, "depletable", static_cast<int>(depletable()));
12,881✔
1081
  if (volume_ > 0.0) {
12,881✔
1082
    write_attribute(material_group, "volume", volume_);
2,608✔
1083
  }
1084
  if (temperature_ > 0.0) {
12,881✔
1085
    write_attribute(material_group, "temperature", temperature_);
1,914✔
1086
  }
1087
  write_dataset(material_group, "name", name_);
12,881✔
1088
  write_dataset(material_group, "atom_density", density_);
12,881✔
1089

1090
  // Copy nuclide/macro name for each nuclide to vector
1091
  vector<std::string> nuc_names;
12,881✔
1092
  vector<std::string> macro_names;
12,881✔
1093
  vector<double> nuc_densities;
12,881✔
1094
  if (settings::run_CE) {
12,881✔
1095
    for (int i = 0; i < nuclide_.size(); ++i) {
56,728✔
1096
      int i_nuc = nuclide_[i];
45,233✔
1097
      nuc_names.push_back(data::nuclides[i_nuc]->name_);
45,233✔
1098
      nuc_densities.push_back(atom_density_(i));
45,233✔
1099
    }
1100
  } else {
1101
    for (int i = 0; i < nuclide_.size(); ++i) {
2,805✔
1102
      int i_nuc = nuclide_[i];
1,419✔
1103
      if (data::mg.nuclides_[i_nuc].awr != MACROSCOPIC_AWR) {
1,419✔
1104
        nuc_names.push_back(data::mg.nuclides_[i_nuc].name);
88✔
1105
        nuc_densities.push_back(atom_density_(i));
88✔
1106
      } else {
1107
        macro_names.push_back(data::mg.nuclides_[i_nuc].name);
1,331✔
1108
      }
1109
    }
1110
  }
1111

1112
  // Write vector to 'nuclides'
1113
  if (!nuc_names.empty()) {
12,881✔
1114
    write_dataset(material_group, "nuclides", nuc_names);
11,550✔
1115
    write_dataset(material_group, "nuclide_densities", nuc_densities);
11,550✔
1116
  }
1117

1118
  // Write vector to 'macroscopics'
1119
  if (!macro_names.empty()) {
12,881✔
1120
    write_dataset(material_group, "macroscopics", macro_names);
1,331✔
1121
  }
1122

1123
  if (!thermal_tables_.empty()) {
12,881✔
1124
    vector<std::string> sab_names;
1,536✔
1125
    for (const auto& table : thermal_tables_) {
3,138✔
1126
      sab_names.push_back(data::thermal_scatt[table.index_table]->name_);
1,602✔
1127
    }
1128
    write_dataset(material_group, "sab_names", sab_names);
1,536✔
1129
  }
1,536✔
1130

1131
  close_group(material_group);
12,881✔
1132
}
12,881✔
1133

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

1142
void Material::import_properties_hdf5(hid_t group)
135✔
1143
{
1144
  hid_t material_group = open_group(group, "material " + std::to_string(id_));
135✔
1145
  double density;
1146
  read_attribute(material_group, "atom_density", density);
135✔
1147
  this->set_density(density, "atom/b-cm");
135✔
1148
  close_group(material_group);
135✔
1149
}
135✔
1150

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

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

1171
  // Append new nuclide/density
1172
  int i_nuc = data::nuclide_map[name];
15✔
1173
  nuclide_.push_back(i_nuc);
15✔
1174

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

1181
  auto n = nuclide_.size();
15✔
1182

1183
  // Create copy of atom_density_ array with one extra entry
1184
  xt::xtensor<double, 1> atom_density = xt::zeros<double>({n});
15✔
1185
  xt::view(atom_density, xt::range(0, n - 1)) = atom_density_;
15✔
1186
  atom_density(n - 1) = density;
15✔
1187
  atom_density_ = atom_density;
15✔
1188

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

1194
//==============================================================================
1195
// Non-method functions
1196
//==============================================================================
1197

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

1205
  // Calculate the Sternheimer adjustment factor using Newton's method
1206
  double rho = 2.0;
518✔
1207
  int iter;
1208
  for (iter = 0; iter < max_iter; ++iter) {
2,104!
1209
    double rho_0 = rho;
2,104✔
1210

1211
    // Function to find the root of and its derivative
1212
    double g = 0.0;
2,104✔
1213
    double gp = 0.0;
2,104✔
1214

1215
    for (int i = 0; i < n; ++i) {
58,664✔
1216
      // Square of resonance energy of a bound-shell oscillator
1217
      double e_r_sq = e_b_sq[i] * rho * rho + 2.0 / 3.0 * f[i] * e_p_sq;
56,560✔
1218
      g += f[i] * std::log(e_r_sq);
56,560✔
1219
      gp += e_b_sq[i] * f[i] * rho / e_r_sq;
56,560✔
1220
    }
1221
    // Include conduction electrons
1222
    if (n_conduction > 0.0) {
2,104✔
1223
      g += n_conduction * std::log(n_conduction * e_p_sq);
1,822✔
1224
    }
1225

1226
    // Set the next guess: rho_n+1 = rho_n - g(rho_n)/g'(rho_n)
1227
    rho -= (g - 2.0 * log_I) / (2.0 * gp);
2,104✔
1228

1229
    // If the initial guess is too large, rho can be negative
1230
    if (rho < 0.0)
2,104!
1231
      rho = rho_0 / 2.0;
×
1232

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

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

1252
  // Square of the ratio of the speed of light to the velocity of the charged
1253
  // particle
1254
  double beta_sq = E * (E + 2.0 * MASS_ELECTRON_EV) /
103,278✔
1255
                   ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV));
103,278✔
1256

1257
  // For nonmetals, delta = 0 for beta < beta_0, where beta_0 is obtained by
1258
  // setting the frequency w = 0.
1259
  double beta_0_sq = 0.0;
103,278✔
1260
  if (n_conduction == 0.0) {
103,278✔
1261
    for (int i = 0; i < n; ++i) {
110,400✔
1262
      beta_0_sq += f[i] * e_p_sq / (e_b_sq[i] * rho * rho);
95,200✔
1263
    }
1264
    beta_0_sq = 1.0 / (1.0 + beta_0_sq);
15,200✔
1265
  }
1266
  double delta = 0.0;
103,278✔
1267
  if (beta_sq < beta_0_sq)
103,278✔
1268
    return delta;
8,278✔
1269

1270
  // Compute the square of the frequency w^2 using Newton's method, with the
1271
  // initial guess of w^2 equal to beta^2 * gamma^2
1272
  double w_sq = E / MASS_ELECTRON_EV * (E / MASS_ELECTRON_EV + 2);
95,000✔
1273
  int iter;
1274
  for (iter = 0; iter < max_iter; ++iter) {
646,462!
1275
    double w_sq_0 = w_sq;
646,462✔
1276

1277
    // Function to find the root of and its derivative
1278
    double g = 0.0;
646,462✔
1279
    double gp = 0.0;
646,462✔
1280

1281
    for (int i = 0; i < n; ++i) {
20,851,774✔
1282
      double c = e_b_sq[i] * rho * rho / e_p_sq + w_sq;
20,205,312✔
1283
      g += f[i] / c;
20,205,312✔
1284
      gp -= f[i] / (c * c);
20,205,312✔
1285
    }
1286
    // Include conduction electrons
1287
    g += n_conduction / w_sq;
646,462✔
1288
    gp -= n_conduction / (w_sq * w_sq);
646,462✔
1289

1290
    // Set the next guess: w_n+1 = w_n - g(w_n)/g'(w_n)
1291
    w_sq -= (g + 1.0 - 1.0 / beta_sq) / gp;
646,462✔
1292

1293
    // If the initial guess is too large, w can be negative
1294
    if (w_sq < 0.0)
646,462✔
1295
      w_sq = w_sq_0 / 2.0;
141,166✔
1296

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

1308
  // Solve for the density effect correction
1309
  for (int i = 0; i < n; ++i) {
2,831,964✔
1310
    double l_sq = e_b_sq[i] * rho * rho / e_p_sq + 2.0 / 3.0 * f[i];
2,736,964✔
1311
    delta += f[i] * std::log((l_sq + w_sq) / l_sq);
2,736,964✔
1312
  }
1313
  // Include conduction electrons
1314
  if (n_conduction > 0.0) {
95,000✔
1315
    delta += n_conduction * std::log((n_conduction + w_sq) / n_conduction);
88,078✔
1316
  }
1317

1318
  return delta - w_sq * (1.0 - beta_sq);
95,000✔
1319
}
1320

1321
void read_materials_xml()
1,786✔
1322
{
1323
  write_message("Reading materials XML file...", 5);
1,786✔
1324

1325
  pugi::xml_document doc;
1,786✔
1326

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

1333
  // Parse materials.xml file and get root element
1334
  doc.load_file(filename.c_str());
1,786✔
1335

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

1339
  read_materials_xml(root);
1,786✔
1340
}
1,786✔
1341

1342
void read_materials_xml(pugi::xml_node root)
7,748✔
1343
{
1344
  for (pugi::xml_node material_node : root.children("material")) {
23,621✔
1345
    model::materials.push_back(make_unique<Material>(material_node));
15,873✔
1346
  }
1347
  model::materials.shrink_to_fit();
7,748✔
1348
}
7,748✔
1349

1350
void free_memory_material()
8,084✔
1351
{
1352
  model::materials.clear();
8,084✔
1353
  model::material_map.clear();
8,084✔
1354
}
8,084✔
1355

1356
//==============================================================================
1357
// C API
1358
//==============================================================================
1359

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

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

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

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

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

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

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

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

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

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

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

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

1528
  *name = model::materials[index]->name().data();
43✔
1529

1530
  return 0;
43✔
1531
}
1532

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

1540
  model::materials[index]->set_name(name);
15✔
1541

1542
  return 0;
15✔
1543
}
1544

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

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

1569
  *depletable = model::materials[index]->depletable();
30✔
1570

1571
  return 0;
30✔
1572
}
1573

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

1581
  model::materials[index]->depletable() = depletable;
15✔
1582

1583
  return 0;
15✔
1584
}
1585

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

1599
extern "C" size_t n_materials()
136✔
1600
{
1601
  return model::materials.size();
136✔
1602
}
1603

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