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

openmc-dev / openmc / 43314235397

12 Nov 2026 09:50PM UTC coverage: 82.188% (+0.7%) from 81.44%
43314235397

Pull #3877

github

web-flow
Merge 85d867c33 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 %.

84 of 85 new or added lines in 1 file covered. (98.82%)

2101 existing lines in 43 files now uncovered.

62828 of 72667 relevant lines covered (86.46%)

39889466.57 hits per line

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

66.28
/src/mesh.cpp
1
#include "openmc/mesh.h"
2
#include <algorithm> // for copy, equal, min, min_element
3
#include <cassert>
4
#include <cmath>   // for ceil
5
#include <cstddef> // for size_t
6
#include <cstdint> // for uint64_t
7
#include <cstring> // for memcpy
8
#include <limits>
9
#include <numeric> // for accumulate
10
#include <string>
11

12
#ifdef _MSC_VER
13
#include <intrin.h> // for _InterlockedCompareExchange
14
#endif
15

16
#ifdef OPENMC_MPI
17
#include "mpi.h"
18
#endif
19

20
#include "openmc/tensor.h"
21
#include <fmt/core.h> // for fmt
22

23
#include "openmc/capi.h"
24
#include "openmc/constants.h"
25
#include "openmc/container_util.h"
26
#include "openmc/error.h"
27
#include "openmc/file_utils.h"
28
#include "openmc/geometry.h"
29
#include "openmc/hdf5_interface.h"
30
#include "openmc/material.h"
31
#include "openmc/memory.h"
32
#include "openmc/message_passing.h"
33
#include "openmc/openmp_interface.h"
34
#include "openmc/output.h"
35
#include "openmc/particle_data.h"
36
#include "openmc/plot.h"
37
#include "openmc/random_dist.h"
38
#include "openmc/search.h"
39
#include "openmc/settings.h"
40
#include "openmc/string_utils.h"
41
#include "openmc/tallies/filter.h"
42
#include "openmc/tallies/tally.h"
43
#include "openmc/timer.h"
44
#include "openmc/volume_calc.h"
45
#include "openmc/xml_interface.h"
46

47
#ifdef OPENMC_LIBMESH_ENABLED
48
#include "libmesh/mesh_modification.h"
49
#include "libmesh/mesh_tools.h"
50
#include "libmesh/numeric_vector.h"
51
#include "libmesh/replicated_mesh.h"
52
#endif
53

54
#ifdef OPENMC_DAGMC_ENABLED
55
#include "moab/FileOptions.hpp"
56
#endif
57

58
#include "openmc/xdg.h"
59

60
namespace openmc {
61

62
//==============================================================================
63
// Global variables
64
//==============================================================================
65

66
// Value used to indicate an empty slot in the hash table. We use -2 because
67
// the value -1 is used to indicate a void material.
68
constexpr int32_t EMPTY = -2;
69

70
namespace model {
71

72
std::unordered_map<int32_t, int32_t> mesh_map;
73
vector<unique_ptr<Mesh>> meshes;
74

75
} // namespace model
76

77
#ifdef OPENMC_LIBMESH_ENABLED
78
namespace settings {
79
unique_ptr<libMesh::LibMeshInit> libmesh_init;
80
const libMesh::Parallel::Communicator* libmesh_comm {nullptr};
81
} // namespace settings
82
#endif
83

84
//==============================================================================
85
// Helper functions
86
//==============================================================================
87

88
//! Update an intersection point if the given candidate is closer.
89
//
90
//! The first 6 arguments are coordinates for the starting point of a particle
91
//! and its intersection with a mesh surface.  If the distance between these
92
//! two points is shorter than the given `min_distance`, then the `r` argument
93
//! will be updated to match the intersection point, and `min_distance` will
94
//! also be updated.
95

96
inline bool check_intersection_point(double x1, double x0, double y1, double y0,
97
  double z1, double z0, Position& r, double& min_distance)
98
{
99
  double dist =
100
    std::pow(x1 - x0, 2) + std::pow(y1 - y0, 2) + std::pow(z1 - z0, 2);
101
  if (dist < min_distance) {
102
    r.x = x1;
103
    r.y = y1;
104
    r.z = z1;
105
    min_distance = dist;
106
    return true;
107
  }
108
  return false;
109
}
110

111
//! Atomic compare-and-swap for signed 32-bit integer
112
//
113
//! \param[in,out] ptr Pointer to value to update
114
//! \param[in,out] expected Value to compare to
115
//! \param[in] desired If comparison is successful, value to update to
116
//! \return True if the comparison was successful and the value was updated
117
inline bool atomic_cas_int32(int32_t* ptr, int32_t& expected, int32_t desired)
2,014 ✔
118
{
119
#if defined(__GNUC__) || defined(__clang__)
120
  // For gcc/clang, use the __atomic_compare_exchange_n intrinsic
121
  return __atomic_compare_exchange_n(
2,014 ✔
122
    ptr, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
123

124
#elif defined(_MSC_VER)
125
  // For MSVC, use the _InterlockedCompareExchange intrinsic
126
  int32_t old_val =
127
    _InterlockedCompareExchange(reinterpret_cast<volatile long*>(ptr),
128
      static_cast<long>(desired), static_cast<long>(expected));
129
  return (old_val == expected);
130

131
#else
132
#error "No compare-and-swap implementation available for this compiler."
133
#endif
134
}
135

136
// Helper function equivalent to std::bit_cast in C++20
137
template<typename To, typename From>
138
inline To bit_cast_value(const From& value)
24,703,716 ✔
139
{
140
  To out;
141
  std::memcpy(&out, &value, sizeof(To));
39,240 ✔
142
  return out;
143
}
144

145
inline void atomic_update_double(double* ptr, double value, bool is_min)
24,703,632 ✔
146
{
147
#if defined(__GNUC__) || defined(__clang__)
148
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
24,703,632 ✔
149
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
24,703,632 ✔
150
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
24,703,632 ✔
151
  double current = bit_cast_value<double>(current_bits);
24,703,632 ✔
152
  while (is_min ? (value < current) : (value > current)) {
24,703,716 ✔
153
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
39,240 ✔
154
    uint64_t expected_bits = current_bits;
39,240 ✔
155
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
39,240 ✔
156
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
157
      return;
24,703,632 ✔
158
    }
159
    current_bits = expected_bits;
84 ✔
160
    current = bit_cast_value<double>(current_bits);
84 ✔
161
  }
162

163
#elif defined(_MSC_VER)
164
  auto* bits_ptr = reinterpret_cast<volatile long long*>(ptr);
165
  long long current_bits = *bits_ptr;
166
  double current = bit_cast_value<double>(current_bits);
167
  while (is_min ? (value < current) : (value > current)) {
168
    long long desired_bits = bit_cast_value<long long>(value);
169
    long long old_bits =
170
      _InterlockedCompareExchange64(bits_ptr, desired_bits, current_bits);
171
    if (old_bits == current_bits) {
172
      return;
173
    }
174
    current_bits = old_bits;
175
    current = bit_cast_value<double>(current_bits);
176
  }
177

178
#else
179
#error "No compare-and-swap implementation available for this compiler."
180
#endif
181
}
182

183
inline void atomic_max_double(double* ptr, double value)
12,351,816 ✔
184
{
185
  atomic_update_double(ptr, value, false);
4,117,272 ✔
186
}
4,117,272 ✔
187

188
inline void atomic_min_double(double* ptr, double value)
12,351,816 ✔
189
{
190
  atomic_update_double(ptr, value, true);
4,117,272 ✔
191
}
192

193
namespace detail {
194

195
//==============================================================================
196
// MaterialVolumes implementation
197
//==============================================================================
198

199
void MaterialVolumes::add_volume(
5,990,073 ✔
200
  int index_elem, int index_material, double volume, const BoundingBox* bbox)
201
{
202
  // This method handles adding elements to the materials hash table,
203
  // implementing open addressing with linear probing. Consistency across
204
  // multiple threads is handled by with an atomic compare-and-swap operation.
205
  // Ideally, we would use #pragma omp atomic compare, but it was introduced in
206
  // OpenMP 5.1 and is not widely supported yet.
207

208
  // Loop for linear probing
209
  for (int attempt = 0; attempt < table_size_; ++attempt) {
5,990,073 !
210
    // Determine slot to check, making sure it is positive
211
    int slot = (index_material + attempt) % table_size_;
5,990,073 ✔
212
    if (slot < 0)
5,990,073 ✔
213
      slot += table_size_;
3,870,726 ✔
214
    int32_t* slot_ptr = &this->materials(index_elem, slot);
5,990,073 ✔
215

216
    // Non-atomic read of current material
217
    int32_t current_val = *slot_ptr;
5,990,073 ✔
218

219
    // Found the desired material; accumulate volume and bbox
220
    if (current_val == index_material) {
5,990,073 ✔
221
#pragma omp atomic
2,644,145 ✔
222
      this->volumes(index_elem, slot) += volume;
5,988,059 ✔
223
      if (bbox) {
5,988,059 ✔
224
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
4,116,156 ✔
225
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
4,116,156 ✔
226
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
4,116,156 ✔
227
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
4,116,156 ✔
228
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
4,116,156 ✔
229
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
4,116,156 ✔
230
      }
231
      return;
5,988,059 ✔
232
    }
233

234
    // Slot appears to be empty; attempt to claim
235
    if (current_val == EMPTY) {
2,014 !
236
      // Attempt compare-and-swap from EMPTY to index_material
237
      int32_t expected_val = EMPTY;
2,014 ✔
238
      bool claimed_slot =
2,014 ✔
239
        atomic_cas_int32(slot_ptr, expected_val, index_material);
2,014 ✔
240

241
      // If we claimed the slot or another thread claimed it but the same
242
      // material was inserted, proceed to accumulate
243
      if (claimed_slot || (expected_val == index_material)) {
2,014 !
244
#pragma omp atomic
873 ✔
245
        this->volumes(index_elem, slot) += volume;
2,014 ✔
246
        if (bbox) {
2,014 ✔
247
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
1,116 ✔
248
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
1,116 ✔
249
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
1,116 ✔
250
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
1,116 ✔
251
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
1,116 ✔
252
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
1,116 ✔
253
        }
254
        return;
2,014 ✔
255
      }
256
    }
257
  }
258

259
  // If table is full, set a flag that can be checked later
260
  table_full_ = true;
×
261
}
262

263
void MaterialVolumes::add_volume_unsafe(
×
264
  int index_elem, int index_material, double volume, const BoundingBox* bbox)
265
{
266
  // Linear probe
267
  for (int attempt = 0; attempt < table_size_; ++attempt) {
×
268
    // Determine slot to check, making sure it is positive
269
    int slot = (index_material + attempt) % table_size_;
×
270
    if (slot < 0)
×
271
      slot += table_size_;
×
272

273
    // Read current material
274
    int32_t current_val = this->materials(index_elem, slot);
×
275

276
    // Found the desired material; accumulate volume and bbox
277
    if (current_val == index_material) {
×
278
      this->volumes(index_elem, slot) += volume;
×
279
      if (bbox) {
×
280
        this->bboxes(index_elem, slot, 0) =
×
281
          std::min(this->bboxes(index_elem, slot, 0), bbox->min.x);
×
282
        this->bboxes(index_elem, slot, 1) =
×
283
          std::min(this->bboxes(index_elem, slot, 1), bbox->min.y);
×
284
        this->bboxes(index_elem, slot, 2) =
×
285
          std::min(this->bboxes(index_elem, slot, 2), bbox->min.z);
×
286
        this->bboxes(index_elem, slot, 3) =
×
287
          std::max(this->bboxes(index_elem, slot, 3), bbox->max.x);
×
288
        this->bboxes(index_elem, slot, 4) =
×
289
          std::max(this->bboxes(index_elem, slot, 4), bbox->max.y);
×
290
        this->bboxes(index_elem, slot, 5) =
×
291
          std::max(this->bboxes(index_elem, slot, 5), bbox->max.z);
×
292
      }
293
      return;
×
294
    }
295

296
    // Claim empty slot
297
    if (current_val == EMPTY) {
×
298
      this->materials(index_elem, slot) = index_material;
×
299
      this->volumes(index_elem, slot) += volume;
×
300
      if (bbox) {
×
301
        this->bboxes(index_elem, slot, 0) =
×
302
          std::min(this->bboxes(index_elem, slot, 0), bbox->min.x);
×
303
        this->bboxes(index_elem, slot, 1) =
×
304
          std::min(this->bboxes(index_elem, slot, 1), bbox->min.y);
×
305
        this->bboxes(index_elem, slot, 2) =
×
306
          std::min(this->bboxes(index_elem, slot, 2), bbox->min.z);
×
307
        this->bboxes(index_elem, slot, 3) =
×
308
          std::max(this->bboxes(index_elem, slot, 3), bbox->max.x);
×
309
        this->bboxes(index_elem, slot, 4) =
×
310
          std::max(this->bboxes(index_elem, slot, 4), bbox->max.y);
×
311
        this->bboxes(index_elem, slot, 5) =
×
312
          std::max(this->bboxes(index_elem, slot, 5), bbox->max.z);
×
313
      }
314
      return;
×
315
    }
316
  }
317

318
  // If table is full, set a flag that can be checked later
319
  table_full_ = true;
×
320
}
321

322
} // namespace detail
323

324
//==============================================================================
325
// Mesh implementation
326
//==============================================================================
327

328
std::string read_mesh_type(const pugi::xml_node& node)
2,192 ✔
329
{
330
  std::string mesh_type;
2,192 ✔
331
  if (check_for_node(node, "type")) {
2,192 ✔
332
    mesh_type = get_node_value(node, "type");
583 ✔
333
  } else {
334
    mesh_type = "regular";
1,609 ✔
335
  }
336
  return std::move(mesh_type);
4,384 !
337
}
2,192 ✔
338

339
std::string read_mesh_type(hid_t group)
16 ✔
340
{
341
  std::string mesh_type;
16 ✔
342
  if (object_exists(group, "type")) {
16 !
343
    read_dataset(group, "type", mesh_type);
16 ✔
344
  } else {
345
    mesh_type = "regular";
×
346
  }
347
  return std::move(mesh_type);
32 !
348
}
16 ✔
349

350
template<typename T>
351
const std::unique_ptr<Mesh>& Mesh::create(T dataset)
2,208 ✔
352
{
353
  std::string mesh_type = read_mesh_type(dataset);
2,208 ✔
354
  // Determine mesh type. Add to model vector and map
355
  if (mesh_type == RegularMesh::mesh_type) {
2,208 ✔
356
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
1,666 ✔
357
  } else if (mesh_type == RectilinearMesh::mesh_type) {
542 ✔
358
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
69 ✔
359
  } else if (mesh_type == CylindricalMesh::mesh_type) {
473 ✔
360
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
254 ✔
361
  } else if (mesh_type == SphericalMesh::mesh_type) {
219 !
362
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
219 ✔
UNCOV
363
  } else if (mesh_type == UnstructuredMesh::mesh_type) {
×
UNCOV
364
    model::meshes.push_back(UnstructuredMesh::create(dataset));
×
365
  } else {
366
    fatal_error(fmt::format("Invalid mesh type: {}", mesh_type));
×
367
  }
368

369
  // Map ID to position in vector
370
  model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
2,208 ✔
371

372
  return model::meshes.back();
2,208 ✔
373
}
2,208 ✔
374

375
Mesh::Mesh(pugi::xml_node node)
2,241 ✔
376
{
377
  // Read mesh id
378
  id_ = std::stoi(get_node_value(node, "id"));
4,482 ✔
379
  if (check_for_node(node, "name"))
2,241 ✔
380
    name_ = get_node_value(node, "name");
9 ✔
381
}
2,241 ✔
382

383
Mesh::Mesh(hid_t group)
44 ✔
384
{
385
  // Read mesh ID
386
  read_attribute(group, "id", id_);
44 ✔
387

388
  // Read mesh name
389
  if (object_exists(group, "name")) {
44 !
390
    read_dataset(group, "name", name_);
×
391
  }
392
}
44 ✔
393

394
void Mesh::set_id(int32_t id)
280 ✔
395
{
396
  assert(id >= 0 || id == C_NONE);
280 !
397

398
  // Clear entry in mesh map in case one was already assigned
399
  if (id_ != C_NONE) {
280 ✔
400
    model::mesh_map.erase(id_);
14 ✔
401
    id_ = C_NONE;
14 ✔
402
  }
403

404
  // Ensure no other mesh has the same ID
405
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
280 !
406
    throw std::runtime_error {
×
407
      fmt::format("Two meshes have the same ID: {}", id)};
×
408
  }
409

410
  // If no ID is specified, auto-assign the next ID in the sequence
411
  if (id == C_NONE) {
280 !
UNCOV
412
    id = 0;
×
UNCOV
413
    for (const auto& m : model::meshes) {
×
UNCOV
414
      id = std::max(id, m->id_);
×
415
    }
UNCOV
416
    ++id;
×
417
  }
418

419
  // Update ID and entry in the mesh map
420
  id_ = id;
280 ✔
421

422
  // find the index of this mesh in the model::meshes vector
423
  // (search in reverse because this mesh was likely just added to the vector)
424
  auto it = std::find_if(model::meshes.rbegin(), model::meshes.rend(),
560 ✔
425
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
567 !
426

427
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
280 ✔
428
}
280 ✔
429

430
vector<double> Mesh::volumes() const
241 ✔
431
{
432
  vector<double> volumes(n_bins());
241 ✔
433
  for (int i = 0; i < n_bins(); i++) {
796,509 ✔
434
    volumes[i] = this->volume(i);
796,268 ✔
435
  }
436
  return volumes;
241 ✔
437
}
×
438

439
//! Default (Cartesian) axis labels used for surface bin labels.
440
std::array<const char*, 3> Mesh::axis_labels() const
272,524 ✔
441
{
442
  return {"x", "y", "z"};
272,524 ✔
443
}
444

445
//! Build the surface component of a mesh surface tally bin label.
446
//! surf_index: 0=out/min, 1=in/min, 2=out/max, 3=in/max
447
std::string Mesh::surface_bin_label(int surf_index) const
889,756 ✔
448
{
449
  auto labels = this->axis_labels();
889,756 ✔
450
  int dim = surf_index / 4;
889,756 ✔
451
  int code = surf_index % 4;
889,756 ✔
452
  bool incoming = (code == 1) || (code == 3);
889,756 ✔
453
  bool max = (code == 2) || (code == 3);
889,756 ✔
454
  return fmt::format(" {}, {}-{}", incoming ? "Incoming" : "Outgoing",
889,756 ✔
455
    labels[dim], max ? "max" : "min");
1,779,512 ✔
456
}
457

458
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
×
459
  int32_t* materials, double* volumes) const
460
{
461
  this->material_volumes(nx, ny, nz, table_size, materials, volumes, nullptr);
×
462
}
×
463

464
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
147 ✔
465
  int32_t* materials, double* volumes, double* bboxes) const
