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

openmc-dev / openmc / 43316628581

12 Nov 2026 10:05PM UTC coverage: 82.188% (+0.7%) from 81.44%
43316628581

Pull #3877

github

web-flow
Merge 228a3ab7b into 013cfbb99
Pull Request #3877: Add VTKHDF output support for all structured mesh types

19751 of 27809 branches covered (71.02%)

Branch coverage included in aggregate %.

88 of 89 new or added lines in 1 file covered. (98.88%)

2040 existing lines in 43 files now uncovered.

62830 of 72669 relevant lines covered (86.46%)

39888353.97 hits per line

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

38.46
/src/dagmc.cpp
1
#include "openmc/dagmc.h"
2

3
#include <array>
4
#include <cassert>
5

6
#include "openmc/constants.h"
7
#include "openmc/container_util.h"
8
#include "openmc/error.h"
9
#include "openmc/file_utils.h"
10
#include "openmc/geometry.h"
11
#include "openmc/geometry_aux.h"
12
#include "openmc/hdf5_interface.h"
13
#include "openmc/material.h"
14
#include "openmc/settings.h"
15
#include "openmc/string_utils.h"
16

17
#ifdef OPENMC_UWUW_ENABLED
18
#include "uwuw.hpp"
19
#endif
20
#include <fmt/core.h>
21

22
#include <algorithm>
23
#include <filesystem>
24
#include <fstream>
25
#include <sstream>
26
#include <string>
27

28
#ifdef OPENMC_DAGMC_ENABLED
29

