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

openmc-dev / openmc / 15371300071

01 Jun 2025 05:04AM UTC coverage: 85.143% (+0.3%) from 84.827%
15371300071

Pull #3176

github

web-flow
Merge 4f739184a into cb95c784b
Pull Request #3176: MeshFilter rotation - solution to issue #3166

86 of 99 new or added lines in 4 files covered. (86.87%)

3707 existing lines in 117 files now uncovered.

52212 of 61323 relevant lines covered (85.14%)

42831974.38 hits per line

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

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

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

60
  if (check_for_node(node, "name")) {
18,936✔
61
    name_ = get_node_value(node, "name");
8,939✔
62
  }
63

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

71
  if (check_for_node(node, "depletable")) {
18,936✔
72
    depletable_ = get_node_value_bool(node, "depletable");
7,050✔
73
  }
74

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

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

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

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

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

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

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

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

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

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

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

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

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

195
        // Copy atom/weight percents
196
        if (has_ao) {
68,200✔
197
          densities.push_back(std::stod(get_node_value(node_nuc, "ao")));
56,389✔
198
        } else {
199
          densities.push_back(-std::stod(get_node_value(node_nuc, "wo")));
11,811✔
200
        }
201
      }
202
    }
68,200✔
203
  }
204

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

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

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

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

223
  for (int i = 0; i < n; ++i) {
90,086✔
224
    const auto& name {names[i]};
71,150✔
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) {
71,150✔
229
      LibraryKey key {Library::Type::neutron, name};
69,313✔
230
      if (data::library_map.find(key) == data::library_map.end()) {
69,313✔
UNCOV
231
        fatal_error("Could not find nuclide " + name +
×
232
                    " in the "
233
                    "nuclear data library.");
234
      }
235
    }
69,313✔
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()) {
71,150✔
240
      int index = data::nuclide_map.size();
38,514✔
241
      data::nuclide_map[name] = index;
38,514✔
242
      nuclide_.push_back(index);
38,514✔
243
    } else {
244
      nuclide_.push_back(data::nuclide_map[name]);
32,636✔
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) {
71,150✔
250
      std::string element = to_element(name);
1,761✔
251

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

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

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

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

279
      // Apply isotropic-in-lab treatment to specified nuclides
280
      for (int j = 0; j < n; ++j) {
2,486✔
281
        for (const auto& nuc : iso_lab) {
11,550✔
282
          if (names[j] == nuc) {
11,550✔
283
            p0_[j] = true;
2,222✔
284
            break;
2,222✔
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))) {
18,936✔
294
    fatal_error(
×
UNCOV
295
      "Cannot mix atom and weight percents in material " + std::to_string(id_));
×
296
  }
297

298
  // Determine density if it is a sum value
299
  if (sum_density)
18,936✔
300
    density_ = xt::sum(atom_density_)();
3,433✔
301

302
  if (check_for_node(node, "temperature")) {
18,936✔
303
    temperature_ = std::stod(get_node_value(node, "temperature"));
2,665✔
304
  }
305

306
  if (check_for_node(node, "volume")) {
18,936✔
307
    volume_ = std::stod(get_node_value(node, "volume"));
3,179✔
308
  }
309

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

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

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

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

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

367
  // set all other parameters to whatever the calling Material has
368
  mat->name_ = name_;
×
369
  mat->nuclide_ = nuclide_;
×
370
  mat->element_ = element_;
×
371
  mat->ncrystal_mat_ = ncrystal_mat_.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_;
×
UNCOV
381
  mat->temperature_ = temperature_;
×
382

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

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

392
void Material::finalize()
18,341✔
393
{
394
  // Set fissionable if any nuclide is fissionable
395
  if (settings::run_CE) {
18,341✔
396
    for (const auto& i_nuc : nuclide_) {
57,355✔
397
      if (data::nuclides[i_nuc]->fissionable_) {
49,542✔
398
        fissionable_ = true;
7,292✔
399
        break;
7,292✔
400
      }
401
    }
402

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

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

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

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

422
  for (int i = 0; i < nuclide_.size(); ++i) {
87,657✔
423
    // determine atomic weight ratio
424
    int i_nuc = nuclide_[i];
69,316✔
425
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
73,080✔
426
                                  : data::mg.nuclides_[i_nuc].awr;
3,764✔
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)
69,316✔
432
      atom_density_(i) = -atom_density_(i) / awr;
11,811✔
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_)();
18,341✔
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) {
18,341✔
443
    double sum_percent = 0.0;
11,393✔
444
    for (int i = 0; i < nuclide_.size(); ++i) {
51,365✔
445
      int i_nuc = nuclide_[i];
39,972✔
446
      double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
40,082✔
447
                                    : data::mg.nuclides_[i_nuc].awr;
110✔
448
      sum_percent += atom_density_(i) * awr;
39,972✔
449
    }
450
    sum_percent = 1.0 / sum_percent;
11,393✔
451
    density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent;
11,393✔
452
  }
453

454
  // Calculate nuclide atom densities
455
  atom_density_ *= density_;
18,341✔
456

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

554
    for (int j = 0; j < elm.n_electrons_.size(); ++j) {
24,166✔
555
      if (elm.n_electrons_[j] < 0) {
21,214✔
556
        n_conduction -= elm.n_electrons_[j] * atom_density;
2,152✔
557
        continue;
2,152✔
558
      }
559
      e_b_sq.push_back(elm.ionization_energy_[j] * elm.ionization_energy_[j]);
19,062✔
560
      f.push_back(elm.n_electrons_[j] * atom_density);
19,062✔
561
    }
562
  }