466
{
467
  if (mpi::master) {
147 !
468
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
147 ✔
469
  }
470
  write_message(7, "Number of mesh elements = {}", n_bins());
147 ✔
471
  write_message(7, "Number of rays (x) = {}", nx);
147 ✔
472
  write_message(7, "Number of rays (y) = {}", ny);
147 ✔
473
  write_message(7, "Number of rays (z) = {}", nz);
147 ✔
474
  int64_t n_total = static_cast<int64_t>(nx) * ny +
147 ✔
475
                    static_cast<int64_t>(ny) * nz +
147 ✔
476
                    static_cast<int64_t>(nx) * nz;
147 ✔
477
  write_message(7, "Total number of rays = {}", n_total);
147 ✔
478
  write_message(7, "Table size per mesh element = {}", table_size);
147 ✔
479

480
  Timer timer;
147 ✔
481
  timer.start();
147 ✔
482

483
  // Create object for keeping track of materials/volumes
484
  detail::MaterialVolumes result(materials, volumes, bboxes, table_size);
147 ✔
485
  bool compute_bboxes = bboxes != nullptr;
147 ✔
486

487
  // Determine bounding box
488
  auto bbox = this->bounding_box();
147 ✔
489

490
  std::array<int, 3> n_rays = {nx, ny, nz};
147 ✔
491

492
  // Determine effective width of rays
493
  Position width = bbox.max - bbox.min;
147 ✔
494
  width.x = (nx > 0) ? width.x / nx : 0.0;
147 ✔
495
  width.y = (ny > 0) ? width.y / ny : 0.0;
147 ✔
496
  width.z = (nz > 0) ? width.z / nz : 0.0;
147 ✔
497

498
#pragma omp parallel
63 ✔
499
  {
84 ✔
500
    // Preallocate vector for mesh indices and length fractions and particle
501
    vector<int> bins;
84 ✔
502
    vector<double> length_fractions;
84 ✔
503
    Particle p;
84 ✔
504

505
    SourceSite site;
84 ✔
506
    site.E = 1.0;
84 ✔
507
    site.particle = ParticleType::neutron();
84 ✔
508

509
    bool verbose = settings::verbosity >= 10;
84 ✔
510

511
    // Save the cells occupied immediately before a boundary crossing.
512
    auto save_cell_state = [&p]() {
5,543,781 ✔
513
      for (int j = 0; j < p.n_coord(); ++j) {
11,087,562 ✔
514
        p.cell_last(j) = p.coord(j).cell();
5,543,781 ✔
515
      }
516
      p.n_coord_last() = p.n_coord();
5,543,781 ✔
517
    };
5,543,865 ✔
518

519
    // Initialize cell history after locating a ray inside the model.
520
    auto initialize_cell_state = [&p, &save_cell_state]() {
4,264,211 ✔
521
      if (p.cell_born() == C_NONE)
4,264,211 !
522
        p.cell_born() = p.lowest_coord().cell();
4,264,211 ✔
523

524
      save_cell_state();
4,264,211 ✔
525
    };
4,264,295 ✔
526

527
    // Reset a failed coordinate search while preserving position and direction.
528
    auto reset_geometry_state = [&p]() {
113,512 ✔
529
      Position r = p.r();
113,512 ✔
530
      Direction u = p.u();
113,512 ✔
531
      p.init_from_r_u(r, u);
113,512 ✔
532
      p.coord(0).universe() = model::root_universe;
113,512 ✔
533
    };
113,596 ✔
534

535
    for (int axis = 0; axis < 3; ++axis) {
336 ✔
536
      // Set starting position and direction
537
      site.r = {0.0, 0.0, 0.0};
252 ✔
538
      site.r[axis] = bbox.min[axis];
252 ✔
539
      site.u = {0.0, 0.0, 0.0};
252 ✔
540
      site.u[axis] = 1.0;
252 ✔
541

542
      // Determine width of rays and number of rays in other directions
543
      int ax1 = (axis + 1) % 3;
252 ✔
544
      int ax2 = (axis + 2) % 3;
252 ✔
545
      double min1 = bbox.min[ax1];
252 ✔
546
      double min2 = bbox.min[ax2];
252 ✔
547
      double d1 = width[ax1];
252 ✔
548
      double d2 = width[ax2];
252 ✔
549
      int n1 = n_rays[ax1];
252 ✔
550
      int n2 = n_rays[ax2];
252 ✔
551
      if (n1 == 0 || n2 == 0) {
252 ✔
552
        continue;
48 ✔
553
      }
554

555
      // Divide rays in first direction over MPI processes by computing starting
556
      // and ending indices
557
      int min_work = n1 / mpi::n_procs;
204 ✔
558
      int remainder = n1 % mpi::n_procs;
204 ✔
559
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
204 !
560
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
204 !
561
      int i1_end = i1_start + n1_local;
204 ✔
562

563
      // Add the contribution from a ray segment. The positions used here are
564
      // kept separate from the particle position because the latter is moved a
565
      // tiny distance across each surface for robust geometry searches.
566
      auto add_segment = [&](const Position& r0, const Position& r1,
5,633,563 ✔
567
                           int i_material) {
568
        double distance = r1[axis] - r0[axis];
5,633,563 ✔
569
        if (distance <= 0.0)
5,633,563 !
570
          return;
571

572
        bins.clear();
5,633,563 ✔
573
        length_fractions.clear();
5,633,563 ✔
574
        this->bins_crossed(r0, r1, site.u, bins, length_fractions);
22,102,651 ✔
575

576
        double cumulative_frac = 0.0;
5,633,563 ✔
577
        for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
11,623,636 ✔
578
          int mesh_index = bins[i_bin];
5,990,073 ✔
579
          double length = distance * length_fractions[i_bin];
5,990,073 ✔
580
          double volume = length * d1 * d2;
22,459,161 ✔
581

582
          if (compute_bboxes) {
5,990,073 ✔
583
            double axis_start = r0[axis] + distance * cumulative_frac;
4,117,272 ✔
584
            double axis_end = axis_start + length;
4,117,272 ✔
585
            cumulative_frac += length_fractions[i_bin];
4,117,272 ✔
586

587
            Position contrib_min = site.r;
4,117,272 ✔
588
            Position contrib_max = site.r;
4,117,272 ✔
589

590
            contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
4,117,272 ✔
591
            contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
4,117,272 ✔
592
            contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
4,117,272 ✔
593
            contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
4,117,272 ✔
594
            contrib_min[axis] = std::min(axis_start, axis_end);
4,117,272 !
595
            contrib_max[axis] = std::max(axis_start, axis_end);
8,234,544 !
596

597
            BoundingBox contrib_bbox {contrib_min, contrib_max};
4,117,272 ✔
598
            contrib_bbox &= bbox;
4,117,272 ✔
599

600
            result.add_volume(mesh_index, i_material, volume, &contrib_bbox);
4,117,272 ✔
601
          } else {
602
            result.add_volume(mesh_index, i_material, volume);
1,872,801 ✔
603
          }
604
        }
605
      };
204 ✔
606

607
      // Loop over rays on face of bounding box
608
#pragma omp for collapse(2)
609
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
14,584 ✔
610
        for (int i2 = 0; i2 < n2; ++i2) {
2,474,256 ✔
611
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
2,459,876 ✔
612
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
2,459,876 ✔
613

614
          p.from_source(&site);
2,459,876 ✔
615

616
          // Set the physical endpoint of this ray at the far mesh face.
617
          Position r_mesh_end = site.r;
2,459,876 ✔
618
          r_mesh_end[axis] = bbox.max[axis];
2,459,876 ✔
619

620
          // Determine particle's location
621
          bool inside_model = exhaustive_find_cell(p, verbose);
2,459,876 ✔
622

623
          if (inside_model) {
2,459,876 ✔
624
            initialize_cell_state();
2,423,132 ✔
625
          } else {
626
            // Clear any partial descent into nested universes before searching
627
            // for the first root-universe boundary from undefined space.
628
            reset_geometry_state();
36,744 ✔
629
          }
630

631
          // Physical position through which volume has been accumulated. This
632
          // differs by TINY_BIT from p.r() after crossing a surface.
633
          Position r_scored = site.r;
2,459,876 ✔
634

635
          while (r_scored[axis] < r_mesh_end[axis]) {
3,225,604 !
636
            if (!inside_model) {
3,225,604 ✔
637
              // The ray is outside the model. Advance to the next surface of
638
              // any cell in the root universe, as is done for ray-traced
639
              // plots. Undefined space traversed along the way is void.
640
              Position r0 = p.r();
64,864 ✔
641
              p.advance_to_boundary_from_void();
64,864 ✔
642

643
              // If no model surface lies before the mesh edge, score the
644
              // remaining exterior interval as void and finish the ray.
645
              double distance_to_mesh_end = r_mesh_end[axis] - r0[axis];
64,864 ✔
646
              if (p.boundary().surface() == SURFACE_NONE ||
64,864 ✔
647
                  p.boundary().distance() >= distance_to_mesh_end) {
28,120 !
648
                add_segment(r_scored, r_mesh_end, MATERIAL_VOID);
36,744 ✔
649
                break;
36,744 ✔
650
              }
651

652
              // Determine the physical position of the model boundary.
653
              Position r_boundary = r0 + p.boundary().distance() * p.u();
28,120 ✔
654

655
              // Score the exterior interval and record its physical endpoint.
656
              add_segment(r_scored, r_boundary, MATERIAL_VOID);
28,120 ✔
657
              r_scored = r_boundary;
28,120 ✔
658

659
              // Check whether advancing through the surface entered the model.
660
              inside_model = exhaustive_find_cell(p, verbose);
28,120 ✔
661
              if (inside_model) {
28,120 ✔
662
                initialize_cell_state();
13,560 ✔
663
              } else {
664
                // Clear any partial coordinate search before looking for the
665
                // next surface from undefined space.
666
                reset_geometry_state();
14,560 ✔
667
              }
668
              continue;
28,120 ✔
669
            }
28,120 ✔
670

671
            // Find the distance to the nearest boundary
672
            BoundaryInfo boundary = distance_to_boundary(p);
3,160,740 ✔
673

674
            // Convert the material index to a user-facing ID
675
            int i_material = p.material();
3,160,740 ✔
676
            if (i_material != C_NONE) {
3,160,740 ✔
677
              i_material = model::materials[i_material]->id();
1,028,868 ✔
678
            }
679

680
            // If no model boundary lies before the mesh edge, score the
681
            // remaining material interval and finish the ray.
682
            double distance_to_mesh_end = r_mesh_end[axis] - p.r()[axis];
3,160,740 ✔
683
            if (boundary.distance() >= distance_to_mesh_end) {
3,160,740 ✔
684
              add_segment(r_scored, r_mesh_end, i_material);
2,423,132 ✔
685
              break;
686
            }
687

688
            // Determine the physical position of the model boundary.
689
            Position r_boundary = p.r() + boundary.distance() * p.u();
737,608 ✔
690

691
            // Score the material interval and record its physical endpoint.
692
            add_segment(r_scored, r_boundary, i_material);
737,608 ✔
693
            r_scored = r_boundary;
737,608 ✔
694

695
            // Cross the next geometric surface. The small forward movement
696
            // and neighbor-list search mirror Ray::trace, allowing a failed
697
            // search to mean that the ray has left the model rather than that
698
            // a transport particle has been lost.
699
            save_cell_state();
737,608 ✔
700

701
            // Move just beyond the surface to make the next search robust.
702
            p.move_distance(boundary.distance() + TINY_BIT);
737,608 ✔
703

704
            // Set surface that particle is on and adjust coordinate levels
705
            p.surface() = boundary.surface();
737,608 ✔
706
            p.n_coord() = boundary.coord_level();
737,608 ✔
707

708
            // Update the geometry state according to the boundary type.
709
            if (boundary.lattice_translation()[0] != 0 ||
737,608 !
710
                boundary.lattice_translation()[1] != 0 ||
737,608 !
711
                boundary.lattice_translation()[2] != 0) {
737,608 !
712
              // Particle crosses lattice boundary
713
              cross_lattice(p, boundary, verbose);
×
714
              inside_model = true;
715
            } else {
716
              // Search for the cell on the opposite side of a surface.
717
              inside_model = neighbor_list_find_cell(p, verbose);
737,608 ✔
718
            }
719

720
            // Treat a failed cell search as a transition to exterior void.
721
            if (!inside_model) {
737,608 ✔
722
              // Reset the geometry state so the next iteration can search for
723
              // another disjoint portion of the model.
724
              reset_geometry_state();
13,560 ✔
725
            }
726
          }
727
        }
728
      }
729
    }
730
  }
84 ✔
731

732
  // Check for errors
733
  if (result.table_full()) {
147 !
734
    throw std::runtime_error("Maximum number of materials for mesh material "
×
735
                             "volume calculation insufficient.");
×
736
  }
737

738
  // Compute time for raytracing
739
  double t_raytrace = timer.elapsed();
147 ✔
740

741
#ifdef OPENMC_MPI
742
  // Combine results from multiple MPI processes
743
  if (mpi::n_procs > 1) {
42 !
744
    int total = this->n_bins() * table_size;
745
    int total_bbox = total * 6;
746
    if (mpi::master) {
×
747
      // Allocate temporary buffer for receiving data
748
      vector<int32_t> mats(total);
749
      vector<double> vols(total);
×
750
      vector<double> recv_bboxes;
×
751
      if (compute_bboxes) {
×
752
        recv_bboxes.resize(total_bbox);
×
753
      }
754

755
      for (int i = 1; i < mpi::n_procs; ++i) {
×
756
        // Receive material indices and volumes from process i
757
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
758
          MPI_STATUS_IGNORE);
759
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
760
          MPI_STATUS_IGNORE);
761
        if (compute_bboxes) {
×
762
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
763
            mpi::intracomm, MPI_STATUS_IGNORE);
764
        }
765

766
        // Combine with existing results; we can call thread unsafe version of
767
        // add_volume because each thread is operating on a different element
768
#pragma omp for
769
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
770
          for (int k = 0; k < table_size; ++k) {
×
771
            int index = index_elem * table_size + k;
772
            if (mats[index] != EMPTY) {
×
773
              if (compute_bboxes) {
×
774
                int bbox_index = index * 6;
775
                BoundingBox slot_bbox {
776
                  {recv_bboxes[bbox_index + 0], recv_bboxes[bbox_index + 1],
×
777
                    recv_bboxes[bbox_index + 2]},
778
                  {recv_bboxes[bbox_index + 3], recv_bboxes[bbox_index + 4],
×
779
                    recv_bboxes[bbox_index + 5]}};
×
780
                result.add_volume_unsafe(
781
                  index_elem, mats[index], vols[index], &slot_bbox);
×
782
              } else {
783
                result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
784
              }
785
            }
786
          }
787
        }
788
      }
789
    } else {
790
      // Send material indices and volumes to process 0
791
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
792
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
793
      if (compute_bboxes) {
×
794
        MPI_Send(bboxes, total_bbox, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
795
      }
796
    }
797
  }
798

799
  // Report time for MPI communication
800
  double t_mpi = timer.elapsed() - t_raytrace;
42 ✔
801
#else
802
  double t_mpi = 0.0;
105 ✔
803
#endif
804

805
  // Normalize based on known volumes of elements
806
  for (int i = 0; i < this->n_bins(); ++i) {
1,631 ✔
807
    // Estimated total volume in element i
808
    double volume = 0.0;
809
    for (int j = 0; j < table_size; ++j) {
9,856 ✔
810
      volume += result.volumes(i, j);
8,372 ✔
811
    }
812
    // Renormalize volumes based on known volume of element i
813
    double norm = this->volume(i) / volume;
1,484 ✔
814
    for (int j = 0; j < table_size; ++j) {
9,856 ✔
815
      result.volumes(i, j) *= norm;
8,372 ✔
816
    }
817
  }
818

819
  // Get total time and normalization time
820
  timer.stop();
147 ✔
821
  double t_total = timer.elapsed();
147 ✔
822
  double t_norm = t_total - t_raytrace - t_mpi;
147 ✔
823

824
  // Show timing statistics
825
  if (settings::verbosity < 7 || !mpi::master)
147 !
826
    return;
35 ✔
827
  header("Timing Statistics", 7);
112 ✔
828
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
112 ✔
829
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
112 ✔
830
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
112 ✔
831
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
112 ✔
832
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
224 ✔
833
    n_total / t_raytrace);
112 ✔
834
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
176 ✔
835
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
112 ✔
836
  std::fflush(stdout);
112 ✔
837
}
838

839
void Mesh::to_hdf5(hid_t group) const
2,240 ✔
840
{
841
  // Create group for mesh
842
  std::string group_name = fmt::format("mesh {}", id_);
2,240 ✔
843
  hid_t mesh_group = create_group(group, group_name.c_str());
2,240 ✔
844

845
  // Write mesh type
846
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,240 ✔
847

848
  // Write mesh ID
849
  write_attribute(mesh_group, "id", id_);
2,240 ✔
850

851
  // Write mesh name
852
  write_dataset(mesh_group, "name", name_);
2,240 ✔
853

854
  // Write mesh data
855
  this->to_hdf5_inner(mesh_group);
2,240 ✔
856

857
  // Close group
858
  close_group(mesh_group);
2,240 ✔
859
}
2,240 ✔
860

861
//==============================================================================
862
// Structured Mesh implementation
863
//==============================================================================
864

865
std::string StructuredMesh::bin_label(int bin) const
3,381,560 ✔
866
{
867
  MeshIndex ijk = get_indices_from_bin(bin);
3,381,560 ✔
868

869
  if (n_dimension_ > 2) {
3,381,560 ✔
870
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
3,370,913 ✔
871
  } else if (n_dimension_ > 1) {
10,647 ✔
872
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
10,416 ✔
873
  } else {
874
    return fmt::format("Mesh Index ({})", ijk[0]);
231 ✔
875
  }
876
}
877

878
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,079 ✔
879
{
880
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,079 ✔
881
}
882

883
Position StructuredMesh::sample_element(
915,236 ✔
884
  const MeshIndex& ijk, uint64_t* seed) const