30
namespace openmc {
31

32
//==============================================================================
33
// DAGMC Universe implementation
34
//==============================================================================
35

36
DAGUniverse::DAGUniverse(pugi::xml_node node)
37
{
38
  MaterialOverrides material_overrides;
39
  TemperatureOverrides temperature_overrides;
40
  DensityOverrides density_overrides;
41

42
  if (check_for_node(node, "id")) {
43
    id_ = std::stoi(get_node_value(node, "id"));
44
  } else {
45
    fatal_error("Must specify the id of the DAGMC universe");
46
  }
47

48
  if (check_for_node(node, "filename")) {
49
    filename_ = get_node_value(node, "filename");
50
    std::filesystem::path p(filename_);
51
    if (p.is_relative()) {
52
      std::filesystem::path d(dir_name(settings::path_input));
53
      filename_ = (d / p).string();
54
    }
55
  } else {
56
    fatal_error("Must specify a file for the DAGMC universe");
57
  }
58

59
  adjust_geometry_ids_ = false;
60
  if (check_for_node(node, "auto_geom_ids")) {
61
    adjust_geometry_ids_ = get_node_value_bool(node, "auto_geom_ids");
62
  }
63

64
  adjust_material_ids_ = false;
65
  if (check_for_node(node, "auto_mat_ids")) {
66
    adjust_material_ids_ = get_node_value_bool(node, "auto_mat_ids");
67
  }
68

69
  if (check_for_node(node, "length_multiplier")) {
70
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
71
  }
72

73
  // Get material assignment overrides from nested DAGMC cell elements.
74
  if (node.child("cell")) {
75
    for (pugi::xml_node cell_node : node.children("cell")) {
76
      if (!check_for_node(cell_node, "id")) {
77
        fatal_error(
78
          "Must specify id for each DAGMC cell override in <dagmc_universe>.");
79
      }
80

81
      int32_t cell_id = std::stoi(get_node_value(cell_node, "id"));
82

83
      if (check_for_node(cell_node, "region")) {
84
        fatal_error(fmt::format(
85
          "DAGMC cell {} override cannot specify a region.", cell_id));
86
      }
87
      if (check_for_node(cell_node, "fill")) {
88
        fatal_error(fmt::format(
89
          "DAGMC cell {} override currently only supports material fills.",
90
          cell_id));
91
      }
92
      if (check_for_node(cell_node, "universe")) {
93
        fatal_error(fmt::format(
94
          "DAGMC cell {} override cannot specify a universe.", cell_id));
95
      }
96
      if (check_for_node(cell_node, "translation") ||
97
          check_for_node(cell_node, "rotation")) {
98
        fatal_error(fmt::format(
99
          "DAGMC cell {} override does not support translation or rotation.",
100
          cell_id));
101
      }
102
      if (!check_for_node(cell_node, "material")) {
103
        fatal_error(fmt::format(
104
          "DAGMC cell {} override must specify material.", cell_id));
105
      }
106

107
      auto inserted = material_overrides.emplace(
108
        cell_id, parse_cell_material_xml(cell_node, cell_id));
109
      if (!inserted.second) {
110
        fatal_error(fmt::format(
111
          "Duplicate DAGMC cell override specified for cell {}", cell_id));
112
      }
113

114
      if (check_for_node(cell_node, "temperature")) {
115
        temperature_overrides.emplace(
116
          cell_id, parse_cell_temperature_xml(cell_node, cell_id));
117
      }
118

119
      if (check_for_node(cell_node, "density")) {
120
        density_overrides.emplace(
121
          cell_id, parse_cell_density_xml(cell_node, cell_id));
122
      }
123
    }
124
  } else if (check_for_node(node, "material_overrides")) {
125
    if (node.child("cell")) {
126
      fatal_error("DAGMCUniverse cannot specify both <material_overrides> and "
127
                  "<cell> sub-elements. Use <cell> elements only.");
128
    }
129
    warning("DAGMCUniverse <material_overrides> is deprecated. Use nested "
130
            "<cell> elements under <dagmc_universe> instead.");
131
    for (pugi::xml_node co :
132
      node.child("material_overrides").children("cell_override")) {
133
      int32_t cell_id = std::stoi(get_node_value(co, "id"));
134
      std::istringstream iss(co.child("material_ids").text().get());
135
      vector<int32_t> mats;
136
      for (std::string s; iss >> s;) {
137
        mats.push_back(s == "void" ? MATERIAL_VOID : std::stoi(s));
138
      }
139
      material_overrides.emplace(cell_id, mats);
140
    }
141
  }
142

143
  initialize(material_overrides, temperature_overrides, density_overrides);
144
}
145

146
DAGUniverse::DAGUniverse(const std::string& filename, bool auto_geom_ids,
147
  bool auto_mat_ids, double length_multiplier)
148
  : filename_(filename), adjust_geometry_ids_(auto_geom_ids),
149
    adjust_material_ids_(auto_mat_ids), length_multiplier_(length_multiplier)
150
{
151
  set_id();
152
  initialize();
153
}
154

155
DAGUniverse::DAGUniverse(std::shared_ptr<moab::DagMC> dagmc_ptr,
156
  const std::string& filename, bool auto_geom_ids, bool auto_mat_ids,
157
  double length_multiplier)
158
  : dagmc_instance_(dagmc_ptr), filename_(filename),
159
    adjust_geometry_ids_(auto_geom_ids), adjust_material_ids_(auto_mat_ids),
160
    length_multiplier_(length_multiplier)
161
{
162
  MaterialOverrides material_overrides;
163
  TemperatureOverrides temperature_overrides;
164
  DensityOverrides density_overrides;
165
  set_id();
166
  init_metadata();
167
  init_geometry(material_overrides, temperature_overrides, density_overrides);
168
}
169

170
void DAGUniverse::set_id()
171
{
172
  // determine the next universe id
173
  int32_t next_univ_id = 0;
174
  for (const auto& u : model::universes) {
175
    if (u->id_ > next_univ_id)
176
      next_univ_id = u->id_;
177
  }
178
  next_univ_id++;
179

180
  // set the universe id
181
  id_ = next_univ_id;
182
}
183

184
void DAGUniverse::initialize()
185
{
186
  MaterialOverrides material_overrides;
187
  TemperatureOverrides temperature_overrides;
188
  initialize(material_overrides, temperature_overrides);
189
}
190

191
void DAGUniverse::initialize(const MaterialOverrides& material_overrides,
192
  const TemperatureOverrides& temperature_overrides,
193
  const DensityOverrides& density_overrides)
194
{
195
#ifdef OPENMC_UWUW_ENABLED
196
  // read uwuw materials from the .h5m file if present
197
  read_uwuw_materials();
198
#endif
199

200
  init_dagmc();
201

202
  init_metadata();
203

204
  init_geometry(material_overrides, temperature_overrides, density_overrides);
205
}
206

207
void DAGUniverse::init_dagmc()
208
{
209

210
  // create a new DAGMC instance
211
  dagmc_instance_ = std::make_shared<moab::DagMC>();
212

213
  // load the DAGMC geometry
214
  if (!file_exists(filename_)) {
215
    fatal_error("Geometry DAGMC file '" + filename_ + "' does not exist!");
216
  }
217
  moab::ErrorCode rval = dagmc_instance_->load_file(filename_.c_str());
218
  MB_CHK_ERR_CONT(rval);
219

220
  if (length_multiplier_ != 1.0) {
221
    moab::Range verts;
222
    rval =
223
      dagmc_instance_->moab_instance()->get_entities_by_dimension(0, 0, verts);
224
    MB_CHK_ERR_CONT(rval);
225

226
    for (auto vert : verts) {
227
      std::array<double, 3> coord;
228
      rval =
229
        dagmc_instance_->moab_instance()->get_coords(&vert, 1, coord.data());
230
      MB_CHK_ERR_CONT(rval);
231

232
      for (auto& c : coord) {
233
        c *= length_multiplier_;
234
      }
235

236
      rval =
237
        dagmc_instance_->moab_instance()->set_coords(&vert, 1, coord.data());
238
      MB_CHK_ERR_CONT(rval);
239
    }
240
  }
241

242
  // initialize acceleration data structures
243
  rval = dagmc_instance_->init_OBBTree();
244
  MB_CHK_ERR_CONT(rval);
245
}
246

247
void DAGUniverse::init_metadata()
248
{
249
  // parse model metadata
250
  dmd_ptr =
251
    std::make_unique<dagmcMetaData>(dagmc_instance_.get(), false, false);
252
  dmd_ptr->load_property_data();
253

254
  std::vector<std::string> keywords {"temp"};
255
  std::map<std::string, std::string> dum;
256
  std::string delimiters = ":/";
257
  moab::ErrorCode rval;
258
  rval = dagmc_instance_->parse_properties(keywords, dum, delimiters.c_str());
259
  MB_CHK_ERR_CONT(rval);
260
}
261

262
void DAGUniverse::init_geometry(const MaterialOverrides& material_overrides,
263
  const TemperatureOverrides& temperature_overrides,
264
  const DensityOverrides& density_overrides)
265
{
266
  moab::ErrorCode rval;
267

268
  // determine the next cell id
269
  int32_t next_cell_id = 0;
270
  for (const auto& c : model::cells) {
271
    if (c->id_ > next_cell_id)
272
      next_cell_id = c->id_;
273
  }
274
  cell_idx_offset_ = model::cells.size();
275
  next_cell_id++;
276

277
  // initialize cell objects
278
  int n_cells = dagmc_instance_->num_entities(3);
279
  moab::EntityHandle graveyard = 0;
280
  for (int i = 0; i < n_cells; i++) {
281
    moab::EntityHandle vol_handle = dagmc_instance_->entity_by_index(3, i + 1);
282

283
    // set cell ids using global IDs
284
    auto c = std::make_unique<DAGCell>(dagmc_instance_, i + 1);
285
    c->id_ = adjust_geometry_ids_
286
               ? next_cell_id++
287
               : dagmc_instance_->id_by_index(3, c->dag_index());
288
    c->universe_ = this->id_;
289
    c->fill_ = C_NONE; // no fill, single universe
290
    if (dagmc_instance_->is_implicit_complement(vol_handle)) {
291
      c->name_ = "implicit complement";
292
    }
293

294
    auto in_map = model::cell_map.find(c->id_);
295
    if (in_map == model::cell_map.end()) {
296
      model::cell_map[c->id_] = model::cells.size();
297
    } else {
298
      warning(fmt::format("DAGMC Cell IDs: {}", dagmc_ids_for_dim(3)));
299
      fatal_error(fmt::format(
300
        "DAGMC Universe {} contains a cell with ID {}, which "
301
        "already exists elsewhere in the geometry. Setting auto_geom_ids "
302
        "to True when initiating the DAGMC Universe may "
303
        "resolve this issue",
304
        this->id_, c->id_));
305
    }
306

307
    // --- Materials ---
308

309
    // determine volume material assignment
310
    std::string mat_str = dmd_ptr->get_volume_property("material", vol_handle);
311

312
    if (mat_str.empty()) {
313
      fatal_error(fmt::format("Volume {} has no material assignment.", c->id_));
314
    }
315

316
    to_lower(mat_str);
317

318
    if (mat_str == "graveyard") {
319
      graveyard = vol_handle;
320
    }
321
    if (material_overrides.count(c->id_)) {
322
      override_assign_material(c, material_overrides);
323
    } else if (mat_str == "void" || mat_str == "vacuum" ||
324
               mat_str == "graveyard") {
325
      c->material_.push_back(MATERIAL_VOID);
326
    } else if (uses_uwuw()) {
327
      uwuw_assign_material(vol_handle, c);
328
    } else {
329
      legacy_assign_material(mat_str, c);
330
    }
331

332
    if (temperature_overrides.count(c->id_)) {
333
      if (c->material_.empty() || c->material_[0] == MATERIAL_VOID) {
334
        fatal_error(fmt::format("DAGMC cell {} was specified with a "
335
                                "temperature but no non-void material.",
336
          c->id_));
337
      }
338

339
      c->sqrtkT_.clear();
340
      const auto& temp_overrides = temperature_overrides.at(c->id_);
341
      c->sqrtkT_.reserve(temp_overrides.size());
342
      for (auto T : temp_overrides) {
343
        c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * T));
344
      }
345

346
      if (settings::verbosity >= 10) {
347
        std::stringstream override_values;
348
        for (size_t i = 0; i < temp_overrides.size(); ++i) {
349
          if (i > 0) {
350
            override_values << " ";
351
          }
352
          override_values << temp_overrides[i];
353
        }
354
        auto msg = fmt::format("Overriding DAGMC cell {} property "
355
                               "'temperature [K]' with value(s): {}",
356
          c->id_, override_values.str());
357
        write_message(msg, 10);
358
      }
359
    }
360

361
    if (density_overrides.count(c->id_)) {
362
      if (c->material_.empty() || c->material_[0] == MATERIAL_VOID) {
363
        fatal_error(fmt::format("DAGMC cell {} was specified with a density "
364
                                "but no non-void material.",
365
          c->id_));
366
      }
367
      // density_mult_ holds the true density until materials are finalized,
368
      // at which point it is converted to a proper multiplier (same as CSG).
369
      c->density_mult_ = density_overrides.at(c->id_);
370

371
      if (settings::verbosity >= 10) {
372
        const auto& dens = density_overrides.at(c->id_);
373
        std::stringstream override_values;
374
        for (size_t i = 0; i < dens.size(); ++i) {
375
          if (i > 0)
376
            override_values << " ";
377
          override_values << dens[i];
378
        }
379
        write_message(fmt::format("Overriding DAGMC cell {} property "
380
                                  "'density [g/cm³]' with value(s): {}",
381
                        c->id_, override_values.str()),
382
          10);
383
      }
384
    }
385

386
    // check for temperature assignment
387
    std::string temp_value;
388

389
    // no temperature if void
390
    if (c->material_[0] == MATERIAL_VOID) {
391
      model::cells.emplace_back(std::move(c));
392
      continue;
393
    }
394

395
    // assign cell temperature if not explicitly overridden
396
    if (c->sqrtkT_.empty()) {
397
      const auto& mat =
398
        model::materials[model::material_map.at(c->material_[0])];
399
      if (dagmc_instance_->has_prop(vol_handle, "temp")) {
400
        rval = dagmc_instance_->prop_value(vol_handle, "temp", temp_value);
401
        MB_CHK_ERR_CONT(rval);
402
        double temp = std::stod(temp_value);
403
        c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * temp));
404
      } else if (mat->temperature() > 0.0) {
405
        c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * mat->temperature()));