563
  log_I /= electron_density;
680✔
564
  n_conduction /= electron_density;
680✔
565
  for (auto& f_i : f)
19,742✔
566
    f_i /= electron_density;
19,062✔
567

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

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

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

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

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

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

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

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

603
    double tau = E / MASS_ELECTRON_EV;
135,610✔
604

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

707
    // Loop over photon energies
708
    xt::xtensor<double, 1> f({n_e}, 0.0);
680✔
709
    xt::xtensor<double, 1> z({n_e}, 0.0);
680✔
710
    for (int i = 0; i < n_e - 1; ++i) {
135,610✔
711
      double w = data::ttb_e_grid(i);
134,930✔
712

713
      // Loop over incident particle energies
714
      for (int j = i; j < n_e; ++j) {
13,726,590✔
715
        double e = data::ttb_e_grid(j);
13,591,660✔
716

717
        // Reduced photon energy
718
        double k = w / e;
13,591,660✔
719

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

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

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

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

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

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

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

751
        double c = 0.0;
134,250✔
752
        for (int j = i; j < n_e - 1; ++j) {
13,590,300✔
753
          c += spline_integrate(n, &data::ttb_e_grid(i), &f(i), &z(i),
13,456,050✔
754
            data::ttb_e_grid(j), data::ttb_e_grid(j + 1));
13,456,050✔
755

756
          ttb->pdf(j + 1, i) = c;
13,456,050✔
757
        }
758

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

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

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

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

792
      // Set photon number yield
793
      ttb->yield(j) = c;
134,930✔
794
    }
795

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

801
void Material::init_nuclide_index()
24,903✔
802
{
803
  int n = settings::run_CE ? data::nuclides.size() : data::mg.nuclides_.size();
24,903✔
804
  mat_nuclide_index_.resize(n);
24,903✔
805
  std::fill(mat_nuclide_index_.begin(), mat_nuclide_index_.end(), C_NONE);
24,903✔
806
  for (int i = 0; i < nuclide_.size(); ++i) {
167,166✔
807
    mat_nuclide_index_[nuclide_[i]] = i;
142,263✔
808
  }
809
}
24,903✔
810

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

819
  if (p.type() == ParticleType::neutron) {
1,775,026,157✔
820
    this->calculate_neutron_xs(p);
1,690,818,261✔
821
  } else if (p.type() == ParticleType::photon) {
84,207,896✔
822
    this->calculate_photon_xs(p);
18,689,756✔
823
  }
824
}
1,775,026,157✔
825

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

833
  // Determine if this material has S(a,b) tables
834
  bool check_sab = (thermal_tables_.size() > 0);
1,690,818,261✔
835

836
  // Initialize position in i_sab_nuclides
837
  int j = 0;
1,690,818,261✔
838

839
  // Calculate NCrystal cross section
840
  double ncrystal_xs = -1.0;
