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

openmc-dev / openmc / 13686156298

05 Mar 2025 09:45PM UTC coverage: 85.27% (-0.002%) from 85.272%
13686156298

push

github

web-flow
NCrystal becomes runtime rather than buildtime dependency (#3328)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

86 of 98 new or added lines in 6 files covered. (87.76%)

1 existing line in 1 file now uncovered.

51313 of 60177 relevant lines covered (85.27%)

31549565.37 hits per line

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

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

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

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

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

33
namespace openmc {
34

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

39
namespace model {
40

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

44
} // namespace model
45

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

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

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

60
  if (check_for_node(node, "name")) {
12,932✔
61
    name_ = get_node_value(node, "name");
5,828✔
62
  }
63

64
  if (check_for_node(node, "cfg")) {
12,932✔
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")) {
12,932✔
72
    depletable_ = get_node_value_bool(node, "depletable");
4,783✔
73
  }
74

75
  bool sum_density {false};
12,932✔
76
  pugi::xml_node density_node = node.child("density");
12,932✔
77
  std::string units;
12,932✔
78
  if (density_node) {
12,932✔
79
    units = get_node_value(density_node, "units");
12,932✔
80
    if (units == "sum") {
12,932✔
81
      sum_density = true;
2,383✔
82
    } else if (units == "macro") {
10,549✔
83
      if (check_for_node(density_node, "value")) {
1,682✔
84
        density_ = std::stod(get_node_value(density_node, "value"));
1,682✔
85
      } else {
86
        density_ = 1.0;
×
87
      }
88
    } else {
89
      double val = std::stod(get_node_value(density_node, "value"));
8,867✔
90
      if (val <= 0.0) {
8,867✔
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") {
8,867✔
96
        density_ = -val;
8,432✔
97
      } else if (units == "kg/m3") {
435✔
98
        density_ = -1.0e-3 * val;
16✔
99
      } else if (units == "atom/b-cm") {
419✔
100
        density_ = val;
403✔
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")) {
12,932✔
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") &&
14,614✔
126
      !check_for_node(node, "macroscopic")) {
1,682✔
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");
12,932✔
137
  int num_macros = std::distance(node_macros.begin(), node_macros.end());
12,932✔
138

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

149
    // Check for empty name on nuclide
150
    if (!check_for_node(node_nuc, "name")) {
1,682✔
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);
1,682✔
157
    names.push_back(name);
1,682✔
158

159
    // Set density for macroscopic data
160
    if (units == "macro") {
1,682✔
161
      densities.push_back(density_);
1,682✔
162
    } else {
163
      fatal_error("Units can only be macro for macroscopic data " + name);
×
164
    }
165
  } else {
1,682✔
166
    // Create list of nuclides based on those specified
167
    for (auto node_nuc : node.children("nuclide")) {
58,903✔
168
      // Check for empty name on nuclide
169
      if (!check_for_node(node_nuc, "name")) {
47,653✔
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);
47,653✔
176
      names.push_back(name);
47,653✔
177

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

186
        if (!has_ao && !has_wo) {
47,653✔
187
          fatal_error(
×
188
            "No atom or weight percent specified for nuclide: " + name);
×
189
        } else if (has_ao && has_wo) {
47,653✔
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) {
47,653✔
197
          densities.push_back(std::stod(get_node_value(node_nuc, "ao")));
39,190✔
198
        } else {
199
          densities.push_back(-std::stod(get_node_value(node_nuc, "wo")));
8,463✔
200
        }
201
      }
202
    }
47,653✔
203
  }
204

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

208
  vector<std::string> iso_lab;
12,932✔
209
  if (check_for_node(node, "isotropic")) {
12,932✔
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();
12,932✔
218
  nuclide_.reserve(n);
12,932✔
219
  atom_density_ = xt::empty<double>({n});
12,932✔
220
  if (settings::photon_transport)
12,932✔
221
    element_.reserve(n);
259✔
222

223
  for (int i = 0; i < n; ++i) {
62,267✔
224
    const auto& name {names[i]};
49,335✔
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) {
49,335✔
229
      LibraryKey key {Library::Type::neutron, name};
47,997✔
230
      if (data::library_map.find(key) == data::library_map.end()) {
47,997✔
231
        fatal_error("Could not find nuclide " + name +
×
232
                    " in the "
233
                    "nuclear data library.");
234
      }
235
    }
47,997✔
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()) {
49,335✔
240
      int index = data::nuclide_map.size();
26,504✔
241
      data::nuclide_map[name] = index;
26,504✔
242
      nuclide_.push_back(index);
26,504✔
243
    } else {
244
      nuclide_.push_back(data::nuclide_map[name]);
22,831✔
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) {
49,335✔
250
      std::string element = to_element(name);
1,287✔
251

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

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

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

274
  if (settings::run_CE) {
12,932✔
275
    // By default, isotropic-in-lab is not used
276
    if (iso_lab.size() > 0) {
11,042✔
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))) {
12,932✔
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)
12,932✔
300
    density_ = xt::sum(atom_density_)();
2,383✔
301

302
  if (check_for_node(node, "temperature")) {
12,932✔
303
    temperature_ = std::stod(get_node_value(node, "temperature"));
1,831✔
304
  }
305

306
  if (check_for_node(node, "volume")) {
12,932✔
307
    volume_ = std::stod(get_node_value(node, "volume"));
2,120✔
308
  }
309

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

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

324
      // Read the fraction of nuclei affected by this thermal scattering table
325
      double fraction = 1.0;
1,800✔
326
      if (check_for_node(node_sab, "fraction")) {
1,800✔
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) {
1,800✔
333
        LibraryKey key {Library::Type::thermal, name};
1,714✔
334
        if (data::library_map.find(key) == data::library_map.end()) {
1,714✔
335
          fatal_error("Could not find thermal scattering data " + name +
×
336
                      " in cross_sections.xml file.");
337
        }
338
      }
1,714✔
339

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

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

358
Material::~Material()
12,976✔
359
{
360
  model::material_map.erase(id_);
12,976✔
361
}
12,976✔
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_;
×
NEW
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()
12,500✔
393
{
394
  // Set fissionable if any nuclide is fissionable
395
  if (settings::run_CE) {
12,500✔
396
    for (const auto& i_nuc : nuclide_) {
40,363✔
397
      if (data::nuclides[i_nuc]->fissionable_) {
34,819✔
398
        fissionable_ = true;
5,066✔
399
        break;
5,066✔
400
      }
401
    }
402

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

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

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

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

422
  for (int i = 0; i < nuclide_.size(); ++i) {
60,500✔
423
    // determine atomic weight ratio
424
    int i_nuc = nuclide_[i];
48,000✔
425
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
50,274✔
426
                                  : data::mg.nuclides_[i_nuc].awr;
2,274✔
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)
48,000✔
432
      atom_density_(i) = -atom_density_(i) / awr;
8,463✔
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_)();
12,500✔
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) {
12,500✔
443
    double sum_percent = 0.0;
8,012✔
444
    for (int i = 0; i < nuclide_.size(); ++i) {
35,958✔
445
      int i_nuc = nuclide_[i];
27,946✔
446
      double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
28,026✔
447
                                    : data::mg.nuclides_[i_nuc].awr;
80✔
448
      sum_percent += atom_density_(i) * awr;
27,946✔
449
    }
450
    sum_percent = 1.0 / sum_percent;
8,012✔
451
    density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent;
8,012✔
452
  }
453

454
  // Calculate nuclide atom densities
455
  atom_density_ *= density_;
12,500✔
456

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

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

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

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

490
    // Check to make sure thermal scattering table matched a nuclide
491
    if (!found) {
1,726✔
492
      fatal_error("Thermal scattering table " +
×
493
                  data::thermal_scatt[table.index_table]->name_ +
×
494
                  " did not match any nuclide on material " +
×
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) {
19,330✔
501
    for (int k = j + 1; k < tables.size(); ++k) {
2,046✔
502
      if (tables[j].index_nuclide == tables[k].index_nuclide) {
256✔
503
        int index = nuclide_[tables[j].index_nuclide];
×
504
        auto name = data::nuclides[index]->name_;
×
505
        fatal_error(
×
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.");
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) {
17,540✔
518
    return a.index_nuclide < b.index_nuclide;
176✔
519
  });
520

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

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

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

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

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

542
  for (int i = 0; i < element_.size(); ++i) {
2,652✔
543
    const auto& elm = *data::elements[element_[i]];
2,156✔
544
    double awr = data::nuclides[nuclide_[i]]->awr_;
2,156✔
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,156✔
549

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

554
    for (int j = 0; j < elm.n_electrons_.size(); ++j) {
17,646✔
555
      if (elm.n_electrons_[j] < 0) {
15,490✔
556
        n_conduction -= elm.n_electrons_[j] * atom_density;
1,572✔
557
        continue;
1,572✔
558
      }
559
      e_b_sq.push_back(elm.ionization_energy_[j] * elm.ionization_energy_[j]);
13,918✔
560
      f.push_back(elm.n_electrons_[j] * atom_density);
13,918✔
561
    }
562
  }
563
  log_I /= electron_density;
496✔
564
  n_conduction /= electron_density;
496✔
565
  for (auto& f_i : f)
14,414✔
566
    f_i /= electron_density;
13,918✔
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;
496✔
570

571
  // Calculate the square of the plasma energy
572
  double e_p_sq =
496✔
573
    PLANCK_C * PLANCK_C * PLANCK_C * N_AVOGADRO * electron_density * density /
496✔
574
    (2.0 * PI * PI * FINE_STRUCTURE * MASS_ELECTRON_EV * mass_density);
496✔
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);
496✔
579

580
  // Classical electron radius in cm
581
  constexpr double CM_PER_ANGSTROM {1.0e-8};
496✔
582
  constexpr double r_e =
496✔
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};
496✔
587
  double c =
496✔
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) {
99,410✔
592
    double E = data::ttb_e_grid(i);
98,914✔
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);
98,914✔
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) /
98,914✔
601
                     ((E + MASS_ELECTRON_EV) * (E + MASS_ELECTRON_EV));
98,914✔
602

603
    double tau = E / MASS_ELECTRON_EV;
98,914✔
604

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

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

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

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

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

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

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

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

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

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

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

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

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

675
      // Accumulate material radiative stopping power
676
      stopping_power_radiative += atom_density * elm.stopping_power_radiative_;
2,156✔
677
    }
678
    Z_eq_sq /= sum_density;
496✔
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) {
496✔
688
      for (int i = 0; i < n_e; ++i) {
49,705✔
689
        double t = std::log(
49,457✔
690
          1.0 + 1.0e6 * data::ttb_e_grid(i) / (Z_eq_sq * MASS_ELECTRON_EV));
49,457✔
691
        double r =
692
          1.0 -
49,457✔
693
          std::exp(-1.2359e-1 * t + 6.1274e-2 * std::pow(t, 2) -
49,457✔
694
                   3.1516e-2 * std::pow(t, 3) + 7.7446e-3 * std::pow(t, 4) -
49,457✔
695
                   1.0595e-3 * std::pow(t, 5) + 7.0568e-5 * std::pow(t, 6) -
49,457✔
696
                   1.808e-6 * std::pow(t, 7));
49,457✔
697
        stopping_power_radiative(i) *= r;
49,457✔
698
        auto dcs_i = xt::view(dcs, i, xt::all());
49,457✔
699
        dcs_i *= r;
49,457✔
700
      }
49,457✔
701
    }