406
      } else {
407
        c->sqrtkT_.push_back(
408
          std::sqrt(K_BOLTZMANN * settings::temperature_default));
409
      }
410
    }
411

412
    model::cells.emplace_back(std::move(c));
413
  }
414

415
  // allocate the cell overlap count if necessary
416
  if (settings::check_overlaps) {
417
    model::overlap_check_count.resize(model::cells.size(), 0);
418
  }
419

420
  has_graveyard_ = graveyard;
421

422
  // determine the next surface id
423
  int32_t next_surf_id = 0;
424
  for (const auto& s : model::surfaces) {
425
    if (s->id_ > next_surf_id)
426
      next_surf_id = s->id_;
427
  }
428
  surf_idx_offset_ = model::surfaces.size();
429
  next_surf_id++;
430

431
  // initialize surface objects
432
  int n_surfaces = dagmc_instance_->num_entities(2);
433
  for (int i = 0; i < n_surfaces; i++) {
434
    moab::EntityHandle surf_handle = dagmc_instance_->entity_by_index(2, i + 1);
435

436
    // set cell ids using global IDs
437
    auto s = std::make_unique<DAGSurface>(dagmc_instance_, i + 1);
438
    s->id_ = adjust_geometry_ids_ ? next_surf_id++
439
                                  : dagmc_instance_->id_by_index(2, i + 1);
440

441
    // set surface source attribute if needed
442
    if (contains(settings::source_write_surf_id, s->id_) ||
443
        settings::source_write_surf_id.empty()) {
444
      s->surf_source_ = true;
445
    }
446

447
    // set BCs
448
    std::string bc_value =
449
      dmd_ptr->get_surface_property("boundary", surf_handle);
450
    to_lower(bc_value);
451
    if (bc_value.empty() || bc_value == "transmit" ||
452
        bc_value == "transmission") {
453
      // set to transmission by default (nullptr)
454
    } else if (bc_value == "vacuum") {
455
      s->bc_ = make_unique<VacuumBC>();
456
    } else if (bc_value == "reflective" || bc_value == "reflect" ||
457
               bc_value == "reflecting") {
458
      s->bc_ = make_unique<ReflectiveBC>();
459
    } else if (bc_value == "periodic") {
460
      fatal_error("Periodic boundary condition not supported in DAGMC.");
461
    } else {
462
      fatal_error(fmt::format("Unknown boundary condition \"{}\" specified "
463
                              "on surface {}",
464
        bc_value, s->id_));
465
    }
466

467
    // graveyard check
468
    moab::Range parent_vols;
469
    rval = dagmc_instance_->moab_instance()->get_parent_meshsets(
470
      surf_handle, parent_vols);
471
    MB_CHK_ERR_CONT(rval);
472

473
    // if this surface belongs to the graveyard
474
    if (graveyard && parent_vols.find(graveyard) != parent_vols.end()) {
475
      // set graveyard surface BC's to vacuum
476
      s->bc_ = make_unique<VacuumBC>();
477
    }
478

479
    // add to global array and map
480

481
    auto in_map = model::surface_map.find(s->id_);
482
    if (in_map == model::surface_map.end()) {
483
      model::surface_map[s->id_] = model::surfaces.size();
484
    } else {
485
      warning(fmt::format("DAGMC Surface IDs: {}", dagmc_ids_for_dim(2)));
486
      fatal_error(fmt::format("Surface ID {} exists in both Universe {} "
487
                              "and the CSG geometry.",
488
        s->id_, this->id_));
489
    }
490

491
    model::surfaces.emplace_back(std::move(s));
492
  } // end surface loop