885
{
886
  // lookup the lower/upper bounds for the mesh element
887
  double x_min = negative_grid_boundary(ijk, 0);
915,236 ✔
888
  double x_max = positive_grid_boundary(ijk, 0);
915,236 ✔
889

890
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
915,236 !
891
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
915,236 !
892

893
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
915,236 !
894
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
915,236 !
895

896
  return {x_min + (x_max - x_min) * prn(seed),
915,236 ✔
897
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
915,236 ✔
898
}
899

900
//==============================================================================
901
// Unstructured Mesh implementation
902
//==============================================================================
903

UNCOV
904
std::string read_mesh_interface(const pugi::xml_node& node)
×
905
{
UNCOV
906
  std::string mesh_interface;
×
UNCOV
907
  if (check_for_node(node, "interface")) {
×
UNCOV
908
    mesh_interface = get_node_value(node, "interface");
×
909
  } else {
UNCOV
910
    mesh_interface = "native";
×
911
  }
UNCOV
912
  return std::move(mesh_interface);
×
UNCOV
913
}
×
914

915
std::string read_mesh_interface(hid_t group)
×
916
{
917
  std::string mesh_interface;
×
918
  if (object_exists(group, "interface")) {
×
919
    read_dataset(group, "interface", mesh_interface);
×
920
  } else {
921
    mesh_interface = "native";
×
922
  }
923
  return std::move(mesh_interface);
×
924
}
×
925

UNCOV
926
std::string read_mesh_library(const pugi::xml_node& node)
×
927
{
UNCOV
928
  std::string mesh_library;
×
UNCOV
929
  if (check_for_node(node, "library")) {
×
UNCOV
930
    mesh_library = get_node_value(node, "library");
×
931
  } else {
932
    mesh_library = "moab";
×
933
  }
UNCOV
934
  return std::move(mesh_library);
×
UNCOV
935
}
×
936

937
std::string read_mesh_library(hid_t group)
×
938
{
939
  std::string mesh_library;
×
940
  if (object_exists(group, "library")) {
×
941
    read_dataset(group, "library", mesh_library);
×
942
  } else {
943
    mesh_library = "moab";
×
944
  }
945
  return std::move(mesh_library);
×
946
}
×
947

948
template<typename T>
UNCOV
949
std::unique_ptr<UnstructuredMesh> UnstructuredMesh::create(T dataset)
×
950
{
UNCOV
951
  std::string mesh_interface = read_mesh_interface(dataset);
×
UNCOV
952
  std::string mesh_library = read_mesh_library(dataset);
×
953

UNCOV
954
  if (mesh_interface == "xdg") {
×
955
#ifdef OPENMC_XDG_ENABLED
956
    return make_unique<XDGMesh>(dataset);
957
#else
UNCOV
958
    fatal_error(fmt::format(
×
959
      "XDG unstructured mesh interface with library '{}' is not enabled in "
960
      "this build of OpenMC.",
961
      mesh_library));
962
#endif
963
  }
964

UNCOV
965
  if (mesh_interface != "native") {
×
966
    fatal_error(fmt::format(
×
967
      "Unrecognized unstructured mesh interface '{}'.", mesh_interface));
968
  }
969

970
#ifdef OPENMC_DAGMC_ENABLED
971
  if (mesh_library == MOABMesh::mesh_lib_type) {
972
    return make_unique<MOABMesh>(dataset);
973
  }
974
#endif
975

976
#ifdef OPENMC_LIBMESH_ENABLED
977
  if (mesh_library == LibMesh::mesh_lib_type) {
978
    return make_unique<LibMesh>(dataset);
979
  }
980
#endif
981

982
  fatal_error(fmt::format("Native unstructured mesh library '{}' is not "
×
983
                          "enabled in this build of OpenMC.",
984
    mesh_library));
UNCOV
985
}
×
986

UNCOV
987
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
×
988
{
UNCOV
989
  n_dimension_ = 3;
×
990

991
  // check if a length unit multiplier was specified
UNCOV
992
  if (check_for_node(node, "length_multiplier")) {
×
993
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
994
  }
995

996
  // get the filename of the unstructured mesh to load
UNCOV
997
  if (check_for_node(node, "filename")) {
×
UNCOV
998
    filename_ = get_node_value(node, "filename");
×
UNCOV
999
    if (!file_exists(filename_)) {
×
1000
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
1001
    }
1002
  } else {
1003
    fatal_error(fmt::format(
×
1004
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
1005
  }
1006

UNCOV
1007
  if (check_for_node(node, "options")) {
×
UNCOV
1008
    options_ = get_node_value(node, "options");
×
1009
  }
1010

1011
  // check if mesh tally data should be written with
1012
  // statepoint files
UNCOV
1013
  if (check_for_node(node, "output")) {
×
1014
    output_ = get_node_value_bool(node, "output");
×
1015
  }
UNCOV
1016
}
×
1017

1018
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
1019
{
1020
  n_dimension_ = 3;
×
1021

1022
  // check the mesh type
1023
  if (object_exists(group, "type")) {
×
1024
    std::string temp;
×
1025
    read_dataset(group, "type", temp);
×
1026
    if (temp != mesh_type) {
×
1027
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
1028
    }
1029
  }
×
1030

1031
  // check if a length unit multiplier was specified
1032
  if (object_exists(group, "length_multiplier")) {
×
1033
    read_dataset(group, "length_multiplier", length_multiplier_);
×
1034
  }
1035

1036
  // get the filename of the unstructured mesh to load
1037
  if (object_exists(group, "filename")) {
×
1038
    read_dataset(group, "filename", filename_);
×
1039
    if (!file_exists(filename_)) {
×
1040
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
1041
    }
1042
  } else {
1043
    fatal_error(fmt::format(
×
1044
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
1045
  }
1046

1047
  if (attribute_exists(group, "options")) {
×
1048
    read_attribute(group, "options", options_);
×
1049
  }
1050

1051
  // check if mesh tally data should be written with
1052
  // statepoint files
1053
  if (attribute_exists(group, "output")) {
×
1054
    read_attribute(group, "output", output_);
×
1055
  }
1056
}
×
1057

UNCOV
1058
void UnstructuredMesh::determine_bounds()
×
1059
{
UNCOV
1060
  double xmin = INFTY;
×
UNCOV
1061
  double ymin = INFTY;
×
UNCOV
1062
  double zmin = INFTY;
×
UNCOV
1063
  double xmax = -INFTY;
×
UNCOV
1064
  double ymax = -INFTY;
×
UNCOV
1065
  double zmax = -INFTY;
×
UNCOV
1066
  int n = this->n_vertices();
×
UNCOV
1067
  for (int i = 0; i < n; ++i) {
×
UNCOV
1068
    auto v = this->vertex(i);
×
UNCOV
1069
    xmin = std::min(v.x, xmin);
×
UNCOV
1070
    ymin = std::min(v.y, ymin);
×
UNCOV
1071
    zmin = std::min(v.z, zmin);
×
UNCOV
1072
    xmax = std::max(v.x, xmax);
×
UNCOV
1073
    ymax = std::max(v.y, ymax);
×
UNCOV
1074
    zmax = std::max(v.z, zmax);
×
1075
  }
UNCOV
1076
  lower_left_ = {xmin, ymin, zmin};
×
UNCOV
1077
  upper_right_ = {xmax, ymax, zmax};
×
UNCOV
1078
}
×
1079

1080
const std::string UnstructuredMesh::mesh_type = "unstructured";
1081

UNCOV
1082
std::string UnstructuredMesh::get_mesh_type() const
×
1083
{
UNCOV
1084
  return mesh_type;
×
1085
}
1086

1087
void UnstructuredMesh::surface_bins_crossed(
×
1088
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1089
{
1090
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
1091
}
1092

UNCOV
1093
std::string UnstructuredMesh::bin_label(int bin) const
×
1094
{
UNCOV
1095
  return fmt::format("Mesh Index ({})", bin);
×
1096
};
1097

UNCOV
1098
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
×
1099
{
UNCOV
1100
  write_dataset(mesh_group, "filename", filename_);
×
UNCOV
1101
  write_dataset(mesh_group, "library", this->library());
×
UNCOV
1102
  if (interface_ != "native") {
×
UNCOV
1103
    write_dataset(mesh_group, "interface", interface_);
×
1104
  }
UNCOV
1105
  if (!options_.empty()) {
×
UNCOV
1106
    write_attribute(mesh_group, "options", options_);
×
1107
  }
1108

UNCOV
1109
  if (length_multiplier_ > 0.0)
×
UNCOV
1110
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
1111

1112
  // write vertex coordinates
UNCOV
1113
  tensor::Tensor<double> vertices(
×
UNCOV
1114
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
×
UNCOV
1115
  for (int i = 0; i < this->n_vertices(); i++) {
×
UNCOV
1116
    auto v = this->vertex(i);
×
UNCOV
1117
    vertices.slice(i) = {v.x, v.y, v.z};
×
1118
  }
UNCOV
1119
  write_dataset(mesh_group, "vertices", vertices);
×
1120

UNCOV
1121
  int num_elem_skipped = 0;
×
1122

1123
  // write element types and connectivity
UNCOV
1124
  vector<double> volumes;
×
UNCOV
1125
  tensor::Tensor<int> connectivity(
×
UNCOV
1126
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
×
UNCOV
1127
  tensor::Tensor<int> elem_types(
×
UNCOV
1128
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
×
UNCOV
1129
  for (int i = 0; i < this->n_bins(); i++) {
×
UNCOV
1130
    auto conn = this->connectivity(i);
×
1131

UNCOV
1132
    volumes.emplace_back(this->volume(i));
×
1133

1134
    // write linear tet element
UNCOV
1135
    if (conn.size() == 4) {
×
UNCOV
1136
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
×
UNCOV
1137
      connectivity.slice(i) = {
×
UNCOV
1138
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
×
1139
      // write linear hex element
UNCOV
1140
    } else if (conn.size() == 8) {
×
UNCOV
1141
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
×
UNCOV
1142
      connectivity.slice(i) = {
×
UNCOV
1143
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
×
1144
    } else {
1145
      num_elem_skipped++;
×
1146
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
1147
      connectivity.slice(i) = -1;
×
1148
    }
UNCOV
1149
  }
×
1150
  // warn users that some elements were skipped
UNCOV
1151
  if (num_elem_skipped > 0) {
×
1152
    warning(fmt::format("The connectivity of {} elements "
×
1153
                        "on mesh {} were not written "
1154
                        "because they are not of type linear tet/hex.",
1155
      num_elem_skipped, this->id_));
×
1156
  }
1157

UNCOV
1158
  write_dataset(mesh_group, "volumes", volumes);
×
UNCOV
1159
  write_dataset(mesh_group, "connectivity", connectivity);
×
UNCOV
1160
  write_dataset(mesh_group, "element_types", elem_types);
×
UNCOV
1161
}
×
1162

UNCOV
1163
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
×
1164
{
UNCOV
1165
  length_multiplier_ = length_multiplier;
×
UNCOV
1166
}
×
1167

UNCOV
1168
ElementType UnstructuredMesh::element_type(int bin) const
×
1169
{
UNCOV
1170
  auto conn = connectivity(bin);
×
1171

UNCOV
1172
  if (conn.size() == 4)
×
1173
    return ElementType::LINEAR_TET;
1174
  else if (conn.size() == 8)
×
1175
    return ElementType::LINEAR_HEX;
1176
  else
1177
    return ElementType::UNSUPPORTED;
×
UNCOV
1178
}
×
1179

1180
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,175,178,015 ✔
1181
  Position r, bool& in_mesh) const
1182
{
1183
  MeshIndex ijk;
1,175,178,015 ✔
1184
  in_mesh = true;
1,175,178,015 ✔
1185
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647 ✔
1186
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647 ✔
1187

1188
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647 ✔
1189
      in_mesh = false;
63,486,402 ✔
1190
  }
1191
  return ijk;
1,175,178,015 ✔
1192
}
1193

1194
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,633,048,086 ✔
1195
{
1196
  switch (n_dimension_) {
1,633,048,086 !
1197
  case 1:
524,734 ✔
1198
    return ijk[0] - 1;
524,734 ✔
1199
  case 2:
119,598,821 ✔
1200
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
119,598,821 ✔
1201
  case 3:
1,512,924,531 ✔
1202
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,512,924,531 ✔
1203
  default:
×
1204
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1205
  }
1206
}
1207

1208
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
5,152,088 ✔
1209
{
1210
  MeshIndex ijk;
5,152,088 ✔
1211
  if (n_dimension_ == 1) {
5,152,088 ✔
1212
    ijk[0] = bin + 1;
231 ✔
1213
  } else if (n_dimension_ == 2) {
5,151,857 ✔
1214
    ijk[0] = bin % shape_[0] + 1;
10,416 ✔
1215
    ijk[1] = bin / shape_[0] + 1;
10,416 ✔
1216
  } else if (n_dimension_ == 3) {
5,141,441 !
1217
    ijk[0] = bin % shape_[0] + 1;
5,141,441 ✔
1218
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
5,141,441 ✔
1219
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
5,141,441 ✔
1220
  }
1221
  return ijk;
5,152,088 ✔
1222
}
1223

1224
int StructuredMesh::get_bin(Position r) const
387,607,216 ✔
1225
{
1226
  // Determine indices
1227
  bool in_mesh;
387,607,216 ✔
1228
  MeshIndex ijk = get_indices(r, in_mesh);
387,607,216 ✔
1229
  if (!in_mesh)
387,607,216 ✔
1230
    return -1;
1231

1232
  // Convert indices to bin
1233
  return get_bin_from_indices(ijk);
375,117,662 ✔
1234
}
1235

1236
int StructuredMesh::n_bins() const
807,641 ✔
1237
{
1238
  // Bin indices are stored as 32-bit ints in the tally system.
1239
  int64_t n = 1;
807,641 ✔
1240
  for (int i = 0; i < n_dimension_; ++i)
3,230,231 ✔
1241
    n *= shape_[i];
2,422,590 ✔
1242
  if (n > std::numeric_limits<int>::max()) {
807,641 !
1243
    fatal_error(fmt::format(
×
1244
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1245
  }
1246
  return static_cast<int>(n);
807,641 ✔
1247
}
1248

1249
int StructuredMesh::n_surface_bins() const
272 ✔
1250
{
1251
  // Surface bin indices are stored as 32-bit ints in the tally system.
1252
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
272 ✔
1253
  if (n > std::numeric_limits<int>::max()) {
272 !
1254
    fatal_error(fmt::format(
×
1255
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1256
  }
1257
  return static_cast<int>(n);
272 ✔
1258
}
1259

1260
tensor::Tensor<double> StructuredMesh::count_sites(
×
1261
  const SourceSite* bank, int64_t length, bool* outside) const
1262
{
1263
  // Determine shape of array for counts
1264
  std::size_t m = this->n_bins();
×
1265
  vector<std::size_t> shape = {m};
×
1266

1267
  // Create array of zeros
1268
  auto cnt = tensor::zeros<double>(shape);
×
1269
  bool outside_ = false;
1270

1271
  for (int64_t i = 0; i < length; i++) {
×
1272
    const auto& site = bank[i];
×
1273

1274
    // determine scoring bin for entropy mesh
1275
    int mesh_bin = get_bin(site.r);
×
1276

1277
    // if outside mesh, skip particle
1278
    if (mesh_bin < 0) {
×
1279
      outside_ = true;
×
1280
      continue;
×
1281
    }
1282

1283
    // Add to appropriate bin
1284
    cnt(mesh_bin) += site.wgt;
×
1285
  }
1286

1287
  // Create reduced count data
1288
  auto counts = tensor::zeros<double>(shape);
×
1289
  int total = cnt.size();
×
1290

1291
#ifdef OPENMC_MPI
1292
  // collect values from all processors
1293
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
×
1294

1295
  // Check if there were sites outside the mesh for any processor
1296
  if (outside) {
×
1297
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1298
  }
1299
#else
1300
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1301
  if (outside)
×
1302
    *outside = outside_;
1303
#endif
1304

1305
  return counts;
×
1306
}
×
1307

1308
// raytrace through the mesh. The template class T will do the tallying.
1309
// A modern optimizing compiler can recognize the noop method of T and
1310
// eliminate that call entirely.
1311
template<class T>
1312
void StructuredMesh::raytrace_mesh(
783,243,574 ✔
1313
  Position r0, Position r1, const Direction& u, T tally) const
1314
{
1315
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1316
  // enable/disable tally calls for now, T template type needs to provide both
1317
  // surface and track methods, which might be empty. modern optimizing
1318
  // compilers will (hopefully) eliminate the complete code (including
1319
  // calculation of parameters) but for the future: be explicit
1320

1321
  // Compute the length of the entire track.
1322
  double total_distance = (r1 - r0).norm();
783,243,574 ✔
1323
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
783,243,574 ✔
1324
    return;
1325

1326
  // keep a copy of the original global position to pass to get_indices,
1327
  // which performs its own transformation to local coordinates
1328
  Position global_r = r0;
783,238,233 ✔
1329
  Position local_r = local_coords(r0);
783,238,233 ✔
1330

1331
  const int n = n_dimension_;
783,238,233 ✔
1332

1333
  // Flag if position is inside the mesh
1334
  bool in_mesh;
1335

1336
  // Position is r = r0 + u * traveled_distance, start at r0
1337
  double traveled_distance {0.0};
783,238,233 ✔
1338

1339
  // Calculate index of current cell. Offset the position a tiny bit in
1340
  // direction of flight
1341
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
783,238,233 ✔
1342

1343
  // if track is very short, assume that it is completely inside one cell.
1344
  // Only the current cell will score and no surfaces
1345
  if (total_distance < 2 * TINY_BIT) {
783,238,233 ✔
1346
    if (in_mesh) {
462,014 ✔
1347
      tally.track(ijk, 1.0);
461,706 ✔
1348
    }
1349
    return;
462,014 ✔
1350
  }
1351

1352
  // Calculate initial distances to next surfaces in all three dimensions
1353
  std::array<MeshDistance, 3> distances;
1,565,552,438 ✔
1354
  for (int k = 0; k < n; ++k) {
2,147,483,647 ✔
1355
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647 ✔
1356
  }
1357

1358
  // Loop until r = r1 is eventually reached
1359
  while (true) {
1360

1361
    if (in_mesh) {
1,363,854,666 ✔
1362

1363
      // find surface with minimal distance to current position
1364
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,309,627,636 ✔
1365
                     distances.begin();
1,309,627,636 ✔
1366

1367
      // Tally track length delta since last step
1368
      tally.track(ijk,
1,309,627,636 ✔
1369
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
1,958,641,236 ✔
1370
          total_distance);
1371

1372
      // update position and leave, if we have reached end position
1373
      traveled_distance = distances[k].distance;
1,309,627,636 ✔
1374
      if (traveled_distance >= total_distance)
1,309,627,636 ✔
1375
        return;
1376

1377
      // If we have not reached r1, we have hit a surface. Tally outward
1378
      // current
1379
      tally.surface(ijk, k, distances[k].max_surface, false);
576,745,881 ✔
1380

1381
      // Update cell and calculate distance to next surface in k-direction.
1382
      // The two other directions are still valid!
1383
      ijk[k] = distances[k].next_index;
576,745,881 ✔
1384
      distances[k] =
576,745,881 ✔
1385
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
576,745,881 ✔
1386

1387
      // Check if we have left the interior of the mesh
1388
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
581,080,243 ✔
1389

1390
      // If we are still inside the mesh, tally inward current for the next
1391
      // cell
1392
      if (in_mesh)
18,764,963 ✔
1393
        tally.surface(ijk, k, !distances[k].max_surface, true);
580,182,685 ✔
1394

1395
    } else { // not inside mesh
1396

1397
      // For all directions outside the mesh, find the distance that we need
1398
      // to travel to reach the next surface. Use the largest distance, as
1399
      // only this will cross all outer surfaces.
1400
      int k_max {-1};
1401
      for (int k = 0; k < n; ++k) {
216,014,108 ✔
1402
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
161,787,078 ✔
1403
            (distances[k].distance > traveled_distance)) {
59,214,292 ✔
1404
          traveled_distance = distances[k].distance;
1405
          k_max = k;
1406
        }
1407
      }
1408
      // Assure some distance is traveled
1409
      if (k_max == -1) {
54,227,030 !
1410
        traveled_distance += TINY_BIT;
×
1411
      }
1412

1413
      // If r1 is not inside the mesh, exit here
1414
      if (traveled_distance >= total_distance)
54,227,030 ✔
1415
        return;
1416

1417
      // Calculate the new cell index and update all distances to next
1418
      // surfaces.
1419
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
4,332,566 ✔
1420
      for (int k = 0; k < n; ++k) {
17,199,259 ✔
1421
        distances[k] =
12,866,693 ✔
1422
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
12,866,693 ✔
1423
      }
1424

1425
      // If inside the mesh, Tally inward current
1426
      if (in_mesh && k_max >= 0)
4,332,566 !
1427
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
562,298,161 ✔
1428
    }
1429
  }
1430
}
1431

1432
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
711,900,603 ✔
1433
  vector<int>& bins, vector<double>& lengths) const
1434
{
1435

1436
  // Helper tally class.
1437
  // stores a pointer to the mesh class and references to bins and lengths
1438
  // parameters. Performs the actual tally through the track method.
1439
  struct TrackAggregator {
711,900,603 ✔
1440
    TrackAggregator(
711,900,603 ✔
1441
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1442
      : mesh(_mesh), bins(_bins), lengths(_lengths)
711,900,603 ✔
1443
    {}
1444
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1445
    void track(const MeshIndex& ijk, double l) const
1,221,032,633 ✔
1446
    {
1447
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,221,032,633 ✔
1448
      lengths.push_back(l);
1,221,032,633 ✔
1449
    }
1,221,032,633 ✔
1450

1451
    const StructuredMesh* mesh;
1452
    vector<int>& bins;
1453
    vector<double>& lengths;
1454
  };
1455

1456
  // Perform the mesh raytrace with the helper class.
1457
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
711,900,603 ✔
1458
}
711,900,603 ✔
1459

1460
void StructuredMesh::surface_bins_crossed(
71,342,971 ✔
1461
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1462
{
1463

1464
  // Helper tally class.
1465
  // stores a pointer to the mesh class and a reference to the bins parameter.
1466
  // Performs the actual tally through the surface method.
1467
  struct SurfaceAggregator {
71,342,971 ✔
1468
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
71,342,971 ✔
1469
      : mesh(_mesh), bins(_bins)
71,342,971 ✔
1470
    {}
1471
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
36,897,791 ✔
1472
    {
1473
      int i_bin =
36,897,791 ✔
1474
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
36,897,791 ✔
1475
      if (max)
36,897,791 ✔
1476
        i_bin += 2;
18,430,083 ✔
1477
      if (inward)
36,897,791 ✔
1478
        i_bin += 1;
18,132,828 ✔
1479
      bins.push_back(i_bin);
36,897,791 ✔
1480
    }
36,897,791 ✔
1481
    void track(const MeshIndex& idx, double l) const {}
1482

1483
    const StructuredMesh* mesh;
1484
    vector<int>& bins;
1485
  };
1486

1487
  // Perform the mesh raytrace with the helper class.
1488
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
71,342,971 ✔
1489
}
71,342,971 ✔
1490

1491
//==============================================================================
1492
// RegularMesh implementation
1493
//==============================================================================
1494

1495
int RegularMesh::set_grid()
1,694 ✔
1496
{
1497
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
1,694 ✔
1498

1499
  // Check that dimensions are all greater than zero
1500
  if ((shape <= 0).any()) {
5,082 !
1501
    set_errmsg("All entries for a regular mesh dimensions "
×
1502
               "must be positive.");
1503
    return OPENMC_E_INVALID_ARGUMENT;
1504
  }
1505

1506
  // Make sure lower_left and dimension match
1507
  if (lower_left_.size() != n_dimension_) {
1,694 !
1508
    set_errmsg("Number of entries in lower_left must be the same "
×
1509
               "as the regular mesh dimensions.");
1510
    return OPENMC_E_INVALID_ARGUMENT;
1511
  }
1512
  if (width_.size() > 0) {
1,694 ✔
1513

1514
    // Check to ensure width has same dimensions
1515
    if (width_.size() != n_dimension_) {
27 !
1516
      set_errmsg("Number of entries on width must be the same as "
×
1517
                 "the regular mesh dimensions.");
1518
      return OPENMC_E_INVALID_ARGUMENT;
1519
    }
1520

1521
    // Check for negative widths
1522
    if ((width_ < 0.0).any()) {
81 !
1523
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1524
      return OPENMC_E_INVALID_ARGUMENT;
1525
    }
1526

1527
    // Set width and upper right coordinate
1528
    upper_right_ = lower_left_ + shape * width_;
81 ✔
1529

1530
  } else if (upper_right_.size() > 0) {
1,667 !
1531

1532
    // Check to ensure upper_right_ has same dimensions
1533
    if (upper_right_.size() != n_dimension_) {
1,667 !
1534
      set_errmsg("Number of entries on upper_right must be the "
×
1535
                 "same as the regular mesh dimensions.");
1536
      return OPENMC_E_INVALID_ARGUMENT;
1537
    }
1538

1539
    // Check that upper-right is above lower-left
1540
    if ((upper_right_ < lower_left_).any()) {
5,001 !
1541
      set_errmsg(
×
1542
        "The upper_right coordinates of a regular mesh must be greater than "
1543
        "the lower_left coordinates.");
1544
      return OPENMC_E_INVALID_ARGUMENT;
1545
    }
1546

1547
    // Set width
1548
    width_ = (upper_right_ - lower_left_) / shape;
5,001 ✔
1549
  }
1550

1551
  // Set material volumes
1552
  volume_frac_ = 1.0 / shape.prod();
1,694 ✔
1553

1554
  element_volume_ = 1.0;
1,694 ✔
1555
  for (int i = 0; i < n_dimension_; i++) {
6,372 ✔
1556
    element_volume_ *= width_[i];
4,678 ✔
1557
  }
1558
  return 0;
1559
}
1,694 ✔
1560

1561
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
1,671 ✔
1562
{
1563
  // Determine number of dimensions for mesh
1564
  if (!check_for_node(node, "dimension")) {
1,671 !
1565
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1566
  }
1567

1568
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
1,671 ✔
1569
  int n = n_dimension_ = shape.size();
1,671 !
1570
  if (n != 1 && n != 2 && n != 3) {
1,671 !
1571
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1572
  }
1573
  std::copy(shape.begin(), shape.end(), shape_.begin());
1,671 ✔
1574

1575
  // Check for lower-left coordinates
1576
  if (check_for_node(node, "lower_left")) {
1,671 !
1577
    // Read mesh lower-left corner location
1578
    lower_left_ = get_node_tensor<double>(node, "lower_left");
1,671 ✔
1579
  } else {
1580
    fatal_error("Must specify <lower_left> on a mesh.");
×
1581
  }
1582

1583
  if (check_for_node(node, "width")) {
1,671 ✔
1584
    // Make sure one of upper-right or width were specified
1585
    if (check_for_node(node, "upper_right")) {
27 !
1586
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1587
    }
1588

1589
    width_ = get_node_tensor<double>(node, "width");
54 ✔
1590

1591
  } else if (check_for_node(node, "upper_right")) {
1,644 !
1592

1593
    upper_right_ = get_node_tensor<double>(node, "upper_right");
3,288 ✔
1594

1595
  } else {
1596
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1597
  }
1598

1599
  if (set_grid()) {
1,671 !
1600
    fatal_error(get_errmsg());
×
1601
  }
1602
}
1,671 ✔
1603

1604
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
23 ✔
1605
{
1606
  // Determine number of dimensions for mesh
1607
  if (!object_exists(group, "dimension")) {
23 !
1608
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1609
  }
1610

1611
  tensor::Tensor<int> shape;
23 ✔
1612
  read_dataset(group, "dimension", shape);
23 ✔
1613
  int n = n_dimension_ = shape.size();
23 !
1614
  if (n != 1 && n != 2 && n != 3) {
23 !
1615
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1616
  }
1617
  std::copy(shape.begin(), shape.end(), shape_.begin());
23 ✔
1618

1619
  // Check for lower-left coordinates
1620
  if (object_exists(group, "lower_left")) {
23 !
1621
    // Read mesh lower-left corner location
1622
    read_dataset(group, "lower_left", lower_left_);
23 ✔
1623
  } else {
1624
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1625
  }
1626

1627
  if (object_exists(group, "upper_right")) {
23 !
1628

1629
    read_dataset(group, "upper_right", upper_right_);
23 ✔
1630

1631
  } else {
1632
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1633
  }
1634

1635
  if (set_grid()) {
23 !
1636
    fatal_error(get_errmsg());
×
1637
  }
1638
}
23 ✔
1639

1640
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647 ✔
1641
{
1642
  if (r <= lower_left_[i])
2,147,483,647 ✔
1643
    return r == lower_left_[i] ? 1 : 0;
7,986,503 ✔
1644
  if (r >= upper_right_[i])
2,147,483,647 ✔
1645
    return r == upper_right_[i] ? shape_[i] : shape_[i] + 1;
6,498,128 ✔
1646

1647
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647 ✔
1648
}
1649

1650
const std::string RegularMesh::mesh_type = "regular";
1651

1652
std::string RegularMesh::get_mesh_type() const
2,506 ✔
1653
{
1654
  return mesh_type;
2,506 ✔
1655
}
1656

1657
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,274,269,281 ✔
1658
{
1659
  return lower_left_[i] + ijk[i] * width_[i];
1,274,269,281 ✔
1660
}
1661

1662
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,229,817,478 ✔
1663
{
1664
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,229,817,478 ✔
1665
}
1666

1667
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647 ✔
1668
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1669
  double l) const
1670
{
1671
  MeshDistance d;
2,147,483,647 ✔
1672
  d.next_index = ijk[i];
2,147,483,647 ✔
1673
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647 ✔
1674
    return d;
10,196,406 ✔
1675

1676
  d.max_surface = (u[i] > 0);
2,147,483,647 ✔
1677
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647 ✔
1678
    d.next_index++;
1,271,523,573 ✔
1679
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,271,523,573 ✔
1680
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,240,480,690 ✔
1681
    d.next_index--;
1,227,071,770 ✔
1682
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,227,071,770 ✔
1683
  }
1684

1685
  return d;
2,147,483,647 ✔
1686
}
1687

1688
std::pair<vector<double>, vector<double>> RegularMesh::plot(
14 ✔
1689
  Position plot_ll, Position plot_ur) const
1690
{
1691
  // Figure out which axes lie in the plane of the plot.
1692
  array<int, 2> axes {-1, -1};
14 ✔
1693
  if (plot_ur.z == plot_ll.z) {
14 !
1694
    axes[0] = 0;
14 !
1695
    if (n_dimension_ > 1)
14 !
1696
      axes[1] = 1;
14 ✔
1697
  } else if (plot_ur.y == plot_ll.y) {
×
1698
    axes[0] = 0;
×
1699
    if (n_dimension_ > 2)
×
1700
      axes[1] = 2;
×
1701
  } else if (plot_ur.x == plot_ll.x) {
×
1702
    if (n_dimension_ > 1)
×
1703
      axes[0] = 1;
×
1704
    if (n_dimension_ > 2)
×
1705
      axes[1] = 2;
×
1706
  } else {
1707
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1708
  }
1709

1710
  // Get the coordinates of the mesh lines along both of the axes.
1711
  array<vector<double>, 2> axis_lines;
1712
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
42 ✔
1713
    int axis = axes[i_ax];
28 !
1714
    if (axis == -1)
28 !
1715
      continue;
×
1716
    auto& lines {axis_lines[i_ax]};
28 ✔
1717

1718
    double coord = lower_left_[axis];
28 ✔
1719
    for (int i = 0; i < shape_[axis] + 1; ++i) {
182 ✔
1720
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
154 !
1721
        lines.push_back(coord);
154 ✔
1722
      coord += width_[axis];
154 ✔
1723
    }
1724
  }
1725

1726
  return {axis_lines[0], axis_lines[1]};
28 ✔
1727
}
1728

1729
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
1,687 ✔
1730
{
1731
  write_dataset(mesh_group, "dimension", get_shape_tensor());
1,687 ✔
1732
  write_dataset(mesh_group, "lower_left", lower_left_);
1,687 ✔
1733
  write_dataset(mesh_group, "upper_right", upper_right_);
1,687 ✔
1734
  write_dataset(mesh_group, "width", width_);
1,687 ✔
1735
}
1,687 ✔
1736

1737
tensor::Tensor<double> RegularMesh::count_sites(
4,966 ✔
1738
  const SourceSite* bank, int64_t length, bool* outside) const
1739
{
1740
  // Determine shape of array for counts
1741
  std::size_t m = this->n_bins();
4,966 ✔
1742
  vector<std::size_t> shape = {m};
4,966 ✔
1743

1744
  // Create array of zeros
1745
  auto cnt = tensor::zeros<double>(shape);
4,966 ✔
1746
  bool outside_ = false;
1,446 ✔
1747

1748
  for (int64_t i = 0; i < length; i++) {
4,884,253 ✔
1749
    const auto& site = bank[i];
4,879,287 ✔
1750

1751
    // determine scoring bin for entropy mesh
1752
    int mesh_bin = get_bin(site.r);
4,879,287 ✔
1753

1754
    // if outside mesh, skip particle
1755
    if (mesh_bin < 0) {
4,879,287 !
1756
      outside_ = true;
×
1757
      continue;
×
1758
    }
1759

1760
    // Add to appropriate bin
1761
    cnt(mesh_bin) += site.wgt;
4,879,287 ✔
1762
  }
1763

1764
  // Create reduced count data
1765
  auto counts = tensor::zeros<double>(shape);
4,966 ✔
1766
  int total = cnt.size();
4,966 ✔
1767

1768
#ifdef OPENMC_MPI
1769
  // collect values from all processors
1770
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
1,446 ✔
1771

1772
  // Check if there were sites outside the mesh for any processor
1773
  if (outside) {
1,446 !
1774
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
1,446 ✔
1775
  }
1776
#else
1777
  std::copy(cnt.data(), cnt.data() + total, counts.data());
3,520 ✔
1778
  if (outside)
3,520 !
1779
    *outside = outside_;
3,520 ✔
1780
#endif
1781

1782
  return counts;
4,966 ✔
1783
}
4,966 ✔
1784

1785
double RegularMesh::volume(const MeshIndex& ijk) const
797,969 ✔
1786
{
1787
  return element_volume_;
797,969 ✔
1788
}
1789

1790
//==============================================================================
1791
// RectilinearMesh implementation
1792
//==============================================================================
1793

1794
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
83 ✔
1795
{
1796
  n_dimension_ = 3;
83 ✔
1797

1798
  grid_[0] = get_node_array<double>(node, "x_grid");
83 ✔
1799
  grid_[1] = get_node_array<double>(node, "y_grid");
83 ✔
1800
  grid_[2] = get_node_array<double>(node, "z_grid");
83 ✔
1801

1802
  if (set_grid()) {
83 !
1803
    fatal_error(get_errmsg());
×
1804
  }
1805
}
83 ✔
1806

1807
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
7 ✔
1808
{
1809
  n_dimension_ = 3;
7 ✔
1810

1811
  read_dataset(group, "x_grid", grid_[0]);
7 ✔
1812
  read_dataset(group, "y_grid", grid_[1]);
7 ✔
1813
  read_dataset(group, "z_grid", grid_[2]);
7 ✔
1814

1815
  if (set_grid()) {
7 !
1816
    fatal_error(get_errmsg());
×
1817
  }
1818
}
7 ✔
1819

1820
const std::string RectilinearMesh::mesh_type = "rectilinear";
1821

1822
std::string RectilinearMesh::get_mesh_type() const
203 ✔
1823
{
1824
  return mesh_type;
203 ✔
1825
}
1826

1827
double RectilinearMesh::positive_grid_boundary(
16,686,194 ✔
1828
  const MeshIndex& ijk, int i) const
1829
{
1830
  return grid_[i][ijk[i]];
16,686,194 ✔
1831
}
1832

1833
double RectilinearMesh::negative_grid_boundary(
16,204,818 ✔
1834
  const MeshIndex& ijk, int i) const
1835
{
1836
  return grid_[i][ijk[i] - 1];
16,204,818 ✔
1837
}
1838

1839
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
33,713,113 ✔
1840
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1841
  double l) const
1842
{
1843
  MeshDistance d;
33,713,113 ✔
1844
  d.next_index = ijk[i];
33,713,113 ✔
1845
  if (std::abs(u[i]) < FP_PRECISION)
33,713,113 ✔
1846
    return d;
363,888 ✔
1847

1848
  d.max_surface = (u[i] > 0);
33,349,225 ✔
1849
  if (d.max_surface && (ijk[i] <= shape_[i])) {
33,349,225 ✔
1850
    d.next_index++;
16,686,194 ✔
1851
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
16,686,194 ✔
1852
  } else if (!d.max_surface && (ijk[i] > 0)) {
16,663,031 ✔
1853
    d.next_index--;
16,204,818 ✔
1854
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
16,204,818 ✔
1855
  }
1856
  return d;
33,349,225 ✔
1857
}
1858

1859
int RectilinearMesh::set_grid()
139 ✔
1860
{
1861
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
139 ✔
1862
    static_cast<int>(grid_[1].size()) - 1,
139 ✔
1863
    static_cast<int>(grid_[2].size()) - 1};
139 ✔
1864

1865
  for (const auto& g : grid_) {
556 ✔
1866
    if (g.size() < 2) {
417 !
1867
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1868
                 "must each have at least 2 points");
1869
      return OPENMC_E_INVALID_ARGUMENT;
×
1870
    }
1871
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
417 !
1872
        g.end()) {
417 !
1873
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1874
                 "rectilinear meshes must be sorted and unique.");
1875
      return OPENMC_E_INVALID_ARGUMENT;
×
1876
    }
1877
  }
1878

1879
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
139 ✔
1880
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
139 ✔
1881

1882
  return 0;
139 ✔
1883
}
1884

1885
int RectilinearMesh::get_index_in_direction(double r, int i) const
46,798,745 ✔
1886
{
1887
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
46,798,745 ✔
1888
}
1889

1890
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
7 ✔
1891
  Position plot_ll, Position plot_ur) const
1892
{
1893
  // Figure out which axes lie in the plane of the plot.
1894
  array<int, 2> axes {-1, -1};
7 ✔
1895
  if (plot_ur.z == plot_ll.z) {
7 !
1896
    axes = {0, 1};
×
1897
  } else if (plot_ur.y == plot_ll.y) {
7 !
1898
    axes = {0, 2};
7 ✔
1899
  } else if (plot_ur.x == plot_ll.x) {
×
1900
    axes = {1, 2};
×
1901
  } else {
1902
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1903
  }
1904

1905
  // Get the coordinates of the mesh lines along both of the axes.
1906
  array<vector<double>, 2> axis_lines;
1907
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
21 ✔
1908
    int axis = axes[i_ax];
14 ✔
1909
    vector<double>& lines {axis_lines[i_ax]};
14 ✔
1910

1911
    for (auto coord : grid_[axis]) {
70 ✔
1912
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
56 !
1913
        lines.push_back(coord);
56 ✔
1914
    }
1915
  }
1916

1917
  return {axis_lines[0], axis_lines[1]};
14 ✔
1918
}
1919

1920
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
84 ✔
1921
{
1922
  write_dataset(mesh_group, "x_grid", grid_[0]);
84 ✔
1923
  write_dataset(mesh_group, "y_grid", grid_[1]);
84 ✔
1924
  write_dataset(mesh_group, "z_grid", grid_[2]);
84 ✔
1925
}
84 ✔
1926

1927
double RectilinearMesh::volume(const MeshIndex& ijk) const
84 ✔
1928
{
1929
  double vol {1.0};
84 ✔
1930

1931
  for (int i = 0; i < n_dimension_; i++) {
336 ✔
1932
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
252 ✔
1933
  }
1934
  return vol;
84 ✔
1935
}
1936

1937
//==============================================================================
1938
// CylindricalMesh implementation
1939
//==============================================================================
1940

1941
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
261 ✔
1942
  : PeriodicStructuredMesh {node}
261 ✔
1943
{
1944
  n_dimension_ = 3;
261 ✔
1945
  grid_[0] = get_node_array<double>(node, "r_grid");
261 ✔
1946
  grid_[1] = get_node_array<double>(node, "phi_grid");
261 ✔
1947
  grid_[2] = get_node_array<double>(node, "z_grid");
261 ✔
1948
  origin_ = get_node_position(node, "origin");
261 ✔
1949

1950
  if (set_grid()) {
261 !
1951
    fatal_error(get_errmsg());
×
1952
  }
1953
}
261 ✔
1954

1955
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
7 ✔
1956
{
1957
  n_dimension_ = 3;
7 ✔
1958
  read_dataset(group, "r_grid", grid_[0]);
7 ✔
1959
  read_dataset(group, "phi_grid", grid_[1]);
7 ✔
1960
  read_dataset(group, "z_grid", grid_[2]);
7 ✔
1961
  read_dataset(group, "origin", origin_);
7 ✔
1962

1963
  if (set_grid()) {
7 !
1964
    fatal_error(get_errmsg());
×
1965
  }
1966
}
7 ✔
1967

1968
const std::string CylindricalMesh::mesh_type = "cylindrical";
1969

1970
std::string CylindricalMesh::get_mesh_type() const
329 ✔
1971
{
1972
  return mesh_type;
329 ✔
1973
}
1974

1975
std::array<const char*, 3> CylindricalMesh::axis_labels() const
411,432 ✔
1976
{
1977
  return {"r", "phi", "z"};
411,432 ✔
1978
}
1979

1980
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
30,333,982 ✔
1981
  Position r, bool& in_mesh) const
1982
{
1983
  r = local_coords(r);
30,333,982 ✔
1984

1985
  Position mapped_r;
30,333,982 ✔
1986
  mapped_r[0] = std::hypot(r.x, r.y);
30,333,982 ✔
1987
  mapped_r[2] = r[2];
30,333,982 ✔
1988

1989
  if (mapped_r[0] < FP_PRECISION) {
30,333,982 !
1990
    mapped_r[1] = 0.0;
1991
  } else {
1992
    mapped_r[1] = std::atan2(r.y, r.x);
30,333,982 ✔
1993
    if (mapped_r[1] < 0)
30,333,982 ✔
1994
      mapped_r[1] += 2 * PI;
15,180,172 ✔
1995
  }
1996

1997
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
30,333,982 ✔
1998

1999
  idx[1] = sanitize_phi(idx[1]);
30,333,982 ✔
2000

2001
  return idx;
30,333,982 ✔
2002
}
2003

2004
Position CylindricalMesh::sample_element(
56,070 ✔
2005
  const MeshIndex& ijk, uint64_t* seed) const
2006
{
2007
  double r_min = this->r(ijk[0] - 1);
56,070 ✔
2008
  double r_max = this->r(ijk[0]);
56,070 ✔
2009

2010
  double phi_min = this->phi(ijk[1] - 1);
56,070 ✔
2011
  double phi_max = this->phi(ijk[1]);
56,070 ✔
2012

2013
  double z_min = this->z(ijk[2] - 1);
56,070 ✔
2014
  double z_max = this->z(ijk[2]);
56,070 ✔
2015

2016
  double r_min_sq = r_min * r_min;
56,070 ✔
2017
  double r_max_sq = r_max * r_max;
56,070 ✔
2018
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
56,070 ✔
2019
  double phi = uniform_distribution(phi_min, phi_max, seed);
56,070 ✔
2020
  double z = uniform_distribution(z_min, z_max, seed);
56,070 ✔
2021

2022
  double x = r * std::cos(phi);
56,070 ✔
2023
  double y = r * std::sin(phi);
56,070 ✔
2024

2025
  return origin_ + Position(x, y, z);
56,070 ✔
2026
}
2027

2028
double CylindricalMesh::find_r_crossing(
90,628,226 ✔
2029
  const Position& r, const Direction& u, double l, int shell) const
2030
{
2031

2032
  if ((shell < 0) || (shell > shape_[0]))
90,628,226 !
2033
    return INFTY;
2034

2035
  // solve r.x^2 + r.y^2 == r0^2
2036
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
2037
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
2038

2039
  const double r0 = grid_[0][shell];
79,261,762 ✔
2040
  if (r0 == 0.0)
79,261,762 ✔
2041
    return INFTY;
2042

2043
  const double denominator = u.x * u.x + u.y * u.y;
74,720,911 ✔
2044

2045
  // Direction of flight is in z-direction. Will never intersect r.
2046
  if (std::abs(denominator) < FP_PRECISION)
74,720,911 ✔
2047
    return INFTY;
2048

2049
  // inverse of dominator to help the compiler to speed things up
2050
  const double inv_denominator = 1.0 / denominator;
74,683,391 ✔
2051

2052
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
74,683,391 ✔
2053
  double R = std::sqrt(r.x * r.x + r.y * r.y);
74,683,391 ✔
2054
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
74,683,391 ✔
2055

2056
  if (D < 0.0)
74,683,391 ✔
2057
    return INFTY;
2058

2059
  D = std::sqrt(D);
68,503,917 ✔
2060

2061
  // Particle is already on the shell surface; avoid spurious crossing
2062
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
68,503,917 ✔
2063
    return INFTY;
2064

2065
  // Check -p - D first because it is always smaller as -p + D
2066
  if (-p - D > l)
64,282,679 ✔
2067
    return -p - D;
2068
  if (-p + D > l)
51,434,331 ✔
2069
    return -p + D;
31,846,522 ✔
2070

2071
  return INFTY;
2072
}
2073

2074
double CylindricalMesh::find_phi_crossing(
47,279,890 ✔
2075
  const Position& r, const Direction& u, double l, int shell) const
2076
{
2077
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2078
  if (full_phi_ && (shape_[1] == 1))
47,279,890 ✔
2079
    return INFTY;
2080

2081
  shell = sanitize_phi(shell);
27,879,894 ✔
2082

2083
  const double p0 = grid_[1][shell];
27,879,894 ✔
2084

2085
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2086
  // => x(s) * cos(p0) = y(s) * sin(p0)
2087
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2088
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2089

2090
  const double c0 = std::cos(p0);
27,879,894 ✔
2091
  const double s0 = std::sin(p0);
27,879,894 ✔
2092

2093
  const double denominator = (u.x * s0 - u.y * c0);
27,879,894 ✔
2094

2095
  // Check if direction of flight is not parallel to phi surface
2096
  if (std::abs(denominator) > FP_PRECISION) {
27,879,894 ✔
2097
    const double s = -(r.x * s0 - r.y * c0) / denominator;
27,713,966 ✔
2098
    // Check if solution is in positive direction of flight and crosses the
2099
    // correct phi surface (not -phi)
2100
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
27,713,966 ✔
2101
      return s;
12,821,599 ✔
2102
  }
2103

2104
  return INFTY;
2105
}
2106

2107
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
23,303,770 ✔
2108
  const Position& r, const Direction& u, double l, int shell) const
2109
{
2110
  MeshDistance d;
23,303,770 ✔
2111
  d.next_index = shell;
23,303,770 ✔
2112

2113
  // Direction of flight is within xy-plane. Will never intersect z.
2114
  if (std::abs(u.z) < FP_PRECISION)
23,303,770 ✔
2115
    return d;
711,592 ✔
2116

2117
  d.max_surface = (u.z > 0.0);
22,592,178 ✔
2118
  if (d.max_surface && (shell <= shape_[2])) {
22,592,178 ✔
2119
    d.next_index += 1;
10,719,527 ✔
2120
    d.distance = (grid_[2][shell] - r.z) / u.z;
10,719,527 ✔
2121
  } else if (!d.max_surface && (shell > 0)) {
11,872,651 ✔
2122
    d.next_index -= 1;
10,698,051 ✔
2123
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
10,698,051 ✔
2124
  }
2125
  return d;
22,592,178 ✔
2126
}
2127

2128
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
92,257,828 ✔
2129
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2130
  double l) const