702

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

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

713
      // Loop over incident particle energies
714
      for (int j = i; j < n_e; ++j) {
10,012,038✔
715
        double e = data::ttb_e_grid(j);
9,913,620✔
716

717
        // Reduced photon energy
718
        double k = w / e;
9,913,620✔
719

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

724
        // Get the interpolation bounds
725
        double k_l = data::ttb_k_grid(i_k);
9,913,620✔
726
        double k_r = data::ttb_k_grid(i_k + 1);
9,913,620✔
727
        double x_l = dcs(j, i_k);
9,913,620✔
728
        double x_r = dcs(j, i_k + 1);
9,913,620✔
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);
9,913,620✔
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) /
9,913,620✔
737
                         ((e + MASS_ELECTRON_EV) * (e + MASS_ELECTRON_EV));
9,913,620✔
738

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

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

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

751
        double c = 0.0;
97,922✔
752
        for (int j = i; j < n_e - 1; ++j) {
9,912,628✔
753
          c += spline_integrate(n, &data::ttb_e_grid(i), &f(i), &z(i),
9,814,706✔
754
            data::ttb_e_grid(j), data::ttb_e_grid(j + 1));
9,814,706✔
755

756
          ttb->pdf(j + 1, i) = c;
9,814,706✔
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));
496✔
762
        double e_r = std::log(data::ttb_e_grid(i + 1));