1,690,818,261✔
841
  if (ncrystal_mat_ && p.E() < NCRYSTAL_MAX_ENERGY) {
1,690,818,261✔
842
    ncrystal_xs = ncrystal_mat_.xs(p);
15,216,585✔
843
  }
844

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

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

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

862
        // If particle energy is greater than the highest energy for the
863
        // S(a,b) table, then don't use the S(a,b) table
864
        if (p.E() > data::thermal_scatt[i_sab]->energy_max_)
407,250,134✔
865
          i_sab = C_NONE;
265,721,491✔
866

867
        // Increment position in thermal_tables_
868
        ++j;
407,250,134✔
869

870
        // Don't check for S(a,b) tables if there are no more left
871
        if (j == thermal_tables_.size())
407,250,134✔
872
          check_sab = false;
406,930,199✔
873
      }
874
    }
875

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

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

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

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

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

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

900
void Material::calculate_photon_xs(Particle& p) const
18,689,756✔
901
{
902
  p.macro_xs().coherent = 0.0;
18,689,756✔
903
  p.macro_xs().incoherent = 0.0;
18,689,756✔
904
  p.macro_xs().photoelectric = 0.0;
18,689,756✔
905
  p.macro_xs().pair_production = 0.0;
18,689,756✔
906

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

912
    // Determine microscopic cross sections for this nuclide
913
    int i_element = element_[i];
101,316,637✔
914

915
    // Calculate microscopic cross section for this nuclide
916
    const auto& micro {p.photon_xs(i_element)};
101,316,637✔
917
    if (p.E() != micro.last_E) {
101,316,637✔
918
      data::elements[i_element]->calculate_xs(p);
46,887,492✔
919
    }
920

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

924
    // Copy atom density of nuclide in material
925
    double atom_density = atom_density_(i);
101,316,637✔
926

927
    // Add contributions to material macroscopic cross sections
928
    p.macro_xs().total += atom_density * micro.total;
101,316,637✔
929
    p.macro_xs().coherent += atom_density * micro.coherent;
101,316,637✔
930
    p.macro_xs().incoherent += atom_density * micro.incoherent;
101,316,637✔
931
    p.macro_xs().photoelectric += atom_density * micro.photoelectric;
101,316,637✔
932
    p.macro_xs().pair_production += atom_density * micro.pair_production;
101,316,637✔
933
  }
934
}
18,689,756✔
935