2131
{
2132
  if (i == 0) {
92,257,828 ✔
2133

2134
    return std::min(
90,628,226 ✔
2135
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
45,314,113 ✔
2136
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
90,628,226 ✔
2137

2138
  } else if (i == 1) {
46,943,715 ✔
2139

2140
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
23,639,945 ✔
2141
                      find_phi_crossing(r0, u, l, ijk[i])),
23,639,945 ✔
2142
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
23,639,945 ✔
2143
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
47,279,890 ✔
2144

2145
  } else {
2146
    return find_z_crossing(r0, u, l, ijk[i]);
23,303,770 ✔
2147
  }
2148
}
2149

2150
int CylindricalMesh::set_grid()
324 ✔
2151
{
2152
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
324 ✔
2153
    static_cast<int>(grid_[1].size()) - 1,
324 ✔
2154
    static_cast<int>(grid_[2].size()) - 1};
324 ✔
2155

2156
  for (const auto& g : grid_) {
1,296 ✔
2157
    if (g.size() < 2) {
972 !
2158
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2159
                 "must each have at least 2 points");
2160
      return OPENMC_E_INVALID_ARGUMENT;
×
2161
    }
2162
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
972 !
2163
        g.end()) {
972 !
2164
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2165
                 "cylindrical meshes must be sorted and unique.");