496✔
763
        double x_l = std::log(f(i));
496✔
764
        double x_r = std::log(f(i + 1));
496✔
765

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

771
    // Loop over incident particle energies
772
    for (int j = 1; j < n_e; ++j) {
98,914✔
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);
98,418✔
776

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

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

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

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

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

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

818
  if (p.type() == ParticleType::neutron) {
1,249,849,905✔
819
    this->calculate_neutron_xs(p);
1,187,133,717✔
820
  } else if (p.type() == ParticleType::photon) {
62,716,188✔
821
    this->calculate_photon_xs(p);
13,890,536✔
822
  }
823
}
1,249,849,905✔
824

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

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

835
  // Initialize position in i_sab_nuclides
836
  int j = 0;
1,187,133,717✔
837

838
  // Calculate NCrystal cross section
839
  double ncrystal_xs = -1.0;
1,187,133,717✔
840
  if (ncrystal_mat_ && p.E() < NCRYSTAL_MAX_ENERGY) {
1,187,133,717✔
841
    ncrystal_xs = ncrystal_mat_.xs(p);
11,158,829✔
842
  }
843

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

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

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

861
        // If particle energy is greater than the highest energy for the
862
        // S(a,b) table, then don't use the S(a,b) table
863
        if (p.E() > data::thermal_scatt[i_sab]->energy_max_)
