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

openmc-dev / openmc / 14515233533

17 Apr 2025 12:06PM UTC coverage: 83.16% (-2.3%) from 85.414%
14515233533

Pull #3087

github

web-flow
Merge 6ed397e9d into 47ca2916a
Pull Request #3087: wheel building with scikit build core

140769 of 169274 relevant lines covered (83.16%)

11830168.1 hits per line

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

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

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

60
  if (check_for_node(node, "name")) {
9,681✔
61
    name_ = get_node_value(node, "name");
5,606✔
62
  }
63

64
  if (check_for_node(node, "cfg")) {
9,681✔
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")) {
9,681✔
72
    depletable_ = get_node_value_bool(node, "depletable");
2,540✔
73
  }
74

75
  bool sum_density {false};
9,681✔
76
  pugi::xml_node density_node = node.child("density");
9,681✔
77
  std::string units;
9,681✔
78
  if (density_node) {
9,681✔
79
    units = get_node_value(density_node, "units");
9,681✔
80
    if (units == "sum") {
9,681✔
81
      sum_density = true;
637✔
82
    } else if (units == "macro") {
9,044✔
83
      if (check_for_node(density_node, "value")) {
2,146✔
84
        density_ = std::stod(get_node_value(density_node, "value"));
2,146✔
85
      } else {
86
        density_ = 1.0;
×
87
      }
88
    } else {
89
      double val = std::stod(get_node_value(density_node, "value"));
6,898✔
90
      if (val <= 0.0) {
6,898✔
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") {
6,898✔
96
        density_ = -val;
6,546✔
97
      } else if (units == "kg/m3") {
352✔
98
        density_ = -1.0e-3 * val;
16✔
99
      } else if (units == "atom/b-cm") {
336✔
100
        density_ = val;
320✔
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")) {
9,681✔
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") &&
11,827✔
126
      !check_for_node(node, "macroscopic")) {
2,146✔
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");
9,681✔
137
  int num_macros = std::distance(node_macros.begin(), node_macros.end());
9,681✔
138

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

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

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

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

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

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

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

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

223
  for (int i = 0; i < n; ++i) {
38,538✔
224
    const auto& name {names[i]};
28,857✔
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) {
28,857✔
229
      LibraryKey key {Library::Type::neutron, name};
27,519✔
230
      if (data::library_map.find(key) == data::library_map.end()) {
27,519✔
231
        fatal_error("Could not find nuclide " + name +
×
232
                    " in the "
233
                    "nuclear data library.");
234
      }
235
    }
27,519✔
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()) {
28,857✔
240
      int index = data::nuclide_map.size();
20,322✔
241
      data::nuclide_map[name] = index;
20,322✔
242
      nuclide_.push_back(index);
20,322✔
243
    } else {
244
      nuclide_.push_back(data::nuclide_map[name]);
8,535✔
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) {
28,857✔
250
      std::string element = to_element(name);
1,078✔
251

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

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

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

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

302
  if (check_for_node(node, "temperature")) {
9,681✔
303
    temperature_ = std::stod(get_node_value(node, "temperature"));
70✔
304
  }
305

306
  if (check_for_node(node, "volume")) {
9,681✔
307
    volume_ = std::stod(get_node_value(node, "volume"));
110✔
308
  }
309

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

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

324
      // Read the fraction of nuclei affected by this thermal scattering table
325
      double fraction = 1.0;
1,610✔
326
      if (check_for_node(node_sab, "fraction")) {
1,610✔
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,610✔
333
        LibraryKey key {Library::Type::thermal, name};
1,524✔
334
        if (data::library_map.find(key) == data::library_map.end()) {
1,524✔
335
          fatal_error("Could not find thermal scattering data " + name +
×
336
                      " in cross_sections.xml file.");
337
        }
338
      }
1,524✔
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,610✔
344
        index_table = data::thermal_scatt_map.size();
922✔
345
        data::thermal_scatt_map[name] = index_table;
922✔
346
      } else {
347
        index_table = data::thermal_scatt_map[name];
688✔
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,610✔
354
    }
1,610✔
355
  }
7,327✔
356
}
9,681✔
357

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

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

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

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

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