936
void Material::set_id(int32_t id)
18,996✔
937
{
938
  assert(id >= 0 || id == C_NONE);
16,452✔
939

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

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

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

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

966
void Material::set_density(double density, const std::string& units)
10,243✔
967
{
968
  assert(density >= 0.0);
8,925✔
969

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

974
  if (units == "atom/b-cm") {
10,243✔
975
    // Set total density based on value provided
976
    density_ = density;
10,183✔
977

978
    // Determine normalized atom percents
979
    double sum_percent = xt::sum(atom_density_)();
10,183✔
980
    atom_density_ /= sum_percent;
10,183✔
981

982
    // Recalculate nuclide atom densities based on given density
983
    atom_density_ *= density;
10,183✔
984

985
    // Calculate density in g/cm^3.
986
    density_gpcc_ = 0.0;
10,183✔
987
    for (int i = 0; i < nuclide_.size(); ++i) {
107,210✔
988
      int i_nuc = nuclide_[i];
97,027✔
989
      double awr = data::nuclides[i_nuc]->awr_;
97,027✔
990
      density_gpcc_ += atom_density_(i) * awr * MASS_NEUTRON / N_AVOGADRO;
97,027✔
991
    }
992
  } else if (units == "g/cm3" || units == "g/cc") {
60✔
993
    // Determine factor by which to change densities
994
    double previous_density_gpcc = density_gpcc_;
45✔
995
    double f = density / previous_density_gpcc;
45✔
996

997
    // Update densities
998
    density_gpcc_ = density;
45✔
999
    density_ *= f;
45✔
1000
    atom_density_ *= f;
45✔
1001
  } else {
1002
    throw std::invalid_argument {
15✔
1003
      "Invalid units '" + std::string(units.data()) + "' specified."};
30✔
1004
  }
1005
}
10,228✔
1006

1007
void Material::set_densities(
10,018✔
1008
  const vector<std::string>& name, const vector<double>& density)
1009
{
1010
  auto n = name.size();
10,018✔
1011
  assert(n > 0);
8,730✔
1012
  assert(n == density.size());
8,730✔
1013

1014
  if (n != nuclide_.size()) {
10,018✔
1015
    nuclide_.resize(n);
2,364✔
1016
    atom_density_ = xt::zeros<double>({n});
2,364✔
1017
    if (settings::photon_transport)
2,364✔
UNCOV
1018
      element_.resize(n);
×
1019
  }
1020

1021
  double sum_density = 0.0;
10,018✔
1022
  for (int64_t i = 0; i < n; ++i) {
106,310✔
1023
    const auto& nuc {name[i]};
96,292✔
1024
    if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) {
96,292✔
1025
      int err = openmc_load_nuclide(nuc.c_str(), nullptr, 0);
×
UNCOV
1026
      if (err < 0)
×
UNCOV
1027
        throw std::runtime_error {openmc_err_msg};
×
1028
    }
1029

1030
    nuclide_[i] = data::nuclide_map.at(nuc);
96,292✔
1031
    assert(density[i] > 0.0);
83,880✔
1032
    atom_density_(i) = density[i];
96,292✔
1033
    sum_density += density[i];
96,292✔
1034

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

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

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

1050
  // Assign S(a,b) tables
1051
  this->init_thermal();
10,018✔
1052
}
10,018✔
1053

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

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

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

1073
  write_attribute(material_group, "depletable", static_cast<int>(depletable()));
14,796✔
1074
  if (volume_ > 0.0) {
14,796✔
1075
    write_attribute(material_group, "volume", volume_);
3,164✔
1076
  }
1077
  if (temperature_ > 0.0) {
14,796✔
1078
    write_attribute(material_group, "temperature", temperature_);
2,644✔
1079
  }
1080
  write_dataset(material_group, "name", name_);
14,796✔
1081
  write_dataset(material_group, "atom_density", density_);
14,796✔
1082

1083
  // Copy nuclide/macro name for each nuclide to vector
1084
  vector<std::string> nuc_names;
14,796✔
1085
  vector<std::string> macro_names;
14,796✔
1086
  vector<double> nuc_densities;
14,796✔
1087
  if (settings::run_CE) {
14,796✔
1088
    for (int i = 0; i < nuclide_.size(); ++i) {
69,877✔
1089
      int i_nuc = nuclide_[i];
56,926✔
1090
      nuc_names.push_back(data::nuclides[i_nuc]->name_);
56,926✔
1091
      nuc_densities.push_back(atom_density_(i));
56,926✔
1092
    }
1093
  } else {
1094
    for (int i = 0; i < nuclide_.size(); ++i) {
3,735✔
1095
      int i_nuc = nuclide_[i];
1,890✔
1096
      if (data::mg.nuclides_[i_nuc].awr != MACROSCOPIC_AWR) {
1,890✔
1097
        nuc_names.push_back(data::mg.nuclides_[i_nuc].name);
120✔
1098
        nuc_densities.push_back(atom_density_(i));
120✔
1099
      } else {
1100
        macro_names.push_back(data::mg.nuclides_[i_nuc].name);
1,770✔
1101
      }
1102
    }
1103
  }
1104

1105
  // Write vector to 'nuclides'
1106
  if (!nuc_names.empty()) {
14,796✔
1107
    write_dataset(material_group, "nuclides", nuc_names);
13,026✔
1108
    write_dataset(material_group, "nuclide_densities", nuc_densities);
13,026✔
1109
  }
1110

1111
  // Write vector to 'macroscopics'
1112
  if (!macro_names.empty()) {
14,796✔
1113
    write_dataset(material_group, "macroscopics", macro_names);
1,770✔
1114
  }
1115

1116
  if (!thermal_tables_.empty()) {
14,796✔
1117
    vector<std::string> sab_names;
1,809✔
1118
    for (const auto& table : thermal_tables_) {
3,708✔
1119
      sab_names.push_back(data::thermal_scatt[table.index_table]->name_);
1,899✔
1120
    }
1121
    write_dataset(material_group, "sab_names", sab_names);
1,809✔
1122
  }
1,809✔
1123

1124
  close_group(material_group);
14,796✔
1125
}
14,796✔
1126

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

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

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

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

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

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

1174
  auto n = nuclide_.size();
15✔
1175

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

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

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

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

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

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