286,685,269✔
864
          i_sab = C_NONE;
188,303,891✔
865

866
        // Increment position in thermal_tables_
867
        ++j;
286,685,269✔
868

869
        // Don't check for S(a,b) tables if there are no more left
870
        if (j == thermal_tables_.size())
286,685,269✔
871
          check_sab = false;
286,450,650✔
872
      }
873
    }
874

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

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

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

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

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

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

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

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

911
    // Determine microscopic cross sections for this nuclide
912
    int i_element = element_[i];
75,719,127✔
913

914
    // Calculate microscopic cross section for this nuclide
915
    const auto& micro {p.photon_xs(i_element)};
75,719,127✔
916
    if (p.E() != micro.last_E) {
75,719,127✔
917
      data::elements[i_element]->calculate_xs(p);
34,982,691✔
918
    }
919

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

923
    // Copy atom density of nuclide in material
924
    double atom_density = atom_density_(i);
75,719,127✔
925

926
    // Add contributions to material macroscopic cross sections
927
    p.macro_xs().total += atom_density * micro.total;
75,719,127✔
928
    p.macro_xs().coherent += atom_density * micro.coherent;
75,719,127✔
929
    p.macro_xs().incoherent += atom_density * micro.incoherent;
75,719,127✔
930
    p.macro_xs().photoelectric += atom_density * micro.photoelectric;
75,719,127✔
931
    p.macro_xs().pair_production += atom_density * micro.pair_production;
75,719,127✔
932
  }
933
}
13,890,536✔
934

