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

openmc-dev / openmc / 29883510714

22 Jul 2026 01:35AM UTC coverage: 81.406% (+0.07%) from 81.336%
29883510714

Pull #3965

github

web-flow
Merge 31aade0bc into 852f92780
Pull Request #3965: MGXS Bootstrapping

18382 of 26608 branches covered (69.08%)

Branch coverage included in aggregate %.

102 of 102 new or added lines in 5 files covered. (100.0%)

328 existing lines in 4 files now uncovered.

59960 of 69628 relevant lines covered (86.11%)

49146988.38 hits per line

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

70.83
/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
namespace openmc {
59

60
//==============================================================================
61
// Global variables
62
//==============================================================================
63

64
#ifdef OPENMC_LIBMESH_ENABLED
65
const bool LIBMESH_ENABLED = true;
66
#else
67
const bool LIBMESH_ENABLED = false;
68
#endif
69

70
// Value used to indicate an empty slot in the hash table. We use -2 because
71
// the value -1 is used to indicate a void material.
72
constexpr int32_t EMPTY = -2;
73

74
namespace model {
75

76
std::unordered_map<int32_t, int32_t> mesh_map;
77
vector<unique_ptr<Mesh>> meshes;
78

79
} // namespace model
80

81
#ifdef OPENMC_LIBMESH_ENABLED
82
namespace settings {
83
unique_ptr<libMesh::LibMeshInit> libmesh_init;
84
const libMesh::Parallel::Communicator* libmesh_comm {nullptr};
85
} // namespace settings
86
#endif
87

88
//==============================================================================
89
// Helper functions
90
//==============================================================================
91

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

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

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

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

135
#else
136
#error "No compare-and-swap implementation available for this compiler."
137
#endif
138
}
139

140
// Helper function equivalent to std::bit_cast in C++20
141
template<typename To, typename From>
142
inline To bit_cast_value(const From& value)
38,814,570✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
37,700✔
146
  return out;
147
}
148

149
inline void atomic_update_double(double* ptr, double value, bool is_min)
38,814,480✔
150
{
151
#if defined(__GNUC__) || defined(__clang__)
152
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
38,814,480✔
153
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
38,814,480✔
154
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
38,814,480✔
155
  double current = bit_cast_value<double>(current_bits);
38,814,480✔
156
  while (is_min ? (value < current) : (value > current)) {
38,814,570✔
157
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
37,700✔
158
    uint64_t expected_bits = current_bits;
37,700✔
159
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
37,700✔
160
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
161
      return;
38,814,480✔
162
    }
163
    current_bits = expected_bits;
90✔
164
    current = bit_cast_value<double>(current_bits);
90✔
165
  }
166

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

182
#else
183
#error "No compare-and-swap implementation available for this compiler."
184
#endif
185
}
186

187
inline void atomic_max_double(double* ptr, double value)
19,407,240✔
188
{
189
  atomic_update_double(ptr, value, false);
6,469,080✔
190
}
6,469,080✔
191

192
inline void atomic_min_double(double* ptr, double value)
19,407,240✔
193
{
194
  atomic_update_double(ptr, value, true);
6,469,080✔
195
}
196

197
namespace detail {
198

199
//==============================================================================
200
// MaterialVolumes implementation
201
//==============================================================================
202

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

212
  // Loop for linear probing
213
  for (int attempt = 0; attempt < table_size_; ++attempt) {
9,122,467!
214
    // Determine slot to check, making sure it is positive
215
    int slot = (index_material + attempt) % table_size_;
9,122,467✔
216
    if (slot < 0)
9,122,467✔
217
      slot += table_size_;
5,872,054✔
218
    int32_t* slot_ptr = &this->materials(index_elem, slot);
9,122,467✔
219

220
    // Non-atomic read of current material
221
    int32_t current_val = *slot_ptr;
9,122,467✔
222

223
    // Found the desired material; accumulate volume and bbox
224
    if (current_val == index_material) {
9,122,467✔
225
#pragma omp atomic
5,137,735✔
226
      this->volumes(index_elem, slot) += volume;
9,120,900✔
227
      if (bbox) {
9,120,900✔
228
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,468,907✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,468,907✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,468,907✔
231
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,468,907✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,468,907✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,468,907✔
234
      }
235
      return;
9,120,900✔
236
    }
237

238
    // Slot appears to be empty; attempt to claim
239
    if (current_val == EMPTY) {
1,567!
240
      // Attempt compare-and-swap from EMPTY to index_material
241
      int32_t expected_val = EMPTY;
1,567✔
242
      bool claimed_slot =
1,567✔
243
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,567✔
244

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

263
  // If table is full, set a flag that can be checked later
UNCOV
264
  table_full_ = true;
×
265
}
266

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

277
    // Read current material
UNCOV
278
    int32_t current_val = this->materials(index_elem, slot);
×
279

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

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

322
  // If table is full, set a flag that can be checked later
UNCOV
323
  table_full_ = true;
×
324
}
325

326
} // namespace detail
327

328
//==============================================================================
329
// Mesh implementation
330
//==============================================================================
331

332
template<typename T>
333
const std::unique_ptr<Mesh>& Mesh::create(
3,376✔
334
  T dataset, const std::string& mesh_type, const std::string& mesh_library)
335
{
336
  // Determine mesh type. Add to model vector and map
337
  if (mesh_type == RegularMesh::mesh_type) {
3,376✔
338
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
2,493✔
339
  } else if (mesh_type == RectilinearMesh::mesh_type) {
883✔
340
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
111✔
341
  } else if (mesh_type == CylindricalMesh::mesh_type) {
772✔
342
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
389✔
343
  } else if (mesh_type == SphericalMesh::mesh_type) {
383✔
344
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
334✔
345
#ifdef OPENMC_DAGMC_ENABLED
346
  } else if (mesh_type == UnstructuredMesh::mesh_type &&
24!
347
             mesh_library == MOABMesh::mesh_lib_type) {
24!
348
    model::meshes.push_back(make_unique<MOABMesh>(dataset));
24✔
349
#endif
350
#ifdef OPENMC_LIBMESH_ENABLED
351
  } else if (mesh_type == UnstructuredMesh::mesh_type &&
25!
352
             mesh_library == LibMesh::mesh_lib_type) {
25!
353
    model::meshes.push_back(make_unique<LibMesh>(dataset));
25✔
354
#endif
UNCOV
355
  } else if (mesh_type == UnstructuredMesh::mesh_type) {
×
356
    fatal_error("Unstructured mesh support is not enabled or the mesh "
×
357
                "library is invalid.");
358
  } else {
UNCOV
359
    fatal_error(fmt::format("Invalid mesh type: {}", mesh_type));
×
360
  }
361

362
  // Map ID to position in vector
363
  model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3,376✔
364

365
  return model::meshes.back();
3,376✔
366
}
367

368
Mesh::Mesh(pugi::xml_node node)
3,394✔
369
{
370
  // Read mesh id
371
  id_ = std::stoi(get_node_value(node, "id"));
6,788✔
372
  if (check_for_node(node, "name"))
3,394✔
373
    name_ = get_node_value(node, "name");
15✔
374
}
3,394✔
375

376
Mesh::Mesh(hid_t group)
70✔
377
{
378
  // Read mesh ID
379
  read_attribute(group, "id", id_);
70✔
380

381
  // Read mesh name
382
  if (object_exists(group, "name")) {
70!
UNCOV
383
    read_dataset(group, "name", name_);
×
384
  }
385
}
70✔
386

387
void Mesh::set_id(int32_t id)
23✔
388
{
389
  assert(id >= 0 || id == C_NONE);
23!
390

391
  // Clear entry in mesh map in case one was already assigned
392
  if (id_ != C_NONE) {
23✔
393
    model::mesh_map.erase(id_);
22✔
394
    id_ = C_NONE;
22✔
395
  }
396

397
  // Ensure no other mesh has the same ID
398
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
23!
UNCOV
399
    throw std::runtime_error {
×
400
      fmt::format("Two meshes have the same ID: {}", id)};
×
401
  }
402

403
  // If no ID is specified, auto-assign the next ID in the sequence
404
  if (id == C_NONE) {
23✔
405
    id = 0;
1✔
406
    for (const auto& m : model::meshes) {
3✔
407
      id = std::max(id, m->id_);
3✔
408
    }
409
    ++id;
1✔
410
  }
411

412
  // Update ID and entry in the mesh map
413
  id_ = id;
23✔
414

415
  // find the index of this mesh in the model::meshes vector
416
  // (search in reverse because this mesh was likely just added to the vector)
417
  auto it = std::find_if(model::meshes.rbegin(), model::meshes.rend(),
46✔
418
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
57!
419

420
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
23✔
421
}
23✔
422

423
vector<double> Mesh::volumes() const
331✔
424
{
425
  vector<double> volumes(n_bins());
331✔
426
  for (int i = 0; i < n_bins(); i++) {
1,243,675✔
427
    volumes[i] = this->volume(i);
1,243,344✔
428
  }
429
  return volumes;
331✔
UNCOV
430
}
×
431

UNCOV
432
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
×
433
  int32_t* materials, double* volumes) const
434
{
UNCOV
435
  this->material_volumes(nx, ny, nz, table_size, materials, volumes, nullptr);
×
436
}
×
437

438
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
209✔
439
  int32_t* materials, double* volumes, double* bboxes) const
440
{
441
  if (mpi::master) {
209!
442
    header("MESH MATERIAL VOLUMES CALCULATION", 7);
209✔
443
  }
444
  write_message(7, "Number of mesh elements = {}", n_bins());
209✔
445
  write_message(7, "Number of rays (x) = {}", nx);
209✔
446
  write_message(7, "Number of rays (y) = {}", ny);
209✔
447
  write_message(7, "Number of rays (z) = {}", nz);
209✔
448
  int64_t n_total = static_cast<int64_t>(nx) * ny +
209✔
449
                    static_cast<int64_t>(ny) * nz +
209✔
450
                    static_cast<int64_t>(nx) * nz;
209✔
451
  write_message(7, "Total number of rays = {}", n_total);
209✔
452
  write_message(7, "Table size per mesh element = {}", table_size);
209✔
453

454
  Timer timer;
209✔
455
  timer.start();
209✔
456

457
  // Create object for keeping track of materials/volumes
458
  detail::MaterialVolumes result(materials, volumes, bboxes, table_size);
209✔
459
  bool compute_bboxes = bboxes != nullptr;
209✔
460

461
  // Determine bounding box
462
  auto bbox = this->bounding_box();
209✔
463

464
  std::array<int, 3> n_rays = {nx, ny, nz};
209✔
465

466
  // Determine effective width of rays
467
  Position width = bbox.max - bbox.min;
209✔
468
  width.x = (nx > 0) ? width.x / nx : 0.0;
209✔
469
  width.y = (ny > 0) ? width.y / ny : 0.0;
209✔
470
  width.z = (nz > 0) ? width.z / nz : 0.0;
209✔
471

472
  // Set flag for mesh being contained within model
473
  bool out_of_model = false;
209✔
474

475
#pragma omp parallel
114✔
476
  {
95✔
477
    // Preallocate vector for mesh indices and length fractions and particle
478
    vector<int> bins;
95✔
479
    vector<double> length_fractions;
95✔
480
    Particle p;
95✔
481

482
    SourceSite site;
95✔
483
    site.E = 1.0;
95✔
484
    site.particle = ParticleType::neutron();
95✔
485

486
    for (int axis = 0; axis < 3; ++axis) {
380✔
487
      // Set starting position and direction
488
      site.r = {0.0, 0.0, 0.0};
285✔
489
      site.r[axis] = bbox.min[axis];
285✔
490
      site.u = {0.0, 0.0, 0.0};
285✔
491
      site.u[axis] = 1.0;
285✔
492

493
      // Determine width of rays and number of rays in other directions
494
      int ax1 = (axis + 1) % 3;
285✔
495
      int ax2 = (axis + 2) % 3;
285✔
496
      double min1 = bbox.min[ax1];
285✔
497
      double min2 = bbox.min[ax2];
285✔
498
      double d1 = width[ax1];
285✔
499
      double d2 = width[ax2];
285✔
500
      int n1 = n_rays[ax1];
285✔
501
      int n2 = n_rays[ax2];
285✔
502
      if (n1 == 0 || n2 == 0) {
285✔
503
        continue;
60✔
504
      }
505

506
      // Divide rays in first direction over MPI processes by computing starting
507
      // and ending indices
508
      int min_work = n1 / mpi::n_procs;
225✔
509
      int remainder = n1 % mpi::n_procs;
225✔
510
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
225!
511
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
225!
512
      int i1_end = i1_start + n1_local;
225✔
513

514
      // Loop over rays on face of bounding box
515
#pragma omp for collapse(2)
516
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
17,600✔
517
        for (int i2 = 0; i2 < n2; ++i2) {
3,080,220✔
518
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,062,845✔
519
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,062,845✔
520

521
          p.from_source(&site);
3,062,845✔
522

523
          // Determine particle's location
524
          if (!exhaustive_find_cell(p)) {
3,062,845✔
525
            out_of_model = true;
39,930✔
526
            continue;
39,930✔
527
          }
528

529
          // Set birth cell attribute
530
          if (p.cell_born() == C_NONE)
3,022,915!
531
            p.cell_born() = p.lowest_coord().cell();
3,022,915✔
532

533
          // Initialize last cells from current cell
534
          for (int j = 0; j < p.n_coord(); ++j) {
6,045,830✔
535
            p.cell_last(j) = p.coord(j).cell();
3,022,915✔
536
          }
537
          p.n_coord_last() = p.n_coord();
3,022,915✔
538

539
          while (true) {
4,817,267✔
540
            // Ray trace from r_start to r_end
541
            Position r0 = p.r();
3,920,091✔
542
            double max_distance = bbox.max[axis] - r0[axis];
3,920,091✔
543

544
            // Find the distance to the nearest boundary
545
            BoundaryInfo boundary = distance_to_boundary(p);
3,920,091✔
546

547
            // Advance particle forward
548
            double distance = std::min(boundary.distance(), max_distance);
3,920,091✔
549
            p.move_distance(distance);
3,920,091✔
550

551
            // Determine what mesh elements were crossed by particle
552
            bins.clear();
3,920,091✔
553
            length_fractions.clear();
3,920,091✔
554
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
3,920,091✔
555

556
            // Add volumes to any mesh elements that were crossed
557
            int i_material = p.material();
3,920,091✔
558
            if (i_material != C_NONE) {
3,920,091✔
559
              i_material = model::materials[i_material]->id();
1,244,193✔
560
            }
561
            double cumulative_frac = 0.0;
3,920,091✔
562
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
8,058,832✔
563
              int mesh_index = bins[i_bin];
4,138,741✔
564
              double length = distance * length_fractions[i_bin];
4,138,741✔
565
              double volume = length * d1 * d2;
4,138,741✔
566

567
              if (compute_bboxes) {
4,138,741✔
568
                double axis_start = r0[axis] + distance * cumulative_frac;
2,932,656✔
569
                double axis_end = axis_start + length;
2,932,656✔
570
                cumulative_frac += length_fractions[i_bin];
2,932,656✔
571

572
                Position contrib_min = site.r;
2,932,656✔
573
                Position contrib_max = site.r;
2,932,656✔
574

575
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,932,656✔
576
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,932,656✔
577
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,932,656✔
578
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,932,656✔
579
                contrib_min[axis] = std::min(axis_start, axis_end);
2,932,656!
580
                contrib_max[axis] = std::max(axis_start, axis_end);
5,865,312!
581

582
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,932,656✔
583
                contrib_bbox &= bbox;
2,932,656✔
584

585
                result.add_volume(
2,932,656✔
586
                  mesh_index, i_material, volume, &contrib_bbox);
587
              } else {
588
                // Add volume to result
589
                result.add_volume(mesh_index, i_material, volume);
1,206,085✔
590
              }
591
            }
592

593
            if (distance == max_distance)
3,920,091✔
594
              break;
595

596
            // cross next geometric surface
597
            for (int j = 0; j < p.n_coord(); ++j) {
1,794,352✔
598
              p.cell_last(j) = p.coord(j).cell();
897,176✔
599
            }
600
            p.n_coord_last() = p.n_coord();
897,176✔
601

602
            // Set surface that particle is on and adjust coordinate levels
603
            p.surface() = boundary.surface();
897,176✔
604
            p.n_coord() = boundary.coord_level();
897,176✔
605

606
            if (boundary.lattice_translation()[0] != 0 ||
897,176!
607
                boundary.lattice_translation()[1] != 0 ||
897,176!
608
                boundary.lattice_translation()[2] != 0) {
897,176!
609
              // Particle crosses lattice boundary
610
              cross_lattice(p, boundary);
×
611
            } else {
612
              // Particle crosses surface
613
              const auto& surf {model::surfaces[p.surface_index()].get()};
897,176✔
614
              p.cross_surface(*surf);
897,176✔
615
            }
616
          }
897,176✔
617
        }
618
      }
619
    }