2166
      return OPENMC_E_INVALID_ARGUMENT;
×
2167
    }
2168
  }
2169
  if (grid_[0].front() < 0.0) {
324 !
2170
    set_errmsg("r-grid for "
×
2171
               "cylindrical meshes must start at r >= 0.");
2172
    return OPENMC_E_INVALID_ARGUMENT;
×
2173
  }
2174
  if (grid_[1].front() < 0.0) {
324 !
2175
    set_errmsg("phi-grid for "
×
2176
               "cylindrical meshes must start at phi >= 0.");
2177
    return OPENMC_E_INVALID_ARGUMENT;
×
2178
  }
2179
  if (grid_[1].back() > 2.0 * PI) {
324 !
2180
    set_errmsg("phi-grids for "
×
2181
               "cylindrical meshes must end with theta <= 2*pi.");
2182

2183
    return OPENMC_E_INVALID_ARGUMENT;
×
2184
  }
2185

2186
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
324 !
2187

2188
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
324 ✔
2189
    origin_[2] + grid_[2].front()};
324 ✔
2190
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
324 ✔
2191
    origin_[2] + grid_[2].back()};
324 ✔
2192

2193
  return 0;
324 ✔
2194
}
2195

2196
int CylindricalMesh::get_index_in_direction(double r, int i) const
91,001,946 ✔
2197
{
2198
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
91,001,946 ✔
2199
}
2200

2201
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2202
  Position plot_ll, Position plot_ur) const
2203
{
2204
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2205

2206
  // Figure out which axes lie in the plane of the plot.
2207
  array<vector<double>, 2> axis_lines;
2208
  return {axis_lines[0], axis_lines[1]};
2209
}
2210

2211
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
252 ✔
2212
{
2213
  write_dataset(mesh_group, "r_grid", grid_[0]);
252 ✔
2214
  write_dataset(mesh_group, "phi_grid", grid_[1]);
252 ✔
2215
  write_dataset(mesh_group, "z_grid", grid_[2]);
252 ✔
2216
  write_dataset(mesh_group, "origin", origin_);
252 ✔
2217
}
252 ✔
2218

2219
double CylindricalMesh::volume(const MeshIndex& ijk) const
504 ✔
2220
{
2221
  double r_i = grid_[0][ijk[0] - 1];
504 ✔
2222
  double r_o = grid_[0][ijk[0]];
504 ✔
2223

2224
  double phi_i = grid_[1][ijk[1] - 1];
504 ✔
2225
  double phi_o = grid_[1][ijk[1]];
504 ✔
2226

2227
  double z_i = grid_[2][ijk[2] - 1];
504 ✔
2228
  double z_o = grid_[2][ijk[2]];
504 ✔
2229

2230
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
504 ✔
2231
}
2232

2233
//==============================================================================
2234
// SphericalMesh implementation
2235
//==============================================================================
2236

2237
SphericalMesh::SphericalMesh(pugi::xml_node node)
226 ✔
2238
  : PeriodicStructuredMesh {node}
226 ✔
2239
{
2240
  n_dimension_ = 3;
226 ✔
2241

2242
  grid_[0] = get_node_array<double>(node, "r_grid");
226 ✔
2243
  grid_[1] = get_node_array<double>(node, "theta_grid");
226 ✔
2244
  grid_[2] = get_node_array<double>(node, "phi_grid");
226 ✔
2245
  origin_ = get_node_position(node, "origin");
226 ✔
2246

2247
  if (set_grid()) {
226 !
2248
    fatal_error(get_errmsg());
×
2249
  }
2250
}
226 ✔
2251

2252
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
7 ✔
2253
{
2254
  n_dimension_ = 3;
7 ✔
2255

2256
  read_dataset(group, "r_grid", grid_[0]);
7 ✔
2257
  read_dataset(group, "theta_grid", grid_[1]);
7 ✔
2258
  read_dataset(group, "phi_grid", grid_[2]);
7 ✔
2259
  read_dataset(group, "origin", origin_);
7 ✔
2260

2261
  if (set_grid()) {
7 !
2262
    fatal_error(get_errmsg());
×
2263
  }
2264
}
7 ✔
2265

2266
const std::string SphericalMesh::mesh_type = "spherical";
2267

2268
std::string SphericalMesh::get_mesh_type() const
266 ✔
2269
{
2270
  return mesh_type;
266 ✔
2271
}
2272

2273
std::array<const char*, 3> SphericalMesh::axis_labels() const
205,800 ✔
2274
{
2275
  return {"r", "theta", "phi"};
205,800 ✔
2276
}
2277

2278
StructuredMesh::MeshIndex SphericalMesh::get_indices(
43,608,852 ✔
2279
  Position r, bool& in_mesh) const
2280
{
2281
  r = local_coords(r);
43,608,852 ✔
2282

2283
  Position mapped_r;
43,608,852 ✔
2284
  mapped_r[0] = r.norm();
43,608,852 ✔
2285

2286
  if (mapped_r[0] < FP_PRECISION) {
43,608,852 !
2287
    mapped_r[1] = 0.0;
2288
    mapped_r[2] = 0.0;
2289
  } else {
2290
    mapped_r[1] = std::acos(r.z / mapped_r.x);
43,608,852 ✔
2291
    mapped_r[2] = std::atan2(r.y, r.x);
43,608,852 ✔
2292
    if (mapped_r[2] < 0)
43,608,852 ✔
2293
      mapped_r[2] += 2 * PI;
21,794,850 ✔
2294
  }
2295

2296
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
43,608,852 ✔
2297

2298
  idx[1] = sanitize_theta(idx[1]);
43,608,852 ✔
2299
  idx[2] = sanitize_phi(idx[2]);
43,608,852 ✔
2300

2301
  return idx;
43,608,852 ✔
2302
}
2303

2304
Position SphericalMesh::sample_element(
70 ✔
2305
  const MeshIndex& ijk, uint64_t* seed) const
2306
{
2307
  double r_min = this->r(ijk[0] - 1);
70 ✔
2308
  double r_max = this->r(ijk[0]);
70 ✔
2309

2310
  double theta_min = this->theta(ijk[1] - 1);
70 ✔
2311
  double theta_max = this->theta(ijk[1]);
70 ✔
2312

2313
  double phi_min = this->phi(ijk[2] - 1);
70 ✔
2314
  double phi_max = this->phi(ijk[2]);
70 ✔
2315

2316
  double cos_theta =
70 ✔
2317
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
70 ✔
2318
  double sin_theta = std::sin(std::acos(cos_theta));
70 ✔
2319
  double phi = uniform_distribution(phi_min, phi_max, seed);
70 ✔
2320
  double r_min_cub = std::pow(r_min, 3);
70 ✔
2321
  double r_max_cub = std::pow(r_max, 3);
70 ✔
2322
  // might be faster to do rejection here?
2323
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
70 ✔
2324

2325
  double x = r * std::cos(phi) * sin_theta;
70 ✔
2326
  double y = r * std::sin(phi) * sin_theta;
70 ✔
2327
  double z = r * cos_theta;
70 ✔
2328

2329
  return origin_ + Position(x, y, z);
70 ✔
2330
}
2331

2332
double SphericalMesh::find_r_crossing(
282,446,500 ✔
2333
  const Position& r, const Direction& u, double l, int shell) const
2334
{
2335
  if ((shell < 0) || (shell > shape_[0]))
282,446,500 ✔
2336
    return INFTY;
2337

2338
  // solve |r+s*u| = r0
2339
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2340
  const double r0 = grid_[0][shell];
257,270,762 ✔
2341
  if (r0 == 0.0)
257,270,762 ✔
2342
    return INFTY;
2343
  const double p = r.dot(u);
252,384,342 ✔
2344
  double R = r.norm();
252,384,342 ✔
2345
  double D = p * p - (R - r0) * (R + r0);
252,384,342 ✔
2346

2347
  // Particle is already on the shell surface; avoid spurious crossing
2348
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
252,384,342 ✔
2349
    return INFTY;
2350

2351
  if (D >= 0.0) {
245,569,744 ✔
2352
    D = std::sqrt(D);
227,855,145 ✔
2353
    // Check -p - D first because it is always smaller as -p + D
2354
    if (-p - D > l)
227,855,145 ✔
2355
      return -p - D;
2356
    if (-p + D > l)
186,932,629 ✔
2357
      return -p + D;
112,784,413 ✔
2358
  }
2359

2360
  return INFTY;
2361
}
2362

2363
double SphericalMesh::find_theta_crossing(
70,016,534 ✔
2364
  const Position& r, const Direction& u, double l, int shell) const
2365
{
2366
  // Theta grid is [0, π], thus there is no real surface to cross
2367
  if (full_theta_ && (shape_[1] == 1))
70,016,534 ✔
2368
    return INFTY;
2369

2370
  shell = sanitize_theta(shell);
24,323,824 ✔
2371

2372
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2373
  // yields
2374
  // a*s^2 + 2*b*s + c == 0 with
2375
  // a = cos(theta)^2 - u.z * u.z
2376
  // b = r*u * cos(theta)^2 - u.z * r.z
2377
  // c = r*r * cos(theta)^2 - r.z^2
2378

2379
  const double cos_t = std::cos(grid_[1][shell]);
24,323,824 ✔
2380
  const bool sgn = std::signbit(cos_t);
24,323,824 ✔
2381
  const double cos_t_2 = cos_t * cos_t;
24,323,824 ✔
2382

2383
  const double a = cos_t_2 - u.z * u.z;
24,323,824 ✔
2384
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
24,323,824 ✔
2385
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
24,323,824 ✔
2386

2387
  // if factor of s^2 is zero, direction of flight is parallel to theta
2388
  // surface
2389
  if (std::abs(a) < FP_PRECISION) {
24,323,824 ✔
2390
    // if b vanishes, direction of flight is within theta surface and crossing
2391
    // is not possible
2392
    if (std::abs(b) < FP_PRECISION)
307,076 !
2393
      return INFTY;
2394

2395
    const double s = -0.5 * c / b;
×
2396
    // Check if solution is in positive direction of flight and has correct
2397
    // sign
2398
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2399
      return s;
×
2400

2401
    // no crossing is possible
2402
    return INFTY;
2403
  }
2404

2405
  const double p = b / a;
24,016,748 ✔
2406
  double D = p * p - c / a;
24,016,748 ✔
2407

2408
  if (D < 0.0)
24,016,748 ✔
2409
    return INFTY;
2410

2411
  D = std::sqrt(D);
17,069,472 ✔
2412

2413
  // the solution -p-D is always smaller as -p+D : Check this one first
2414
  double s = -p - D;
17,069,472 ✔
2415
  // Check if solution is in positive direction of flight and has correct sign
2416
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
17,069,472 ✔
2417
    return s;
2418

2419
  s = -p + D;
13,722,807 ✔
2420
  // Check if solution is in positive direction of flight and has correct sign
2421
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
13,722,807 ✔
2422
    return s;
6,444,998 ✔
2423

2424
  return INFTY;
2425
}
2426

2427
double SphericalMesh::find_phi_crossing(
71,018,122 ✔
2428
  const Position& r, const Direction& u, double l, int shell) const
2429
{
2430
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2431
  if (full_phi_ && (shape_[2] == 1))
71,018,122 ✔
2432
    return INFTY;
2433

2434
  shell = sanitize_phi(shell);
25,325,412 ✔
2435

2436
  const double p0 = grid_[2][shell];
25,325,412 ✔
2437

2438
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2439
  // => x(s) * cos(p0) = y(s) * sin(p0)
2440
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2441
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2442

2443
  const double c0 = std::cos(p0);
25,325,412 ✔
2444
  const double s0 = std::sin(p0);
25,325,412 ✔
2445

2446
  const double denominator = (u.x * s0 - u.y * c0);
25,325,412 ✔
2447

2448
  // Check if direction of flight is not parallel to phi surface
2449
  if (std::abs(denominator) > FP_PRECISION) {
25,325,412 ✔
2450
    const double s = -(r.x * s0 - r.y * c0) / denominator;
25,176,508 ✔
2451
    // Check if solution is in positive direction of flight and crosses the
2452
    // correct phi surface (not -phi)
2453
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
25,176,508 ✔
2454
      return s;
11,144,280 ✔
2455
  }
2456

2457
  return INFTY;
2458
}
2459

2460
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
211,740,578 ✔
2461
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2462
  double l) const
2463
{
2464

2465
  if (i == 0) {
211,740,578 ✔
2466
    return std::min(
282,446,500 ✔
2467
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
141,223,250 ✔
2468
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
282,446,500 ✔
2469

2470
  } else if (i == 1) {
70,517,328 ✔
2471
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
35,008,267 ✔
2472
                      find_theta_crossing(r0, u, l, ijk[i])),
35,008,267 ✔
2473
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
35,008,267 ✔
2474
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
70,016,534 ✔
2475

2476
  } else {
2477
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
35,509,061 ✔
2478
                      find_phi_crossing(r0, u, l, ijk[i])),
35,509,061 ✔
2479
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
35,509,061 ✔
2480
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
71,018,122 ✔
2481
  }
2482
}
2483

2484
int SphericalMesh::set_grid()
289 ✔
2485
{
2486
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
289 ✔
2487
    static_cast<int>(grid_[1].size()) - 1,
289 ✔
2488
    static_cast<int>(grid_[2].size()) - 1};
289 ✔
2489

2490
  for (const auto& g : grid_) {
1,156 ✔
2491
    if (g.size() < 2) {
867 !
2492
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2493
                 "must each have at least 2 points");
2494
      return OPENMC_E_INVALID_ARGUMENT;
×
2495
    }
2496
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
867 !
2497
        g.end()) {
867 !
2498
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2499
                 "spherical meshes must be sorted and unique.");
2500
      return OPENMC_E_INVALID_ARGUMENT;
×
2501
    }
2502
    if (g.front() < 0.0) {
867 !
2503
      set_errmsg("r-, theta-, and phi- grids for "
×
2504
                 "spherical meshes must start at v >= 0.");
2505
      return OPENMC_E_INVALID_ARGUMENT;
×
2506
    }
2507
  }
2508
  if (grid_[1].back() > PI) {
289 !
2509
    set_errmsg("theta-grids for "
×
2510
               "spherical meshes must end with theta <= pi.");
2511

2512
    return OPENMC_E_INVALID_ARGUMENT;
×
2513
  }