493
}
494

495
int32_t DAGUniverse::cell_index(moab::EntityHandle vol) const
496
{
497
  // return the index of the volume in the DAGMC instance and then
498
  // adjust by the offset into the model cells for this DAGMC universe
499
  return dagmc_ptr()->index_by_handle(vol) + cell_idx_offset_;
500
}
501

502
int32_t DAGUniverse::surface_index(moab::EntityHandle surf) const
503
{
504
  // return the index of the surface in the DAGMC instance and then
505
  // adjust by the offset into the model cells for this DAGMC universe
506
  return dagmc_ptr()->index_by_handle(surf) + surf_idx_offset_;
507
}
508

509
std::string DAGUniverse::dagmc_ids_for_dim(int dim) const
510
{
511
  // generate a vector of ids
512
  std::vector<int> id_vec;
513
  int n_ents = dagmc_instance_->num_entities(dim);
514
  for (int i = 1; i <= n_ents; i++) {
515
    id_vec.push_back(dagmc_instance_->id_by_index(dim, i));
516
  }
517

518
  // sort the vector of ids
519
  std::sort(id_vec.begin(), id_vec.end());
520

521
  // generate a string representation of the ID range(s)
522
  std::stringstream out;
523

524
  int i = 0;
525
  int start_id = id_vec[0]; // initialize with first ID
526
  int stop_id;
527
  // loop over all cells in the universe
528
  while (i < n_ents) {
529

530
    stop_id = id_vec[i];
531

532
    // if the next ID is not in this contiguous set of IDS,
533
    // figure out how to write the string representing this set
534
    if (id_vec[i + 1] > stop_id + 1) {
535

536
      if (start_id != stop_id) {
537
        // there are several IDs in a row, print condensed version (i.e. 1-10,
538
        // 12-20)
539
        out << start_id << "-" << stop_id;
540
      } else {
541
        // only one ID in this contiguous block (i.e. 3, 5, 7, 9)
542
        out << start_id;
543
      }
544
      // insert a comma as long as we aren't in the last ID set
545
      if (i < n_ents - 1) {
546
        out << ", ";
547
      }
548

549
      // if we are at the end of a set, set the start ID to the first value
550
      // in the next set.
551
      start_id = id_vec[++i];
552
    }
553

554
    i++;
555
  }
556

557
  return out.str();
558
}
559