392
void Material::finalize()
9,249✔
393
{
394
  // Set fissionable if any nuclide is fissionable
395
  if (settings::run_CE) {
9,249✔
396
    for (const auto& i_nuc : nuclide_) {
25,296✔
397
      if (data::nuclides[i_nuc]->fissionable_) {
21,314✔
398
        fissionable_ = true;
2,913✔
399
        break;
2,913✔
400
      }
401
    }
402

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

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

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

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

422
  for (int i = 0; i < nuclide_.size(); ++i) {
36,771✔
423
    // determine atomic weight ratio
424
    int i_nuc = nuclide_[i];
27,522✔
425
    double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
30,260✔
426
                                  : data::mg.nuclides_[i_nuc].awr;
2,738✔
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)
27,522✔
432
      atom_density_(i) = -atom_density_(i) / awr;
7,440✔
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_)();
9,249✔
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) {
9,249✔
443
    double sum_percent = 0.0;
6,126✔
444
    for (int i = 0; i < nuclide_.size(); ++i) {
28,264✔
445
      int i_nuc = nuclide_[i];
22,138✔
446
      double awr = settings::run_CE ? data::nuclides[i_nuc]->awr_
22,218✔
447
                                    : data::mg.nuclides_[i_nuc].awr;
80✔
448
      sum_percent += atom_density_(i) * awr;
22,138✔
449
    }
450
    sum_percent = 1.0 / sum_percent;
6,126✔
451
    density_ = -density_ * N_AVOGADRO / MASS_NEUTRON * sum_percent;
6,126✔
452
  }
453

454
  // Calculate nuclide atom densities
455
  atom_density_ *= density_;
9,249✔
456

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

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

470
  std::unordered_set<int> already_checked;
6,895✔
471
  for (const auto& table : thermal_tables_) {
8,420✔
472
    // Make sure each S(a,b) table only gets checked once
473
    if (already_checked.find(table.index_table) != already_checked.end()) {
1,525✔
474
      continue;
×
475
    }
476
    already_checked.insert(table.index_table);
1,525✔
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,525✔
482
    for (int j = 0; j < nuclide_.size(); ++j) {
10,624✔
483
      const auto& name {data::nuclides[nuclide_[j]]->name_};
9,099✔
484
      if (contains(data::thermal_scatt[table.index_table]->nuclides_, name)) {
9,099✔
485
        tables.push_back({table.index_table, j, table.fraction});
1,589✔
486
        found = true;
1,589✔
487
      }
488
    }
489

490
    // Check to make sure thermal scattering table matched a nuclide
491
    if (!found) {
1,525✔
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) {
8,484✔
501
    for (int k = j + 1; k < tables.size(); ++k) {
1,845✔
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) {
6,895✔
518
    return a.index_nuclide < b.index_nuclide;
176✔
519
  });
520

521
  // Update the list of thermal tables
522
  thermal_tables_ = tables;
6,895✔
523
}
6,895✔
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()
9,218✔
801
{
802
  int n = settings::run_CE ? data::nuclides.size() : data::mg.nuclides_.size();
9,218✔
803
  mat_nuclide_index_.resize(n);
9,218✔
804
  std::fill(mat_nuclide_index_.begin(), mat_nuclide_index_.end(), C_NONE);
9,218✔
805
  for (int i = 0; i < nuclide_.size(); ++i) {
36,314✔
806
    mat_nuclide_index_[nuclide_[i]] = i;
27,096✔
807
  }
808
}
9,218✔
809

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

818
  if (p.type() == ParticleType::neutron) {
736,668,178✔
819
    this->calculate_neutron_xs(p);
673,955,078✔
820
  } else if (p.type() == ParticleType::photon) {
62,713,100✔
821
    this->calculate_photon_xs(p);
13,889,148✔
822
  }
823
}
736,668,178✔
824

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

832
  // Determine if this material has S(a,b) tables
833
  bool check_sab = (thermal_tables_.size() > 0);
673,955,078✔
834

835
  // Initialize position in i_sab_nuclides
836
  int j = 0;
673,955,078✔
837

838
  // Calculate NCrystal cross section
839
  double ncrystal_xs = -1.0;
673,955,078✔
840
  if (ncrystal_mat_ && p.E() < NCRYSTAL_MAX_ENERGY) {
673,955,078✔
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]};
235,939,123✔
856
      if (i == sab.index_nuclide) {
235,939,123✔
857
        // Get index in sab_tables
858
        i_sab = sab.index_table;
124,556,830✔
859
        sab_frac = sab.fraction;
124,556,830✔
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_)
124,556,830✔
864
          i_sab = C_NONE;
78,520,998✔
865

866
        // Increment position in thermal_tables_
867
        ++j;
124,556,830✔
868

869
        // Don't check for S(a,b) tables if there are no more left
870
        if (j == thermal_tables_.size())
124,556,830✔
871
          check_sab = false;