620
  }
95✔
621

622
  // Check for errors
623
  if (out_of_model) {
209✔
624
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
625
  } else if (result.table_full()) {
198!
UNCOV
626
    throw std::runtime_error("Maximum number of materials for mesh material "
×
627
                             "volume calculation insufficient.");
×
628
  }
629

630
  // Compute time for raytracing
631
  double t_raytrace = timer.elapsed();
198✔
632

633
#ifdef OPENMC_MPI
634
  // Combine results from multiple MPI processes
635
  if (mpi::n_procs > 1) {
72!
636
    int total = this->n_bins() * table_size;
637
    int total_bbox = total * 6;
638
    if (mpi::master) {
×
639
      // Allocate temporary buffer for receiving data
640
      vector<int32_t> mats(total);
641
      vector<double> vols(total);
×
642
      vector<double> recv_bboxes;
×
643
      if (compute_bboxes) {
×
644
        recv_bboxes.resize(total_bbox);
×
645
      }
646

647
      for (int i = 1; i < mpi::n_procs; ++i) {
×
648
        // Receive material indices and volumes from process i
649
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
650
          MPI_STATUS_IGNORE);
651
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
652
          MPI_STATUS_IGNORE);
653
        if (compute_bboxes) {
×
654
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
655
            mpi::intracomm, MPI_STATUS_IGNORE);
656
        }
657

658
        // Combine with existing results; we can call thread unsafe version of
659
        // add_volume because each thread is operating on a different element
660
#pragma omp for
661
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
662
          for (int k = 0; k < table_size; ++k) {
×
663
            int index = index_elem * table_size + k;
664
            if (mats[index] != EMPTY) {
×
665
              if (compute_bboxes) {
×
666
                int bbox_index = index * 6;
667
                BoundingBox slot_bbox {
668
                  {recv_bboxes[bbox_index + 0], recv_bboxes[bbox_index + 1],
×
669
                    recv_bboxes[bbox_index + 2]},
670
                  {recv_bboxes[bbox_index + 3], recv_bboxes[bbox_index + 4],
×
671
                    recv_bboxes[bbox_index + 5]}};
×
672
                result.add_volume_unsafe(
673
                  index_elem, mats[index], vols[index], &slot_bbox);
×
674
              } else {
675
                result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
676
              }
677
            }
678
          }
679
        }
680
      }
681
    } else {
682
      // Send material indices and volumes to process 0
683
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
684
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
685
      if (compute_bboxes) {
×
686
        MPI_Send(bboxes, total_bbox, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
687
      }
688
    }
689
  }
690

691
  // Report time for MPI communication
692
  double t_mpi = timer.elapsed() - t_raytrace;
72✔
693
#else
694
  double t_mpi = 0.0;
108✔
695
#endif
696

697
  // Normalize based on known volumes of elements
698
  for (int i = 0; i < this->n_bins(); ++i) {
1,111✔
699
    // Estimated total volume in element i
700
    double volume = 0.0;
701
    for (int j = 0; j < table_size; ++j) {
8,349✔
702
      volume += result.volumes(i, j);
7,436✔
703
    }
704
    // Renormalize volumes based on known volume of element i
705
    double norm = this->volume(i) / volume;
913✔
706
    for (int j = 0; j < table_size; ++j) {
8,349✔
707
      result.volumes(i, j) *= norm;
7,436✔
708
    }
709
  }
710

711
  // Get total time and normalization time
712
  timer.stop();
198✔
713
  double t_total = timer.elapsed();
198✔
714
  double t_norm = t_total - t_raytrace - t_mpi;
198✔
715

716
  // Show timing statistics
717
  if (settings::verbosity < 7 || !mpi::master)
198!
718
    return;
44✔
719
  header("Timing Statistics", 7);
154✔
720
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
154✔
721
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
154✔
722
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
154✔
723
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
154✔
724
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
308✔
725
    n_total / t_raytrace);
154✔
726
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
224✔
727
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
154✔
728
  std::fflush(stdout);
154✔
729
}
730

731
void Mesh::to_hdf5(hid_t group) const
3,302✔
732
{
733
  // Create group for mesh
734
  std::string group_name = fmt::format("mesh {}", id_);
3,302✔
735
  hid_t mesh_group = create_group(group, group_name.c_str());
3,302✔
736

737
  // Write mesh type
738
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,302✔
739

740
  // Write mesh ID
741
  write_attribute(mesh_group, "id", id_);
3,302✔
742

743
  // Write mesh name
744
  write_dataset(mesh_group, "name", name_);
3,302✔
745

746
  // Write mesh data
747
  this->to_hdf5_inner(mesh_group);
3,302✔
748

749
  // Close group
750
  close_group(mesh_group);
3,302✔
751
}
3,302✔
752

753
//==============================================================================
754
// Structured Mesh implementation
755
//==============================================================================
756

757
std::string StructuredMesh::bin_label(int bin) const
5,314,412✔
758
{
759
  MeshIndex ijk = get_indices_from_bin(bin);
5,314,412✔
760

761
  if (n_dimension_ > 2) {
5,314,412✔
762
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,298,077✔
763
  } else if (n_dimension_ > 1) {
16,335✔
764
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
16,060✔
765
  } else {
766
    return fmt::format("Mesh Index ({})", ijk[0]);
275✔
767
  }
768
}
769

770
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,905✔
771
{
772
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,905✔
773
}
774

775
Position StructuredMesh::sample_element(
1,438,198✔
776
  const MeshIndex& ijk, uint64_t* seed) const