1208
    for (int i = 0; i < n; ++i) {
79,902✔
1209
      // Square of resonance energy of a bound-shell oscillator
1210
      double e_r_sq = e_b_sq[i] * rho * rho + 2.0 / 3.0 * f[i] * e_p_sq;
77,168✔
1211
      g += f[i] * std::log(e_r_sq);
77,168✔
1212
      gp += e_b_sq[i] * f[i] * rho / e_r_sq;
77,168✔
1213
    }
1214
    // Include conduction electrons
1215
    if (n_conduction > 0.0) {
2,734✔
1216
      g += n_conduction * std::log(n_conduction * e_p_sq);
2,348✔
1217
    }
1218

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

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

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

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

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

1250
  // For nonmetals, delta = 0 for beta < beta_0, where beta_0 is obtained by
1251
  // setting the frequency w = 0.
1252
  double beta_0_sq = 0.0;
135,610✔
1253
  if (n_conduction == 0.0) {
135,610✔
1254
    for (int i = 0; i < n; ++i) {
151,200✔
1255
      beta_0_sq += f[i] * e_p_sq / (e_b_sq[i] * rho * rho);
130,400✔
1256
    }
1257
    beta_0_sq = 1.0 / (1.0 + beta_0_sq);
20,800✔
1258
  }
1259
  double delta = 0.0;
135,610✔
1260
  if (beta_sq < beta_0_sq)
135,610✔
1261
    return delta;
11,322✔
1262

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

1270
    // Function to find the root of and its derivative
1271
    double g = 0.0;
856,952✔
1272
    double gp = 0.0;
856,952✔
1273

1274
    for (int i = 0; i < n; ++i) {
28,478,808✔
1275
      double c = e_b_sq[i] * rho * rho / e_p_sq + w_sq;
27,621,856✔
1276
      g += f[i] / c;
27,621,856✔
1277
      gp -= f[i] / (c * c);
27,621,856✔
1278
    }
1279
    // Include conduction electrons
1280
    g += n_conduction / w_sq;
856,952✔
1281
    gp -= n_conduction / (w_sq * w_sq);
856,952✔
1282

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

1286
    // If the initial guess is too large, w can be negative
1287
    if (w_sq < 0.0)
856,952✔
1288
      w_sq = w_sq_0 / 2.0;
190,756✔
1289

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

1301
  // Solve for the density effect correction
1302
  for (int i = 0; i < n; ++i) {
3,861,412✔
1303
    double l_sq = e_b_sq[i] * rho * rho / e_p_sq + 2.0 / 3.0 * f[i];
3,737,124✔
1304
    delta += f[i] * std::log((l_sq + w_sq) / l_sq);
3,737,124✔
1305
  }
1306
  // Include conduction electrons
1307
  if (n_conduction > 0.0) {
124,288✔
1308
    delta += n_conduction * std::log((n_conduction + w_sq) / n_conduction);
114,810✔
1309
  }
1310

1311
  return delta - w_sq * (1.0 - beta_sq);
124,288✔
1312
}
1313

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

1318
  pugi::xml_document doc;
1,863✔
1319

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

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

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

1332
  read_materials_xml(root);
1,863✔
1333
}
1,863✔
1334

1335
void read_materials_xml(pugi::xml_node root)
9,054✔
1336
{
1337
  for (pugi::xml_node material_node : root.children("material")) {
27,982✔
1338
    model::materials.push_back(make_unique<Material>(material_node));
18,928✔
1339
  }
1340
  model::materials.shrink_to_fit();
9,054✔
1341
}
9,054✔
1342

1343
void free_memory_material()
9,188✔
1344
{
1345
  model::materials.clear();
9,188✔
1346
  model::material_map.clear();
9,188✔
1347
}
9,188✔
1348

1349
//==============================================================================
1350
// C API
1351
//==============================================================================
1352

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

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

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

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

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

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

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

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

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

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

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

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

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

1523
  return 0;
45✔
1524
}
1525

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

1533
  model::materials[index]->set_name(name);
15✔
1534

1535
  return 0;
15✔
1536
}
1537

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

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

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

1564
  return 0;
30✔
1565
}
1566

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

1574
  model::materials[index]->depletable() = depletable;
15✔
1575

1576
  return 0;
15✔
1577
}
1578

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

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

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