2514
  if (grid_[2].back() > 2 * PI) {
289 !
2515
    set_errmsg("phi-grids for "
×
2516
               "spherical meshes must end with phi <= 2*pi.");
2517
    return OPENMC_E_INVALID_ARGUMENT;
×
2518
  }
2519

2520
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
289 !
2521
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
289 ✔
2522

2523
  double r = grid_[0].back();
289 ✔
2524
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
289 ✔
2525
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
289 ✔
2526

2527
  return 0;
289 ✔
2528
}
2529

2530
int SphericalMesh::get_index_in_direction(double r, int i) const
130,826,556 ✔
2531
{
2532
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
130,826,556 ✔
2533
}
2534

2535
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2536
  Position plot_ll, Position plot_ur) const
2537
{
2538
  fatal_error("Plot of spherical Mesh not implemented");
×
2539

2540
  // Figure out which axes lie in the plane of the plot.
2541
  array<vector<double>, 2> axis_lines;
2542
  return {axis_lines[0], axis_lines[1]};
2543
}
2544

2545
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
217 ✔
2546
{
2547
  write_dataset(mesh_group, "r_grid", grid_[0]);
217 ✔
2548
  write_dataset(mesh_group, "theta_grid", grid_[1]);
217 ✔
2549
  write_dataset(mesh_group, "phi_grid", grid_[2]);
217 ✔
2550
  write_dataset(mesh_group, "origin", origin_);
217 ✔
2551
}
217 ✔
2552

2553
double SphericalMesh::volume(const MeshIndex& ijk) const
595 ✔
2554
{
2555
  double r_i = grid_[0][ijk[0] - 1];
595 ✔
2556
  double r_o = grid_[0][ijk[0]];
595 ✔
2557

2558
  double theta_i = grid_[1][ijk[1] - 1];
595 ✔
2559
  double theta_o = grid_[1][ijk[1]];
595 ✔
2560

2561
  double phi_i = grid_[2][ijk[2] - 1];
595 ✔
2562
  double phi_o = grid_[2][ijk[2]];
595 ✔
2563

2564
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,190 ✔
2565
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
595 ✔
2566
}
2567

2568
//==============================================================================
2569
// Helper functions for the C API
2570
//==============================================================================
2571

2572
int check_mesh(int32_t index)
5,138 ✔
2573
{
2574
  if (index < 0 || index >= model::meshes.size()) {
5,138 !
2575
    set_errmsg("Index in meshes array is out of bounds.");
×
2576
    return OPENMC_E_OUT_OF_BOUNDS;
×
2577
  }
2578
  return 0;
2579
}
2580

2581
template<class T>
2582
int check_mesh_type(int32_t index)
931 ✔
2583
{
2584
  if (int err = check_mesh(index))
931 !
2585
    return err;
2586

2587
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
931 !
2588
  if (!mesh) {
931 !
2589
    set_errmsg("This function is not valid for input mesh.");
×
2590
    return OPENMC_E_INVALID_TYPE;
×
2591
  }
2592
  return 0;
2593
}
2594

2595
template<class T>
2596
bool is_mesh_type(int32_t index)
2597
{
2598
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2599
  return mesh;
2600
}
2601

2602
//==============================================================================
2603
// C API functions
2604
//==============================================================================
2605

2606
// Return the type of mesh as a C string
2607
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,064 ✔
2608
{
2609
  if (int err = check_mesh(index))
1,064 !
2610
    return err;
2611

2612
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,064 ✔
2613

2614
  return 0;
1,064 ✔
2615
}
2616

2617
//! Extend the meshes array by n elements
2618
extern "C" int openmc_extend_meshes(
266 ✔
2619
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2620
{
2621
  if (index_start)
266 !
2622
    *index_start = model::meshes.size();
266 ✔
2623
  std::string mesh_type;
266 ✔
2624

2625
  for (int i = 0; i < n; ++i) {
532 ✔
2626
    if (RegularMesh::mesh_type == type) {
266 ✔
2627
      model::meshes.push_back(make_unique<RegularMesh>());
161 ✔
2628
    } else if (RectilinearMesh::mesh_type == type) {
105 ✔
2629
      model::meshes.push_back(make_unique<RectilinearMesh>());
49 ✔
2630
    } else if (CylindricalMesh::mesh_type == type) {
56 ✔
2631
      model::meshes.push_back(make_unique<CylindricalMesh>());
28 ✔
2632
    } else if (SphericalMesh::mesh_type == type) {
28 !
2633
      model::meshes.push_back(make_unique<SphericalMesh>());
28 ✔
2634
    } else {
2635
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2636
    }
2637
  }
2638
  if (index_end)
266 !
2639
    *index_end = model::meshes.size() - 1;
×
2640

2641
  return 0;
266 ✔
2642
}
266 ✔
2643

2644
//! Adds a new unstructured mesh to OpenMC with all supported properties
UNCOV
2645
extern "C" int openmc_add_unstructured_mesh(const char filename[],
×
2646
  const char library[], double length_multiplier, const char options[],
2647
  int32_t id, int32_t* index)
2648
{
UNCOV
2649
  std::string lib_name(library);
×
UNCOV
2650
  std::string mesh_file(filename);
×
UNCOV
2651
  std::string mesh_options(options ? options : "");
×
UNCOV
2652
  bool valid_lib = false;
×
2653

2654
#ifdef OPENMC_DAGMC_ENABLED
2655
  if (lib_name == MOABMesh::mesh_lib_type) {
2656
    model::meshes.push_back(
2657
      make_unique<MOABMesh>(mesh_file, length_multiplier, mesh_options));
2658
    valid_lib = true;
2659
  }
2660
#endif
2661

2662
#ifdef OPENMC_LIBMESH_ENABLED
2663
  if (lib_name == LibMesh::mesh_lib_type) {
2664
    model::meshes.push_back(
2665
      make_unique<LibMesh>(mesh_file, length_multiplier, mesh_options));
2666
    valid_lib = true;
2667
  }
2668
#endif
2669

UNCOV
2670
  if (!valid_lib) {
×
2671
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2672
                           "by this build of OpenMC",
2673
      lib_name));
2674
    return OPENMC_E_INVALID_ARGUMENT;
×
2675
  }
2676

2677
  model::meshes.back()->set_id(id);
2678
  *index = model::meshes.size() - 1;
2679

2680
  return 0;
UNCOV
2681
}
×
2682

2683
//! Return the index in the meshes array of a mesh with a given ID
2684
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
413 ✔
2685
{
2686
  auto pair = model::mesh_map.find(id);
413 ✔
2687
  if (pair == model::mesh_map.end()) {
413 ✔
2688
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
126 ✔
2689
    return OPENMC_E_INVALID_ID;
63 ✔
2690
  }
2691
  *index = pair->second;
350 ✔
2692
  return 0;
350 ✔
2693
}
2694

2695
//! Return the ID of a mesh
2696
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,142 ✔
2697
{
2698
  if (int err = check_mesh(index))
2,142 !
2699
    return err;
2700
  *id = model::meshes[index]->id_;
2,142 ✔
2701
  return 0;
2,142 ✔
2702
}
2703

2704
//! Set the ID of a mesh
2705
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
266 ✔
2706
{
2707
  if (int err = check_mesh(index))
266 !
2708
    return err;
2709
  model::meshes[index]->set_id(id);
266 ✔
2710
  return 0;
266 ✔
2711
}
2712

2713
//! Return the name of a mesh
2714
extern "C" int openmc_mesh_get_name(int32_t index, const char** name)
35 ✔
2715
{
2716
  if (int err = check_mesh(index))
35 !
2717
    return err;
2718
  *name = model::meshes[index]->name().c_str();
35 ✔
2719
  return 0;
35 ✔
2720
}
2721

2722
//! Set the name of a mesh
2723
extern "C" int openmc_mesh_set_name(int32_t index, const char* name)
70 ✔
2724
{
2725
  if (int err = check_mesh(index))
70 !
2726
    return err;
2727
  model::meshes[index]->set_name(name);
140 ✔
2728
  return 0;
70 ✔
2729
}
2730

2731
//! Get the number of elements in a mesh
2732
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
203 ✔
2733
{
2734
  if (int err = check_mesh(index))
203 !
2735
    return err;
2736
  *n = model::meshes[index]->n_bins();
203 ✔
2737
  return 0;
203 ✔
2738
}
2739

2740
//! Get the volume of each element in the mesh
2741
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
56 ✔
2742
{
2743
  if (int err = check_mesh(index))
56 !
2744
    return err;
2745
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
616 ✔
2746
    volumes[i] = model::meshes[index]->volume(i);
560 ✔
2747
  }
2748
  return 0;
2749
}
2750

2751
//! Get the bounding box of a mesh
2752
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
112 ✔
2753
{
2754
  if (int err = check_mesh(index))
112 !
2755
    return err;
2756

2757
  BoundingBox bbox = model::meshes[index]->bounding_box();
112 ✔
2758

2759
  // set lower left corner values
2760
  ll[0] = bbox.min.x;
112 ✔
2761
  ll[1] = bbox.min.y;
112 ✔
2762
  ll[2] = bbox.min.z;
112 ✔
2763

2764
  // set upper right corner values
2765
  ur[0] = bbox.max.x;
112 ✔
2766
  ur[1] = bbox.max.y;
112 ✔
2767
  ur[2] = bbox.max.z;
112 ✔
2768
  return 0;
112 ✔
2769
}
2770

2771
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
147 ✔
2772
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2773
{
2774
  if (int err = check_mesh(index))
147 !
2775
    return err;
2776

2777
  try {
147 ✔
2778
    model::meshes[index]->material_volumes(
147 ✔
2779
      nx, ny, nz, table_size, materials, volumes, bboxes);
2780
  } catch (const std::exception& e) {
×
2781
    set_errmsg(e.what());
×
2782
    if (starts_with(e.what(), "Mesh")) {
×
2783
      return OPENMC_E_GEOMETRY;
2784
    } else {
2785
      return OPENMC_E_ALLOCATE;
×
2786
    }
2787
  }
×
2788

2789
  return 0;
2790
}
2791

2792
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
28 ✔
2793
  Position width, int basis, int* pixels, int32_t* data)
2794
{
2795
  if (int err = check_mesh(index))
28 !
2796
    return err;
2797
  const auto& mesh = model::meshes[index].get();
28 !
2798

2799
  int pixel_width = pixels[0];
28 ✔
2800
  int pixel_height = pixels[1];
28 ✔
2801

2802
  // get pixel size
2803
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
28 ✔
2804
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
28 ✔
2805

2806
  // setup basis indices and initial position centered on pixel
2807
  int in_i, out_i;
28 ✔
2808
  Position xyz = origin;
28 ✔
2809
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
28 ✔
2810
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
28 ✔
2811
  switch (basis_enum) {
28 !
2812
  case PlotBasis::xy:
2813
    in_i = 0;
2814
    out_i = 1;
2815
    break;
2816
  case PlotBasis::xz:
2817
    in_i = 0;
2818
    out_i = 2;
2819
    break;
2820
  case PlotBasis::yz:
2821
    in_i = 1;
2822
    out_i = 2;
2823
    break;
2824
  default:
×
2825
    UNREACHABLE();
×
2826
  }
2827

2828
  // set initial position
2829
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
28 ✔
2830
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
28 ✔
2831

2832
#pragma omp parallel
12 ✔
2833
  {
16 ✔
2834
    Position r = xyz;
16 ✔
2835

2836
#pragma omp for
2837
    for (int y = 0; y < pixel_height; y++) {
336 ✔
2838
      r[out_i] = xyz[out_i] - out_pixel * y;
320 ✔
2839
      for (int x = 0; x < pixel_width; x++) {
6,720 ✔
2840
        r[in_i] = xyz[in_i] + in_pixel * x;
6,400 ✔
2841
        data[pixel_width * y + x] = mesh->get_bin(r);
6,400 ✔
2842
      }
2843
    }
2844
  }
2845

2846
  return 0;
28 ✔
2847
}
2848

2849
//! Get the dimension of a regular mesh
2850
extern "C" int openmc_regular_mesh_get_dimension(
14 ✔
2851
  int32_t index, int** dims, int* n)
2852
{
2853
  if (int err = check_mesh_type<RegularMesh>(index))
14 !
2854
    return err;
2855
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
14 !
2856
  *dims = mesh->shape_.data();
14 ✔
2857
  *n = mesh->n_dimension_;
14 ✔
2858
  return 0;
14 ✔
2859
}
2860

2861
//! Set the dimension of a regular mesh
2862
extern "C" int openmc_regular_mesh_set_dimension(
175 ✔
2863
  int32_t index, int n, const int* dims)
2864
{
2865
  if (int err = check_mesh_type<RegularMesh>(index))
175 !
2866
    return err;
2867
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
175 !
2868

2869
  // Copy dimension
2870
  mesh->n_dimension_ = n;
175 ✔
2871
  std::copy(dims, dims + n, mesh->shape_.begin());
175 ✔
2872
  return 0;
175 ✔
2873
}
2874

2875
//! Get the regular mesh parameters
2876
extern "C" int openmc_regular_mesh_get_params(
147 ✔
2877
  int32_t index, double** ll, double** ur, double** width, int* n)
2878
{
2879
  if (int err = check_mesh_type<RegularMesh>(index))
147 !
2880
    return err;
2881
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
147 !
2882

2883
  if (m->lower_left_.empty()) {
147 !
2884
    set_errmsg("Mesh parameters have not been set.");
×
2885
    return OPENMC_E_ALLOCATE;
×
2886
  }
2887

2888
  *ll = m->lower_left_.data();
147 ✔
2889
  *ur = m->upper_right_.data();
147 ✔
2890
  *width = m->width_.data();
147 ✔
2891
  *n = m->n_dimension_;
147 ✔
2892
  return 0;
147 ✔
2893
}
2894

2895
//! Set the regular mesh parameters
2896
extern "C" int openmc_regular_mesh_set_params(
196 ✔
2897
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2898
{
2899
  if (int err = check_mesh_type<RegularMesh>(index))
196 !
2900
    return err;
2901
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
196 !
2902

2903
  if (m->n_dimension_ == -1) {
196 !
2904
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2905
    return OPENMC_E_UNASSIGNED;
×
2906
  }
2907

2908
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
196 ✔
2909
  if (ll && ur) {
196 ✔
2910
    m->lower_left_ = tensor::Tensor<double>(ll, n);
182 ✔
2911
    m->upper_right_ = tensor::Tensor<double>(ur, n);
182 ✔
2912
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
728 ✔
2913
  } else if (ll && width) {
14 ✔
2914
    m->lower_left_ = tensor::Tensor<double>(ll, n);
7 ✔
2915
    m->width_ = tensor::Tensor<double>(width, n);
7 ✔
2916
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
28 ✔
2917
  } else if (ur && width) {
7 !
2918
    m->upper_right_ = tensor::Tensor<double>(ur, n);
7 ✔
2919
    m->width_ = tensor::Tensor<double>(width, n);
7 ✔
2920
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
28 ✔
2921
  } else {
2922
    set_errmsg("At least two parameters must be specified.");
×
2923
    return OPENMC_E_INVALID_ARGUMENT;
2924
  }
2925

2926
  // Set material volumes
2927

2928
  // TODO: incorporate this into method in RegularMesh that can be called from
2929
  // here and from constructor
2930
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
196 ✔
2931
  m->element_volume_ = 1.0;
196 ✔
2932
  for (int i = 0; i < m->n_dimension_; i++) {
770 ✔
2933
    m->element_volume_ *= m->width_[i];
574 ✔
2934
  }
2935

2936
  return 0;
2937
}
196 ✔
2938

2939
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2940
template<class C>
2941
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
105 ✔
2942
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2943
  const int nz)
2944
{
2945
  if (int err = check_mesh_type<C>(index))
105 !
2946
    return err;
2947

2948
  C* m = dynamic_cast<C*>(model::meshes[index].get());
105 !
2949

2950
  m->n_dimension_ = 3;
105 ✔
2951

2952
  m->grid_[0].reserve(nx);
105 ✔
2953
  m->grid_[1].reserve(ny);
105 ✔
2954
  m->grid_[2].reserve(nz);
105 ✔
2955

2956
  for (int i = 0; i < nx; i++) {
728 ✔
2957
    m->grid_[0].push_back(grid_x[i]);
623 ✔
2958
  }
2959
  for (int i = 0; i < ny; i++) {
462 ✔
2960
    m->grid_[1].push_back(grid_y[i]);
357 ✔
2961
  }
2962
  for (int i = 0; i < nz; i++) {
427 ✔
2963
    m->grid_[2].push_back(grid_z[i]);
322 ✔
2964
  }
2965

2966
  int err = m->set_grid();
105 ✔
2967
  return err;
105 ✔
2968
}
2969

2970
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2971
template<class C>
2972
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
294 ✔
2973
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2974
{
2975
  if (int err = check_mesh_type<C>(index))
294 !
2976
    return err;
2977
  C* m = dynamic_cast<C*>(model::meshes[index].get());
294 !
2978

2979
  if (m->lower_left_.empty()) {
294 !
2980
    set_errmsg("Mesh parameters have not been set.");
×
2981
    return OPENMC_E_ALLOCATE;
×
2982
  }
2983

2984
  *grid_x = m->grid_[0].data();
294 ✔
2985
  *nx = m->grid_[0].size();
294 ✔
2986
  *grid_y = m->grid_[1].data();
294 ✔
2987
  *ny = m->grid_[1].size();
294 ✔
2988
  *grid_z = m->grid_[2].data();
294 ✔
2989
  *nz = m->grid_[2].size();
294 ✔
2990

2991
  return 0;
294 ✔
2992
}
2993

2994
//! Get the rectilinear mesh grid
2995
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
112 ✔
2996
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2997
{
2998
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
112 ✔
2999
    index, grid_x, nx, grid_y, ny, grid_z, nz);
112 ✔
3000
}
3001

3002
//! Set the rectilienar mesh parameters
3003
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
49 ✔
3004
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3005
  const double* grid_z, const int nz)
3006
{
3007
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
49 ✔
3008
    index, grid_x, nx, grid_y, ny, grid_z, nz);
49 ✔
3009
}
3010

3011
//! Get the cylindrical mesh grid
3012
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
91 ✔
3013
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3014
{
3015
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
91 ✔
3016
    index, grid_x, nx, grid_y, ny, grid_z, nz);
91 ✔
3017
}
3018

3019
//! Set the cylindrical mesh parameters
3020
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
28 ✔
3021
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3022
  const double* grid_z, const int nz)
3023
{
3024
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
28 ✔
3025
    index, grid_x, nx, grid_y, ny, grid_z, nz);
28 ✔
3026
}
3027

3028
//! Get the spherical mesh grid
3029
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
91 ✔
3030
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
3031
{
3032

3033
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
91 ✔
3034
    index, grid_x, nx, grid_y, ny, grid_z, nz);
91 ✔
3035
  ;
91 ✔
3036
}
3037

3038
//! Set the spherical mesh parameters
3039
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
28 ✔
3040
  const double* grid_x, const int nx, const double* grid_y, const int ny,
3041
  const double* grid_z, const int nz)
3042
{
3043
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
28 ✔
3044
    index, grid_x, nx, grid_y, ny, grid_z, nz);
28 ✔
3045
}
3046

3047
template<class T>
3048
int openmc_periodic_mesh_get_origin_impl(int32_t index, double origin[3])
28 ✔
3049
{
3050
  if (int err = check_mesh(index))
28 !
3051
    return err;
3052
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
28 !
3053
  if (!mesh) {
28 !
3054
    set_errmsg("This mesh is not of the expected type.");
×
3055
    return OPENMC_E_INVALID_TYPE;
×
3056
  }
3057
  const auto& mesh_origin = mesh->origin();
28 ✔
3058
  origin[0] = mesh_origin.x;
28 ✔
3059
  origin[1] = mesh_origin.y;
28 ✔
3060
  origin[2] = mesh_origin.z;
28 ✔
3061
  return 0;
28 ✔
3062
}
3063

3064
template<class T>
3065
int openmc_periodic_mesh_set_origin_impl(int32_t index, const double origin[3])
56 ✔
3066
{
3067
  if (int err = check_mesh(index))
56 !
3068
    return err;
3069
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
56 !
3070
  if (!mesh) {
56 !
3071
    set_errmsg("This mesh is not of the expected type.");
×
3072
    return OPENMC_E_INVALID_TYPE;
×
3073
  }
3074
  return mesh->set_origin({origin[0], origin[1], origin[2]});
56 ✔
3075
}
3076

3077
extern "C" int openmc_cylindrical_mesh_get_origin(
14 ✔
3078
  int32_t index, double origin[3])
3079
{
3080
  return openmc_periodic_mesh_get_origin_impl<CylindricalMesh>(index, origin);
14 ✔
3081
}
3082

3083
extern "C" int openmc_cylindrical_mesh_set_origin(
28 ✔
3084
  int32_t index, const double origin[3])
3085
{
3086
  return openmc_periodic_mesh_set_origin_impl<CylindricalMesh>(index, origin);
28 ✔
3087
}
3088

3089
extern "C" int openmc_spherical_mesh_get_origin(int32_t index, double origin[3])
14 ✔
3090
{
3091
  return openmc_periodic_mesh_get_origin_impl<SphericalMesh>(index, origin);
14 ✔
3092
}
3093

3094
extern "C" int openmc_spherical_mesh_set_origin(
28 ✔
3095
  int32_t index, const double origin[3])
3096
{
3097
  return openmc_periodic_mesh_set_origin_impl<SphericalMesh>(index, origin);
28 ✔
3098
}
3099

3100
#ifdef OPENMC_DAGMC_ENABLED
3101

3102
const std::string MOABMesh::mesh_lib_type = "moab";
3103

3104
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
3105
{
3106
  initialize();
3107
}
3108

3109
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
3110
{
3111
  initialize();
3112
}
3113

3114
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier,
3115
  const std::string& options)
3116
  : UnstructuredMesh()
3117
{
3118
  n_dimension_ = 3;
3119
  filename_ = filename;
3120
  options_ = options;
3121
  set_length_multiplier(length_multiplier);
3122
  initialize();
3123
}
3124

3125
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
3126
{
3127
  mbi_ = external_mbi;
3128
  filename_ = "unknown (external file)";
3129
  this->initialize();
3130
}
3131

3132
void MOABMesh::initialize()
3133
{
3134
  // Create the MOAB interface and load data from file
3135
  this->create_interface();
3136

3137
  // Initialise MOAB error code
3138
  moab::ErrorCode rval = moab::MB_SUCCESS;
3139

3140
  // Set the dimension
3141
  n_dimension_ = 3;
3142

3143
  // set member range of tetrahedral entities
3144
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
3145
  if (rval != moab::MB_SUCCESS) {
3146
    fatal_error("Failed to get all tetrahedral elements");
3147
  }
3148

3149
  if (!ehs_.all_of_type(moab::MBTET)) {
3150
    warning("Non-tetrahedral elements found in unstructured "
3151
            "mesh file: " +
3152
            filename_);
3153
  }
3154

3155
  // set member range of vertices
3156
  int vertex_dim = 0;
3157
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
3158
  if (rval != moab::MB_SUCCESS) {
3159
    fatal_error("Failed to get all vertex handles");
3160
  }
3161

3162
  // make an entity set for all tetrahedra
3163
  // this is used for convenience later in output
3164
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
3165
  if (rval != moab::MB_SUCCESS) {
3166
    fatal_error("Failed to create an entity set for the tetrahedral elements");
3167
  }
3168

3169
  rval = mbi_->add_entities(tetset_, ehs_);
3170
  if (rval != moab::MB_SUCCESS) {
3171
    fatal_error("Failed to add tetrahedra to an entity set.");
3172
  }
3173

3174
  if (length_multiplier_ > 0.0) {
3175
    // get the connectivity of all tets
3176
    moab::Range adj;
3177
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
3178
    if (rval != moab::MB_SUCCESS) {
3179
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
3180
    }
3181
    // scale all vertex coords by multiplier (done individually so not all
3182
    // coordinates are in memory twice at once)
3183
    for (auto vert : adj) {
3184
      // retrieve coords
3185
      std::array<double, 3> coord;
3186
      rval = mbi_->get_coords(&vert, 1, coord.data());
3187
      if (rval != moab::MB_SUCCESS) {
3188
        fatal_error("Could not get coordinates of vertex.");
3189
      }
3190
      // scale coords
3191
      for (auto& c : coord) {
3192
        c *= length_multiplier_;
3193
      }
3194
      // set new coords
3195
      rval = mbi_->set_coords(&vert, 1, coord.data());
3196
      if (rval != moab::MB_SUCCESS) {
3197
        fatal_error("Failed to set new vertex coordinates");
3198
      }
3199
    }
3200
  }
3201

3202
  // Determine bounds of mesh
3203
  this->determine_bounds();
3204
}
3205

3206
void MOABMesh::prepare_for_point_location()
3207
{
3208
  // if the KDTree has already been constructed, do nothing
3209
  if (kdtree_)
3210
    return;
3211

3212
  // build acceleration data structures
3213
  compute_barycentric_data(ehs_);
3214
  build_kdtree(ehs_);
3215
}
3216

3217
void MOABMesh::create_interface()
3218
{
3219
  // Do not create a MOAB instance if one is already in memory
3220
  if (mbi_)
3221
    return;
3222

3223
  // create MOAB instance
3224
  mbi_ = std::make_shared<moab::Core>();
3225

3226
  // load unstructured mesh file
3227
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
3228
  if (rval != moab::MB_SUCCESS) {
3229
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3230
  }
3231
}
3232

3233
void MOABMesh::build_kdtree(const moab::Range& all_tets)
3234
{
3235
  moab::Range all_tris;
3236
  int adj_dim = 2;
3237
  write_message("Getting tet adjacencies...", 7);
3238
  moab::ErrorCode rval = mbi_->get_adjacencies(
3239
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3240
  if (rval != moab::MB_SUCCESS) {
3241
    fatal_error("Failed to get adjacent triangles for tets");
3242
  }
3243

3244
  if (!all_tris.all_of_type(moab::MBTRI)) {
3245
    warning("Non-triangle elements found in tet adjacencies in "
3246
            "unstructured mesh file: " +
3247
            filename_);
3248
  }
3249

3250
  // combine into one range
3251
  moab::Range all_tets_and_tris;
3252
  all_tets_and_tris.merge(all_tets);
3253
  all_tets_and_tris.merge(all_tris);
3254

3255
  // create a kd-tree instance
3256
  write_message(
3257
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
3258
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
3259

3260
  // Determine what options to use
3261
  std::ostringstream options_stream;
3262
  if (options_.empty()) {
3263
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
3264
  } else {
3265
    options_stream << options_;
3266
  }
3267
  moab::FileOptions file_opts(options_stream.str().c_str());
3268

3269
  // Build the k-d tree
3270
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
3271
  if (rval != moab::MB_SUCCESS) {
3272
    fatal_error("Failed to construct KDTree for the "
3273
                "unstructured mesh file: " +
3274
                filename_);
3275
  }
3276
}
3277

3278
void MOABMesh::intersect_track(const moab::CartVect& start,
3279
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3280
{
3281
  hits.clear();
3282

3283
  moab::ErrorCode rval;
3284
  vector<moab::EntityHandle> tris;
3285
  // get all intersections with triangles in the tet mesh
3286
  // (distances are relative to the start point, not the previous
3287
  // intersection)
3288
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
3289
    dir.array(), start.array(), tris, hits, 0, track_len);
3290
  if (rval != moab::MB_SUCCESS) {
3291
    fatal_error(
3292
      "Failed to compute intersections on unstructured mesh: " + filename_);
3293
  }
3294

3295
  // remove duplicate intersection distances
3296
  std::unique(hits.begin(), hits.end());
3297

3298
  // sorts by first component of std::pair by default
3299
  std::sort(hits.begin(), hits.end());
3300
}
3301

3302
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3303
  vector<int>& bins, vector<double>& lengths) const
3304
{
3305
  moab::CartVect start(r0.x, r0.y, r0.z);
3306
  moab::CartVect end(r1.x, r1.y, r1.z);
3307
  moab::CartVect dir(u.x, u.y, u.z);
3308
  dir.normalize();
3309

3310
  double track_len = (end - start).length();
3311
  if (track_len == 0.0)
3312
    return;
3313

3314
  start -= TINY_BIT * dir;
3315
  end += TINY_BIT * dir;
3316

3317
  vector<double> hits;
3318
  intersect_track(start, dir, track_len, hits);
3319

3320
  bins.clear();
3321
  lengths.clear();
3322

3323
  // if there are no intersections the track may lie entirely
3324
  // within a single tet. If this is the case, apply entire
3325
  // score to that tet and return.
3326
  if (hits.size() == 0) {
3327
    Position midpoint = r0 + u * (track_len * 0.5);
3328
    int bin = this->get_bin(midpoint);
3329
    if (bin != -1) {
3330
      bins.push_back(bin);
3331
      lengths.push_back(1.0);
3332
    }
3333
    return;
3334
  }
3335

3336
  // for each segment in the set of tracks, try to look up a tet
3337
  // at the midpoint of the segment
3338
  Position current = r0;
3339
  double last_dist = 0.0;
3340
  for (const auto& hit : hits) {
3341
    // get the segment length
3342
    double segment_length = hit - last_dist;
3343
    last_dist = hit;
3344
    // find the midpoint of this segment
3345
    Position midpoint = current + u * (segment_length * 0.5);
3346
    // try to find a tet for this position
3347
    int bin = this->get_bin(midpoint);
3348

3349
    // determine the start point for this segment
3350
    current = r0 + u * hit;
3351

3352
    if (bin == -1) {
3353
      continue;
3354
    }
3355

3356
    bins.push_back(bin);
3357
    lengths.push_back(segment_length / track_len);
3358
  }
3359

3360
  // tally remaining portion of track after last hit if
3361
  // the last segment of the track is in the mesh but doesn't
3362
  // reach the other side of the tet
3363
  if (hits.back() < track_len) {
3364
    Position segment_start = r0 + u * hits.back();
3365
    double segment_length = track_len - hits.back();
3366
    Position midpoint = segment_start + u * (segment_length * 0.5);
3367
    int bin = this->get_bin(midpoint);
3368
    if (bin != -1) {
3369
      bins.push_back(bin);
3370
      lengths.push_back(segment_length / track_len);
3371
    }
3372
  }
3373
};
3374

3375
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
3376
{
3377
  moab::CartVect pos(r.x, r.y, r.z);
3378
  // find the leaf of the kd-tree for this position
3379
  moab::AdaptiveKDTreeIter kdtree_iter;
3380
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
3381
  if (rval != moab::MB_SUCCESS) {
3382
    return 0;
3383
  }
3384

3385
  // retrieve the tet elements of this leaf
3386
  moab::EntityHandle leaf = kdtree_iter.handle();
3387
  moab::Range tets;
3388
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
3389
  if (rval != moab::MB_SUCCESS) {
3390
    warning("MOAB error finding tets.");
3391
  }
3392

3393
  // loop over the tets in this leaf, returning the containing tet if found
3394
  for (const auto& tet : tets) {
3395
    if (point_in_tet(pos, tet)) {
3396
      return tet;
3397
    }
3398
  }
3399

3400
  // if no tet is found, return an invalid handle
3401
  return 0;
3402
}
3403

3404
double MOABMesh::volume(int bin) const
3405
{
3406
  return tet_volume(get_ent_handle_from_bin(bin));
3407
}
3408

3409
std::string MOABMesh::library() const
3410
{
3411
  return mesh_lib_type;
3412
}
3413

3414
// Sample position within a tet for MOAB type tets
3415
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
3416
{
3417
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
3418

3419
  // Get vertex coordinates for MOAB tet
3420
  const moab::EntityHandle* conn1;
3421
  int conn1_size;
3422
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
3423
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
3424
    fatal_error(fmt::format(
3425
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3426
      conn1_size));
3427
  }
3428
  moab::CartVect p[4];
3429
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
3430
  if (rval != moab::MB_SUCCESS) {
3431
    fatal_error("Failed to get tet coords");
3432
  }
3433

3434
  // Samples position within tet using Barycentric stuff
3435
  return this->sample_tet<moab::CartVect>({p, 4}, seed);
3436
}
3437

3438
double MOABMesh::tet_volume(moab::EntityHandle tet) const
3439
{
3440
  vector<moab::EntityHandle> conn;
3441
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
3442
  if (rval != moab::MB_SUCCESS) {
3443
    fatal_error("Failed to get tet connectivity");
3444
  }
3445

3446
  moab::CartVect p[4];
3447
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
3448
  if (rval != moab::MB_SUCCESS) {
3449
    fatal_error("Failed to get tet coords");
3450
  }
3451

3452
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
3453
}
3454

3455
int MOABMesh::get_bin(Position r) const
3456
{
3457
  moab::EntityHandle tet = get_tet(r);
3458
  if (tet == 0) {
3459
    return -1;
3460
  } else {
3461
    return get_bin_from_ent_handle(tet);
3462
  }
3463
}
3464

3465
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
3466
{
3467
  moab::ErrorCode rval;
3468

3469
  baryc_data_.clear();
3470
  baryc_data_.resize(tets.size());
3471

3472
  // compute the barycentric data for each tet element
3473
  // and store it as a 3x3 matrix
3474
  for (auto& tet : tets) {
3475
    vector<moab::EntityHandle> verts;
3476
    rval = mbi_->get_connectivity(&tet, 1, verts);
3477
    if (rval != moab::MB_SUCCESS) {
3478
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
3479
    }
3480

3481
    moab::CartVect p[4];
3482
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
3483
    if (rval != moab::MB_SUCCESS) {
3484
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
3485
    }
3486

3487
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
3488

3489
    // invert now to avoid this cost later
3490
    a = a.transpose().inverse();
3491
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
3492
  }
3493
}
3494

3495
bool MOABMesh::point_in_tet(
3496
  const moab::CartVect& r, moab::EntityHandle tet) const
3497
{
3498

3499
  moab::ErrorCode rval;
3500

3501
  // get tet vertices
3502
  vector<moab::EntityHandle> verts;
3503
  rval = mbi_->get_connectivity(&tet, 1, verts);
3504
  if (rval != moab::MB_SUCCESS) {
3505
    warning("Failed to get vertices of tet in umesh: " + filename_);
3506
    return false;
3507
  }
3508

3509
  // first vertex is used as a reference point for the barycentric data -
3510
  // retrieve its coordinates
3511
  moab::CartVect p_zero;
3512
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
3513
  if (rval != moab::MB_SUCCESS) {
3514
    warning("Failed to get coordinates of a vertex in "
3515
            "unstructured mesh: " +
3516
            filename_);
3517
    return false;
3518
  }
3519

3520
  // look up barycentric data
3521
  int idx = get_bin_from_ent_handle(tet);
3522
  const moab::Matrix3& a_inv = baryc_data_[idx];
3523

3524
  moab::CartVect bary_coords = a_inv * (r - p_zero);
3525

3526
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
3527
          bary_coords[2] >= 0.0 &&
3528
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
3529
}
3530

3531
int MOABMesh::get_bin_from_index(int idx) const
3532
{
3533
  if (idx >= n_bins()) {
3534
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3535
  }
3536
  return ehs_[idx] - ehs_[0];
3537
}
3538

3539
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3540
{
3541
  int bin = get_bin(r);
3542
  *in_mesh = bin != -1;
3543
  return bin;
3544
}
3545

3546
int MOABMesh::get_index_from_bin(int bin) const
3547
{
3548
  return bin;
3549
}
3550

3551
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3552
  Position plot_ll, Position plot_ur) const
3553
{
3554
  // TODO: Implement mesh lines
3555
  return {};
3556
}
3557

3558
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
3559
{
3560
  int idx = vert - verts_[0];
3561
  if (idx >= n_vertices()) {
3562
    fatal_error(
3563
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
3564
  }
3565
  return idx;
3566
}
3567

3568
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
3569
{
3570
  int bin = eh - ehs_[0];
3571
  if (bin >= n_bins()) {
3572
    fatal_error(fmt::format("Invalid bin: {}", bin));
3573
  }
3574
  return bin;
3575
}
3576

3577
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
3578
{
3579
  if (bin >= n_bins()) {
3580
    fatal_error(fmt::format("Invalid bin index: ", bin));
3581
  }
3582
  return ehs_[0] + bin;
3583
}
3584

3585
int MOABMesh::n_bins() const
3586
{
3587
  return ehs_.size();
3588
}
3589

3590
int MOABMesh::n_surface_bins() const
3591
{
3592
  // collect all triangles in the set of tets for this mesh
3593
  moab::Range tris;
3594
  moab::ErrorCode rval;
3595
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
3596
  if (rval != moab::MB_SUCCESS) {
3597
    warning("Failed to get all triangles in the mesh instance");
3598
    return -1;
3599
  }
3600
  return 2 * tris.size();
3601
}
3602

3603
Position MOABMesh::centroid(int bin) const
3604
{
3605
  moab::ErrorCode rval;
3606

3607
  auto tet = this->get_ent_handle_from_bin(bin);
3608

3609
  // look up the tet connectivity
3610
  vector<moab::EntityHandle> conn;
3611
  rval = mbi_->get_connectivity(&tet, 1, conn);
3612
  if (rval != moab::MB_SUCCESS) {
3613
    warning("Failed to get connectivity of a mesh element.");
3614
    return {};
3615
  }
3616

3617
  // get the coordinates
3618
  vector<moab::CartVect> coords(conn.size());
3619
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
3620
  if (rval != moab::MB_SUCCESS) {
3621
    warning("Failed to get the coordinates of a mesh element.");
3622
    return {};
3623
  }
3624

3625
  // compute the centroid of the element vertices
3626
  moab::CartVect centroid(0.0, 0.0, 0.0);
3627
  for (const auto& coord : coords) {
3628
    centroid += coord;
3629
  }
3630
  centroid /= double(coords.size());
3631

3632
  return {centroid[0], centroid[1], centroid[2]};
3633
}
3634

3635
int MOABMesh::n_vertices() const
3636
{
3637
  return verts_.size();
3638
}
3639

3640
Position MOABMesh::vertex(int id) const
3641
{
3642

3643
  moab::ErrorCode rval;
3644

3645
  moab::EntityHandle vert = verts_[id];
3646

3647
  moab::CartVect coords;
3648
  rval = mbi_->get_coords(&vert, 1, coords.array());
3649
  if (rval != moab::MB_SUCCESS) {
3650
    fatal_error("Failed to get the coordinates of a vertex.");
3651
  }
3652

3653
  return {coords[0], coords[1], coords[2]};
3654
}
3655

3656
std::vector<int> MOABMesh::connectivity(int bin) const
3657
{
3658
  moab::ErrorCode rval;
3659

3660
  auto tet = get_ent_handle_from_bin(bin);
3661

3662
  // look up the tet connectivity
3663
  vector<moab::EntityHandle> conn;
3664
  rval = mbi_->get_connectivity(&tet, 1, conn);
3665
  if (rval != moab::MB_SUCCESS) {
3666
    fatal_error("Failed to get connectivity of a mesh element.");
3667
    return {};
3668
  }
3669

3670
  std::vector<int> verts(4);
3671
  for (int i = 0; i < verts.size(); i++) {
3672
    verts[i] = get_vert_idx_from_handle(conn[i]);
3673
  }
3674

3675
  return verts;
3676
}
3677

3678
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3679
  std::string score) const
3680
{
3681
  moab::ErrorCode rval;
3682
  // add a tag to the mesh
3683
  // all scores are treated as a single value
3684
  // with an uncertainty
3685
  moab::Tag value_tag;
3686

3687
  // create the value tag if not present and get handle
3688
  double default_val = 0.0;
3689
  auto val_string = score + "_mean";
3690
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3691
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3692
  if (rval != moab::MB_SUCCESS) {
3693
    auto msg =
3694
      fmt::format("Could not create or retrieve the value tag for the score {}"
3695
                  " on unstructured mesh {}",
3696
        score, id_);
3697
    fatal_error(msg);
3698
  }
3699

3700
  // create the std dev tag if not present and get handle
3701
  moab::Tag error_tag;
3702
  std::string err_string = score + "_std_dev";
3703
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
3704
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3705
  if (rval != moab::MB_SUCCESS) {
3706
    auto msg =
3707
      fmt::format("Could not create or retrieve the error tag for the score {}"
3708
                  " on unstructured mesh {}",
3709
        score, id_);
3710
    fatal_error(msg);
3711
  }
3712

3713
  // return the populated tag handles
3714
  return {value_tag, error_tag};
3715
}
3716