777
{
778
  // lookup the lower/upper bounds for the mesh element
779
  double x_min = negative_grid_boundary(ijk, 0);
1,438,198✔
780
  double x_max = positive_grid_boundary(ijk, 0);
1,438,198✔
781

782
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,438,198!
783
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,438,198!
784

785
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,438,198!
786
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,438,198!
787

788
  return {x_min + (x_max - x_min) * prn(seed),
1,438,198✔
789
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,438,198✔
790
}
791

792
//==============================================================================
793
// Unstructured Mesh implementation
794
//==============================================================================
795

796
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
49!
797
{
798
  n_dimension_ = 3;
49✔
799

800
  // check the mesh type
801
  if (check_for_node(node, "type")) {
49!
802
    auto temp = get_node_value(node, "type", true, true);
49!
803
    if (temp != mesh_type) {
49!
UNCOV
804
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
805
    }
806
  }
49✔
807

808
  // check if a length unit multiplier was specified
809
  if (check_for_node(node, "length_multiplier")) {
49!
UNCOV
810
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
811
  }
812

813
  // get the filename of the unstructured mesh to load
814
  if (check_for_node(node, "filename")) {
49!
815
    filename_ = get_node_value(node, "filename");
49!
816
    if (!file_exists(filename_)) {
49!
UNCOV
817
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
818
    }
819
  } else {
UNCOV
820
    fatal_error(fmt::format(
×
821
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
822
  }
823

824
  if (check_for_node(node, "options")) {
49!
825
    options_ = get_node_value(node, "options");
16!
826
  }
827

828
  // check if mesh tally data should be written with
829
  // statepoint files
830
  if (check_for_node(node, "output")) {
49!
UNCOV
831
    output_ = get_node_value_bool(node, "output");
×
832
  }
833
}
49✔
834

UNCOV
835
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
836
{
UNCOV
837
  n_dimension_ = 3;
×
838

839
  // check the mesh type
UNCOV
840
  if (object_exists(group, "type")) {
×
841
    std::string temp;
×
842
    read_dataset(group, "type", temp);
×
843
    if (temp != mesh_type) {
×
844
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
845
    }
UNCOV
846
  }
×
847

848
  // check if a length unit multiplier was specified
UNCOV
849
  if (object_exists(group, "length_multiplier")) {
×
850
    read_dataset(group, "length_multiplier", length_multiplier_);
×
851
  }
852

853
  // get the filename of the unstructured mesh to load
UNCOV
854
  if (object_exists(group, "filename")) {
×
855
    read_dataset(group, "filename", filename_);
×
856
    if (!file_exists(filename_)) {
×
857
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
858
    }
859
  } else {
UNCOV
860
    fatal_error(fmt::format(
×
861
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
862
  }
863

UNCOV
864
  if (attribute_exists(group, "options")) {
×
865
    read_attribute(group, "options", options_);
×
866
  }
867

868
  // check if mesh tally data should be written with
869
  // statepoint files
UNCOV
870
  if (attribute_exists(group, "output")) {
×
871
    read_attribute(group, "output", output_);
×
872
  }
UNCOV
873
}
×
874

875
void UnstructuredMesh::determine_bounds()
25✔
876
{
877
  double xmin = INFTY;
25✔
878
  double ymin = INFTY;
25✔
879
  double zmin = INFTY;
25✔
880
  double xmax = -INFTY;
25✔
881
  double ymax = -INFTY;
25✔
882
  double zmax = -INFTY;
25✔
883
  int n = this->n_vertices();
25✔
884
  for (int i = 0; i < n; ++i) {
55,951✔
885
    auto v = this->vertex(i);
55,926✔
886
    xmin = std::min(v.x, xmin);
55,926✔
887
    ymin = std::min(v.y, ymin);
55,926✔
888
    zmin = std::min(v.z, zmin);
55,926✔
889
    xmax = std::max(v.x, xmax);
55,926✔
890
    ymax = std::max(v.y, ymax);
55,926✔
891
    zmax = std::max(v.z, zmax);
79,911✔
892
  }
893
  lower_left_ = {xmin, ymin, zmin};
25✔
894
  upper_right_ = {xmax, ymax, zmax};
25✔
895
}
25✔
896

897
Position UnstructuredMesh::sample_tet(
601,230✔
898
  std::array<Position, 4> coords, uint64_t* seed) const
899
{
900
  // Uniform distribution
901
  double s = prn(seed);
601,230✔
902
  double t = prn(seed);
601,230✔
903
  double u = prn(seed);
601,230✔
904

905
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
906
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
907
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
908
  if (s + t > 1) {
601,230✔
909
    s = 1.0 - s;
300,882✔
910
    t = 1.0 - t;
300,882✔
911
  }
912
  if (s + t + u > 1) {
601,230✔
913
    if (t + u > 1) {
400,122✔
914
      double old_t = t;
200,373✔
915
      t = 1.0 - u;
200,373✔
916
      u = 1.0 - s - old_t;
200,373✔
917
    } else if (t + u <= 1) {
199,749!
918
      double old_s = s;
199,749✔
919
      s = 1.0 - t - u;
199,749✔
920
      u = old_s + t + u - 1;
199,749✔
921
    }
922
  }
923
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,803,690✔
924
         u * (coords[3] - coords[0]) + coords[0];
601,230✔
925
}
926

927
const std::string UnstructuredMesh::mesh_type = "unstructured";
928

929
std::string UnstructuredMesh::get_mesh_type() const
34✔
930
{
931
  return mesh_type;
34✔
932
}
933

UNCOV
934
void UnstructuredMesh::surface_bins_crossed(
×
935
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
936
{
UNCOV
937
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
938
}
939

940
std::string UnstructuredMesh::bin_label(int bin) const
207,736✔
941
{
942
  return fmt::format("Mesh Index ({})", bin);
207,736✔
943
};
944

945
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
34✔
946
{
947
  write_dataset(mesh_group, "filename", filename_);
34!
948
  write_dataset(mesh_group, "library", this->library());
34!
949
  if (!options_.empty()) {
34✔
950
    write_attribute(mesh_group, "options", options_);
8✔
951
  }
952

953
  if (length_multiplier_ > 0.0)
34!
UNCOV
954
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
955

956
  // write vertex coordinates
957
  tensor::Tensor<double> vertices(
34✔
958
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
34✔
959
  for (int i = 0; i < this->n_vertices(); i++) {
72,939!
960
    auto v = this->vertex(i);
72,905!
961
    vertices.slice(i) = {v.x, v.y, v.z};
145,810!
962
  }
963
  write_dataset(mesh_group, "vertices", vertices);
34!
964

965
  int num_elem_skipped = 0;
34✔
966

967
  // write element types and connectivity
968
  vector<double> volumes;
34!
969
  tensor::Tensor<int> connectivity(
34✔
970
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
34!
971
  tensor::Tensor<int> elem_types(
34✔
972
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
34!
973
  for (int i = 0; i < this->n_bins(); i++) {
351,770!
974
    auto conn = this->connectivity(i);
351,736!
975

976
    volumes.emplace_back(this->volume(i));
351,736!
977

978
    // write linear tet element
979
    if (conn.size() == 4) {
351,736✔
980
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
347,736!
981
      connectivity.slice(i) = {
347,736!
982
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
695,472!
983
      // write linear hex element
984
    } else if (conn.size() == 8) {
4,000!
985
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
4,000!
986
      connectivity.slice(i) = {
4,000!
987
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
8,000!
988
    } else {
UNCOV
989
      num_elem_skipped++;
×
990
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
991
      connectivity.slice(i) = -1;
×
992
    }
993
  }
351,736✔
994

995
  // warn users that some elements were skipped
996
  if (num_elem_skipped > 0) {
34!
UNCOV
997
    warning(fmt::format("The connectivity of {} elements "
×
998
                        "on mesh {} were not written "
999
                        "because they are not of type linear tet/hex.",
UNCOV
1000
      num_elem_skipped, this->id_));
×
1001
  }
1002

1003
  write_dataset(mesh_group, "volumes", volumes);
34!
1004
  write_dataset(mesh_group, "connectivity", connectivity);
34!
1005
  write_dataset(mesh_group, "element_types", elem_types);
34!
1006
}
102✔
1007

1008
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
25✔
1009
{
1010
  length_multiplier_ = length_multiplier;
25✔
1011
}
25✔
1012

1013
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1014
{
1015
  auto conn = connectivity(bin);
120,000✔
1016

1017
  if (conn.size() == 4)
120,000!
1018
    return ElementType::LINEAR_TET;
UNCOV
1019
  else if (conn.size() == 8)
×
1020
    return ElementType::LINEAR_HEX;
1021
  else
UNCOV
1022
    return ElementType::UNSUPPORTED;
×
1023
}
120,000✔
1024

1025
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,790,889,772✔
1026
  Position r, bool& in_mesh) const
1027
{
1028
  MeshIndex ijk;
1,790,889,772✔
1029
  in_mesh = true;
1,790,889,772✔
1030
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1031
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1032

1033
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1034
      in_mesh = false;
102,839,607✔
1035
  }
1036
  return ijk;
1,790,889,772✔
1037
}
1038

1039
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647✔
1040
{
1041
  switch (n_dimension_) {
2,147,483,647!
1042
  case 1:
880,605✔
1043
    return ijk[0] - 1;
880,605✔
1044
  case 2:
141,663,247✔
1045
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
141,663,247✔
1046
  case 3:
2,147,483,647✔
1047
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,147,483,647✔
UNCOV
1048
  default:
×
1049
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1050
  }
1051
}
1052

1053
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,087,287✔
1054
{
1055
  MeshIndex ijk;
8,087,287✔
1056
  if (n_dimension_ == 1) {
8,087,287✔
1057
    ijk[0] = bin + 1;
275✔
1058
  } else if (n_dimension_ == 2) {
8,087,012✔
1059
    ijk[0] = bin % shape_[0] + 1;
16,060✔
1060
    ijk[1] = bin / shape_[0] + 1;
16,060✔
1061
  } else if (n_dimension_ == 3) {
8,070,952!
1062
    ijk[0] = bin % shape_[0] + 1;
8,070,952✔
1063
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,070,952✔
1064
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,070,952✔
1065
  }
1066
  return ijk;
8,087,287✔
1067
}
1068

1069
int StructuredMesh::get_bin(Position r) const
576,161,825✔
1070
{
1071
  // Determine indices
1072
  bool in_mesh;
576,161,825✔
1073
  MeshIndex ijk = get_indices(r, in_mesh);
576,161,825✔
1074
  if (!in_mesh)
576,161,825✔
1075
    return -1;
1076

1077
  // Convert indices to bin
1078
  return get_bin_from_indices(ijk);
555,067,668✔
1079
}
1080

1081
int StructuredMesh::n_bins() const
1,259,256✔
1082
{
1083
  // Bin indices are stored as 32-bit ints in the tally system.
1084
  int64_t n = 1;
1,259,256✔
1085
  for (int i = 0; i < n_dimension_; ++i)
5,036,597✔
1086
    n *= shape_[i];
3,777,341✔
1087
  if (n > std::numeric_limits<int>::max()) {
1,259,256!
UNCOV
1088
    fatal_error(fmt::format(
×
1089
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1090
  }
1091
  return static_cast<int>(n);
1,259,256✔
1092
}
1093

1094
int StructuredMesh::n_surface_bins() const
370✔
1095
{
1096
  // Surface bin indices are stored as 32-bit ints in the tally system.
1097
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
370✔
1098
  if (n > std::numeric_limits<int>::max()) {
370!
UNCOV
1099
    fatal_error(fmt::format(
×
1100
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1101
  }
1102
  return static_cast<int>(n);
370✔
1103
}
1104

UNCOV
1105
tensor::Tensor<double> StructuredMesh::count_sites(
×
1106
  const SourceSite* bank, int64_t length, bool* outside) const
1107
{
1108
  // Determine shape of array for counts
UNCOV
1109
  std::size_t m = this->n_bins();
×
1110
  vector<std::size_t> shape = {m};
×
1111

1112
  // Create array of zeros
UNCOV
1113
  auto cnt = tensor::zeros<double>(shape);
×
1114
  bool outside_ = false;
1115

UNCOV
1116
  for (int64_t i = 0; i < length; i++) {
×
1117
    const auto& site = bank[i];
×
1118

1119
    // determine scoring bin for entropy mesh
UNCOV
1120
    int mesh_bin = get_bin(site.r);
×
1121

1122
    // if outside mesh, skip particle
UNCOV
1123
    if (mesh_bin < 0) {
×
1124
      outside_ = true;
×
1125
      continue;
×
1126
    }
1127

1128
    // Add to appropriate bin
UNCOV
1129
    cnt(mesh_bin) += site.wgt;
×
1130
  }
1131

1132
  // Create reduced count data
UNCOV
1133
  auto counts = tensor::zeros<double>(shape);
×
1134
  int total = cnt.size();
×
1135

1136
#ifdef OPENMC_MPI
1137
  // collect values from all processors
1138
  MPI_Reduce(
×
1139
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1140

1141
  // Check if there were sites outside the mesh for any processor
1142
  if (outside) {
×
1143
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1144
  }
1145
#else
1146
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1147
  if (outside)
×
1148
    *outside = outside_;
1149
#endif
1150

UNCOV
1151
  return counts;
×
1152
}
×
1153

1154
// raytrace through the mesh. The template class T will do the tallying.
1155
// A modern optimizing compiler can recognize the noop method of T and
1156
// eliminate that call entirely.
1157
template<class T>
1158
void StructuredMesh::raytrace_mesh(
1,261,898,631✔
1159
  Position r0, Position r1, const Direction& u, T tally) const
1160
{
1161
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1162
  // enable/disable tally calls for now, T template type needs to provide both
1163
  // surface and track methods, which might be empty. modern optimizing
1164
  // compilers will (hopefully) eliminate the complete code (including
1165
  // calculation of parameters) but for the future: be explicit
1166

1167
  // Compute the length of the entire track.
1168
  double total_distance = (r1 - r0).norm();
1,261,898,631✔
1169
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,261,898,631✔
1170
    return;
1171

1172
  // keep a copy of the original global position to pass to get_indices,
1173
  // which performs its own transformation to local coordinates
1174
  Position global_r = r0;
1,207,552,119✔
1175
  Position local_r = local_coords(r0);
1,207,552,119✔
1176

1177
  const int n = n_dimension_;
1,207,552,119✔
1178

1179
  // Flag if position is inside the mesh
1180
  bool in_mesh;
1181

1182
  // Position is r = r0 + u * traveled_distance, start at r0
1183
  double traveled_distance {0.0};
1,207,552,119✔
1184

1185
  // Calculate index of current cell. Offset the position a tiny bit in
1186
  // direction of flight
1187
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,207,552,119✔
1188

1189
  // if track is very short, assume that it is completely inside one cell.
1190
  // Only the current cell will score and no surfaces
1191
  if (total_distance < 2 * TINY_BIT) {
1,207,552,119✔
1192
    if (in_mesh) {
675,882✔
1193
      tally.track(ijk, 1.0);
675,398✔
1194
    }
1195
    return;
675,882✔
1196
  }
1197

1198
  // Calculate initial distances to next surfaces in all three dimensions
1199
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1200
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1201
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1202
  }
1203

1204
  // Loop until r = r1 is eventually reached
1205
  while (true) {
1206

1207
    if (in_mesh) {
2,068,070,824✔
1208

1209
      // find surface with minimal distance to current position
1210
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,981,603,667✔
1211
                     distances.begin();
1,981,603,667✔
1212

1213
      // Tally track length delta since last step
1214
      tally.track(ijk,
1,981,603,667✔
1215
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1216
          total_distance);
1217

1218
      // update position and leave, if we have reached end position
1219
      traveled_distance = distances[k].distance;
1,981,603,667✔
1220
      if (traveled_distance >= total_distance)
1,981,603,667✔
1221
        return;
1222

1223
      // If we have not reached r1, we have hit a surface. Tally outward
1224
      // current
1225
      tally.surface(ijk, k, distances[k].max_surface, false);
854,018,759✔
1226

1227
      // Update cell and calculate distance to next surface in k-direction.
1228
      // The two other directions are still valid!
1229
      ijk[k] = distances[k].next_index;
854,018,759✔
1230
      distances[k] =
854,018,759✔
1231
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
854,018,759✔
1232

1233
      // Check if we have left the interior of the mesh
1234
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
860,871,014✔
1235

1236
      // If we are still inside the mesh, tally inward current for the next
1237
      // cell
1238
      if (in_mesh)
29,576,899✔
1239
        tally.surface(ijk, k, !distances[k].max_surface, true);
859,778,370✔
1240

1241
    } else { // not inside mesh
1242

1243
      // For all directions outside the mesh, find the distance that we need
1244
      // to travel to reach the next surface. Use the largest distance, as
1245
      // only this will cross all outer surfaces.
1246
      int k_max {-1};
1247
      for (int k = 0; k < n; ++k) {
344,399,666✔
1248
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,932,509✔
1249
            (distances[k].distance > traveled_distance)) {
94,475,072✔
1250
          traveled_distance = distances[k].distance;
1251
          k_max = k;
1252
        }
1253
      }
1254
      // Assure some distance is traveled
1255
      if (k_max == -1) {
86,467,157✔
1256
        traveled_distance += TINY_BIT;
110✔
1257
      }
1258

1259
      // If r1 is not inside the mesh, exit here
1260
      if (traveled_distance >= total_distance)
86,467,157✔
1261
        return;
1262

1263
      // Calculate the new cell index and update all distances to next
1264
      // surfaces.
1265
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,175,828✔
1266
      for (int k = 0; k < n; ++k) {
28,494,774✔
1267
        distances[k] =
21,318,946✔
1268
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,318,946✔
1269
      }
1270

1271
      // If inside the mesh, Tally inward current
1272
      if (in_mesh && k_max >= 0)
7,175,828!
1273
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
831,594,720✔
1274
    }
1275
  }
1276
}
1277

1278
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,149,771,066✔
1279
  vector<int>& bins, vector<double>& lengths) const
1280
{
1281

1282
  // Helper tally class.
1283
  // stores a pointer to the mesh class and references to bins and lengths
1284
  // parameters. Performs the actual tally through the track method.
1285
  struct TrackAggregator {
1,149,771,066✔
1286
    TrackAggregator(
1,149,771,066✔
1287
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1288
      : mesh(_mesh), bins(_bins), lengths(_lengths)
1,149,771,066✔
1289
    {}
1290
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1291
    void track(const MeshIndex& ijk, double l) const
1,842,234,501✔
1292
    {
1293
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,842,234,501✔
1294
      lengths.push_back(l);
1,842,234,501✔
1295
    }
1,842,234,501✔
1296

1297
    const StructuredMesh* mesh;
1298
    vector<int>& bins;
1299
    vector<double>& lengths;
1300
  };
1301

1302
  // Perform the mesh raytrace with the helper class.
1303
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,149,771,066✔
1304
}
1,149,771,066✔
1305

1306
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1307
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1308
{
1309

1310
  // Helper tally class.
1311
  // stores a pointer to the mesh class and a reference to the bins parameter.
1312
  // Performs the actual tally through the surface method.
1313
  struct SurfaceAggregator {
112,127,565✔
1314
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,565✔
1315
      : mesh(_mesh), bins(_bins)
112,127,565✔
1316
    {}
1317
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,189✔
1318
    {
1319
      int i_bin =
58,159,189✔
1320
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,189✔
1321
      if (max)
58,159,189✔
1322
        i_bin += 2;
29,051,440✔
1323
      if (inward)
58,159,189✔
1324
        i_bin += 1;
28,582,290✔
1325
      bins.push_back(i_bin);
58,159,189✔
1326
    }
58,159,189✔
1327
    void track(const MeshIndex& idx, double l) const {}
1328

1329
    const StructuredMesh* mesh;
1330
    vector<int>& bins;
1331
  };
1332

1333
  // Perform the mesh raytrace with the helper class.
1334
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1335
}
112,127,565✔
1336

1337
//==============================================================================
1338
// RegularMesh implementation
1339
//==============================================================================
1340

1341
int RegularMesh::set_grid()
2,515✔
1342
{
1343
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,515✔
1344

1345
  // Check that dimensions are all greater than zero
1346
  if ((shape <= 0).any()) {
7,545!
UNCOV
1347
    set_errmsg("All entries for a regular mesh dimensions "
×
1348
               "must be positive.");
UNCOV
1349
    return OPENMC_E_INVALID_ARGUMENT;
×
1350
  }
1351

1352
  // Make sure lower_left and dimension match
1353
  if (lower_left_.size() != n_dimension_) {
2,515!
UNCOV
1354
    set_errmsg("Number of entries in lower_left must be the same "
×
1355
               "as the regular mesh dimensions.");
UNCOV
1356
    return OPENMC_E_INVALID_ARGUMENT;
×
1357
  }
1358
  if (width_.size() > 0) {
2,515✔
1359

1360
    // Check to ensure width has same dimensions
1361
    if (width_.size() != n_dimension_) {
46!
UNCOV
1362
      set_errmsg("Number of entries on width must be the same as "
×
1363
                 "the regular mesh dimensions.");
UNCOV
1364
      return OPENMC_E_INVALID_ARGUMENT;
×
1365
    }
1366

1367
    // Check for negative widths
1368
    if ((width_ < 0.0).any()) {
138!
UNCOV
1369
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1370
      return OPENMC_E_INVALID_ARGUMENT;
×
1371
    }
1372

1373
    // Set width and upper right coordinate
1374
    upper_right_ = lower_left_ + shape * width_;
138✔
1375

1376
  } else if (upper_right_.size() > 0) {
2,469!
1377

1378
    // Check to ensure upper_right_ has same dimensions
1379
    if (upper_right_.size() != n_dimension_) {
2,469!
UNCOV
1380
      set_errmsg("Number of entries on upper_right must be the "
×
1381
                 "same as the regular mesh dimensions.");
UNCOV
1382
      return OPENMC_E_INVALID_ARGUMENT;
×
1383
    }
1384

1385
    // Check that upper-right is above lower-left
1386
    if ((upper_right_ < lower_left_).any()) {
7,407!
UNCOV
1387
      set_errmsg(
×
1388
        "The upper_right coordinates of a regular mesh must be greater than "
1389
        "the lower_left coordinates.");
UNCOV
1390
      return OPENMC_E_INVALID_ARGUMENT;
×
1391
    }
1392

1393
    // Set width
1394
    width_ = (upper_right_ - lower_left_) / shape;
7,407✔
1395
  }
1396

1397
  // Set material volumes
1398
  volume_frac_ = 1.0 / shape.prod();
2,515✔
1399

1400
  element_volume_ = 1.0;
2,515✔
1401
  for (int i = 0; i < n_dimension_; i++) {
9,498✔
1402
    element_volume_ *= width_[i];
6,983✔
1403
  }
1404
  return 0;
1405
}
2,515✔
1406

1407
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,478✔
1408
{
1409
  // Determine number of dimensions for mesh
1410
  if (!check_for_node(node, "dimension")) {
2,478!
UNCOV
1411
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1412
  }
1413

1414
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,478✔
1415
  int n = n_dimension_ = shape.size();
2,478!
1416
  if (n != 1 && n != 2 && n != 3) {
2,478!
UNCOV
1417
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1418
  }
1419
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,478✔
1420

1421
  // Check for lower-left coordinates
1422
  if (check_for_node(node, "lower_left")) {
2,478!
1423
    // Read mesh lower-left corner location
1424
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,478✔
1425
  } else {
UNCOV
1426
    fatal_error("Must specify <lower_left> on a mesh.");
×
1427
  }
1428

1429
  if (check_for_node(node, "width")) {
2,478✔
1430
    // Make sure one of upper-right or width were specified
1431
    if (check_for_node(node, "upper_right")) {
46!
UNCOV
1432
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1433
    }
1434

1435
    width_ = get_node_tensor<double>(node, "width");
92✔
1436

1437
  } else if (check_for_node(node, "upper_right")) {
2,432!
1438

1439
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,864✔
1440

1441
  } else {
UNCOV
1442
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1443
  }
1444

1445
  if (int err = set_grid()) {
2,478!
UNCOV
1446
    fatal_error(openmc_err_msg);
×
1447
  }
1448
}
2,478✔
1449

1450
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
37✔
1451
{
1452
  // Determine number of dimensions for mesh
1453
  if (!object_exists(group, "dimension")) {
37!
UNCOV
1454
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1455
  }
1456

1457
  tensor::Tensor<int> shape;
37✔
1458
  read_dataset(group, "dimension", shape);
37✔
1459
  int n = n_dimension_ = shape.size();
37!
1460
  if (n != 1 && n != 2 && n != 3) {
37!
UNCOV
1461
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1462
  }
1463
  std::copy(shape.begin(), shape.end(), shape_.begin());
37✔
1464

1465
  // Check for lower-left coordinates
1466
  if (object_exists(group, "lower_left")) {
37!
1467
    // Read mesh lower-left corner location
1468
    read_dataset(group, "lower_left", lower_left_);
37✔
1469
  } else {
UNCOV
1470
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1471
  }
1472

1473
  if (object_exists(group, "upper_right")) {
37!
1474

1475
    read_dataset(group, "upper_right", upper_right_);
37✔
1476

1477
  } else {
UNCOV
1478
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1479
  }
1480

1481
  if (int err = set_grid()) {
37!
UNCOV
1482
    fatal_error(openmc_err_msg);
×
1483
  }
1484
}
37✔
1485

1486
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1487
{
1488
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1489
}
1490

1491
const std::string RegularMesh::mesh_type = "regular";
1492

1493
std::string RegularMesh::get_mesh_type() const
3,620✔
1494
{
1495
  return mesh_type;
3,620✔
1496
}
1497

1498
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,953,248,182✔
1499
{
1500
  return lower_left_[i] + ijk[i] * width_[i];
1,953,248,182✔
1501
}
1502

1503
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,883,637,066✔
1504
{
1505
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,883,637,066✔
1506
}
1507

1508
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1509
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1510
  double l) const
1511
{
1512
  MeshDistance d;
2,147,483,647✔
1513
  d.next_index = ijk[i];
2,147,483,647✔
1514
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1515
    return d;
15,364,584✔
1516

1517
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1518
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1519
    d.next_index++;
1,948,933,588✔
1520
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,948,933,588✔
1521
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,900,904,016✔
1522
    d.next_index--;
1,879,322,472✔
1523
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,879,322,472✔
1524
  }
1525

1526
  return d;
2,147,483,647✔
1527
}
1528

1529
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1530
  Position plot_ll, Position plot_ur) const
1531
{
1532
  // Figure out which axes lie in the plane of the plot.
1533
  array<int, 2> axes {-1, -1};
22✔
1534
  if (plot_ur.z == plot_ll.z) {
22!
1535
    axes[0] = 0;
22!
1536
    if (n_dimension_ > 1)
22!
1537
      axes[1] = 1;
22✔
UNCOV
1538
  } else if (plot_ur.y == plot_ll.y) {
×
1539
    axes[0] = 0;
×
1540
    if (n_dimension_ > 2)
×
1541
      axes[1] = 2;
×
1542
  } else if (plot_ur.x == plot_ll.x) {
×
1543
    if (n_dimension_ > 1)
×
1544
      axes[0] = 1;
×
1545
    if (n_dimension_ > 2)
×
1546
      axes[1] = 2;
×
1547
  } else {
UNCOV
1548
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1549
  }
1550

1551
  // Get the coordinates of the mesh lines along both of the axes.
1552
  array<vector<double>, 2> axis_lines;
1553
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1554
    int axis = axes[i_ax];
44!
1555
    if (axis == -1)
44!
UNCOV
1556
      continue;
×
1557
    auto& lines {axis_lines[i_ax]};
44✔
1558

1559
    double coord = lower_left_[axis];
44✔
1560
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1561
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1562
        lines.push_back(coord);
242✔
1563
      coord += width_[axis];
242✔
1564
    }
1565
  }
1566

1567
  return {axis_lines[0], axis_lines[1]};
44✔
1568
}
1569

1570
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,465✔
1571
{
1572
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,465✔
1573
  write_dataset(mesh_group, "lower_left", lower_left_);
2,465✔
1574
  write_dataset(mesh_group, "upper_right", upper_right_);
2,465✔
1575
  write_dataset(mesh_group, "width", width_);
2,465✔
1576
}
2,465✔
1577

1578
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1579
  const SourceSite* bank, int64_t length, bool* outside) const
1580
{
1581
  // Determine shape of array for counts
1582
  std::size_t m = this->n_bins();
7,820✔
1583
  vector<std::size_t> shape = {m};
7,820✔
1584

1585
  // Create array of zeros
1586
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1587
  bool outside_ = false;
2,892✔
1588

1589
  for (int64_t i = 0; i < length; i++) {
7,675,271✔
1590
    const auto& site = bank[i];
7,667,451✔
1591

1592
    // determine scoring bin for entropy mesh
1593
    int mesh_bin = get_bin(site.r);
7,667,451✔
1594

1595
    // if outside mesh, skip particle
1596
    if (mesh_bin < 0) {
7,667,451!
UNCOV
1597
      outside_ = true;
×
1598
      continue;
×
1599
    }
1600

1601
    // Add to appropriate bin
1602
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1603
  }
1604

1605
  // Create reduced count data
1606
  auto counts = tensor::zeros<double>(shape);
7,820✔
1607
  int total = cnt.size();
7,820✔
1608

1609
#ifdef OPENMC_MPI
1610
  // collect values from all processors
1611
  MPI_Reduce(
2,892✔
1612
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1613

1614
  // Check if there were sites outside the mesh for any processor
1615
  if (outside) {
2,892!
1616
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892✔
1617
  }
1618
#else
1619
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928✔
1620
  if (outside)
4,928!
1621
    *outside = outside_;
4,928✔
1622
#endif
1623

1624
  return counts;
7,820✔
1625
}
7,820✔
1626

1627
double RegularMesh::volume(const MeshIndex& ijk) const
1,244,598✔
1628
{
1629
  return element_volume_;
1,244,598✔
1630
}
1631

1632
//==============================================================================
1633
// RectilinearMesh implementation
1634
//==============================================================================
1635

1636
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
122✔
1637
{
1638
  n_dimension_ = 3;
122✔
1639

1640
  grid_[0] = get_node_array<double>(node, "x_grid");
122✔
1641
  grid_[1] = get_node_array<double>(node, "y_grid");
122✔
1642
  grid_[2] = get_node_array<double>(node, "z_grid");
122✔
1643

1644
  if (int err = set_grid()) {
122!
UNCOV
1645
    fatal_error(openmc_err_msg);
×
1646
  }
1647
}
122✔
1648

1649
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1650
{
1651
  n_dimension_ = 3;
11✔
1652

1653
  read_dataset(group, "x_grid", grid_[0]);
11✔
1654
  read_dataset(group, "y_grid", grid_[1]);
11✔
1655
  read_dataset(group, "z_grid", grid_[2]);
11✔
1656

1657
  if (int err = set_grid()) {
11!
UNCOV
1658
    fatal_error(openmc_err_msg);
×
1659
  }
1660
}
11✔
1661

1662
const std::string RectilinearMesh::mesh_type = "rectilinear";
1663

1664
std::string RectilinearMesh::get_mesh_type() const
275✔
1665
{
1666
  return mesh_type;
275✔
1667
}
1668

1669
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1670
  const MeshIndex& ijk, int i) const
1671
{
1672
  return grid_[i][ijk[i]];
26,505,963✔
1673
}
1674

1675
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1676
  const MeshIndex& ijk, int i) const
1677
{
1678
  return grid_[i][ijk[i] - 1];
25,739,406✔
1679
}
1680

1681
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,087✔
1682
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1683
  double l) const
1684
{
1685
  MeshDistance d;
53,602,087✔
1686
  d.next_index = ijk[i];
53,602,087✔
1687
  if (std::abs(u[i]) < FP_PRECISION)
53,602,087✔
1688
    return d;
571,824✔
1689

1690
  d.max_surface = (u[i] > 0);
53,030,263✔
1691
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,263✔
1692
    d.next_index++;
26,505,963✔
1693
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,963✔
1694
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,300✔
1695
    d.next_index--;
25,739,406✔
1696
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406✔
1697
  }
1698
  return d;
53,030,263✔
1699
}
1700

1701
int RectilinearMesh::set_grid()
177✔
1702
{
1703
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
177✔
1704
    static_cast<int>(grid_[1].size()) - 1,
177✔
1705
    static_cast<int>(grid_[2].size()) - 1};
177✔
1706

1707
  for (const auto& g : grid_) {
708✔
1708
    if (g.size() < 2) {
531!
UNCOV
1709
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1710
                 "must each have at least 2 points");
UNCOV
1711
      return OPENMC_E_INVALID_ARGUMENT;
×
1712
    }
1713
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
531!
1714
        g.end()) {
531!
UNCOV
1715
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1716
                 "rectilinear meshes must be sorted and unique.");
UNCOV
1717
      return OPENMC_E_INVALID_ARGUMENT;
×
1718
    }
1719
  }