560
int32_t DAGUniverse::implicit_complement_idx() const
561
{
562
  moab::EntityHandle ic;
563
  moab::ErrorCode rval =
564
    dagmc_instance_->geom_tool()->get_implicit_complement(ic);
565
  MB_CHK_SET_ERR_CONT(rval, "Failed to get implicit complement");
566
  // off-by-one: DAGMC indices start at one
567
  return cell_idx_offset_ + dagmc_instance_->index_by_handle(ic) - 1;
568
}
569

570
bool DAGUniverse::find_cell(GeometryState& p) const
571
{
572
  // if the particle isn't in any of the other DagMC
573
  // cells, place it in the implicit complement
574
  bool found = Universe::find_cell(p);
575
  if (!found && model::universe_map[this->id_] != model::root_universe) {
576
    p.lowest_coord().cell() = implicit_complement_idx();
577
    found = true;
578
  }
579
  return found;
580
}
581

582
void DAGUniverse::to_hdf5(hid_t universes_group) const
583
{
584
  // Create a group for this universe.
585
  auto group = create_group(universes_group, fmt::format("universe {}", id_));
586

587
  // Write the geometry representation type.
588
  write_string(group, "geom_type", "dagmc", false);
589

590
  // Write other properties of the DAGMC Universe
591
  write_string(group, "filename", filename_, false);
592
  write_attribute(
593
    group, "auto_geom_ids", static_cast<int>(adjust_geometry_ids_));
594
  write_attribute(
595
    group, "auto_mat_ids", static_cast<int>(adjust_material_ids_));
596
  write_attribute(group, "length_multiplier", length_multiplier_);
597

598
  close_group(group);
599
}
600

601
bool DAGUniverse::uses_uwuw() const
602
{
603
#ifdef OPENMC_UWUW_ENABLED
604
  return uwuw_ && !uwuw_->material_library.empty();
605
#else
606
  return false;
607
#endif // OPENMC_UWUW_ENABLED
608
}
609

610
std::string DAGUniverse::get_uwuw_materials_xml() const
611
{
612
#ifdef OPENMC_UWUW_ENABLED
613
  if (!uses_uwuw()) {
614
    throw std::runtime_error("This DAGMC Universe does not use UWUW materials");
615
  }
616

617
  std::stringstream ss;
618
  // write header
619
  ss << "<?xml version=\"1.0\"?>\n";
620
  ss << "<materials>\n";
621
  const auto& mat_lib = uwuw_->material_library;
622
  // write materials
623
  for (auto mat : mat_lib) {
624
    ss << mat.second->openmc("atom");
625
  }
626
  // write footer
627
  ss << "</materials>";
628

629
  return ss.str();
630
#else
631
  fatal_error("DAGMC was not configured with UWUW.");
632
#endif // OPENMC_UWUW_ENABLED
633
}
634

635
void DAGUniverse::write_uwuw_materials_xml(const std::string& outfile) const
636
{
637
#ifdef OPENMC_UWUW_ENABLED
638
  if (!uses_uwuw()) {
639
    throw std::runtime_error(
640
      "This DAGMC universe does not use UWUW materials.");
641
  }
642

643
  std::string xml_str = get_uwuw_materials_xml();
644
  // if there is a material library in the file
645
  std::ofstream mats_xml(outfile);
646
  mats_xml << xml_str;
647
  mats_xml.close();
648
#else
649
  fatal_error("DAGMC was not configured with UWUW.");
650
#endif // OPENMC_UWUW_ENABLED
651
}
652

653
void DAGUniverse::legacy_assign_material(
654
  std::string mat_string, std::unique_ptr<DAGCell>& c) const
655
{
656
  bool mat_found_by_name = false;
657
  // attempt to find a material with a matching name
658
  to_lower(mat_string);
659
  for (const auto& m : model::materials) {
660
    std::string m_name = m->name();
661
    to_lower(m_name);
662
    if (mat_string == m_name) {
663
      // assign the material with that name
664
      if (!mat_found_by_name) {
665
        mat_found_by_name = true;
666
        c->material_.push_back(m->id_);
667
        // report error if more than one material is found
668
      } else {
669
        fatal_error(fmt::format(
670
          "More than one material found with name '{}'. Please ensure "
671
          "materials "
672
          "have unique names if using this property to assign materials.",
673
          mat_string));
674
      }
675
    }
676
  }
677

678
  // if no material was set using a name, assign by id
679
  if (!mat_found_by_name) {
680
    bool found_by_id = true;
681
    try {
682
      auto id = std::stoi(mat_string);
683
      if (model::material_map.find(id) == model::material_map.end())
684
        found_by_id = false;
685
      c->material_.emplace_back(id);
686
    } catch (const std::invalid_argument&) {
687
      found_by_id = false;
688
    }
689

690
    // report failure for failed int conversion or missing material
691
    if (!found_by_id)
692
      fatal_error(
693
        fmt::format("Material with name/ID '{}' not found for volume (cell) {}",
694
          mat_string, c->id_));
695
  }
696

697
  if (settings::verbosity >= 10) {
698
    const auto& m = model::materials[model::material_map.at(c->material_[0])];
699
    std::stringstream msg;
700
    msg << "DAGMC material " << mat_string << " was assigned";
701
    if (mat_found_by_name) {
702
      msg << " using material name: " << m->name_;
703
    } else {
704
      msg << " using material id: " << m->id_;
705
    }
706
    write_message(msg.str(), 10);
707
  }
708
}
709