124,322,211✔
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
}
673,955,078✔
898

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

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

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

914
    // Calculate microscopic cross section for this nuclide
915
    const auto& micro {p.photon_xs(i_element)};
75,716,351✔
916
    if (p.E() != micro.last_E) {
75,716,351✔
917
      data::elements[i_element]->calculate_xs(p);
34,980,119✔
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,716,351✔
925

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

935
void Material::set_id(int32_t id)
9,681✔
936
{
937
  assert(id >= 0 || id == C_NONE);
7,871✔
938

939
  // Clear entry in material map if an ID was already assigned before
940
  if (id_ != C_NONE) {
9,681✔
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()) {
9,681✔
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) {
9,681✔
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;
9,681✔
962
  model::material_map[id] = index_;
9,681✔
963
}
9,681✔
964

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

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

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

977
    // Determine normalized atom percents
978
    double sum_percent = xt::sum(atom_density_)();
×
979
    atom_density_ /= sum_percent;
×
980

981
    // Recalculate nuclide atom densities based on given density
982
    atom_density_ *= density;
×
983

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

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

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

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

1020
  double sum_density = 0.0;
×
1021
  for (int64_t i = 0; i < n; ++i) {
×
1022
    const auto& nuc {name[i]};
×
1023
    if (data::nuclide_map.find(nuc) == data::nuclide_map.end()) {
×
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);
×
1030
    assert(density[i] > 0.0);
1031
    atom_density_(i) = density[i];
×
1032
    sum_density += density[i];
×
1033

1034
    if (settings::photon_transport) {
×
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");
×
1042

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

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

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

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

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

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

1082
  // Copy nuclide/macro name for each nuclide to vector
1083
  vector<std::string> nuc_names;
6,766✔
1084
  vector<std::string> macro_names;
6,766✔
1085
  vector<double> nuc_densities;
6,766✔
1086
  if (settings::run_CE) {
6,766✔
1087
    for (int i = 0; i < nuclide_.size(); ++i) {
24,502✔
1088
      int i_nuc = nuclide_[i];
19,089✔
1089
      nuc_names.push_back(data::nuclides[i_nuc]->name_);
19,089✔
1090
      nuc_densities.push_back(atom_density_(i));
19,089✔
1091
    }
1092
  } else {
1093
    for (int i = 0; i < nuclide_.size(); ++i) {
2,739✔
1094
      int i_nuc = nuclide_[i];
1,386✔
1095
      if (data::mg.nuclides_[i_nuc].awr != MACROSCOPIC_AWR) {
1,386✔
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);
1,298✔
1100
      }
1101
    }
1102
  }
1103

1104
  // Write vector to 'nuclides'
1105
  if (!nuc_names.empty()) {
6,766✔
1106
    write_dataset(material_group, "nuclides", nuc_names);
5,468✔
1107
    write_dataset(material_group, "nuclide_densities", nuc_densities);
5,468✔
1108
  }
1109

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

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

1123
  close_group(material_group);
6,766✔
1124
}
6,766✔
1125

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

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

1143
void Material::add_nuclide(const std::string& name, double density)
×
1144
{
1145
  // Check if nuclide is already in material
1146
  for (int i = 0; i < nuclide_.size(); ++i) {
×
1147
    int i_nuc = nuclide_[i];
×
1148
    if (data::nuclides[i_nuc]->name_ == name) {
×
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);
×
1160
  if (err < 0)
×
1161
    throw std::runtime_error {openmc_err_msg};
×
1162

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

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

1173
  auto n = nuclide_.size();
×
1174

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

1181
  density_ += density;
×
1182
  density_gpcc_ +=
×
1183
    density * data::nuclides[i_nuc]->awr_ * MASS_NEUTRON / N_AVOGADRO;
×
1184
}
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()
868✔
1314
{
1315
  write_message("Reading materials XML file...", 5);
868✔
1316

1317
  pugi::xml_document doc;
868✔
1318

1319
  // Check if materials.xml exists
1320
  std::string filename = settings::path_input + "materials.xml";
868✔
1321
  if (!file_exists(filename)) {
868✔
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());
868✔
1327

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

1331
  read_materials_xml(root);
868✔
1332
}
868✔
1333

1334
void read_materials_xml(pugi::xml_node root)
5,473✔
1335
{
1336
  for (pugi::xml_node material_node : root.children("material")) {
15,146✔
1337
    model::materials.push_back(make_unique<Material>(material_node));
9,673✔
1338
  }
1339
  model::materials.shrink_to_fit();
5,473✔
1340
}
5,473✔
1341

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

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

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

1364
extern "C" int openmc_material_add_nuclide(
×
1365
  int32_t index, const char* name, double density)
1366
{
1367
  int err = 0;
×
1368
  if (index >= 0 && index < model::materials.size()) {
×
1369
    try {
1370
      model::materials[index]->add_nuclide(name, density);
×
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;
×
1379
}
1380

1381
extern "C" int openmc_material_get_densities(
×
1382
  int32_t index, const int** nuclides, const double** densities, int* n)
1383
{
1384
  if (index >= 0 && index < model::materials.size()) {
×
1385
    auto& mat = model::materials[index];
×
1386
    if (!mat->nuclides().empty()) {
×
1387
      *nuclides = mat->nuclides().data();
×
1388
      *densities = mat->densities().data();
×
1389
      *n = mat->nuclides().size();
×
1390
      return 0;
×
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)
×
1402
{
1403
  if (index >= 0 && index < model::materials.size()) {
×
1404
    auto& mat = model::materials[index];
×
1405
    *density = mat->density_gpcc();
×
1406
    return 0;
×
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)
×
1425
{
1426
  if (index >= 0 && index < model::materials.size()) {
×
1427
    *id = model::materials[index]->id();
×
1428
    return 0;
×
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(
×
1436
  int32_t index, double* temperature)
1437
{
1438
  if (index < 0 || index >= model::materials.size()) {
×
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();
×
1443
  return 0;
×
1444
}
1445

1446
extern "C" int openmc_material_get_volume(int32_t index, double* volume)
×
1447
{
1448
  if (index >= 0 && index < model::materials.size()) {
×
1449
    try {
1450
      *volume = model::materials[index]->volume();
×
1451
    } catch (const std::exception& e) {
×
1452
      set_errmsg(e.what());
×
1453
      return OPENMC_E_UNASSIGNED;
×
1454
    }
×
1455
    return 0;
×
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(
×
1463
  int32_t index, double density, const char* units)
1464
{
1465
  if (index >= 0 && index < model::materials.size()) {
×
1466
    try {
1467
      model::materials[index]->set_density(density, units);
×
1468
    } catch (const std::exception& e) {
×
1469
      set_errmsg(e.what());
×
1470
      return OPENMC_E_UNASSIGNED;
×
1471
    }
×
1472
  } else {
1473
    set_errmsg("Index in materials array is out of bounds.");
×
1474
    return OPENMC_E_OUT_OF_BOUNDS;
×
1475
  }
1476
  return 0;
×
1477
}
1478

1479
extern "C" int openmc_material_set_densities(
×
1480
  int32_t index, int n, const char** name, const double* density)
1481
{
1482
  if (index >= 0 && index < model::materials.size()) {
×
1483
    try {
1484
      model::materials[index]->set_densities(
×
1485
        {name, name + n}, {density, density + n});
×
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;
×
1495
}
1496

1497
extern "C" int openmc_material_set_id(int32_t index, int32_t id)
×
1498
{
1499
  if (index >= 0 && index < model::materials.size()) {
×
1500
    try {
1501
      model::materials.at(index)->set_id(id);
×
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;
×
1511
}
1512

1513
extern "C" int openmc_material_get_name(int32_t index, const char** name)
×
1514
{
1515
  if (index < 0 || index >= model::materials.size()) {
×
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();
×
1521

1522
  return 0;
×
1523
}
1524

1525
extern "C" int openmc_material_set_name(int32_t index, const char* name)
×
1526
{
1527
  if (index < 0 || index >= model::materials.size()) {
×
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);
×
1533

1534
  return 0;
×
1535
}
1536

1537
extern "C" int openmc_material_set_volume(int32_t index, double volume)
×
1538
{
1539
  if (index >= 0 && index < model::materials.size()) {
×
1540
    auto& m {model::materials[index]};
×
1541
    if (volume >= 0.0) {
×
1542
      m->volume_ = volume;
×
1543
      return 0;
×
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)
×
1555
{
1556
  if (index < 0 || index >= model::materials.size()) {
×
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();
×
1562

1563
  return 0;
×
1564
}
1565

1566
extern "C" int openmc_material_set_depletable(int32_t index, bool depletable)
×
1567
{
1568
  if (index < 0 || index >= model::materials.size()) {
×
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;
×
1574

1575
  return 0;
×
1576
}
1577

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

1591
extern "C" size_t n_materials()
×
1592
{
1593
  return model::materials.size();
×
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