1720

1721
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
177✔
1722
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
177✔
1723

1724
  return 0;
177✔
1725
}
1726

1727
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,892✔
1728
{
1729
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,892✔
1730
}
1731

1732
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1733
  Position plot_ll, Position plot_ur) const
1734
{
1735
  // Figure out which axes lie in the plane of the plot.
1736
  array<int, 2> axes {-1, -1};
11✔
1737
  if (plot_ur.z == plot_ll.z) {
11!
UNCOV
1738
    axes = {0, 1};
×
1739
  } else if (plot_ur.y == plot_ll.y) {
11!
1740
    axes = {0, 2};
11✔
UNCOV
1741
  } else if (plot_ur.x == plot_ll.x) {
×
1742
    axes = {1, 2};
×
1743
  } else {
UNCOV
1744
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1745
  }
1746

1747
  // Get the coordinates of the mesh lines along both of the axes.
1748
  array<vector<double>, 2> axis_lines;
1749
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1750
    int axis = axes[i_ax];
22✔
1751
    vector<double>& lines {axis_lines[i_ax]};
22✔
1752

1753
    for (auto coord : grid_[axis]) {
110✔
1754
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1755
        lines.push_back(coord);
88✔
1756
    }
1757
  }
1758

1759
  return {axis_lines[0], axis_lines[1]};
22✔
1760
}
1761

1762
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1763
{
1764
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1765
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1766
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1767
}
110✔
1768

1769
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1770
{
1771
  double vol {1.0};
132✔
1772

1773
  for (int i = 0; i < n_dimension_; i++) {
528✔
1774
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1775
  }
1776
  return vol;
132✔
1777
}
1778

1779
//==============================================================================
1780
// CylindricalMesh implementation
1781
//==============================================================================
1782

1783
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
400✔
1784
  : PeriodicStructuredMesh {node}
400✔
1785
{
1786
  n_dimension_ = 3;
400✔
1787
  grid_[0] = get_node_array<double>(node, "r_grid");
400✔
1788
  grid_[1] = get_node_array<double>(node, "phi_grid");
400✔
1789
  grid_[2] = get_node_array<double>(node, "z_grid");
400✔
1790
  origin_ = get_node_position(node, "origin");
400✔
1791

1792
  if (int err = set_grid()) {
400!
UNCOV
1793
    fatal_error(openmc_err_msg);
×
1794
  }
1795
}
400✔
1796

1797
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1798
{
1799
  n_dimension_ = 3;
11✔
1800
  read_dataset(group, "r_grid", grid_[0]);
11✔
1801
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1802
  read_dataset(group, "z_grid", grid_[2]);
11✔
1803
  read_dataset(group, "origin", origin_);
11✔
1804

1805
  if (int err = set_grid()) {
11!
UNCOV
1806
    fatal_error(openmc_err_msg);
×
1807
  }
1808
}
11✔
1809

1810
const std::string CylindricalMesh::mesh_type = "cylindrical";
1811

1812
std::string CylindricalMesh::get_mesh_type() const
484✔
1813
{
1814
  return mesh_type;
484✔
1815
}
1816

1817
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1818
  Position r, bool& in_mesh) const
1819
{
1820
  r = local_coords(r);
47,732,091✔
1821

1822
  Position mapped_r;
47,732,091✔
1823
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1824
  mapped_r[2] = r[2];
47,732,091✔
1825

1826
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1827
    mapped_r[1] = 0.0;
1828
  } else {
1829
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1830
    if (mapped_r[1] < 0)
47,732,091✔
1831
      mapped_r[1] += 2 * PI;
23,874,862✔
1832
  }
1833

1834
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,732,091✔
1835

1836
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1837

1838
  return idx;
47,732,091✔
1839
}
1840

1841
Position CylindricalMesh::sample_element(
88,110✔
1842
  const MeshIndex& ijk, uint64_t* seed) const
1843
{
1844
  double r_min = this->r(ijk[0] - 1);
88,110✔
1845
  double r_max = this->r(ijk[0]);
88,110✔
1846

1847
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1848
  double phi_max = this->phi(ijk[1]);
88,110✔
1849

1850
  double z_min = this->z(ijk[2] - 1);
88,110✔
1851
  double z_max = this->z(ijk[2]);
88,110✔
1852

1853
  double r_min_sq = r_min * r_min;
88,110✔
1854
  double r_max_sq = r_max * r_max;
88,110✔
1855
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1856
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1857
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1858

1859
  double x = r * std::cos(phi);
88,110✔
1860
  double y = r * std::sin(phi);
88,110✔
1861

1862
  return origin_ + Position(x, y, z);
88,110✔
1863
}
1864

1865
double CylindricalMesh::find_r_crossing(
142,592,704✔
1866
  const Position& r, const Direction& u, double l, int shell) const
1867
{
1868

1869
  if ((shell < 0) || (shell > shape_[0]))
142,592,704!
1870
    return INFTY;
1871

1872
  // solve r.x^2 + r.y^2 == r0^2
1873
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1874
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1875

1876
  const double r0 = grid_[0][shell];
124,678,495✔
1877
  if (r0 == 0.0)
124,678,495✔
1878
    return INFTY;
1879

1880
  const double denominator = u.x * u.x + u.y * u.y;
117,542,421✔
1881

1882
  // Direction of flight is in z-direction. Will never intersect r.
1883
  if (std::abs(denominator) < FP_PRECISION)
117,542,421✔
1884
    return INFTY;
1885

1886
  // inverse of dominator to help the compiler to speed things up
1887
  const double inv_denominator = 1.0 / denominator;
117,483,461✔
1888

1889
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,483,461✔
1890
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,483,461✔
1891
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,483,461✔
1892

1893
  if (D < 0.0)
117,483,461✔
1894
    return INFTY;
1895

1896
  D = std::sqrt(D);
107,747,339✔
1897

1898
  // Particle is already on the shell surface; avoid spurious crossing
1899
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,747,339✔
1900
    return INFTY;
1901

1902
  // Check -p - D first because it is always smaller as -p + D
1903
  if (-p - D > l)
101,113,965✔
1904
    return -p - D;
1905
  if (-p + D > l)
80,906,327✔
1906
    return -p + D;
50,080,372✔
1907

1908
  return INFTY;
1909
}
1910

1911
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1912
  const Position& r, const Direction& u, double l, int shell) const
1913
{
1914
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1915
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1916
    return INFTY;
1917

1918
  shell = sanitize_phi(shell);
43,970,718✔
1919

1920
  const double p0 = grid_[1][shell];
43,970,718✔
1921

1922
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1923
  // => x(s) * cos(p0) = y(s) * sin(p0)
1924
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1925
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1926

1927
  const double c0 = std::cos(p0);
43,970,718✔
1928
  const double s0 = std::sin(p0);
43,970,718✔
1929

1930
  const double denominator = (u.x * s0 - u.y * c0);
43,970,718✔
1931

1932
  // Check if direction of flight is not parallel to phi surface
1933
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1934
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1935
    // Check if solution is in positive direction of flight and crosses the
1936
    // correct phi surface (not -phi)
1937
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1938
      return s;
20,219,859✔
1939
  }
1940

1941
  return INFTY;
1942
}
1943

1944
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1945
  const Position& r, const Direction& u, double l, int shell) const
1946
{
1947
  MeshDistance d;
36,695,747✔
1948
  d.next_index = shell;
36,695,747✔
1949

1950
  // Direction of flight is within xy-plane. Will never intersect z.
1951
  if (std::abs(u.z) < FP_PRECISION)
36,695,747✔
1952
    return d;
1,118,216✔
1953

1954
  d.max_surface = (u.z > 0.0);
35,577,531✔
1955
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1956
    d.next_index += 1;
16,875,892✔
1957
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1958
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1959
    d.next_index -= 1;
16,846,225✔
1960
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1961
  }
1962
  return d;
35,577,531✔
1963
}
1964

1965
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,220,301✔
1966
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1967
  double l) const
1968
{
1969
  if (i == 0) {
145,220,301✔
1970

1971
    return std::min(
142,592,704✔
1972
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,296,352✔
1973
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,592,704✔
1974

1975
  } else if (i == 1) {
73,923,949✔
1976

1977
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
1978
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1979
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
1980
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1981

1982
  } else {
1983
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1984
  }
1985
}
1986

1987
int CylindricalMesh::set_grid()
433✔
1988
{
1989
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
1990
    static_cast<int>(grid_[1].size()) - 1,
433✔
1991
    static_cast<int>(grid_[2].size()) - 1};
433✔
1992

1993
  for (const auto& g : grid_) {
1,732✔
1994
    if (g.size() < 2) {
1,299!
UNCOV
1995
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
1996
                 "must each have at least 2 points");
UNCOV
1997
      return OPENMC_E_INVALID_ARGUMENT;
×
1998
    }
1999
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,299!
2000
        g.end()) {
1,299!
UNCOV
2001
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2002
                 "cylindrical meshes must be sorted and unique.");
UNCOV
2003
      return OPENMC_E_INVALID_ARGUMENT;
×
2004
    }
2005
  }
2006
  if (grid_[0].front() < 0.0) {
433!
UNCOV
2007
    set_errmsg("r-grid for "
×
2008
               "cylindrical meshes must start at r >= 0.");
UNCOV
2009
    return OPENMC_E_INVALID_ARGUMENT;
×
2010
  }
2011
  if (grid_[1].front() < 0.0) {
433!
UNCOV
2012
    set_errmsg("phi-grid for "
×
2013
               "cylindrical meshes must start at phi >= 0.");
UNCOV
2014
    return OPENMC_E_INVALID_ARGUMENT;
×
2015
  }
2016
  if (grid_[1].back() > 2.0 * PI) {
433!
UNCOV
2017
    set_errmsg("phi-grids for "
×
2018
               "cylindrical meshes must end with theta <= 2*pi.");
2019

UNCOV
2020
    return OPENMC_E_INVALID_ARGUMENT;
×
2021
  }
2022

2023
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
433!
2024

2025
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2026
    origin_[2] + grid_[2].front()};
433✔
2027
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2028
    origin_[2] + grid_[2].back()};
433✔
2029

2030
  return 0;
433✔
2031
}
2032

2033
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,273✔
2034
{
2035
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2036
}
2037

UNCOV
2038
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2039
  Position plot_ll, Position plot_ur) const
2040
{
UNCOV
2041
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2042

2043
  // Figure out which axes lie in the plane of the plot.
2044
  array<vector<double>, 2> axis_lines;
2045
  return {axis_lines[0], axis_lines[1]};
2046
}
2047

2048
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2049
{
2050
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2051
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2052
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2053
  write_dataset(mesh_group, "origin", origin_);
374✔
2054
}
374✔
2055

2056
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2057
{
2058
  double r_i = grid_[0][ijk[0] - 1];
792✔
2059
  double r_o = grid_[0][ijk[0]];
792✔
2060

2061
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2062
  double phi_o = grid_[1][ijk[1]];
792✔
2063

2064
  double z_i = grid_[2][ijk[2] - 1];
792✔
2065
  double z_o = grid_[2][ijk[2]];
792✔
2066

2067
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2068
}
2069

2070
//==============================================================================
2071
// SphericalMesh implementation
2072
//==============================================================================
2073

2074
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2075
  : PeriodicStructuredMesh {node}
345✔
2076
{
2077
  n_dimension_ = 3;
345✔
2078

2079
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2080
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2081
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2082
  origin_ = get_node_position(node, "origin");
345✔
2083

2084
  if (int err = set_grid()) {
345!
UNCOV
2085
    fatal_error(openmc_err_msg);
×
2086
  }
2087
}
345✔
2088

2089
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2090
{
2091
  n_dimension_ = 3;
11✔
2092

2093
  read_dataset(group, "r_grid", grid_[0]);
11✔
2094
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2095
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2096
  read_dataset(group, "origin", origin_);
11✔
2097

2098
  if (int err = set_grid()) {
11!
UNCOV
2099
    fatal_error(openmc_err_msg);
×
2100
  }
2101
}
11✔
2102

2103
const std::string SphericalMesh::mesh_type = "spherical";
2104

2105
std::string SphericalMesh::get_mesh_type() const
385✔
2106
{
2107
  return mesh_type;
385✔
2108
}
2109

2110
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2111
  Position r, bool& in_mesh) const
2112
{
2113
  r = local_coords(r);
68,592,128✔
2114

2115
  Position mapped_r;
68,592,128✔
2116
  mapped_r[0] = r.norm();
68,592,128✔
2117

2118
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2119
    mapped_r[1] = 0.0;
2120
    mapped_r[2] = 0.0;
2121
  } else {
2122
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2123
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2124
    if (mapped_r[2] < 0)
68,592,128✔
2125
      mapped_r[2] += 2 * PI;
34,268,685✔
2126
  }
2127

2128
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,592,128✔
2129

2130
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2131
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2132

2133
  return idx;
68,592,128✔
2134
}
2135

2136
Position SphericalMesh::sample_element(
110✔
2137
  const MeshIndex& ijk, uint64_t* seed) const
2138
{
2139
  double r_min = this->r(ijk[0] - 1);
110✔
2140
  double r_max = this->r(ijk[0]);
110✔
2141

2142
  double theta_min = this->theta(ijk[1] - 1);
110✔
2143
  double theta_max = this->theta(ijk[1]);
110✔
2144

2145
  double phi_min = this->phi(ijk[2] - 1);
110✔
2146
  double phi_max = this->phi(ijk[2]);
110✔
2147

2148
  double cos_theta =
110✔
2149
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2150
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2151
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2152
  double r_min_cub = std::pow(r_min, 3);
110✔
2153
  double r_max_cub = std::pow(r_max, 3);
110✔
2154
  // might be faster to do rejection here?
2155
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2156

2157
  double x = r * std::cos(phi) * sin_theta;
110✔
2158
  double y = r * std::sin(phi) * sin_theta;
110✔
2159
  double z = r * cos_theta;
110✔
2160

2161
  return origin_ + Position(x, y, z);
110✔
2162
}
2163

2164
double SphericalMesh::find_r_crossing(
444,003,582✔
2165
  const Position& r, const Direction& u, double l, int shell) const
2166
{
2167
  if ((shell < 0) || (shell > shape_[0]))
444,003,582✔
2168
    return INFTY;
2169

2170
  // solve |r+s*u| = r0
2171
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2172
  const double r0 = grid_[0][shell];
404,382,495✔
2173
  if (r0 == 0.0)
404,382,495✔
2174
    return INFTY;
2175
  const double p = r.dot(u);
396,703,978✔
2176
  double R = r.norm();
396,703,978✔
2177
  double D = p * p - (R - r0) * (R + r0);
396,703,978✔
2178

2179
  // Particle is already on the shell surface; avoid spurious crossing
2180
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,703,978✔
2181
    return INFTY;
2182

2183
  if (D >= 0.0) {
385,995,324✔
2184
    D = std::sqrt(D);
358,118,376✔
2185
    // Check -p - D first because it is always smaller as -p + D
2186
    if (-p - D > l)
358,118,376✔
2187
      return -p - D;
2188
    if (-p + D > l)
293,798,472✔
2189
      return -p + D;
177,252,977✔
2190
  }
2191

2192
  return INFTY;
2193
}
2194

2195
double SphericalMesh::find_theta_crossing(
110,161,348✔
2196
  const Position& r, const Direction& u, double l, int shell) const
2197
{
2198
  // Theta grid is [0, π], thus there is no real surface to cross
2199
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2200
    return INFTY;
2201

2202
  shell = sanitize_theta(shell);
38,358,540✔
2203

2204
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2205
  // yields
2206
  // a*s^2 + 2*b*s + c == 0 with
2207
  // a = cos(theta)^2 - u.z * u.z
2208
  // b = r*u * cos(theta)^2 - u.z * r.z
2209
  // c = r*r * cos(theta)^2 - r.z^2
2210

2211
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2212
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2213
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2214

2215
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2216
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2217
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2218

2219
  // if factor of s^2 is zero, direction of flight is parallel to theta
2220
  // surface
2221
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2222
    // if b vanishes, direction of flight is within theta surface and crossing
2223
    // is not possible
2224
    if (std::abs(b) < FP_PRECISION)
482,548!
2225
      return INFTY;
2226

UNCOV
2227
    const double s = -0.5 * c / b;
×
2228
    // Check if solution is in positive direction of flight and has correct
2229
    // sign
UNCOV
2230
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2231
      return s;
×
2232

2233
    // no crossing is possible
2234
    return INFTY;
2235
  }
2236

2237
  const double p = b / a;
37,875,992✔
2238
  double D = p * p - c / a;
37,875,992✔
2239

2240
  if (D < 0.0)
37,875,992✔
2241
    return INFTY;
2242

2243
  D = std::sqrt(D);
26,921,004✔
2244

2245
  // the solution -p-D is always smaller as -p+D : Check this one first
2246
  double s = -p - D;
26,921,004✔
2247
  // Check if solution is in positive direction of flight and has correct sign
2248
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
26,921,004✔
2249
    return s;
2250

2251
  s = -p + D;
21,638,397✔
2252
  // Check if solution is in positive direction of flight and has correct sign
2253
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
21,638,397✔
2254
    return s;
10,163,296✔
2255

2256
  return INFTY;
2257
}
2258

2259
double SphericalMesh::find_phi_crossing(
111,750,826✔
2260
  const Position& r, const Direction& u, double l, int shell) const
2261
{
2262
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2263
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2264
    return INFTY;
2265

2266
  shell = sanitize_phi(shell);
39,948,018✔
2267

2268
  const double p0 = grid_[2][shell];
39,948,018✔
2269

2270
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2271
  // => x(s) * cos(p0) = y(s) * sin(p0)
2272
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2273
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2274

2275
  const double c0 = std::cos(p0);
39,948,018✔
2276
  const double s0 = std::sin(p0);
39,948,018✔
2277

2278
  const double denominator = (u.x * s0 - u.y * c0);
39,948,018✔
2279

2280
  // Check if direction of flight is not parallel to phi surface
2281
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2282
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2283
    // Check if solution is in positive direction of flight and crosses the
2284
    // correct phi surface (not -phi)
2285
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2286
      return s;
17,579,452✔
2287
  }
2288

2289
  return INFTY;
2290
}
2291

2292
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,957,878✔
2293
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2294
  double l) const
2295
{
2296

2297
  if (i == 0) {
332,957,878✔
2298
    return std::min(
444,003,582✔
2299
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
222,001,791✔
2300
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
444,003,582✔
2301

2302
  } else if (i == 1) {
110,956,087✔
2303
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2304
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2305
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2306
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2307

2308
  } else {
2309
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2310
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2311
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2312
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2313
  }
2314
}
2315

2316
int SphericalMesh::set_grid()
378✔
2317
{
2318
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2319
    static_cast<int>(grid_[1].size()) - 1,
378✔
2320
    static_cast<int>(grid_[2].size()) - 1};
378✔
2321

2322
  for (const auto& g : grid_) {
1,512✔
2323
    if (g.size() < 2) {
1,134!
UNCOV
2324
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2325
                 "must each have at least 2 points");
UNCOV
2326
      return OPENMC_E_INVALID_ARGUMENT;
×
2327
    }
2328
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,134!
2329
        g.end()) {
1,134!
UNCOV
2330
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2331
                 "spherical meshes must be sorted and unique.");
UNCOV
2332
      return OPENMC_E_INVALID_ARGUMENT;
×
2333
    }
2334
    if (g.front() < 0.0) {
1,134!
UNCOV
2335
      set_errmsg("r-, theta-, and phi- grids for "
×
2336
                 "spherical meshes must start at v >= 0.");
UNCOV
2337
      return OPENMC_E_INVALID_ARGUMENT;
×
2338
    }
2339
  }
2340
  if (grid_[1].back() > PI) {
378!
UNCOV
2341
    set_errmsg("theta-grids for "
×
2342
               "spherical meshes must end with theta <= pi.");
2343

UNCOV
2344
    return OPENMC_E_INVALID_ARGUMENT;
×
2345
  }
2346
  if (grid_[2].back() > 2 * PI) {
378!
UNCOV
2347
    set_errmsg("phi-grids for "
×
2348
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2349
    return OPENMC_E_INVALID_ARGUMENT;
×
2350
  }
2351

2352
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2353
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2354

2355
  double r = grid_[0].back();
378✔
2356
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2357
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2358

2359
  return 0;
378✔
2360
}
2361

2362
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,384✔
2363
{
2364
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2365
}
2366

UNCOV
2367
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2368
  Position plot_ll, Position plot_ur) const
2369
{
UNCOV
2370
  fatal_error("Plot of spherical Mesh not implemented");
×
2371

2372
  // Figure out which axes lie in the plane of the plot.
2373
  array<vector<double>, 2> axis_lines;
2374
  return {axis_lines[0], axis_lines[1]};
2375
}
2376

2377
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2378
{
2379
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2380
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2381
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2382
  write_dataset(mesh_group, "origin", origin_);
319✔
2383
}
319✔
2384

2385
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2386
{
2387
  double r_i = grid_[0][ijk[0] - 1];
935✔
2388
  double r_o = grid_[0][ijk[0]];
935✔
2389

2390
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2391
  double theta_o = grid_[1][ijk[1]];
935✔
2392

2393
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2394
  double phi_o = grid_[2][ijk[2]];
935✔
2395

2396
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2397
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2398
}
2399

2400
//==============================================================================
2401
// Helper functions for the C API
2402
//==============================================================================
2403

2404
int check_mesh(int32_t index)
6,490✔
2405
{
2406
  if (index < 0 || index >= model::meshes.size()) {
6,490!
UNCOV
2407
    set_errmsg("Index in meshes array is out of bounds.");
×
2408
    return OPENMC_E_OUT_OF_BOUNDS;
×
2409
  }
2410
  return 0;
2411
}
2412

2413
template<class T>
2414
int check_mesh_type(int32_t index)
1,100✔
2415
{
2416
  if (int err = check_mesh(index))
1,100!
2417
    return err;
2418

2419
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2420
  if (!mesh) {
1,100!
UNCOV
2421
    set_errmsg("This function is not valid for input mesh.");
×
2422
    return OPENMC_E_INVALID_TYPE;
×
2423
  }
2424
  return 0;
2425
}
2426

2427
template<class T>
2428
bool is_mesh_type(int32_t index)
2429
{
2430
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2431
  return mesh;
2432
}
2433

2434
//==============================================================================
2435
// C API functions
2436
//==============================================================================
2437

2438
// Return the type of mesh as a C string
2439
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2440
{
2441
  if (int err = check_mesh(index))
1,496!
2442
    return err;
2443

2444
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,496✔
2445

2446
  return 0;
1,496✔
2447
}
2448

2449
//! Extend the meshes array by n elements
2450
extern "C" int openmc_extend_meshes(
253✔
2451
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2452
{
2453
  if (index_start)
253!
2454
    *index_start = model::meshes.size();
253✔
2455
  std::string mesh_type;
253✔
2456

2457
  for (int i = 0; i < n; ++i) {
506✔
2458
    if (RegularMesh::mesh_type == type) {
253✔
2459
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2460
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2461
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2462
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2463
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2464
    } else if (SphericalMesh::mesh_type == type) {
22!
2465
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2466
    } else {
UNCOV
2467
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2468
    }
2469
  }
2470
  if (index_end)
253!
UNCOV
2471
    *index_end = model::meshes.size() - 1;
×
2472

2473
  return 0;
253✔
2474
}
253✔
2475

2476
//! Adds a new unstructured mesh to OpenMC
UNCOV
2477
extern "C" int openmc_add_unstructured_mesh(
×
2478
  const char filename[], const char library[], int* id)
2479
{
UNCOV
2480
  std::string lib_name(library);
×
2481
  std::string mesh_file(filename);
×
2482
  bool valid_lib = false;
×
2483

2484
#ifdef OPENMC_DAGMC_ENABLED
2485
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2486
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2487
    valid_lib = true;
2488
  }
2489
#endif
2490

2491
#ifdef OPENMC_LIBMESH_ENABLED
2492
  if (lib_name == LibMesh::mesh_lib_type) {
×
2493
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2494
    valid_lib = true;
2495
  }
2496
#endif
2497

UNCOV
2498
  if (!valid_lib) {
×
2499
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2500
                           "by this build of OpenMC",
2501
      lib_name));
UNCOV
2502
    return OPENMC_E_INVALID_ARGUMENT;
×
2503
  }
2504

2505
  // auto-assign new ID
2506
  model::meshes.back()->set_id(-1);
×
2507
  *id = model::meshes.back()->id_;
2508

2509
  return 0;
UNCOV
2510
}
×
2511

2512
//! Return the index in the meshes array of a mesh with a given ID
2513
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2514
{
2515
  auto pair = model::mesh_map.find(id);
429!
2516
  if (pair == model::mesh_map.end()) {
429!
UNCOV
2517
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2518
    return OPENMC_E_INVALID_ID;
×
2519
  }
2520
  *index = pair->second;
429✔
2521
  return 0;
429✔
2522
}
2523

2524
//! Return the ID of a mesh
2525
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,827✔
2526
{
2527
  if (int err = check_mesh(index))
2,827!
2528
    return err;
2529
  *id = model::meshes[index]->id_;
2,827✔
2530
  return 0;
2,827✔
2531
}
2532

2533
//! Set the ID of a mesh
2534
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2535
{
2536
  if (int err = check_mesh(index))
253!
2537
    return err;
2538
  model::meshes[index]->id_ = id;
253✔
2539
  model::mesh_map[id] = index;
253✔
2540
  return 0;
253✔
2541
}
2542

2543
//! Get the number of elements in a mesh
2544
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2545
{
2546
  if (int err = check_mesh(index))
297!
2547
    return err;
2548
  *n = model::meshes[index]->n_bins();
297✔
2549
  return 0;
297✔
2550
}
2551

2552
//! Get the volume of each element in the mesh
2553
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2554
{
2555
  if (int err = check_mesh(index))
88!
2556
    return err;
2557
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2558
    volumes[i] = model::meshes[index]->volume(i);
880✔
2559
  }
2560
  return 0;
2561
}
2562

2563
//! Get the bounding box of a mesh
2564
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2565
{
2566
  if (int err = check_mesh(index))
176!
2567
    return err;
2568

2569
  BoundingBox bbox = model::meshes[index]->bounding_box();
176✔
2570

2571
  // set lower left corner values
2572
  ll[0] = bbox.min.x;
176✔
2573
  ll[1] = bbox.min.y;
176✔
2574
  ll[2] = bbox.min.z;
176✔
2575

2576
  // set upper right corner values
2577
  ur[0] = bbox.max.x;
176✔
2578
  ur[1] = bbox.max.y;
176✔
2579
  ur[2] = bbox.max.z;
176✔
2580
  return 0;
176✔
2581
}
2582

2583
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2584
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2585
{
2586
  if (int err = check_mesh(index))
209!
2587
    return err;
2588

2589
  try {
209✔
2590
    model::meshes[index]->material_volumes(
209✔
2591
      nx, ny, nz, table_size, materials, volumes, bboxes);
2592
  } catch (const std::exception& e) {
11!
2593
    set_errmsg(e.what());
11✔
2594
    if (starts_with(e.what(), "Mesh")) {
11!
2595
      return OPENMC_E_GEOMETRY;
11✔
2596
    } else {
UNCOV
2597
      return OPENMC_E_ALLOCATE;
×
2598
    }
2599
  }
11✔
2600

2601
  return 0;
2602
}
2603

2604
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2605
  Position width, int basis, int* pixels, int32_t* data)
2606
{
2607
  if (int err = check_mesh(index))
44!
2608
    return err;
2609
  const auto& mesh = model::meshes[index].get();
44!
2610

2611
  int pixel_width = pixels[0];
44✔
2612
  int pixel_height = pixels[1];
44✔
2613

2614
  // get pixel size
2615
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2616
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2617

2618
  // setup basis indices and initial position centered on pixel
2619
  int in_i, out_i;
44✔
2620
  Position xyz = origin;
44✔
2621
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2622
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2623
  switch (basis_enum) {
44!
2624
  case PlotBasis::xy:
2625
    in_i = 0;
2626
    out_i = 1;
2627
    break;
2628
  case PlotBasis::xz:
2629
    in_i = 0;
2630
    out_i = 2;
2631
    break;
2632
  case PlotBasis::yz:
2633
    in_i = 1;
2634
    out_i = 2;
2635
    break;
UNCOV
2636
  default:
×
2637
    UNREACHABLE();
×
2638
  }
2639

2640
  // set initial position
2641
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2642
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2643

2644
#pragma omp parallel
24✔
2645
  {
20✔
2646
    Position r = xyz;
20✔
2647

2648
#pragma omp for
2649
    for (int y = 0; y < pixel_height; y++) {
420✔
2650
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2651
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2652
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2653
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2654
      }
2655
    }
2656
  }
2657

2658
  return 0;
44✔
2659
}
2660

2661
//! Get the dimension of a regular mesh
2662
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2663
  int32_t index, int** dims, int* n)
2664
{
2665
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2666
    return err;
2667
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2668
  *dims = mesh->shape_.data();
11✔
2669
  *n = mesh->n_dimension_;
11✔
2670
  return 0;
11✔
2671
}
2672

2673
//! Set the dimension of a regular mesh
2674
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2675
  int32_t index, int n, const int* dims)
2676
{
2677
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2678
    return err;
2679
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2680

2681
  // Copy dimension
2682
  mesh->n_dimension_ = n;
187✔
2683
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2684
  return 0;
187✔
2685
}
2686

2687
//! Get the regular mesh parameters
2688
extern "C" int openmc_regular_mesh_get_params(
209✔
2689
  int32_t index, double** ll, double** ur, double** width, int* n)
2690
{
2691
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2692
    return err;
2693
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2694

2695
  if (m->lower_left_.empty()) {
209!
UNCOV
2696
    set_errmsg("Mesh parameters have not been set.");
×
2697
    return OPENMC_E_ALLOCATE;
×
2698
  }
2699

2700
  *ll = m->lower_left_.data();
209✔
2701
  *ur = m->upper_right_.data();
209✔
2702
  *width = m->width_.data();
209✔
2703
  *n = m->n_dimension_;
209✔
2704
  return 0;
209✔
2705
}
2706

2707
//! Set the regular mesh parameters
2708
extern "C" int openmc_regular_mesh_set_params(
220✔
2709
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2710
{
2711
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2712
    return err;
2713
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2714

2715
  if (m->n_dimension_ == -1) {
220!
UNCOV
2716
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2717
    return OPENMC_E_UNASSIGNED;
×
2718
  }
2719

2720
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2721
  if (ll && ur) {
220✔
2722
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2723
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2724
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2725
  } else if (ll && width) {
22✔
2726
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2727
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2728
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2729
  } else if (ur && width) {
11!
2730
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2731
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2732
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2733
  } else {
UNCOV
2734
    set_errmsg("At least two parameters must be specified.");
×
2735
    return OPENMC_E_INVALID_ARGUMENT;
×
2736
  }
2737

2738
  // Set material volumes
2739

2740
  // TODO: incorporate this into method in RegularMesh that can be called from
2741
  // here and from constructor
2742
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2743
  m->element_volume_ = 1.0;
220✔
2744
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2745
    m->element_volume_ *= m->width_[i];
660✔
2746
  }
2747

2748
  return 0;
2749
}
220✔
2750

2751
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2752
template<class C>
2753
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2754
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2755
  const int nz)
2756
{
2757
  if (int err = check_mesh_type<C>(index))
88!
2758
    return err;
2759

2760
  C* m = dynamic_cast<C*>(model::meshes[index].get());
88!
2761

2762
  m->n_dimension_ = 3;
88✔
2763

2764
  m->grid_[0].reserve(nx);
88✔
2765
  m->grid_[1].reserve(ny);
88✔
2766
  m->grid_[2].reserve(nz);
88✔
2767

2768
  for (int i = 0; i < nx; i++) {
572✔
2769
    m->grid_[0].push_back(grid_x[i]);
484✔
2770
  }
2771
  for (int i = 0; i < ny; i++) {
341✔
2772
    m->grid_[1].push_back(grid_y[i]);
253✔
2773
  }
2774
  for (int i = 0; i < nz; i++) {
319✔
2775
    m->grid_[2].push_back(grid_z[i]);
231✔
2776
  }
2777

2778
  int err = m->set_grid();
88✔
2779
  return err;
88✔
2780
}
2781

2782
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2783
template<class C>
2784
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2785
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2786
{
2787
  if (int err = check_mesh_type<C>(index))
385!
2788
    return err;
2789
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2790

2791
  if (m->lower_left_.empty()) {
385!
UNCOV
2792
    set_errmsg("Mesh parameters have not been set.");
×
2793
    return OPENMC_E_ALLOCATE;
×
2794
  }
2795

2796
  *grid_x = m->grid_[0].data();
385✔
2797
  *nx = m->grid_[0].size();
385✔
2798
  *grid_y = m->grid_[1].data();
385✔
2799
  *ny = m->grid_[1].size();
385✔
2800
  *grid_z = m->grid_[2].data();
385✔
2801
  *nz = m->grid_[2].size();
385✔
2802

2803
  return 0;
385✔
2804
}
2805

2806
//! Get the rectilinear mesh grid
2807
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2808
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2809
{
2810
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2811
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2812
}
2813

2814
//! Set the rectilienar mesh parameters
2815
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2816
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2817
  const double* grid_z, const int nz)
2818
{
2819
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2820
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2821
}
2822

2823
//! Get the cylindrical mesh grid
2824
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2825
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2826
{
2827
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2828
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2829
}
2830

2831
//! Set the cylindrical mesh parameters
2832
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2833
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2834
  const double* grid_z, const int nz)
2835
{
2836
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2837
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2838
}
2839

2840
//! Get the spherical mesh grid
2841
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2842
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2843
{
2844

2845
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2846
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2847
  ;
121✔
2848
}
2849

2850
//! Set the spherical mesh parameters
2851
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2852
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2853
  const double* grid_z, const int nz)
2854
{
2855
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2856
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2857
}
2858

2859
#ifdef OPENMC_DAGMC_ENABLED
2860

2861
const std::string MOABMesh::mesh_lib_type = "moab";
2862

2863
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2864
{
2865
  initialize();
24✔
2866
}
24!
2867

2868
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2869
{
2870
  initialize();
×
2871
}
×
2872

2873
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2874
  : UnstructuredMesh()
×
2875
{
2876
  n_dimension_ = 3;
2877
  filename_ = filename;
×
2878
  set_length_multiplier(length_multiplier);
×
2879
  initialize();
×
2880
}
×
2881

2882
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2883
{
2884
  mbi_ = external_mbi;
1✔
2885
  filename_ = "unknown (external file)";
1✔
2886
  this->initialize();
1✔
2887
}
1!
2888

2889
void MOABMesh::initialize()
25✔
2890
{
2891

2892
  // Create the MOAB interface and load data from file
2893
  this->create_interface();
25✔
2894

2895
  // Initialise MOAB error code
2896
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2897

2898
  // Set the dimension
2899
  n_dimension_ = 3;
25✔
2900

2901
  // set member range of tetrahedral entities
2902
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2903
  if (rval != moab::MB_SUCCESS) {
25!
2904
    fatal_error("Failed to get all tetrahedral elements");
2905
  }
2906

2907
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2908
    warning("Non-tetrahedral elements found in unstructured "
×
2909
            "mesh file: " +
2910
            filename_);
2911
  }
2912

2913
  // set member range of vertices
2914
  int vertex_dim = 0;
25✔
2915
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2916
  if (rval != moab::MB_SUCCESS) {
25!
2917
    fatal_error("Failed to get all vertex handles");
2918
  }
2919

2920
  // make an entity set for all tetrahedra
2921
  // this is used for convenience later in output
2922
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2923
  if (rval != moab::MB_SUCCESS) {
25!
2924
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2925
  }
2926

2927
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2928
  if (rval != moab::MB_SUCCESS) {
25!
2929
    fatal_error("Failed to add tetrahedra to an entity set.");
2930
  }
2931

2932
  if (length_multiplier_ > 0.0) {
25!
2933
    // get the connectivity of all tets
2934
    moab::Range adj;
×
2935
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
2936
    if (rval != moab::MB_SUCCESS) {
×
2937
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2938
    }
2939
    // scale all vertex coords by multiplier (done individually so not all
2940
    // coordinates are in memory twice at once)
2941
    for (auto vert : adj) {
×
2942
      // retrieve coords
2943
      std::array<double, 3> coord;
2944
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
2945
      if (rval != moab::MB_SUCCESS) {
×
2946
        fatal_error("Could not get coordinates of vertex.");
2947
      }
2948
      // scale coords
2949
      for (auto& c : coord) {
×
2950
        c *= length_multiplier_;
2951
      }
2952
      // set new coords
2953
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2954
      if (rval != moab::MB_SUCCESS) {
×
2955
        fatal_error("Failed to set new vertex coordinates");
2956
      }
2957
    }
2958
  }
2959

2960
  // Determine bounds of mesh
2961
  this->determine_bounds();
25✔
2962
}
25✔
2963

2964
void MOABMesh::prepare_for_point_location()
21✔
2965
{
2966
  // if the KDTree has already been constructed, do nothing
2967
  if (kdtree_)
21!
2968
    return;
2969

2970
  // build acceleration data structures
2971
  compute_barycentric_data(ehs_);
21✔
2972
  build_kdtree(ehs_);
21✔
2973
}
2974

2975
void MOABMesh::create_interface()
25✔
2976
{
2977
  // Do not create a MOAB instance if one is already in memory
2978
  if (mbi_)
25✔
2979
    return;
2980

2981
  // create MOAB instance
2982
  mbi_ = std::make_shared<moab::Core>();
24!
2983

2984
  // load unstructured mesh file
2985
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
2986
  if (rval != moab::MB_SUCCESS) {
24!
2987
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2988
  }
2989
}
2990

2991
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
2992
{
2993
  moab::Range all_tris;
21✔
2994
  int adj_dim = 2;
21✔
2995
  write_message("Getting tet adjacencies...", 7);
21✔
2996
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
2997
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2998
  if (rval != moab::MB_SUCCESS) {
21!
2999
    fatal_error("Failed to get adjacent triangles for tets");
3000
  }
3001

3002
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3003
    warning("Non-triangle elements found in tet adjacencies in "
×
3004
            "unstructured mesh file: " +
3005
            filename_);
×
3006
  }
3007

3008
  // combine into one range
3009
  moab::Range all_tets_and_tris;
21✔
3010
  all_tets_and_tris.merge(all_tets);
21✔
3011
  all_tets_and_tris.merge(all_tris);
21✔
3012

3013
  // create a kd-tree instance
3014
  write_message(
21✔
3015
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3016
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3017

3018
  // Determine what options to use
3019
  std::ostringstream options_stream;
21✔
3020
  if (options_.empty()) {
21✔
3021
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3022
  } else {
3023
    options_stream << options_;
16✔
3024
  }
3025
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3026

3027
  // Build the k-d tree
3028
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3029
  if (rval != moab::MB_SUCCESS) {
21!
3030
    fatal_error("Failed to construct KDTree for the "
3031
                "unstructured mesh file: " +
3032
                filename_);
×
3033
  }
3034
}
21✔
3035

3036
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3037
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3038
{
3039
  hits.clear();
1,543,584!
3040

3041
  moab::ErrorCode rval;
1,543,584✔
3042
  vector<moab::EntityHandle> tris;
1,543,584✔
3043
  // get all intersections with triangles in the tet mesh
3044
  // (distances are relative to the start point, not the previous
3045
  // intersection)
3046
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3047
    dir.array(), start.array(), tris, hits, 0, track_len);
3048
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3049
    fatal_error(
3050
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3051
  }
3052

3053
  // remove duplicate intersection distances
3054
  std::unique(hits.begin(), hits.end());
1,543,584✔
3055

3056
  // sorts by first component of std::pair by default
3057
  std::sort(hits.begin(), hits.end());
1,543,584✔
3058
}
1,543,584✔
3059

3060
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3061
  vector<int>& bins, vector<double>& lengths) const
3062
{
3063
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3064
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3065
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3066
  dir.normalize();
1,543,584✔
3067

3068
  double track_len = (end - start).length();
1,543,584✔
3069
  if (track_len == 0.0)
1,543,584!
3070
    return;
721,692✔
3071

3072
  start -= TINY_BIT * dir;
1,543,584✔
3073
  end += TINY_BIT * dir;
1,543,584✔
3074

3075
  vector<double> hits;
1,543,584✔
3076
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3077

3078
  bins.clear();
1,543,584!
3079
  lengths.clear();
1,543,584!
3080

3081
  // if there are no intersections the track may lie entirely
3082
  // within a single tet. If this is the case, apply entire
3083
  // score to that tet and return.
3084
  if (hits.size() == 0) {
1,543,584✔
3085
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3086
    int bin = this->get_bin(midpoint);
721,692✔
3087
    if (bin != -1) {
721,692✔
3088
      bins.push_back(bin);
242,866✔
3089
      lengths.push_back(1.0);
242,866✔
3090
    }
3091
    return;
721,692✔
3092
  }
3093

3094
  // for each segment in the set of tracks, try to look up a tet
3095
  // at the midpoint of the segment
3096
  Position current = r0;
3097
  double last_dist = 0.0;
3098
  for (const auto& hit : hits) {
5,516,161✔
3099
    // get the segment length
3100
    double segment_length = hit - last_dist;
4,694,269✔
3101
    last_dist = hit;
4,694,269✔
3102
    // find the midpoint of this segment
3103
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3104
    // try to find a tet for this position
3105
    int bin = this->get_bin(midpoint);
4,694,269✔
3106

3107
    // determine the start point for this segment
3108
    current = r0 + u * hit;
4,694,269✔
3109

3110
    if (bin == -1) {
4,694,269✔
3111
      continue;
20,522✔
3112
    }
3113

3114
    bins.push_back(bin);
4,673,747✔
3115
    lengths.push_back(segment_length / track_len);
4,673,747✔
3116
  }
3117

3118
  // tally remaining portion of track after last hit if
3119
  // the last segment of the track is in the mesh but doesn't
3120
  // reach the other side of the tet
3121
  if (hits.back() < track_len) {
821,892!
3122
    Position segment_start = r0 + u * hits.back();
821,892✔
3123
    double segment_length = track_len - hits.back();
821,892✔
3124
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3125
    int bin = this->get_bin(midpoint);
821,892✔
3126
    if (bin != -1) {
821,892✔
3127
      bins.push_back(bin);
766,509✔
3128
      lengths.push_back(segment_length / track_len);
766,509✔
3129
    }
3130
  }
3131
};
1,543,584✔
3132

3133
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3134
{
3135
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3136
  // find the leaf of the kd-tree for this position
3137
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3138
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3139
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3140
    return 0;
3141
  }
3142

3143
  // retrieve the tet elements of this leaf
3144
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3145
  moab::Range tets;
6,305,335✔
3146
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3147
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3148
    warning("MOAB error finding tets.");
×
3149
  }
3150

3151
  // loop over the tets in this leaf, returning the containing tet if found
3152
  for (const auto& tet : tets) {
260,211,273✔
3153
    if (point_in_tet(pos, tet)) {
260,208,426✔
3154
      return tet;
6,302,488✔
3155
    }
3156
  }
3157

3158
  // if no tet is found, return an invalid handle
3159
  return 0;
2,847✔
3160
}
14,634,464✔
3161

3162
double MOABMesh::volume(int bin) const
167,880✔
3163
{
3164
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3165
}
3166

3167
std::string MOABMesh::library() const
34✔
3168
{
3169
  return mesh_lib_type;
34✔
3170
}
3171

3172
// Sample position within a tet for MOAB type tets
3173
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3174
{
3175

3176
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3177

3178
  // Get vertex coordinates for MOAB tet
3179
  const moab::EntityHandle* conn1;
200,410✔
3180
  int conn1_size;
200,410✔
3181
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3182
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3183
    fatal_error(fmt::format(
3184
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3185
      conn1_size));
3186
  }
3187
  moab::CartVect p[4];
200,410✔
3188
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3189
  if (rval != moab::MB_SUCCESS) {
200,410!
3190
    fatal_error("Failed to get tet coords");
3191
  }
3192

3193
  std::array<Position, 4> tet_verts;
200,410✔
3194
  for (int i = 0; i < 4; i++) {
1,002,050✔
3195
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3196
  }
3197
  // Samples position within tet using Barycentric stuff
3198
  return this->sample_tet(tet_verts, seed);
200,410✔
3199
}
3200

3201
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3202
{
3203
  vector<moab::EntityHandle> conn;
167,880✔
3204
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3205
  if (rval != moab::MB_SUCCESS) {
167,880!
3206
    fatal_error("Failed to get tet connectivity");
3207
  }
3208

3209
  moab::CartVect p[4];
167,880✔
3210
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3211
  if (rval != moab::MB_SUCCESS) {
167,880!
3212
    fatal_error("Failed to get tet coords");
3213
  }
3214

3215
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3216
}
167,880✔
3217

3218
int MOABMesh::get_bin(Position r) const
7,317,232✔
3219
{
3220
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3221
  if (tet == 0) {
7,317,232✔
3222
    return -1;
3223
  } else {
3224
    return get_bin_from_ent_handle(tet);
6,302,488✔
3225
  }
3226
}
3227

3228
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3229
{
3230
  moab::ErrorCode rval;
21✔
3231

3232
  baryc_data_.clear();
21!
3233
  baryc_data_.resize(tets.size());
21✔
3234

3235
  // compute the barycentric data for each tet element
3236
  // and store it as a 3x3 matrix
3237
  for (auto& tet : tets) {
239,757✔
3238
    vector<moab::EntityHandle> verts;
239,736✔
3239
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3240
    if (rval != moab::MB_SUCCESS) {
239,736!
3241
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3242
    }
3243

3244
    moab::CartVect p[4];
239,736✔
3245
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3246
    if (rval != moab::MB_SUCCESS) {
239,736!
3247
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3248
    }
3249

3250
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
239,736✔
3251

3252
    // invert now to avoid this cost later
3253
    a = a.transpose().inverse();
239,736✔
3254
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3255
  }
239,736✔
3256
}
21✔
3257

3258
bool MOABMesh::point_in_tet(
260,208,426✔
3259
  const moab::CartVect& r, moab::EntityHandle tet) const
3260
{
3261

3262
  moab::ErrorCode rval;
260,208,426✔
3263

3264
  // get tet vertices
3265
  vector<moab::EntityHandle> verts;
260,208,426✔
3266
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3267
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3268
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3269
    return false;
3270
  }
3271

3272
  // first vertex is used as a reference point for the barycentric data -
3273
  // retrieve its coordinates
3274
  moab::CartVect p_zero;
260,208,426✔
3275
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3276
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3277
    warning("Failed to get coordinates of a vertex in "
×
3278
            "unstructured mesh: " +
3279
            filename_);
×
3280
    return false;
3281
  }
3282

3283
  // look up barycentric data
3284
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3285
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3286

3287
  moab::CartVect bary_coords = a_inv * (r - p_zero);
260,208,426✔
3288

3289
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3290
          bary_coords[2] >= 0.0 &&
318,957,185✔
3291
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3292
}
260,208,426✔
3293

3294
int MOABMesh::get_bin_from_index(int idx) const
3295
{
3296
  if (idx >= n_bins()) {
×
3297
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3298
  }
3299
  return ehs_[idx] - ehs_[0];
3300
}
3301

3302
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3303
{
3304
  int bin = get_bin(r);
3305
  *in_mesh = bin != -1;
3306
  return bin;
3307
}
3308

3309
int MOABMesh::get_index_from_bin(int bin) const
3310
{
3311
  return bin;
3312
}
3313

3314
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3315
  Position plot_ll, Position plot_ur) const
3316
{
3317
  // TODO: Implement mesh lines
3318
  return {};
3319
}
3320

3321
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3322
{
3323
  int idx = vert - verts_[0];
815,520✔
3324
  if (idx >= n_vertices()) {
815,520!
3325
    fatal_error(
3326
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3327
  }
3328
  return idx;
815,520✔
3329
}
3330

3331
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3332
{
3333
  int bin = eh - ehs_[0];
266,750,650✔
3334
  if (bin >= n_bins()) {
266,750,650!
3335
    fatal_error(fmt::format("Invalid bin: {}", bin));
3336
  }
3337
  return bin;
266,750,650✔
3338
}
3339

3340
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3341
{
3342
  if (bin >= n_bins()) {
572,170!
3343
    fatal_error(fmt::format("Invalid bin index: ", bin));
3344
  }
3345
  return ehs_[0] + bin;
572,170✔
3346
}
3347

3348
int MOABMesh::n_bins() const
267,526,773✔
3349
{
3350
  return ehs_.size();
267,526,773✔
3351
}
3352

3353
int MOABMesh::n_surface_bins() const
3354
{
3355
  // collect all triangles in the set of tets for this mesh
3356
  moab::Range tris;
×
3357
  moab::ErrorCode rval;
3358
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3359
  if (rval != moab::MB_SUCCESS) {
×
3360
    warning("Failed to get all triangles in the mesh instance");
×
3361
    return -1;
3362
  }
3363
  return 2 * tris.size();
×
3364
}
3365

3366
Position MOABMesh::centroid(int bin) const
3367
{
3368
  moab::ErrorCode rval;
3369

3370
  auto tet = this->get_ent_handle_from_bin(bin);
3371

3372
  // look up the tet connectivity
3373
  vector<moab::EntityHandle> conn;
×
3374
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3375
  if (rval != moab::MB_SUCCESS) {
×
3376
    warning("Failed to get connectivity of a mesh element.");
×
3377
    return {};
3378
  }
3379

3380
  // get the coordinates
3381
  vector<moab::CartVect> coords(conn.size());
×
3382
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3383
  if (rval != moab::MB_SUCCESS) {
×
3384
    warning("Failed to get the coordinates of a mesh element.");
×
3385
    return {};
3386
  }
3387

3388
  // compute the centroid of the element vertices
3389
  moab::CartVect centroid(0.0, 0.0, 0.0);
3390
  for (const auto& coord : coords) {
×
3391
    centroid += coord;
3392
  }
3393
  centroid /= double(coords.size());
3394

3395
  return {centroid[0], centroid[1], centroid[2]};
3396
}
3397

3398
int MOABMesh::n_vertices() const
845,874✔
3399
{
3400
  return verts_.size();
845,874✔
3401
}
3402

3403
Position MOABMesh::vertex(int id) const
86,227✔
3404
{
3405

3406
  moab::ErrorCode rval;
86,227✔
3407

3408
  moab::EntityHandle vert = verts_[id];
86,227✔
3409

3410
  moab::CartVect coords;
86,227✔
3411
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3412
  if (rval != moab::MB_SUCCESS) {
86,227!
3413
    fatal_error("Failed to get the coordinates of a vertex.");
3414
  }
3415

3416
  return {coords[0], coords[1], coords[2]};
86,227✔
3417
}
3418

3419
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3420
{
3421
  moab::ErrorCode rval;
203,880✔
3422

3423
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3424

3425
  // look up the tet connectivity
3426
  vector<moab::EntityHandle> conn;
203,880✔
3427
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3428
  if (rval != moab::MB_SUCCESS) {
203,880!
3429
    fatal_error("Failed to get connectivity of a mesh element.");
3430
    return {};
3431
  }
3432

3433
  std::vector<int> verts(4);
203,880✔
3434
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3435
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3436
  }
3437

3438
  return verts;
203,880✔
3439
}
203,880✔
3440

3441
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3442
  std::string score) const
3443
{
3444
  moab::ErrorCode rval;
3445
  // add a tag to the mesh
3446
  // all scores are treated as a single value
3447
  // with an uncertainty
3448
  moab::Tag value_tag;
3449

3450
  // create the value tag if not present and get handle
3451
  double default_val = 0.0;
3452
  auto val_string = score + "_mean";
3453
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3454
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3455
  if (rval != moab::MB_SUCCESS) {
×
3456
    auto msg =
3457
      fmt::format("Could not create or retrieve the value tag for the score {}"
3458
                  " on unstructured mesh {}",
3459
        score, id_);
×
3460
    fatal_error(msg);
3461
  }
3462

3463
  // create the std dev tag if not present and get handle
3464
  moab::Tag error_tag;
3465
  std::string err_string = score + "_std_dev";
×
3466
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3467
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3468
  if (rval != moab::MB_SUCCESS) {
×
3469
    auto msg =
3470
      fmt::format("Could not create or retrieve the error tag for the score {}"
3471
                  " on unstructured mesh {}",
3472
        score, id_);
×
3473
    fatal_error(msg);
3474
  }
3475

3476
  // return the populated tag handles
3477
  return {value_tag, error_tag};
3478
}
3479

3480
void MOABMesh::add_score(const std::string& score)
3481
{
3482
  auto score_tags = get_score_tags(score);
×
3483
  tag_names_.push_back(score);
3484
}
3485

3486
void MOABMesh::remove_scores()
3487
{
3488
  for (const auto& name : tag_names_) {
×
3489
    auto value_name = name + "_mean";
3490
    moab::Tag tag;
3491
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3492
    if (rval != moab::MB_SUCCESS)
×
3493
      return;
3494

3495
    rval = mbi_->tag_delete(tag);
×
3496
    if (rval != moab::MB_SUCCESS) {
×
3497
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3498
                             " on unstructured mesh {}",
3499
        name, id_);
×
3500
      fatal_error(msg);
3501
    }
3502

3503
    auto std_dev_name = name + "_std_dev";
×
3504
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3505
    if (rval != moab::MB_SUCCESS) {
×
3506
      auto msg =
3507
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3508
                    " on unstructured mesh {}",
3509
          name, id_);
×
3510
    }
3511

3512
    rval = mbi_->tag_delete(tag);
×
3513
    if (rval != moab::MB_SUCCESS) {
×
3514
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3515
                             " on unstructured mesh {}",
3516
        name, id_);
×
3517
      fatal_error(msg);
3518
    }
3519
  }
3520
  tag_names_.clear();
3521
}
3522

3523
void MOABMesh::set_score_data(const std::string& score,
3524
  const vector<double>& values, const vector<double>& std_dev)
3525
{
3526
  auto score_tags = this->get_score_tags(score);
×
3527

3528
  moab::ErrorCode rval;
3529
  // set the score value
3530
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3531
  if (rval != moab::MB_SUCCESS) {
×
3532
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3533
                           "on unstructured mesh {}",
3534
      score, id_);
3535
    warning(msg);
×
3536
  }
3537

3538
  // set the error value
3539
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3540
  if (rval != moab::MB_SUCCESS) {
×
3541
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3542
                           "on unstructured mesh {}",
3543
      score, id_);
3544
    warning(msg);
×
3545
  }
3546
}
3547

3548
void MOABMesh::write(const std::string& base_filename) const
3549
{
3550
  // add extension to the base name
3551
  auto filename = base_filename + ".vtk";
3552
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3553
  filename = settings::path_output + filename;
×
3554

3555
  // write the tetrahedral elements of the mesh only
3556
  // to avoid clutter from zero-value data on other
3557
  // elements during visualization
3558
  moab::ErrorCode rval;
3559
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3560
  if (rval != moab::MB_SUCCESS) {
×
3561
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3562
    warning(msg);
×
3563
  }
3564
}
3565

3566
#endif
3567

3568
#ifdef OPENMC_LIBMESH_ENABLED
3569

3570
const std::string LibMesh::mesh_lib_type = "libmesh";
3571

3572
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3573
{
3574
  // filename_ and length_multiplier_ will already be set by the
3575
  // UnstructuredMesh constructor
3576
  set_mesh_pointer_from_filename(filename_);
25✔
3577
  set_length_multiplier(length_multiplier_);
25✔
3578
  initialize();
25✔
3579
}
25✔
3580

3581
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3582
{
3583
  // filename_ and length_multiplier_ will already be set by the
3584
  // UnstructuredMesh constructor
3585
  set_mesh_pointer_from_filename(filename_);
×
3586
  set_length_multiplier(length_multiplier_);
×
3587
  initialize();
×
3588
}
3589

3590
// create the mesh from a pointer to a libMesh Mesh
3591
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3592
{
3593
  if (!input_mesh.is_replicated()) {
×
3594
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3595
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3596
  }
3597

3598
  m_ = &input_mesh;
3599
  set_length_multiplier(length_multiplier);
×
3600
  initialize();
×
3601
}
3602

3603
// create the mesh from an input file
3604
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3605
{
3606
  n_dimension_ = 3;
3607
  set_mesh_pointer_from_filename(filename);
×
3608
  set_length_multiplier(length_multiplier);
×
3609
  initialize();
×
3610
}
3611

3612
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3613
{
3614
  filename_ = filename;
25✔
3615
  unique_m_ =
25✔
3616
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3617
  m_ = unique_m_.get();
25✔
3618
  m_->read(filename_);
25✔
3619
}
25✔
3620

3621
// build a libMesh equation system for storing values
3622
void LibMesh::build_eqn_sys()
17✔
3623
{
3624
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3625
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3626
  libMesh::ExplicitSystem& eq_sys =
17✔
3627
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3628
}
17✔
3629

3630
// intialize from mesh file
3631
void LibMesh::initialize()
25✔
3632
{
3633
  if (!settings::libmesh_comm) {
25!
3634
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3635
                "communicator.");
3636
  }
3637

3638
  // assuming that unstructured meshes used in OpenMC are 3D
3639
  n_dimension_ = 3;
25✔
3640

3641
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3642
  // Otherwise assume that it is prepared by its owning application
3643
  if (unique_m_) {
25!
3644
    m_->prepare_for_use();
25✔
3645
  }
3646

3647
  // ensure that the loaded mesh is 3 dimensional
3648
  if (m_->mesh_dimension() != n_dimension_) {
25!
3649
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3650
                            "mesh is not a 3D mesh.",
3651
      filename_));
3652
  }
3653

3654
  for (int i = 0; i < num_threads(); i++) {
69✔
3655
    pl_.emplace_back(m_->sub_point_locator());
44✔
3656
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
44✔
3657
    pl_.back()->enable_out_of_mesh_mode();
44✔
3658
  }
3659

3660
  // store first element in the mesh to use as an offset for bin indices
3661
  auto first_elem = *m_->elements_begin();
50✔
3662
  first_element_id_ = first_elem->id();
25✔
3663

3664
  // bounding box for the mesh for quick rejection checks
3665
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3666
  libMesh::Point ll = bbox_.min();
25!
3667
  libMesh::Point ur = bbox_.max();
25!
3668
  if (length_multiplier_ > 0.0) {
25!
3669
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3670
      length_multiplier_ * ll(2)};
3671
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3672
      length_multiplier_ * ur(2)};
3673
  } else {
3674
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3675
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3676
  }
3677
}
25✔
3678

3679
// Sample position within a tet for LibMesh type tets
3680
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3681
{
3682
  const auto& elem = get_element_from_bin(bin);
400,820✔
3683
  // Get tet vertex coordinates from LibMesh
3684
  std::array<Position, 4> tet_verts;
400,820✔
3685
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3686
    const auto& node_ref = elem.node_ref(i);
1,603,280✔
3687
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3688
  }
3689
  // Samples position within tet using Barycentric coordinates
3690
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3691
  if (length_multiplier_ > 0.0) {
400,820!
3692
    return length_multiplier_ * sampled_position;
3693
  } else {
3694
    return sampled_position;
400,820✔
3695
  }
3696
}
3697

3698
Position LibMesh::centroid(int bin) const
3699
{
3700
  const auto& elem = this->get_element_from_bin(bin);
3701
  auto centroid = elem.vertex_average();
3702
  if (length_multiplier_ > 0.0) {
×
3703
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3704
  } else {
3705
    return {centroid(0), centroid(1), centroid(2)};
3706
  }
3707
}
3708

3709
int LibMesh::n_vertices() const
42,644✔
3710
{
3711
  return m_->n_nodes();
42,644✔
3712
}
3713

3714
Position LibMesh::vertex(int vertex_id) const
42,604✔
3715
{
3716
  const auto& node_ref = m_->node_ref(vertex_id);
42,604✔
3717
  if (length_multiplier_ > 0.0) {
42,604!
3718
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3719
  } else {
3720
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3721
  }
3722
}
3723

3724
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3725
{
3726
  std::vector<int> conn;
267,856✔
3727
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3728
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3729
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3730
  }
3731
  return conn;
267,856✔
3732
}
3733

3734
std::string LibMesh::library() const
37✔
3735
{
3736
  return mesh_lib_type;
37✔
3737
}
3738

3739
int LibMesh::n_bins() const
1,788,419✔
3740
{
3741
  return m_->n_elem();
1,788,419✔
3742
}
3743

3744
int LibMesh::n_surface_bins() const
3745
{
3746
  int n_bins = 0;
3747
  for (int i = 0; i < this->n_bins(); i++) {
×
3748
    const libMesh::Elem& e = get_element_from_bin(i);
3749
    n_bins += e.n_faces();
3750
    // if this is a boundary element, it will only be visited once,
3751
    // the number of surface bins is incremented to
3752
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3753
      // null neighbor pointer indicates a boundary face
3754
      if (!neighbor_ptr) {
×
3755
        n_bins++;
3756
      }
3757
    }
3758
  }
3759
  return n_bins;
3760
}
3761

3762
void LibMesh::add_score(const std::string& var_name)
17✔
3763
{
3764
  if (!equation_systems_) {
17!
3765
    build_eqn_sys();
17✔
3766
  }
3767

3768
  // check if this is a new variable
3769
  std::string value_name = var_name + "_mean";
17✔
3770
  if (!variable_map_.count(value_name)) {
17✔
3771
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3772
    auto var_num =
17✔
3773
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3774
    variable_map_[value_name] = var_num;
17✔
3775
  }
3776

3777
  std::string std_dev_name = var_name + "_std_dev";
17✔
3778
  // check if this is a new variable
3779
  if (!variable_map_.count(std_dev_name)) {
17✔
3780
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3781
    auto var_num =
17✔
3782
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3783
    variable_map_[std_dev_name] = var_num;
17✔
3784
  }
3785
}
17✔
3786

3787
void LibMesh::remove_scores()
17✔
3788
{
3789
  if (equation_systems_) {
17!
3790
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3791
    eqn_sys.clear();
17✔
3792
    variable_map_.clear();
17✔
3793
  }
3794
}
17✔
3795

3796
void LibMesh::set_score_data(const std::string& var_name,
17✔
3797
  const vector<double>& values, const vector<double>& std_dev)
3798
{
3799
  if (!equation_systems_) {
17!
3800
    build_eqn_sys();
3801
  }
3802

3803
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3804

3805
  if (!eqn_sys.is_initialized()) {
17!
3806
    equation_systems_->init();
17✔
3807
  }
3808

3809
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3810

3811
  // look up the value variable
3812
  std::string value_name = var_name + "_mean";
17✔
3813
  unsigned int value_num = variable_map_.at(value_name);
17✔
3814
  // look up the std dev variable
3815
  std::string std_dev_name = var_name + "_std_dev";
17✔
3816
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3817

3818
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3819
       it++) {
3820
    if (!(*it)->active()) {
99,856!
3821
      continue;
3822
    }
3823

3824
    auto bin = get_bin_from_element(*it);
99,856✔
3825

3826
    // set value
3827
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3828
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3829
    assert(value_dof_indices.size() == 1);
99,856✔
3830
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3831

3832
    // set std dev
3833
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3834
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3835
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3836
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3837
  }
99,873✔
3838
}
17✔
3839

3840
void LibMesh::write(const std::string& filename) const
17✔
3841
{
3842
  write_message(fmt::format(
17✔
3843
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3844
  libMesh::ExodusII_IO exo(*m_);
17✔
3845
  std::set<std::string> systems_out = {eq_system_name_};
34!
3846
  exo.write_discontinuous_exodusII(
17✔
3847
    filename + ".e", *equation_systems_, &systems_out);
34✔
3848
}
17✔
3849

3850
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3851
  vector<int>& bins, vector<double>& lengths) const
3852
{
3853
  // TODO: Implement triangle crossings here
3854
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3855
}
3856

3857
int LibMesh::get_bin(Position r) const
2,340,604✔
3858
{
3859
  // look-up a tet using the point locator
3860
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3861

3862
  if (length_multiplier_ > 0.0) {
2,340,604!
3863
    // Scale the point down
3864
    p /= length_multiplier_;
2,340,604✔
3865
  }
3866

3867
  // quick rejection check
3868
  if (!bbox_.contains_point(p)) {
2,340,604✔
3869
    return -1;
3870
  }
3871

3872
  const auto& point_locator = pl_.at(thread_num());
1,421,808✔
3873

3874
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3875
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3876
}
2,340,604✔
3877

3878
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3879
{
3880
  int bin = elem->id() - first_element_id_;
1,520,434✔
3881
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3882
    fatal_error(fmt::format("Invalid bin: {}", bin));
3883
  }
3884
  return bin;
1,520,434✔
3885
}
3886

3887
std::pair<vector<double>, vector<double>> LibMesh::plot(
3888
  Position plot_ll, Position plot_ur) const
3889
{
3890
  return {};
3891
}
3892

3893
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3894
{
3895
  return m_->elem_ref(bin);
769,460✔
3896
}
3897

3898
double LibMesh::volume(int bin) const
368,640✔
3899
{
3900
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3901
         length_multiplier_ * length_multiplier_;
368,640✔
3902
}
3903

3904
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3905
  double length_multiplier,
3906
  const std::set<libMesh::subdomain_id_type>& block_ids)
3907
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3908
    block_restrict_(!block_ids_.empty()),
×
3909
    num_active_(
×
3910
      block_restrict_
3911
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
3912
            m_->active_subdomain_set_elements_end(block_ids_))
×
3913
        : m_->n_active_elem())
×
3914
{
3915
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3916
  // contiguous in ID space, so we need to map from bin indices (defined over
3917
  // active elements) to global dof ids
3918
  bin_to_elem_map_.reserve(num_active_);
×
3919
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3920
  auto begin = block_restrict_
3921
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
3922
                 : m_->active_elements_begin();
×
3923
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
3924
                             : m_->active_elements_end();
×
3925
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
3926
    bin_to_elem_map_.push_back(elem->id());
×
3927
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3928
  }
3929
}
3930

3931
int AdaptiveLibMesh::n_bins() const
3932
{
3933
  return num_active_;
3934
}
3935

3936
void AdaptiveLibMesh::add_score(const std::string& var_name)
3937
{
3938
  warning(fmt::format(
×
3939
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3940
    this->id_));
3941
}
3942

3943
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3944
  const vector<double>& values, const vector<double>& std_dev)
3945
{
3946
  warning(fmt::format(
×
3947
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3948
    this->id_));
3949
}
3950

3951
void AdaptiveLibMesh::write(const std::string& filename) const
3952
{
3953
  warning(fmt::format(
×
3954
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3955
    this->id_));
3956
}
3957

3958
int AdaptiveLibMesh::get_bin(Position r) const
3959
{
3960
  // look-up a tet using the point locator
3961
  libMesh::Point p(r.x, r.y, r.z);
×
3962

3963
  if (length_multiplier_ > 0.0) {
×
3964
    // Scale the point down
3965
    p /= length_multiplier_;
3966
  }
3967

3968
  // quick rejection check
3969
  if (!bbox_.contains_point(p)) {
×
3970
    return -1;
3971
  }
3972

3973
  const auto& point_locator = pl_.at(thread_num());
×
3974

3975
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3976
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3977
}
3978

3979
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3980
{
3981
  int bin = elem_to_bin_map_[elem->id()];
3982
  if (bin >= n_bins() || bin < 0) {
×
3983
    fatal_error(fmt::format("Invalid bin: {}", bin));
3984
  }
3985
  return bin;
3986
}
3987

3988
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3989
{
3990
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3991
}
3992

3993
#endif // OPENMC_LIBMESH_ENABLED
3994

3995
//==============================================================================
3996
// Non-member functions
3997
//==============================================================================
3998

3999
void read_meshes(pugi::xml_node root)
13,983✔
4000
{
4001
  std::unordered_set<int> mesh_ids;
13,983✔
4002

4003
  for (auto node : root.children("mesh")) {
17,333✔
4004
    // Check to make sure multiple meshes in the same file don't share IDs
4005
    int id = std::stoi(get_node_value(node, "id"));
6,700✔
4006
    if (contains(mesh_ids, id)) {
6,700!
UNCOV
4007
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4008
                              "'{}' in the same input file",
4009
        id));
4010
    }
4011
    mesh_ids.insert(id);
3,350✔
4012

4013
    // If we've already read a mesh with the same ID in a *different* file,
4014
    // assume it is the same here
4015
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,350!
UNCOV
4016
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4017
      continue;
×
4018
    }
4019

4020
    std::string mesh_type;
3,350✔
4021
    if (check_for_node(node, "type")) {
3,350✔
4022
      mesh_type = get_node_value(node, "type", true, true);
950✔
4023
    } else {
4024
      mesh_type = "regular";
2,400✔
4025
    }
4026

4027
    // determine the mesh library to use
4028
    std::string mesh_lib;
3,350✔
4029
    if (check_for_node(node, "library")) {
3,350✔
4030
      mesh_lib = get_node_value(node, "library", true, true);
49!
4031
    }
4032

4033
    Mesh::create(node, mesh_type, mesh_lib);
3,350✔
4034
  }
3,350✔
4035
}
13,983✔
4036

4037
void read_meshes(hid_t group)
48✔
4038
{
4039
  std::unordered_set<int> mesh_ids;
48✔
4040

4041
  std::vector<int> ids;
48✔
4042
  read_attribute(group, "ids", ids);
48✔
4043

4044
  for (auto id : ids) {
107✔
4045

4046
    // Check to make sure multiple meshes in the same file don't share IDs
4047
    if (contains(mesh_ids, id)) {
118!
UNCOV
4048
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4049
                              "'{}' in the same HDF5 input file",
4050
        id));
4051
    }
4052
    mesh_ids.insert(id);
59✔
4053

4054
    // If we've already read a mesh with the same ID in a *different* file,
4055
    // assume it is the same here
4056
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
59✔
4057
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4058
      continue;
33✔
4059
    }
4060

4061
    std::string name = fmt::format("mesh {}", id);
26✔
4062
    hid_t mesh_group = open_group(group, name.c_str());
26✔
4063

4064
    std::string mesh_type;
26✔
4065
    if (object_exists(mesh_group, "type")) {
26!
4066
      read_dataset(mesh_group, "type", mesh_type);
26✔
4067
    } else {
UNCOV
4068
      mesh_type = "regular";
×
4069
    }
4070

4071
    // determine the mesh library to use
4072
    std::string mesh_lib;
26✔
4073
    if (object_exists(mesh_group, "library")) {
26!
4074
      read_dataset(mesh_group, "library", mesh_lib);
×
4075
    }
4076

4077
    Mesh::create(mesh_group, mesh_type, mesh_lib);
26✔
4078
  }
26✔
4079
}
96✔
4080

4081
void meshes_to_hdf5(hid_t group)
7,833✔
4082
{
4083
  // Write number of meshes
4084
  hid_t meshes_group = create_group(group, "meshes");
7,833✔
4085
  int32_t n_meshes = model::meshes.size();
7,833✔
4086
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,833✔
4087

4088
  if (n_meshes > 0) {
7,833✔
4089
    // Write IDs of meshes
4090
    vector<int> ids;
2,425✔
4091
    for (const auto& m : model::meshes) {
5,539✔
4092
      m->to_hdf5(meshes_group);
3,114✔
4093
      ids.push_back(m->id_);
3,114✔
4094
    }
4095
    write_attribute(meshes_group, "ids", ids);
2,425✔
4096
  }
2,425✔
4097

4098
  close_group(meshes_group);
7,833✔
4099
}
7,833✔
4100

4101
void free_memory_mesh()
9,126✔
4102
{
4103
  model::meshes.clear();
9,126✔
4104
  model::mesh_map.clear();
9,126✔
4105
}
9,126✔
4106

4107
extern "C" int n_meshes()
308✔
4108
{
4109
  return model::meshes.size();
308✔
4110
}
4111

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