710
void DAGUniverse::read_uwuw_materials()
711
{
712
#ifdef OPENMC_UWUW_ENABLED
713
  // If no filename was provided, don't read UWUW materials
714
  if (filename_ == "")
715
    return;
716

717
  uwuw_ = std::make_shared<UWUW>(filename_.c_str());
718

719
  if (!uses_uwuw())
720
    return;
721

722
  // Notify user if UWUW materials are going to be used
723
  write_message("Found UWUW Materials in the DAGMC geometry file.", 6);
724

725
  // if we're using automatic IDs, update the UWUW material metadata
726
  if (adjust_material_ids_) {
727
    int32_t next_material_id = 0;
728
    for (const auto& m : model::materials) {
729
      next_material_id = std::max(m->id_, next_material_id);
730
    }
731
    next_material_id++;
732

733
    for (auto& mat : uwuw_->material_library) {
734
      mat.second->metadata["mat_number"] = next_material_id++;
735
    }
736
  }
737

738
  std::string mat_xml_string = get_uwuw_materials_xml();
739

740
  // create a pugi XML document from this string
741
  pugi::xml_document doc;
742
  auto result = doc.load_string(mat_xml_string.c_str());
743
  if (!result) {
744
    fatal_error("Error processing XML created using DAGMC UWUW materials.");
745
  }
746
  pugi::xml_node root = doc.document_element();
747
  for (pugi::xml_node material_node : root.children("material")) {
748
    model::materials.push_back(std::make_unique<Material>(material_node));
749
  }
750
#else
751
  fatal_error("DAGMC was not configured with UWUW.");
752
#endif // OPENMC_UWUW_ENABLED
753
}
754

755
void DAGUniverse::uwuw_assign_material(
756
  moab::EntityHandle vol_handle, std::unique_ptr<DAGCell>& c) const
757
{
758
#ifdef OPENMC_UWUW_ENABLED
759
  // lookup material in uwuw if present
760
  std::string uwuw_mat = dmd_ptr->volume_material_property_data_eh[vol_handle];
761
  if (uwuw_->material_library.count(uwuw_mat) != 0) {
762
    // Note: material numbers are set by UWUW
763
    int mat_number = uwuw_->material_library.get_material(uwuw_mat)
764
                       .metadata["mat_number"]
765
                       .asInt();
766
    c->material_.push_back(mat_number);
767
  } else {
768
    fatal_error(fmt::format("Material with value '{}' not found in the "
769
                            "UWUW material library",
770
      uwuw_mat));
771
  }
772
#else
773
  fatal_error("DAGMC was not configured with UWUW.");
774
#endif // OPENMC_UWUW_ENABLED
775
}
776

777
void DAGUniverse::override_assign_material(std::unique_ptr<DAGCell>& c,
778
  const MaterialOverrides& material_overrides) const
779
{
780
  // if Cell ID matches an override key, use it to override the material
781
  // assignment else if UWUW is used, get the material assignment from the DAGMC
782
  // metadata
783
  // Notify User that an override is being applied on a DAGMCCell
784
  write_message(fmt::format("Applying override for DAGMCCell {}", c->id_), 8);
785

786
  const auto& mat_overrides = material_overrides.at(c->id_);
787
  if (settings::verbosity >= 10) {
788
    std::stringstream override_values;
789
    for (size_t i = 0; i < mat_overrides.size(); ++i) {
790
      if (i > 0) {
791
        override_values << " ";
792
      }
793
      if (mat_overrides[i] == MATERIAL_VOID) {
794
        override_values << "void";
795
      } else {
796
        override_values << mat_overrides[i];
797
      }
798
    }
799
    auto msg = fmt::format("Overriding DAGMC cell {} property 'material' "
800
                           "with value(s): {}",
801
      c->id_, override_values.str());
802
    write_message(msg, 10);
803
  }
804

805
  // Override the material assignment for each cell instance using the legacy
806
  // assignement
807
  for (auto mat_id : mat_overrides) {
808
    if (mat_id != MATERIAL_VOID &&
809
        model::material_map.find(mat_id) == model::material_map.end()) {
810
      fatal_error(fmt::format(
811
        "Material with ID '{}' not found for DAGMC cell {}", mat_id, c->id_));
812
    }
813
    c->material_.push_back(mat_id);
814
  }
815
}
816

817
//==============================================================================
818
// DAGMC Cell implementation
819
//==============================================================================
820

821
DAGCell::DAGCell(std::shared_ptr<moab::DagMC> dag_ptr, int32_t dag_idx)
822
  : Cell {}, dagmc_ptr_(dag_ptr), dag_index_(dag_idx) {};
823

824
std::pair<double, int32_t> DAGCell::distance(
825
  Position r, Direction u, int32_t on_surface, GeometryState* p) const