935
void Material::set_id(int32_t id)
12,976✔
936
{
937
  assert(id >= 0 || id == C_NONE);
10,570✔
938

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

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

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

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

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

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

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

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

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

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

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

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

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

1020
  double sum_density = 0.0;
6,930✔
1021
  for (int64_t i = 0; i < n; ++i) {
74,360✔
1022
    const auto& nuc {name[i]};
67,430✔
1023
    if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) {
67,430✔
1024
      int err = openmc_load_nuclide(nuc.c_str(), nullptr, 0);
×
1025
      if (err < 0)
×
1026
        throw std::runtime_error {openmc_err_msg};
×
1027
    }
1028

1029
    nuclide_[i] = data::nuclide_map.at(nuc);
67,430✔
1030
    assert(density[i] > 0.0);
55,170✔
1031
    atom_density_(i) = density[i];
67,430✔
1032
    sum_density += density[i];
67,430✔
1033

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

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

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

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

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

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

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

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

1082
  // Copy nuclide/macro name for each nuclide to vector
1083
  vector<std::string> nuc_names;
10,119✔
1084
  vector<std::string> macro_names;
10,119✔
1085
  vector<double> nuc_densities;
10,119✔
1086
  if (settings::run_CE) {
10,119✔
1087
    for (int i = 0; i < nuclide_.size(); ++i) {
48,622✔
1088
      int i_nuc = nuclide_[i];
39,537✔
1089
      nuc_names.push_back(data::nuclides[i_nuc]->name_);
39,537✔
1090
      nuc_densities.push_back(atom_density_(i));
39,537✔
1091
    }
1092
  } else {
1093
    for (int i = 0; i < nuclide_.size(); ++i) {
2,101✔
1094
      int i_nuc = nuclide_[i];
1,067✔
1095
      if (data::mg.nuclides_[i_nuc].awr != MACROSCOPIC_AWR) {
1,067✔
1096
        nuc_names.push_back(data::mg.nuclides_[i_nuc].name);
88✔
1097
        nuc_densities.push_back(atom_density_(i));
88✔
1098
      } else {
1099
        macro_names.push_back(data::mg.nuclides_[i_nuc].name);
979✔
1100
      }
1101
    }
1102
  }
1103

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

1110
  // Write vector to 'macroscopics'
1111
  if (!macro_names.empty()) {
10,119✔
1112
    write_dataset(material_group, "macroscopics", macro_names);
979✔
1113
  }
1114

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

1123
  close_group(material_group);
10,119✔
1124
}
10,119✔
1125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1273
    for (int i = 0; i < n; ++i) {
20,789,848✔
1274
      double c = e_b_sq[i] * rho * rho / e_p_sq + w_sq;
20,164,988✔
1275
      g += f[i] / c;
20,164,988✔
1276
      gp -= f[i] / (c * c);
20,164,988✔
1277
    }
1278
    // Include conduction electrons
1279
    g += n_conduction / w_sq;
624,860✔
1280
    gp -= n_conduction / (w_sq * w_sq);
624,860✔
1281

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

1285
    // If the initial guess is too large, w can be negative
1286
    if (w_sq < 0.0)
624,860✔
1287
      w_sq = w_sq_0 / 2.0;
139,052✔
1288

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

1300
  // Solve for the density effect correction
1301
  for (int i = 0; i < n; ++i) {
2,819,232✔
1302
    double l_sq = e_b_sq[i] * rho * rho / e_p_sq + 2.0 / 3.0 * f[i];
2,728,596✔
1303
    delta += f[i] * std::log((l_sq + w_sq) / l_sq);
2,728,596✔
1304
  }
1305
  // Include conduction electrons
1306
  if (n_conduction > 0.0) {
90,636✔
1307
    delta += n_conduction * std::log((n_conduction + w_sq) / n_conduction);
83,714✔
1308
  }
1309

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

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

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

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

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

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

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

1334
void read_materials_xml(pugi::xml_node root)
6,258✔
1335
{
1336
  for (pugi::xml_node material_node : root.children("material")) {
19,182✔
1337
    model::materials.push_back(make_unique<Material>(material_node));
12,924✔
1338
  }
1339
  model::materials.shrink_to_fit();
6,258✔
1340
}
6,258✔
1341

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1522
  return 0;
33✔
1523
}
1524

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

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

1534
  return 0;
11✔
1535
}
1536

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

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

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

1563
  return 0;
22✔
1564
}
1565

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

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

1575
  return 0;
11✔
1576
}
1577

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

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

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

© 2025 Coveralls, Inc