3717
void MOABMesh::add_score(const std::string& score)
3718
{
3719
  auto score_tags = get_score_tags(score);
3720
  tag_names_.push_back(score);
3721
}
3722

3723
void MOABMesh::remove_scores()
3724
{
3725
  for (const auto& name : tag_names_) {
3726
    auto value_name = name + "_mean";
3727
    moab::Tag tag;
3728
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
3729
    if (rval != moab::MB_SUCCESS)
3730
      return;
3731

3732
    rval = mbi_->tag_delete(tag);
3733
    if (rval != moab::MB_SUCCESS) {
3734
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3735
                             " on unstructured mesh {}",
3736
        name, id_);
3737
      fatal_error(msg);
3738
    }
3739

3740
    auto std_dev_name = name + "_std_dev";
3741
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
3742
    if (rval != moab::MB_SUCCESS) {
3743
      auto msg =
3744
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3745
                    " on unstructured mesh {}",
3746
          name, id_);
3747
    }
3748

3749
    rval = mbi_->tag_delete(tag);
3750
    if (rval != moab::MB_SUCCESS) {
3751
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3752
                             " on unstructured mesh {}",
3753
        name, id_);
3754
      fatal_error(msg);
3755
    }
3756
  }
3757
  tag_names_.clear();
3758
}
3759

3760
void MOABMesh::set_score_data(const std::string& score,
3761
  const vector<double>& values, const vector<double>& std_dev)
3762
{
3763
  auto score_tags = this->get_score_tags(score);
3764

3765
  moab::ErrorCode rval;
3766
  // set the score value
3767
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3768
  if (rval != moab::MB_SUCCESS) {
3769
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3770
                           "on unstructured mesh {}",
3771
      score, id_);
3772
    warning(msg);
3773
  }
3774

3775
  // set the error value
3776
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3777
  if (rval != moab::MB_SUCCESS) {
3778
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3779
                           "on unstructured mesh {}",
3780
      score, id_);
3781
    warning(msg);
3782
  }
3783
}
3784

3785
void MOABMesh::write(const std::string& base_filename) const
3786
{
3787
  // add extension to the base name
3788
  auto filename = base_filename + ".vtk";
3789
  write_message(5, "Writing unstructured mesh {}...", filename);
3790
  filename = settings::path_output + filename;
3791

3792
  // write the tetrahedral elements of the mesh only
3793
  // to avoid clutter from zero-value data on other
3794
  // elements during visualization
3795
  moab::ErrorCode rval;
3796
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
3797
  if (rval != moab::MB_SUCCESS) {
3798
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
3799
    warning(msg);
3800
  }
3801
}
3802

3803
#endif
3804

3805
#ifdef OPENMC_LIBMESH_ENABLED
3806

3807
const std::string LibMesh::mesh_lib_type = "libmesh";
3808

3809
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
3810
{
3811
  // filename_ and length_multiplier_ will already be set by the
3812
  // UnstructuredMesh constructor
3813
  set_mesh_pointer_from_filename(filename_);
3814
  set_length_multiplier(length_multiplier_);
3815
  initialize();
3816
}
3817

3818
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
3819
{
3820
  // filename_ and length_multiplier_ will already be set by the
3821
  // UnstructuredMesh constructor
3822
  set_mesh_pointer_from_filename(filename_);
3823
  set_length_multiplier(length_multiplier_);
3824
  initialize();
3825
}
3826

3827
// create the mesh from a pointer to a libMesh Mesh
3828
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3829
{
3830
  if (!input_mesh.is_replicated()) {
3831
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3832
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3833
  }
3834

3835
  m_ = &input_mesh;
3836
  set_length_multiplier(length_multiplier);
3837
  initialize();
3838
}
3839

3840
// create the mesh from an input file
3841
LibMesh::LibMesh(const std::string& filename, double length_multiplier,
3842
  const std::string& options)
3843
{
3844
  n_dimension_ = 3;
3845
  options_ = options;
3846
  set_mesh_pointer_from_filename(filename);
3847
  set_length_multiplier(length_multiplier);
3848
  initialize();
3849
}
3850

3851
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3852
{
3853
  filename_ = filename;
3854
  unique_m_ =
3855
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
3856
  m_ = unique_m_.get();
3857
  m_->read(filename_);
3858
}
3859

3860
// build a libMesh equation system for storing values
3861
void LibMesh::build_eqn_sys()
3862
{
3863
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
3864
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3865
  libMesh::ExplicitSystem& eq_sys =
3866
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
3867
}
3868

3869
// intialize from mesh file
3870
void LibMesh::initialize()
3871
{
3872
  if (!settings::libmesh_comm) {
3873
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3874
                "communicator.");
3875
  }
3876

3877
  // assuming that unstructured meshes used in OpenMC are 3D
3878
  n_dimension_ = 3;
3879

3880
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3881
  // Otherwise assume that it is prepared by its owning application
3882
  if (unique_m_) {
3883
    m_->prepare_for_use();
3884
  }
3885

3886
  // ensure that the loaded mesh is 3 dimensional
3887
  if (m_->mesh_dimension() != n_dimension_) {
3888
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3889
                            "mesh is not a 3D mesh.",
3890
      filename_));
3891
  }
3892

3893
  for (int i = 0; i < num_threads(); i++) {
3894
    pl_.emplace_back(m_->sub_point_locator());
3895
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3896
    pl_.back()->enable_out_of_mesh_mode();
3897
  }
3898

3899
  // store first element in the mesh to use as an offset for bin indices
3900
  auto first_elem = *m_->elements_begin();
3901
  first_element_id_ = first_elem->id();
3902

3903
  // bounding box for the mesh for quick rejection checks
3904
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3905
  libMesh::Point ll = bbox_.min();
3906
  libMesh::Point ur = bbox_.max();
3907
  if (length_multiplier_ > 0.0) {
3908
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3909
      length_multiplier_ * ll(2)};
3910
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3911
      length_multiplier_ * ur(2)};
3912
  } else {
3913
    lower_left_ = {ll(0), ll(1), ll(2)};
3914
    upper_right_ = {ur(0), ur(1), ur(2)};
3915
  }
3916
}
3917

3918
// Sample position within a tet for LibMesh type tets
3919
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
3920
{
3921
  const auto& elem = get_element_from_bin(bin);
3922
  // Get tet vertex coordinates from LibMesh
3923
  std::array<Position, 4> tet_verts;
3924
  for (int i = 0; i < elem.n_nodes(); i++) {
3925
    const auto& node_ref = elem.node_ref(i);
3926
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
3927
  }
3928
  // Samples position within tet using Barycentric coordinates
3929
  Position sampled_position =
3930
    this->sample_tet<Position>({tet_verts.begin(), tet_verts.end()}, seed);
3931
  if (length_multiplier_ > 0.0) {
3932
    return length_multiplier_ * sampled_position;
3933
  } else {
3934
    return sampled_position;
3935
  }
3936
}
3937

3938
Position LibMesh::centroid(int bin) const
3939
{
3940
  const auto& elem = this->get_element_from_bin(bin);
3941
  auto centroid = elem.vertex_average();
3942
  if (length_multiplier_ > 0.0) {
3943
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3944
  } else {
3945
    return {centroid(0), centroid(1), centroid(2)};
3946
  }
3947
}
3948

3949
int LibMesh::n_vertices() const
3950
{
3951
  return m_->n_nodes();
3952
}
3953

3954
Position LibMesh::vertex(int vertex_id) const
3955
{
3956
  const auto& node_ref = m_->node_ref(vertex_id);
3957
  if (length_multiplier_ > 0.0) {
3958
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3959
  } else {
3960
    return {node_ref(0), node_ref(1), node_ref(2)};
3961
  }
3962
}
3963

3964
std::vector<int> LibMesh::connectivity(int elem_id) const
3965
{
3966
  std::vector<int> conn;
3967
  const auto* elem_ptr = m_->elem_ptr(elem_id);
3968
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3969
    conn.push_back(elem_ptr->node_id(i));
3970
  }
3971
  return conn;
3972
}
3973

3974
std::string LibMesh::library() const
3975
{
3976
  return mesh_lib_type;
3977
}
3978

3979
int LibMesh::n_bins() const
3980
{
3981
  return m_->n_elem();
3982
}
3983

3984
int LibMesh::n_surface_bins() const
3985
{
3986
  int n_bins = 0;
3987
  for (int i = 0; i < this->n_bins(); i++) {
3988
    const libMesh::Elem& e = get_element_from_bin(i);
3989
    n_bins += e.n_faces();
3990
    // if this is a boundary element, it will only be visited once,
3991
    // the number of surface bins is incremented to
3992
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
3993
      // null neighbor pointer indicates a boundary face
3994
      if (!neighbor_ptr) {
3995
        n_bins++;
3996
      }
3997
    }
3998
  }
3999
  return n_bins;
4000
}
4001

4002
void LibMesh::add_score(const std::string& var_name)
4003
{
4004
  if (!equation_systems_) {
4005
    build_eqn_sys();
4006
  }
4007

4008
  // check if this is a new variable
4009
  std::string value_name = var_name + "_mean";
4010
  if (!variable_map_.count(value_name)) {
4011
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
4012
    auto var_num =
4013
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
4014
    variable_map_[value_name] = var_num;
4015
  }
4016

4017
  std::string std_dev_name = var_name + "_std_dev";
4018
  // check if this is a new variable
4019
  if (!variable_map_.count(std_dev_name)) {
4020
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
4021
    auto var_num =
4022
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
4023
    variable_map_[std_dev_name] = var_num;
4024
  }
4025
}
4026

4027
void LibMesh::remove_scores()
4028
{
4029
  if (equation_systems_) {
4030
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
4031
    eqn_sys.clear();
4032
    variable_map_.clear();
4033
  }
4034
}
4035

4036
void LibMesh::set_score_data(const std::string& var_name,
4037
  const vector<double>& values, const vector<double>& std_dev)
4038
{
4039
  if (!equation_systems_) {
4040
    build_eqn_sys();
4041
  }
4042

4043
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
4044

4045
  if (!eqn_sys.is_initialized()) {
4046
    equation_systems_->init();
4047
  }
4048

4049
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
4050

4051
  // look up the value variable
4052
  std::string value_name = var_name + "_mean";
4053
  unsigned int value_num = variable_map_.at(value_name);
4054
  // look up the std dev variable
4055
  std::string std_dev_name = var_name + "_std_dev";
4056
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
4057

4058
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
4059
       it++) {
4060
    if (!(*it)->active()) {
4061
      continue;
4062
    }
4063

4064
    auto bin = get_bin_from_element(*it);
4065

4066
    // set value
4067
    vector<libMesh::dof_id_type> value_dof_indices;
4068
    dof_map.dof_indices(*it, value_dof_indices, value_num);
4069
    assert(value_dof_indices.size() == 1);
4070
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
4071

4072
    // set std dev
4073
    vector<libMesh::dof_id_type> std_dev_dof_indices;
4074
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
4075
    assert(std_dev_dof_indices.size() == 1);
4076
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
4077
  }
4078
}
4079

4080
void LibMesh::write(const std::string& filename) const
4081
{
4082
  // A serial libMesh communicator considers every OpenMC rank to be its
4083
  // processor 0. Restrict the non-collective write to the OpenMC master in
4084
  // that case. With a parallel communicator, all ranks must participate in
4085
  // libMesh's solution assembly.
4086
  if (settings::libmesh_comm->size() == 1 && !mpi::master) {
4087
    return;
4088
  }
4089

4090
  write_message(fmt::format(
4091
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
4092
  libMesh::ExodusII_IO exo(*m_);
4093
  std::set<std::string> systems_out = {eq_system_name_};
4094
  exo.write_discontinuous_exodusII(
4095
    filename + ".e", *equation_systems_, &systems_out);
4096
}
4097

4098
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
4099
  vector<int>& bins, vector<double>& lengths) const
4100
{
4101
  // TODO: Implement triangle crossings here
4102
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
4103
}
4104

4105
int LibMesh::get_bin(Position r) const
4106
{
4107
  // look-up a tet using the point locator
4108
  libMesh::Point p(r.x, r.y, r.z);
4109

4110
  if (length_multiplier_ > 0.0) {
4111
    // Scale the point down
4112
    p /= length_multiplier_;
4113
  }
4114

4115
  // quick rejection check
4116
  if (!bbox_.contains_point(p)) {
4117
    return -1;
4118
  }
4119

4120
  const auto& point_locator = pl_.at(thread_num());
4121

4122
  const auto elem_ptr = (*point_locator)(p);
4123
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
4124
}
4125

4126
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4127
{
4128
  int bin = elem->id() - first_element_id_;
4129
  if (bin >= n_bins() || bin < 0) {
4130
    fatal_error(fmt::format("Invalid bin: {}", bin));
4131
  }
4132
  return bin;
4133
}
4134

4135
std::pair<vector<double>, vector<double>> LibMesh::plot(
4136
  Position plot_ll, Position plot_ur) const
4137
{
4138
  return {};
4139
}
4140

4141
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
4142
{
4143
  return m_->elem_ref(bin);
4144
}
4145

4146
double LibMesh::volume(int bin) const
4147
{
4148
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
4149
         length_multiplier_ * length_multiplier_;
4150
}
4151

4152
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
4153
  double length_multiplier,
4154
  const std::set<libMesh::subdomain_id_type>& block_ids)
4155
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
4156
    block_restrict_(!block_ids_.empty()),
4157
    num_active_(
4158
      block_restrict_
4159
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
4160
            m_->active_subdomain_set_elements_end(block_ids_))
4161
        : m_->n_active_elem())
4162
{
4163
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
4164
  // contiguous in ID space, so we need to map from bin indices (defined over
4165
  // active elements) to global dof ids
4166
  bin_to_elem_map_.reserve(num_active_);
4167
  elem_to_bin_map_.resize(m_->n_elem(), -1);
4168
  auto begin = block_restrict_
4169
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
4170
                 : m_->active_elements_begin();
4171
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
4172
                             : m_->active_elements_end();
4173
  for (const auto& elem : libMesh::as_range(begin, end)) {
4174
    bin_to_elem_map_.push_back(elem->id());
4175
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
4176
  }
4177
}
4178

4179
int AdaptiveLibMesh::n_bins() const
4180
{
4181
  return num_active_;
4182
}
4183

4184
void AdaptiveLibMesh::add_score(const std::string& var_name)
4185
{
4186
  warning(fmt::format(
4187
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4188
    this->id_));
4189
}
4190

4191
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
4192
  const vector<double>& values, const vector<double>& std_dev)
4193
{
4194
  warning(fmt::format(
4195
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4196
    this->id_));
4197
}
4198

4199
void AdaptiveLibMesh::write(const std::string& filename) const
4200
{
4201
  warning(fmt::format(
4202
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4203
    this->id_));
4204
}
4205

4206
int AdaptiveLibMesh::get_bin(Position r) const
4207
{
4208
  // look-up a tet using the point locator
4209
  libMesh::Point p(r.x, r.y, r.z);
4210

4211
  if (length_multiplier_ > 0.0) {
4212
    // Scale the point down
4213
    p /= length_multiplier_;
4214
  }
4215

4216
  // quick rejection check
4217
  if (!bbox_.contains_point(p)) {
4218
    return -1;
4219
  }
4220

4221
  const auto& point_locator = pl_.at(thread_num());
4222

4223
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
4224
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
4225
}
4226

4227
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4228
{
4229
  int bin = elem_to_bin_map_[elem->id()];
4230
  if (bin >= n_bins() || bin < 0) {
4231
    fatal_error(fmt::format("Invalid bin: {}", bin));
4232
  }
4233
  return bin;
4234
}
4235

4236
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4237
{
4238
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4239
}
4240

4241
#endif // OPENMC_LIBMESH_ENABLED
4242

4243
//==============================================================================
4244
// Non-member functions
4245
//==============================================================================
4246

4247
void read_meshes(pugi::xml_node root)
9,422 ✔
4248
{
4249
  std::unordered_set<int> mesh_ids;
9,422 ✔
4250

4251
  for (auto node : root.children("mesh")) {
11,614 ✔
4252
    // Check to make sure multiple meshes in the same file don't share IDs
4253
    int id = std::stoi(get_node_value(node, "id"));
4,384 ✔
4254
    if (contains(mesh_ids, id)) {
4,384 !
4255
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4256
                              "'{}' in the same input file",
4257
        id));
4258
    }
4259
    mesh_ids.insert(id);
2,192 ✔
4260

4261
    // If we've already read a mesh with the same ID in a *different* file,
4262
    // assume it is the same here
4263
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
2,192 !
4264
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4265
      continue;
×
4266
    }
4267

4268
    std::string mesh_type;
2,192 ✔
4269
    if (check_for_node(node, "type")) {
2,192 ✔
4270
      mesh_type = get_node_value(node, "type", true, true);
583 ✔
4271
    } else {
4272
      // legacy support: older versions of XML do not specify a type,
4273
      // so assume a regular mesh
4274
      mesh_type = "regular";
1,609 ✔
4275
    }
4276

4277
    Mesh::create(node);
2,192 ✔
4278
  }
2,192 ✔
4279
}
9,422 ✔
4280

4281
void read_meshes(hid_t group)
30 ✔
4282
{
4283
  std::unordered_set<int> mesh_ids;
30 ✔
4284

4285
  std::vector<int> ids;
30 ✔
4286
  read_attribute(group, "ids", ids);
30 ✔
4287

4288
  for (auto id : ids) {
67 ✔
4289

4290
    // Check to make sure multiple meshes in the same file don't share IDs
4291
    if (contains(mesh_ids, id)) {
74 !
4292
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4293
                              "'{}' in the same HDF5 input file",
4294
        id));
4295
    }
4296
    mesh_ids.insert(id);
37 ✔
4297

4298
    // If we've already read a mesh with the same ID in a *different* file,
4299
    // assume it is the same here
4300
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
37 ✔
4301
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
21 ✔
4302
      continue;
21 ✔
4303
    }
4304

4305
    std::string name = fmt::format("mesh {}", id);
16 ✔
4306
    hid_t mesh_group = open_group(group, name.c_str());
16 ✔
4307

4308
    std::string mesh_type;
16 ✔
4309
    if (object_exists(mesh_group, "type")) {
16 !
4310
      read_dataset(mesh_group, "type", mesh_type);
16 ✔
4311
    } else {
4312
      // legacy support: older versions of HDF5 do not specify a type,
4313
      // so assume a regular mesh
4314
      mesh_type = "regular";
×
4315
    }
4316

4317
    Mesh::create(mesh_group);
16 ✔
4318
  }
16 ✔
4319
}
60 ✔
4320

4321
void meshes_to_hdf5(hid_t group)
5,304 ✔
4322
{
4323
  // Write number of meshes
4324
  hid_t meshes_group = create_group(group, "meshes");
5,304 ✔
4325
  int32_t n_meshes = model::meshes.size();
5,304 ✔
4326
  write_attribute(meshes_group, "n_meshes", n_meshes);
5,304 ✔
4327

4328
  if (n_meshes > 0) {
5,304 ✔
4329
    // Write IDs of meshes
4330
    vector<int> ids;
1,617 ✔
4331
    for (const auto& m : model::meshes) {
3,703 ✔
4332
      m->to_hdf5(meshes_group);
2,086 ✔
4333
      ids.push_back(m->id_);
2,086 ✔
4334
    }
4335
    write_attribute(meshes_group, "ids", ids);
1,617 ✔
4336
  }
1,617 ✔
4337

4338
  close_group(meshes_group);
5,304 ✔
4339
}
5,304 ✔
4340

4341
void free_memory_mesh()
6,100 ✔
4342
{
4343
  model::meshes.clear();
6,100 ✔
4344
  model::mesh_map.clear();
6,100 ✔
4345
}
6,100 ✔
4346

4347
extern "C" int n_meshes()
238 ✔
4348
{
4349
  return model::meshes.size();
238 ✔
4350
}
4351

4352
} // namespace openmc
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