826
{
827
  // if we've changed direction or we're not on a surface,
828
  // reset the history and update last direction
829
  if (u != p->last_dir()) {
830
    p->last_dir() = u;
831
    p->history().reset();
832
  }
833
  if (on_surface == SURFACE_NONE) {
834
    p->history().reset();
835
  }
836

837
  const auto& univ = model::universes[p->lowest_coord().universe()];
838

839
  DAGUniverse* dag_univ = static_cast<DAGUniverse*>(univ.get());
840
  if (!dag_univ)
841
    fatal_error("DAGMC call made for particle in a non-DAGMC universe");
842

843
  // initialize to lost particle conditions
844
  int surf_idx = -1;
845
  double dist = INFINITY;
846

847
  moab::EntityHandle vol = dagmc_ptr_->entity_by_index(3, dag_index_);
848
  moab::EntityHandle hit_surf;
849

850
  // create the ray
851
  double pnt[3] = {r.x, r.y, r.z};
852
  double dir[3] = {u.x, u.y, u.z};
853
  MB_CHK_ERR_CONT(
854
    dagmc_ptr_->ray_fire(vol, pnt, dir, hit_surf, dist, &p->history()));
855
  if (hit_surf != 0) {
856
    surf_idx =
857
      dag_univ->surf_idx_offset_ + dagmc_ptr_->index_by_handle(hit_surf);
858
  } else if (!dagmc_ptr_->is_implicit_complement(vol) ||
859
             is_root_universe(dag_univ->id_)) {
860
    // Surface boundary conditions are ignored for projection plotting, meaning
861
    // that the particle may move through the graveyard (bounding) volume and
862
    // into the implicit complement on the other side where no intersection
863
    // will be found. A no-hit result is also expected when querying root cells
864
    // for the next boundary from undefined space, when no containing cell is
865
    // assigned. In both cases, return an infinite distance and invalid surface
866
    // index rather than marking a particle as lost.
867
    if (settings::run_mode == RunMode::PLOTTING ||
868
        p->lowest_coord().cell() == C_NONE)
869
      return {INFTY, -1};
870

871
    // the particle should be marked as lost immediately if an intersection
872
    // isn't found in a volume that is not the implicit complement. In the case
873
    // that the DAGMC model is the root universe of the geometry, even a missing
874
    // intersection in the implicit complement should trigger this condition.
875
    std::string material_id =
876
      p->material() == MATERIAL_VOID
877
        ? "-1 (VOID)"
878
        : std::to_string(model::materials[p->material()]->id());
879
    p->mark_as_lost(fmt::format(
880
      "No intersection found with DAGMC cell {}, filled with material {}", id_,
881
      material_id));
882
  }
883

884
  return {dist, surf_idx};
885
}
886

887
bool DAGCell::contains(Position r, Direction u, int32_t on_surface) const
888
{
889
  moab::ErrorCode rval;
890
  moab::EntityHandle vol = dagmc_ptr_->entity_by_index(3, dag_index_);
891

892
  int result = 0;
893
  double pnt[3] = {r.x, r.y, r.z};
894
  double dir[3] = {u.x, u.y, u.z};
895
  rval = dagmc_ptr_->point_in_volume(vol, pnt, result, dir);
896
  MB_CHK_ERR_CONT(rval);
897
  return result;
898
}
899

900
moab::EntityHandle DAGCell::mesh_handle() const
901
{
902
  return dagmc_ptr()->entity_by_index(3, dag_index());
903
}
904

905
void DAGCell::to_hdf5_inner(hid_t group_id) const
906
{
907
  write_string(group_id, "geom_type", "dagmc", false);
908
}
909

910
BoundingBox DAGCell::bounding_box() const
911
{
912
  moab::ErrorCode rval;
913
  moab::EntityHandle vol = dagmc_ptr_->entity_by_index(3, dag_index_);
914
  double min[3], max[3];
915
  rval = dagmc_ptr_->getobb(vol, min, max);
916
  MB_CHK_ERR_CONT(rval);
917
  return {{min[0], min[1], min[2]}, {max[0], max[1], max[2]}};
918
}
919

920
//==============================================================================
921
// DAGSurface implementation
922
//==============================================================================
923

924
DAGSurface::DAGSurface(std::shared_ptr<moab::DagMC> dag_ptr, int32_t dag_idx)
925
  : Surface {}, dagmc_ptr_(dag_ptr), dag_index_(dag_idx)
926
{} // empty constructor
927

928
moab::EntityHandle DAGSurface::mesh_handle() const
929
{
930
  return dagmc_ptr()->entity_by_index(2, dag_index());
931
}
932

933
double DAGSurface::evaluate(Position r) const
934
{
935
  return 0.0;
936
}
937

938
double DAGSurface::distance(Position r, Direction u, bool coincident) const
939
{
940
  moab::ErrorCode rval;
941
  moab::EntityHandle surf = dagmc_ptr_->entity_by_index(2, dag_index_);
942
  moab::EntityHandle hit_surf;
943
  double dist;
944
  double pnt[3] = {r.x, r.y, r.z};
945
  double dir[3] = {u.x, u.y, u.z};
946
  rval = dagmc_ptr_->ray_fire(surf, pnt, dir, hit_surf, dist, NULL, 0, 0);
947
  MB_CHK_ERR_CONT(rval);
948
  if (dist < 0.0)
949
    dist = INFTY;
950
  return dist;
951
}
952

953
Direction DAGSurface::normal(Position r) const
954
{
955
  moab::ErrorCode rval;
956
  moab::EntityHandle surf = dagmc_ptr_->entity_by_index(2, dag_index_);
957
  double pnt[3] = {r.x, r.y, r.z};
958
  double dir[3];
959
  rval = dagmc_ptr_->get_angle(surf, pnt, dir);
960
  MB_CHK_ERR_CONT(rval);
961
  return dir;
962
}
963

964
Direction DAGSurface::reflect(Position r, Direction u, GeometryState* p) const
965
{
966
  assert(p);
967
  double pnt[3] = {r.x, r.y, r.z};
968
  double dir[3];
969
  moab::ErrorCode rval =
970
    dagmc_ptr_->get_angle(mesh_handle(), pnt, dir, &p->history());
971
  MB_CHK_ERR_CONT(rval);
972
  return u.reflect(dir);
973
}
974

975
//==============================================================================
976
// Non-member functions
977
//==============================================================================
978

979
void read_dagmc_universes(pugi::xml_node node)
980
{
981
  for (pugi::xml_node dag_node : node.children("dagmc_universe")) {
982
    model::universes.push_back(std::make_unique<DAGUniverse>(dag_node));
983
    model::universe_map[model::universes.back()->id_] =
984
      model::universes.size() - 1;
985
  }
986
}
987

988
void check_dagmc_root_univ()
989
{
990
  const auto& ru = model::universes[model::root_universe];
991
  if (ru->geom_type() == GeometryType::DAG) {
992
    // if the root universe contains DAGMC geometry, warn the user
993
    // if it does not contain a graveyard volume
994
    auto dag_univ = dynamic_cast<DAGUniverse*>(ru.get());
995
    if (dag_univ && !dag_univ->has_graveyard()) {
996
      warning(
997
        "No graveyard volume found in the DagMC model. "
998
        "This may result in lost particles and rapid simulation failure.");
999
    }
1000
  }
1001
}
1002

1003
int32_t next_cell(int32_t surf, int32_t curr_cell, int32_t univ)
1004
{
1005
  auto surfp = dynamic_cast<DAGSurface*>(model::surfaces[surf].get());
1006
  auto cellp = dynamic_cast<DAGCell*>(model::cells[curr_cell].get());
1007
  auto univp = static_cast<DAGUniverse*>(model::universes[univ].get());
1008

1009
  moab::EntityHandle surf_handle = surfp->mesh_handle();
1010
  moab::EntityHandle curr_vol = cellp->mesh_handle();
1011

1012
  moab::EntityHandle new_vol;
1013
  moab::ErrorCode rval =
1014
    cellp->dagmc_ptr()->next_vol(surf_handle, curr_vol, new_vol);
1015
  if (rval != moab::MB_SUCCESS)
1016
    return -1;
1017

1018
  return univp->cell_index(new_vol);
1019
}
1020

1021
extern "C" int openmc_dagmc_universe_get_cell_ids(
1022
  int32_t univ_id, int32_t* ids, size_t* n)
1023
{
1024
  // make sure the universe id is a DAGMC Universe
1025
  const auto& univ = model::universes[model::universe_map[univ_id]];
1026
  if (univ->geom_type() != GeometryType::DAG) {
1027
    set_errmsg(fmt::format("Universe {} is not a DAGMC Universe", univ_id));
1028
    return OPENMC_E_INVALID_TYPE;
1029
  }
1030

1031
  std::vector<int32_t> dag_cell_ids;
1032
  for (const auto& cell_index : univ->cells_) {
1033
    const auto& cell = model::cells[cell_index];
1034
    if (cell->geom_type() == GeometryType::CSG) {
1035
      set_errmsg(fmt::format("Cell {} is not a DAGMC Cell", cell->id_));
1036
      return OPENMC_E_INVALID_TYPE;
1037
    }
1038
    dag_cell_ids.push_back(cell->id_);
1039
  }
1040
  std::copy(dag_cell_ids.begin(), dag_cell_ids.end(), ids);
1041
  *n = dag_cell_ids.size();
1042
  return 0;
1043
}
1044

1045
extern "C" int openmc_dagmc_universe_get_num_cells(int32_t univ_id, size_t* n)
1046
{
1047
  // make sure the universe id is a DAGMC Universe
1048
  const auto& univ = model::universes[model::universe_map[univ_id]];
1049
  if (univ->geom_type() != GeometryType::DAG) {
1050
    set_errmsg(fmt::format("Universe {} is not a DAGMC universe", univ_id));
1051
    return OPENMC_E_INVALID_TYPE;
1052
  }
1053
  *n = univ->cells_.size();
1054
  return 0;
1055
}
1056

1057
} // namespace openmc
1058

1059
#else
1060

1061
namespace openmc {
1062

UNCOV
1063
extern "C" int openmc_dagmc_universe_get_cell_ids(
×
1064
  int32_t univ_id, int32_t* ids, size_t* n)
1065
{
UNCOV
1066
  set_errmsg("OpenMC was not configured with DAGMC");
×
UNCOV
1067
  return OPENMC_E_UNASSIGNED;
×
1068
};
1069

UNCOV
1070
extern "C" int openmc_dagmc_universe_get_num_cells(int32_t univ_id, size_t* n)
×
1071
{
UNCOV
1072
  set_errmsg("OpenMC was not configured with DAGMC");
×
UNCOV
1073
  return OPENMC_E_UNASSIGNED;
×
1074
};
1075

1076
void read_dagmc_universes(pugi::xml_node node)
6,050 ✔
1077
{
1078
  if (check_for_node(node, "dagmc_universe")) {
6,050 !
UNCOV
1079
    fatal_error("DAGMC Universes are present but OpenMC was not configured "
×
1080
                "with DAGMC");
1081
  }
1082
};
6,050 ✔
1083

1084
void check_dagmc_root_univ() {};
6,050 ✔
1085

1086
int32_t next_cell(int32_t surf, int32_t curr_cell, int32_t univ);
1087

1088
} // namespace openmc
1089

1090
#endif // OPENMC_DAGMC_ENABLED
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc