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

openmc-dev / openmc / 22914090227

10 Mar 2026 04:53PM UTC coverage: 81.569% (+0.003%) from 81.566%
22914090227

Pull #3853

github

web-flow
Merge bc1513221 into 1dc4aa988
Pull Request #3853: Fix numerical cancellation in RectLattice::distance for large pitch values

17553 of 25260 branches covered (69.49%)

Branch coverage included in aggregate %.

14 of 14 new or added lines in 2 files covered. (100.0%)

159 existing lines in 2 files now uncovered.

57964 of 67321 relevant lines covered (86.1%)

44900321.08 hits per line

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

70.13
/src/mesh.cpp
1
#include "openmc/mesh.h"
2
#include <algorithm> // for copy, equal, min, min_element
3
#include <cassert>
4
#include <cstdint>        // for uint64_t
5
#include <cstring>        // for memcpy
6
#define _USE_MATH_DEFINES // to make M_PI declared in Intel and MSVC compilers
7
#include <cmath>          // for ceil
8
#include <cstddef>        // for size_t
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/math_functions.h"
32
#include "openmc/memory.h"
33
#include "openmc/message_passing.h"
34
#include "openmc/openmp_interface.h"
35
#include "openmc/output.h"
36
#include "openmc/particle_data.h"
37
#include "openmc/plot.h"
38
#include "openmc/random_dist.h"
39
#include "openmc/search.h"
40
#include "openmc/settings.h"
41
#include "openmc/string_utils.h"
42
#include "openmc/tallies/filter.h"
43
#include "openmc/tallies/tally.h"
44
#include "openmc/timer.h"
45
#include "openmc/volume_calc.h"
46
#include "openmc/xml_interface.h"
47

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

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

59
namespace openmc {
60

61
//==============================================================================
62
// Global variables
63
//==============================================================================
64

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

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

75
namespace model {
76

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

80
} // namespace model
81

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

89
//==============================================================================
90
// Helper functions
91
//==============================================================================
92

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

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

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

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

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

141
// Helper function equivalent to std::bit_cast in C++20
142
template<typename To, typename From>
143
inline To bit_cast_value(const From& value)
36,950,533✔
144
{
145
  To out;
146
  std::memcpy(&out, &value, sizeof(To));
33,320✔
147
  return out;
148
}
149

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

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

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

188
inline void atomic_max_double(double* ptr, double value)
18,475,224✔
189
{
190
  atomic_update_double(ptr, value, false);
6,158,408✔
191
}
6,158,408✔
192

193
inline void atomic_min_double(double* ptr, double value)
18,475,224✔
194
{
195
  atomic_update_double(ptr, value, true);
6,158,408✔
196
}
197

198
namespace detail {
199

200
//==============================================================================
201
// MaterialVolumes implementation
202
//==============================================================================
203

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

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

221
    // Non-atomic read of current material
222
    int32_t current_val = *slot_ptr;
8,811,795✔
223

224
    // Found the desired material; accumulate volume and bbox
225
    if (current_val == index_material) {
8,811,795✔
226
#pragma omp atomic
4,861,914✔
227
      this->volumes(index_elem, slot) += volume;
8,810,279✔
228
      if (bbox) {
8,810,279✔
229
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,158,284✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,158,284✔
231
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,158,284✔
232
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,158,284✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,158,284✔
234
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,158,284✔
235
      }
236
      return;
8,810,279✔
237
    }
238

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

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

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

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

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

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

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

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

327
} // namespace detail
328

329
//==============================================================================
330
// Mesh implementation
331
//==============================================================================
332

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

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

366
  return model::meshes.back();
2,985✔
367
}
368

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

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

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

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

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

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

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

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

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

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

424
vector<double> Mesh::volumes() const
246✔
425
{
426
  vector<double> volumes(n_bins());
246✔
427
  for (int i = 0; i < n_bins(); i++) {
1,111,189✔
428
    volumes[i] = this->volume(i);
1,110,943✔
429
  }
430
  return volumes;
246✔
UNCOV
431
}
×
432

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

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

455
  Timer timer;
187✔
456
  timer.start();
187✔
457

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

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

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

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

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

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

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

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

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

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

515
      // Loop over rays on face of bounding box
516
#pragma omp for collapse(2)
517
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
15,800✔
518
        for (int i2 = 0; i2 < n2; ++i2) {
2,978,340✔
519
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
2,962,735✔
520
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
2,962,735✔
521

522
          p.from_source(&site);
2,962,735✔
523

524
          // Determine particle's location
525
          if (!exhaustive_find_cell(p)) {
2,962,735✔
526
            out_of_model = true;
39,930✔
527
            continue;
39,930✔
528
          }
529

530
          // Set birth cell attribute
531
          if (p.cell_born() == C_NONE)
2,922,805!
532
            p.cell_born() = p.lowest_coord().cell();
2,922,805✔
533

534
          // Initialize last cells from current cell
535
          for (int j = 0; j < p.n_coord(); ++j) {
5,845,610✔
536
            p.cell_last(j) = p.coord(j).cell();
2,922,805✔
537
          }
538
          p.n_coord_last() = p.n_coord();
2,922,805✔
539

540
          while (true) {
4,610,097✔
541
            // Ray trace from r_start to r_end
542
            Position r0 = p.r();
3,766,451✔
543
            double max_distance = bbox.max[axis] - r0[axis];
3,766,451✔
544

545
            // Find the distance to the nearest boundary
546
            BoundaryInfo boundary = distance_to_boundary(p);
3,766,451✔
547

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

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

557
            // Add volumes to any mesh elements that were crossed
558
            int i_material = p.material();
3,766,451✔
559
            if (i_material != C_NONE) {
3,766,451✔
560
              i_material = model::materials[i_material]->id();
1,104,893✔
561
            }
562
            double cumulative_frac = 0.0;
3,766,451✔
563
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
7,751,552✔
564
              int mesh_index = bins[i_bin];
3,985,101✔
565
              double length = distance * length_fractions[i_bin];
3,985,101✔
566
              double volume = length * d1 * d2;
3,985,101✔
567

568
              if (compute_bboxes) {
3,985,101✔
569
                double axis_start = r0[axis] + distance * cumulative_frac;
2,779,016✔
570
                double axis_end = axis_start + length;
2,779,016✔
571
                cumulative_frac += length_fractions[i_bin];
2,779,016✔
572

573
                Position contrib_min = site.r;
2,779,016✔
574
                Position contrib_max = site.r;
2,779,016✔
575

576
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,779,016✔
577
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,779,016✔
578
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,779,016✔
579
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,779,016✔
580
                contrib_min[axis] = std::min(axis_start, axis_end);
2,779,016!
581
                contrib_max[axis] = std::max(axis_start, axis_end);
5,558,032!
582

583
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,779,016✔
584
                contrib_bbox &= bbox;
2,779,016✔
585

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

594
            if (distance == max_distance)
3,766,451✔
595
              break;
596

597
            // cross next geometric surface
598
            for (int j = 0; j < p.n_coord(); ++j) {
1,687,292✔
599
              p.cell_last(j) = p.coord(j).cell();
843,646✔
600
            }
601
            p.n_coord_last() = p.n_coord();
843,646✔
602

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

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

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

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

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

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

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

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

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

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

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

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

738
  // Write mesh type
739
  write_dataset(mesh_group, "type", this->get_mesh_type());
2,927✔
740

741
  // Write mesh ID
742
  write_attribute(mesh_group, "id", id_);
2,927✔
743

744
  // Write mesh name
745
  write_dataset(mesh_group, "name", name_);
2,927✔
746

747
  // Write mesh data
748
  this->to_hdf5_inner(mesh_group);
2,927✔
749

750
  // Close group
751
  close_group(mesh_group);
2,927✔
752
}
2,927✔
753

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

758
std::string StructuredMesh::bin_label(int bin) const
5,134,881✔
759
{
760
  MeshIndex ijk = get_indices_from_bin(bin);
5,134,881✔
761

762
  if (n_dimension_ > 2) {
5,134,881✔
763
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,118,942✔
764
  } else if (n_dimension_ > 1) {
15,939✔
765
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
15,664✔
766
  } else {
767
    return fmt::format("Mesh Index ({})", ijk[0]);
275✔
768
  }
769
}
770

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

957
  // write vertex coordinates
958
  tensor::Tensor<double> vertices(
32✔
959
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
32✔
960
  for (int i = 0; i < this->n_vertices(); i++) {
70,275!
961
    auto v = this->vertex(i);
70,243!
962
    vertices.slice(i) = {v.x, v.y, v.z};
140,486!
963
  }
964
  write_dataset(mesh_group, "vertices", vertices);
32!
965

966
  int num_elem_skipped = 0;
32✔
967

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

977
    volumes.emplace_back(this->volume(i));
349,736!
978

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

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

1004
  write_dataset(mesh_group, "volumes", volumes);
32!
1005
  write_dataset(mesh_group, "connectivity", connectivity);
32!
1006
  write_dataset(mesh_group, "element_types", elem_types);
32!
1007
}
96✔
1008

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

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

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

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

1034
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1035
      in_mesh = false;
102,653,580✔
1036
  }
1037
  return ijk;
1,191,134,363✔
1038
}
1039

1040
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
1,754,033,826✔
1041
{
1042
  switch (n_dimension_) {
1,754,033,826!
1043
  case 1:
880,605✔
1044
    return ijk[0] - 1;
880,605✔
1045
  case 2:
136,375,228✔
1046
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
136,375,228✔
1047
  case 3:
1,616,777,993✔
1048
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
1,616,777,993✔
1049
  default:
×
UNCOV
1050
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1051
  }
1052
}
1053

1054
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,775,170✔
1055
{
1056
  MeshIndex ijk;
7,775,170✔
1057
  if (n_dimension_ == 1) {
7,775,170✔
1058
    ijk[0] = bin + 1;
275✔
1059
  } else if (n_dimension_ == 2) {
7,774,895✔
1060
    ijk[0] = bin % shape_[0] + 1;
15,664✔
1061
    ijk[1] = bin / shape_[0] + 1;
15,664✔
1062
  } else if (n_dimension_ == 3) {
7,759,231!
1063
    ijk[0] = bin % shape_[0] + 1;
7,759,231✔
1064
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,759,231✔
1065
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,759,231✔
1066
  }
1067
  return ijk;
7,775,170✔
1068
}
1069

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

1078
  // Convert indices to bin
1079
  return get_bin_from_indices(ijk);
234,581,866✔
1080
}
1081

1082
int StructuredMesh::n_bins() const
1,125,575✔
1083
{
1084
  return std::accumulate(
2,251,150✔
1085
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,125,575✔
1086
}
1087

1088
int StructuredMesh::n_surface_bins() const
370✔
1089
{
1090
  return 4 * n_dimension_ * n_bins();
370✔
1091
}
1092

UNCOV
1093
tensor::Tensor<double> StructuredMesh::count_sites(
×
1094
  const SourceSite* bank, int64_t length, bool* outside) const
1095
{
1096
  // Determine shape of array for counts
1097
  std::size_t m = this->n_bins();
×
UNCOV
1098
  vector<std::size_t> shape = {m};
×
1099

1100
  // Create array of zeros
UNCOV
1101
  auto cnt = tensor::zeros<double>(shape);
×
1102
  bool outside_ = false;
1103

1104
  for (int64_t i = 0; i < length; i++) {
×
UNCOV
1105
    const auto& site = bank[i];
×
1106

1107
    // determine scoring bin for entropy mesh
UNCOV
1108
    int mesh_bin = get_bin(site.r);
×
1109

1110
    // if outside mesh, skip particle
1111
    if (mesh_bin < 0) {
×
1112
      outside_ = true;
×
UNCOV
1113
      continue;
×
1114
    }
1115

1116
    // Add to appropriate bin
UNCOV
1117
    cnt(mesh_bin) += site.wgt;
×
1118
  }
1119

1120
  // Create reduced count data
1121
  auto counts = tensor::zeros<double>(shape);
×
UNCOV
1122
  int total = cnt.size();
×
1123

1124
#ifdef OPENMC_MPI
1125
  // collect values from all processors
1126
  MPI_Reduce(
×
1127
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1128

1129
  // Check if there were sites outside the mesh for any processor
1130
  if (outside) {
×
1131
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1132
  }
1133
#else
1134
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1135
  if (outside)
×
1136
    *outside = outside_;
1137
#endif
1138

1139
  return counts;
×
UNCOV
1140
}
×
1141

1142
// raytrace through the mesh. The template class T will do the tallying.
1143
// A modern optimizing compiler can recognize the noop method of T and
1144
// eliminate that call entirely.
1145
template<class T>
1146
void StructuredMesh::raytrace_mesh(
940,431,762✔
1147
  Position r0, Position r1, const Direction& u, T tally) const
1148
{
1149
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1150
  // enable/disable tally calls for now, T template type needs to provide both
1151
  // surface and track methods, which might be empty. modern optimizing
1152
  // compilers will (hopefully) eliminate the complete code (including
1153
  // calculation of parameters) but for the future: be explicit
1154

1155
  // Compute the length of the entire track.
1156
  double total_distance = (r1 - r0).norm();
940,431,762✔
1157
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
940,431,762✔
1158
    return;
1159

1160
  // keep a copy of the original global position to pass to get_indices,
1161
  // which performs its own transformation to local coordinates
1162
  Position global_r = r0;
928,336,431✔
1163
  Position local_r = local_coords(r0);
928,336,431✔
1164

1165
  const int n = n_dimension_;
928,336,431✔
1166

1167
  // Flag if position is inside the mesh
1168
  bool in_mesh;
1169

1170
  // Position is r = r0 + u * traveled_distance, start at r0
1171
  double traveled_distance {0.0};
928,336,431✔
1172

1173
  // Calculate index of current cell. Offset the position a tiny bit in
1174
  // direction of flight
1175
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
928,336,431✔
1176

1177
  // if track is very short, assume that it is completely inside one cell.
1178
  // Only the current cell will score and no surfaces
1179
  if (total_distance < 2 * TINY_BIT) {
928,336,431✔
1180
    if (in_mesh) {
331,923✔
1181
      tally.track(ijk, 1.0);
331,307✔
1182
    }
1183
    return;
331,923✔
1184
  }
1185

1186
  // Calculate initial distances to next surfaces in all three dimensions
1187
  std::array<MeshDistance, 3> distances;
1,856,009,016✔
1188
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1189
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1190
  }
1191

1192
  // Loop until r = r1 is eventually reached
1193
  while (true) {
1194

1195
    if (in_mesh) {
1,687,276,736✔
1196

1197
      // find surface with minimal distance to current position
1198
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,601,006,028✔
1199
                     distances.begin();
1,601,006,028✔
1200

1201
      // Tally track length delta since last step
1202
      tally.track(ijk,
1,601,006,028✔
1203
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1204
          total_distance);
1205

1206
      // update position and leave, if we have reached end position
1207
      traveled_distance = distances[k].distance;
1,601,006,028✔
1208
      if (traveled_distance >= total_distance)
1,601,006,028✔
1209
        return;
1210

1211
      // If we have not reached r1, we have hit a surface. Tally outward
1212
      // current
1213
      tally.surface(ijk, k, distances[k].max_surface, false);
752,102,010✔
1214

1215
      // Update cell and calculate distance to next surface in k-direction.
1216
      // The two other directions are still valid!
1217
      ijk[k] = distances[k].next_index;
752,102,010✔
1218
      distances[k] =
752,102,010✔
1219
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
752,102,010✔
1220

1221
      // Check if we have left the interior of the mesh
1222
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
758,936,214✔
1223

1224
      // If we are still inside the mesh, tally inward current for the next
1225
      // cell
1226
      if (in_mesh)
29,576,899✔
1227
        tally.surface(ijk, k, !distances[k].max_surface, true);
757,856,011✔
1228

1229
    } else { // not inside mesh
1230

1231
      // For all directions outside the mesh, find the distance that we need
1232
      // to travel to reach the next surface. Use the largest distance, as
1233
      // only this will cross all outer surfaces.
1234
      int k_max {-1};
1235
      for (int k = 0; k < n; ++k) {
343,638,466✔
1236
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,367,758✔
1237
            (distances[k].distance > traveled_distance)) {
94,278,623✔
1238
          traveled_distance = distances[k].distance;
1239
          k_max = k;
1240
        }
1241
      }
1242
      // Assure some distance is traveled
1243
      if (k_max == -1) {
86,270,708✔
1244
        traveled_distance += TINY_BIT;
110✔
1245
      }
1246

1247
      // If r1 is not inside the mesh, exit here
1248
      if (traveled_distance >= total_distance)
86,270,708✔
1249
        return;
1250

1251
      // Calculate the new cell index and update all distances to next
1252
      // surfaces.
1253
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,170,218✔
1254
      for (int k = 0; k < n; ++k) {
28,472,334✔
1255
        distances[k] =
21,302,116✔
1256
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,302,116✔
1257
      }
1258

1259
      // If inside the mesh, Tally inward current
1260
      if (in_mesh && k_max >= 0)
7,170,218!
1261
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
729,672,361✔
1262
    }
1263
  }
1264
}
1265

1266
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
828,304,197✔
1267
  vector<int>& bins, vector<double>& lengths) const
1268
{
1269

1270
  // Helper tally class.
1271
  // stores a pointer to the mesh class and references to bins and lengths
1272
  // parameters. Performs the actual tally through the track method.
1273
  struct TrackAggregator {
828,304,197✔
1274
    TrackAggregator(
828,304,197✔
1275
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1276
      : mesh(_mesh), bins(_bins), lengths(_lengths)
828,304,197✔
1277
    {}
1278
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1279
    void track(const MeshIndex& ijk, double l) const
1,461,292,771✔
1280
    {
1281
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,461,292,771✔
1282
      lengths.push_back(l);
1,461,292,771✔
1283
    }
1,461,292,771✔
1284

1285
    const StructuredMesh* mesh;
1286
    vector<int>& bins;
1287
    vector<double>& lengths;
1288
  };
1289

1290
  // Perform the mesh raytrace with the helper class.
1291
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
828,304,197✔
1292
}
828,304,197✔
1293

1294
void StructuredMesh::surface_bins_crossed(
112,127,565✔
1295
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1296
{
1297

1298
  // Helper tally class.
1299
  // stores a pointer to the mesh class and a reference to the bins parameter.
1300
  // Performs the actual tally through the surface method.
1301
  struct SurfaceAggregator {
112,127,565✔
1302
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,565✔
1303
      : mesh(_mesh), bins(_bins)
112,127,565✔
1304
    {}
1305
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,189✔
1306
    {
1307
      int i_bin =
58,159,189✔
1308
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,189✔
1309
      if (max)
58,159,189✔
1310
        i_bin += 2;
29,051,440✔
1311
      if (inward)
58,159,189✔
1312
        i_bin += 1;
28,582,290✔
1313
      bins.push_back(i_bin);
58,159,189✔
1314
    }
58,159,189✔
1315
    void track(const MeshIndex& idx, double l) const {}
1316

1317
    const StructuredMesh* mesh;
1318
    vector<int>& bins;
1319
  };
1320

1321
  // Perform the mesh raytrace with the helper class.
1322
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,565✔
1323
}
112,127,565✔
1324

1325
//==============================================================================
1326
// RegularMesh implementation
1327
//==============================================================================
1328

1329
int RegularMesh::set_grid()
2,126✔
1330
{
1331
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,126✔
1332

1333
  // Check that dimensions are all greater than zero
1334
  if ((shape <= 0).any()) {
6,378!
UNCOV
1335
    set_errmsg("All entries for a regular mesh dimensions "
×
1336
               "must be positive.");
UNCOV
1337
    return OPENMC_E_INVALID_ARGUMENT;
×
1338
  }
1339

1340
  // Make sure lower_left and dimension match
1341
  if (lower_left_.size() != n_dimension_) {
2,126!
UNCOV
1342
    set_errmsg("Number of entries in lower_left must be the same "
×
1343
               "as the regular mesh dimensions.");
UNCOV
1344
    return OPENMC_E_INVALID_ARGUMENT;
×
1345
  }
1346
  if (width_.size() > 0) {
2,126✔
1347

1348
    // Check to ensure width has same dimensions
1349
    if (width_.size() != n_dimension_) {
46!
UNCOV
1350
      set_errmsg("Number of entries on width must be the same as "
×
1351
                 "the regular mesh dimensions.");
UNCOV
1352
      return OPENMC_E_INVALID_ARGUMENT;
×
1353
    }
1354

1355
    // Check for negative widths
1356
    if ((width_ < 0.0).any()) {
138!
1357
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
UNCOV
1358
      return OPENMC_E_INVALID_ARGUMENT;
×
1359
    }
1360

1361
    // Set width and upper right coordinate
1362
    upper_right_ = lower_left_ + shape * width_;
138✔
1363

1364
  } else if (upper_right_.size() > 0) {
2,080!
1365

1366
    // Check to ensure upper_right_ has same dimensions
1367
    if (upper_right_.size() != n_dimension_) {
2,080!
UNCOV
1368
      set_errmsg("Number of entries on upper_right must be the "
×
1369
                 "same as the regular mesh dimensions.");
UNCOV
1370
      return OPENMC_E_INVALID_ARGUMENT;
×
1371
    }
1372

1373
    // Check that upper-right is above lower-left
1374
    if ((upper_right_ < lower_left_).any()) {
6,240!
UNCOV
1375
      set_errmsg(
×
1376
        "The upper_right coordinates of a regular mesh must be greater than "
1377
        "the lower_left coordinates.");
UNCOV
1378
      return OPENMC_E_INVALID_ARGUMENT;
×
1379
    }
1380

1381
    // Set width
1382
    width_ = (upper_right_ - lower_left_) / shape;
6,240✔
1383
  }
1384

1385
  // Set material volumes
1386
  volume_frac_ = 1.0 / shape.prod();
2,126✔
1387

1388
  element_volume_ = 1.0;
2,126✔
1389
  for (int i = 0; i < n_dimension_; i++) {
7,957✔
1390
    element_volume_ *= width_[i];
5,831✔
1391
  }
1392
  return 0;
1393
}
2,126✔
1394

1395
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,115✔
1396
{
1397
  // Determine number of dimensions for mesh
1398
  if (!check_for_node(node, "dimension")) {
2,115!
UNCOV
1399
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1400
  }
1401

1402
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,115✔
1403
  int n = n_dimension_ = shape.size();
2,115!
1404
  if (n != 1 && n != 2 && n != 3) {
2,115!
UNCOV
1405
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1406
  }
1407
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,115✔
1408

1409
  // Check for lower-left coordinates
1410
  if (check_for_node(node, "lower_left")) {
2,115!
1411
    // Read mesh lower-left corner location
1412
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,115✔
1413
  } else {
UNCOV
1414
    fatal_error("Must specify <lower_left> on a mesh.");
×
1415
  }
1416

1417
  if (check_for_node(node, "width")) {
2,115✔
1418
    // Make sure one of upper-right or width were specified
1419
    if (check_for_node(node, "upper_right")) {
46!
UNCOV
1420
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1421
    }
1422

1423
    width_ = get_node_tensor<double>(node, "width");
92✔
1424

1425
  } else if (check_for_node(node, "upper_right")) {
2,069!
1426

1427
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,138✔
1428

1429
  } else {
UNCOV
1430
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1431
  }
1432

1433
  if (int err = set_grid()) {
2,115!
UNCOV
1434
    fatal_error(openmc_err_msg);
×
1435
  }
1436
}
2,115✔
1437

1438
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
11✔
1439
{
1440
  // Determine number of dimensions for mesh
1441
  if (!object_exists(group, "dimension")) {
11!
UNCOV
1442
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1443
  }
1444

1445
  tensor::Tensor<int> shape;
11✔
1446
  read_dataset(group, "dimension", shape);
11✔
1447
  int n = n_dimension_ = shape.size();
11!
1448
  if (n != 1 && n != 2 && n != 3) {
11!
UNCOV
1449
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1450
  }
1451
  std::copy(shape.begin(), shape.end(), shape_.begin());
11✔
1452

1453
  // Check for lower-left coordinates
1454
  if (object_exists(group, "lower_left")) {
11!
1455
    // Read mesh lower-left corner location
1456
    read_dataset(group, "lower_left", lower_left_);
11✔
1457
  } else {
UNCOV
1458
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1459
  }
1460

1461
  if (object_exists(group, "upper_right")) {
11!
1462

1463
    read_dataset(group, "upper_right", upper_right_);
11✔
1464

1465
  } else {
UNCOV
1466
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1467
  }
1468

1469
  if (int err = set_grid()) {
11!
UNCOV
1470
    fatal_error(openmc_err_msg);
×
1471
  }
1472
}
11✔
1473

1474
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1475
{
1476
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1477
}
1478

1479
const std::string RegularMesh::mesh_type = "regular";
1480

1481
std::string RegularMesh::get_mesh_type() const
3,225✔
1482
{
1483
  return mesh_type;
3,225✔
1484
}
1485

1486
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,486,412,591✔
1487
{
1488
  return lower_left_[i] + ijk[i] * width_[i];
1,486,412,591✔
1489
}
1490

1491
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,417,228,986✔
1492
{
1493
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,417,228,986✔
1494
}
1495

1496
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1497
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1498
  double l) const
1499
{
1500
  MeshDistance d;
2,147,483,647✔
1501
  d.next_index = ijk[i];
2,147,483,647✔
1502
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1503
    return d;
14,737,740✔
1504

1505
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1506
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1507
    d.next_index++;
1,482,098,486✔
1508
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,482,098,486✔
1509
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,434,363,193✔
1510
    d.next_index--;
1,412,914,881✔
1511
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,412,914,881✔
1512
  }
1513

1514
  return d;
2,147,483,647✔
1515
}
1516

1517
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1518
  Position plot_ll, Position plot_ur) const
1519
{
1520
  // Figure out which axes lie in the plane of the plot.
1521
  array<int, 2> axes {-1, -1};
22✔
1522
  if (plot_ur.z == plot_ll.z) {
22!
1523
    axes[0] = 0;
22!
1524
    if (n_dimension_ > 1)
22!
1525
      axes[1] = 1;
22✔
1526
  } else if (plot_ur.y == plot_ll.y) {
×
1527
    axes[0] = 0;
×
1528
    if (n_dimension_ > 2)
×
1529
      axes[1] = 2;
×
1530
  } else if (plot_ur.x == plot_ll.x) {
×
1531
    if (n_dimension_ > 1)
×
1532
      axes[0] = 1;
×
1533
    if (n_dimension_ > 2)
×
UNCOV
1534
      axes[1] = 2;
×
1535
  } else {
UNCOV
1536
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1537
  }
1538

1539
  // Get the coordinates of the mesh lines along both of the axes.
1540
  array<vector<double>, 2> axis_lines;
1541
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1542
    int axis = axes[i_ax];
44!
1543
    if (axis == -1)
44!
UNCOV
1544
      continue;
×
1545
    auto& lines {axis_lines[i_ax]};
44✔
1546

1547
    double coord = lower_left_[axis];
44✔
1548
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1549
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1550
        lines.push_back(coord);
242✔
1551
      coord += width_[axis];
242✔
1552
    }
1553
  }
1554

1555
  return {axis_lines[0], axis_lines[1]};
44✔
1556
}
1557

1558
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,092✔
1559
{
1560
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,092✔
1561
  write_dataset(mesh_group, "lower_left", lower_left_);
2,092✔
1562
  write_dataset(mesh_group, "upper_right", upper_right_);
2,092✔
1563
  write_dataset(mesh_group, "width", width_);
2,092✔
1564
}
2,092✔
1565

1566
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1567
  const SourceSite* bank, int64_t length, bool* outside) const
1568
{
1569
  // Determine shape of array for counts
1570
  std::size_t m = this->n_bins();
7,820✔
1571
  vector<std::size_t> shape = {m};
7,820✔
1572

1573
  // Create array of zeros
1574
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1575
  bool outside_ = false;
2,892✔
1576

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

1580
    // determine scoring bin for entropy mesh
1581
    int mesh_bin = get_bin(site.r);
7,667,451✔
1582

1583
    // if outside mesh, skip particle
1584
    if (mesh_bin < 0) {
7,667,451!
1585
      outside_ = true;
×
UNCOV
1586
      continue;
×
1587
    }
1588

1589
    // Add to appropriate bin
1590
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1591
  }
1592

1593
  // Create reduced count data
1594
  auto counts = tensor::zeros<double>(shape);
7,820✔
1595
  int total = cnt.size();
7,820✔
1596

1597
#ifdef OPENMC_MPI
1598
  // collect values from all processors
1599
  MPI_Reduce(
2,892✔
1600
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1601

1602
  // Check if there were sites outside the mesh for any processor
1603
  if (outside) {
2,892!
1604
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892✔
1605
  }
1606
#else
1607
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928✔
1608
  if (outside)
4,928!
1609
    *outside = outside_;
4,928✔
1610
#endif
1611

1612
  return counts;
7,820✔
1613
}
7,820✔
1614

1615
double RegularMesh::volume(const MeshIndex& ijk) const
1,112,175✔
1616
{
1617
  return element_volume_;
1,112,175✔
1618
}
1619

1620
//==============================================================================
1621
// RectilinearMesh implementation
1622
//==============================================================================
1623

1624
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
122✔
1625
{
1626
  n_dimension_ = 3;
122✔
1627

1628
  grid_[0] = get_node_array<double>(node, "x_grid");
122✔
1629
  grid_[1] = get_node_array<double>(node, "y_grid");
122✔
1630
  grid_[2] = get_node_array<double>(node, "z_grid");
122✔
1631

1632
  if (int err = set_grid()) {
122!
UNCOV
1633
    fatal_error(openmc_err_msg);
×
1634
  }
1635
}
122✔
1636

1637
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1638
{
1639
  n_dimension_ = 3;
11✔
1640

1641
  read_dataset(group, "x_grid", grid_[0]);
11✔
1642
  read_dataset(group, "y_grid", grid_[1]);
11✔
1643
  read_dataset(group, "z_grid", grid_[2]);
11✔
1644

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

1650
const std::string RectilinearMesh::mesh_type = "rectilinear";
1651

1652
std::string RectilinearMesh::get_mesh_type() const
275✔
1653
{
1654
  return mesh_type;
275✔
1655
}
1656

1657
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1658
  const MeshIndex& ijk, int i) const
1659
{
1660
  return grid_[i][ijk[i]];
26,505,963✔
1661
}
1662

1663
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1664
  const MeshIndex& ijk, int i) const
1665
{
1666
  return grid_[i][ijk[i] - 1];
25,739,406✔
1667
}
1668

1669
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,087✔
1670
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1671
  double l) const
1672
{
1673
  MeshDistance d;
53,602,087✔
1674
  d.next_index = ijk[i];
53,602,087✔
1675
  if (std::abs(u[i]) < FP_PRECISION)
53,602,087✔
1676
    return d;
571,824✔
1677

1678
  d.max_surface = (u[i] > 0);
53,030,263✔
1679
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,263✔
1680
    d.next_index++;
26,505,963✔
1681
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,963✔
1682
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,300✔
1683
    d.next_index--;
25,739,406✔
1684
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,406✔
1685
  }
1686
  return d;
53,030,263✔
1687
}
1688

1689
int RectilinearMesh::set_grid()
177✔
1690
{
1691
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
177✔
1692
    static_cast<int>(grid_[1].size()) - 1,
177✔
1693
    static_cast<int>(grid_[2].size()) - 1};
177✔
1694

1695
  for (const auto& g : grid_) {
708✔
1696
    if (g.size() < 2) {
531!
UNCOV
1697
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1698
                 "must each have at least 2 points");
UNCOV
1699
      return OPENMC_E_INVALID_ARGUMENT;
×
1700
    }
1701
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
531!
1702
        g.end()) {
531!
UNCOV
1703
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1704
                 "rectilinear meshes must be sorted and unique.");
UNCOV
1705
      return OPENMC_E_INVALID_ARGUMENT;
×
1706
    }
1707
  }
1708

1709
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
177✔
1710
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
177✔
1711

1712
  return 0;
177✔
1713
}
1714

1715
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,892✔
1716
{
1717
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,892✔
1718
}
1719

1720
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1721
  Position plot_ll, Position plot_ur) const
1722
{
1723
  // Figure out which axes lie in the plane of the plot.
1724
  array<int, 2> axes {-1, -1};
11✔
1725
  if (plot_ur.z == plot_ll.z) {
11!
UNCOV
1726
    axes = {0, 1};
×
1727
  } else if (plot_ur.y == plot_ll.y) {
11!
1728
    axes = {0, 2};
11✔
1729
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1730
    axes = {1, 2};
×
1731
  } else {
UNCOV
1732
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1733
  }
1734

1735
  // Get the coordinates of the mesh lines along both of the axes.
1736
  array<vector<double>, 2> axis_lines;
1737
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1738
    int axis = axes[i_ax];
22✔
1739
    vector<double>& lines {axis_lines[i_ax]};
22✔
1740

1741
    for (auto coord : grid_[axis]) {
110✔
1742
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1743
        lines.push_back(coord);
88✔
1744
    }
1745
  }
1746

1747
  return {axis_lines[0], axis_lines[1]};
22✔
1748
}
1749

1750
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1751
{
1752
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1753
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1754
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1755
}
110✔
1756

1757
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1758
{
1759
  double vol {1.0};
132✔
1760

1761
  for (int i = 0; i < n_dimension_; i++) {
528✔
1762
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1763
  }
1764
  return vol;
132✔
1765
}
1766

1767
//==============================================================================
1768
// CylindricalMesh implementation
1769
//==============================================================================
1770

1771
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
400✔
1772
  : PeriodicStructuredMesh {node}
400✔
1773
{
1774
  n_dimension_ = 3;
400✔
1775
  grid_[0] = get_node_array<double>(node, "r_grid");
400✔
1776
  grid_[1] = get_node_array<double>(node, "phi_grid");
400✔
1777
  grid_[2] = get_node_array<double>(node, "z_grid");
400✔
1778
  origin_ = get_node_position(node, "origin");
400✔
1779

1780
  if (int err = set_grid()) {
400!
UNCOV
1781
    fatal_error(openmc_err_msg);
×
1782
  }
1783
}
400✔
1784

1785
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1786
{
1787
  n_dimension_ = 3;
11✔
1788
  read_dataset(group, "r_grid", grid_[0]);
11✔
1789
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1790
  read_dataset(group, "z_grid", grid_[2]);
11✔
1791
  read_dataset(group, "origin", origin_);
11✔
1792

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

1798
const std::string CylindricalMesh::mesh_type = "cylindrical";
1799

1800
std::string CylindricalMesh::get_mesh_type() const
484✔
1801
{
1802
  return mesh_type;
484✔
1803
}
1804

1805
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1806
  Position r, bool& in_mesh) const
1807
{
1808
  r = local_coords(r);
47,732,091✔
1809

1810
  Position mapped_r;
47,732,091✔
1811
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1812
  mapped_r[2] = r[2];
47,732,091✔
1813

1814
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1815
    mapped_r[1] = 0.0;
1816
  } else {
1817
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1818
    if (mapped_r[1] < 0)
47,732,091✔
1819
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1820
  }
1821

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

1824
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1825

1826
  return idx;
47,732,091✔
1827
}
1828

1829
Position CylindricalMesh::sample_element(
88,110✔
1830
  const MeshIndex& ijk, uint64_t* seed) const
1831
{
1832
  double r_min = this->r(ijk[0] - 1);
88,110✔
1833
  double r_max = this->r(ijk[0]);
88,110✔
1834

1835
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1836
  double phi_max = this->phi(ijk[1]);
88,110✔
1837

1838
  double z_min = this->z(ijk[2] - 1);
88,110✔
1839
  double z_max = this->z(ijk[2]);
88,110✔
1840

1841
  double r_min_sq = r_min * r_min;
88,110✔
1842
  double r_max_sq = r_max * r_max;
88,110✔
1843
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1844
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1845
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1846

1847
  double x = r * std::cos(phi);
88,110✔
1848
  double y = r * std::sin(phi);
88,110✔
1849

1850
  return origin_ + Position(x, y, z);
88,110✔
1851
}
1852

1853
double CylindricalMesh::find_r_crossing(
142,591,814✔
1854
  const Position& r, const Direction& u, double l, int shell) const
1855
{
1856

1857
  if ((shell < 0) || (shell > shape_[0]))
142,591,814!
1858
    return INFTY;
1859

1860
  // solve r.x^2 + r.y^2 == r0^2
1861
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1862
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1863

1864
  const double r0 = grid_[0][shell];
124,677,770✔
1865
  if (isclose(r0, 0.0, 0.0, FP_PRECISION))
124,677,770✔
1866
    return INFTY;
1867

1868
  const double denominator = u.x * u.x + u.y * u.y;
117,541,696✔
1869

1870
  // Direction of flight is in z-direction. Will never intersect r.
1871
  if (isclose(denominator, 0.0, 0.0, FP_PRECISION))
117,541,696✔
1872
    return INFTY;
1873

1874
  // inverse of dominator to help the compiler to speed things up
1875
  const double inv_denominator = 1.0 / denominator;
117,482,736✔
1876

1877
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,482,736✔
1878
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,482,736✔
1879
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,482,736✔
1880

1881
  if (D < 0.0)
117,482,736✔
1882
    return INFTY;
1883

1884
  D = std::sqrt(D);
107,746,614✔
1885

1886
  // Particle is already on the shell surface; avoid spurious crossing
1887
  if (isclose(R, r0, RADIAL_MESH_TOL, FP_PRECISION))
107,746,614✔
1888
    return INFTY;
1889

1890
  // Check -p - D first because it is always smaller as -p + D
1891
  if (-p - D > l)
101,113,240✔
1892
    return -p - D;
1893
  if (-p + D > l)
80,904,697✔
1894
    return -p + D;
50,080,092✔
1895

1896
  return INFTY;
1897
}
1898

1899
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1900
  const Position& r, const Direction& u, double l, int shell) const
1901
{
1902
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1903
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1904
    return INFTY;
1905

1906
  shell = sanitize_phi(shell);
43,970,718✔
1907

1908
  const double p0 = grid_[1][shell];
43,970,718✔
1909

1910
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1911
  // => x(s) * cos(p0) = y(s) * sin(p0)
1912
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1913
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1914

1915
  const double c0 = std::cos(p0);
43,970,718✔
1916
  const double s0 = std::sin(p0);
43,970,718✔
1917

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

1920
  // Check if direction of flight is not parallel to phi surface
1921
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1922
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1923
    // Check if solution is in positive direction of flight and crosses the
1924
    // correct phi surface (not -phi)
1925
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1926
      return s;
20,219,859✔
1927
  }
1928

1929
  return INFTY;
1930
}
1931

1932
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1933
  const Position& r, const Direction& u, double l, int shell) const
1934
{
1935
  MeshDistance d;
36,695,747✔
1936
  d.next_index = shell;
36,695,747✔
1937

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

1942
  d.max_surface = (u.z > 0.0);
35,577,531✔
1943
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1944
    d.next_index += 1;
16,875,892✔
1945
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1946
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1947
    d.next_index -= 1;
16,846,225✔
1948
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1949
  }
1950
  return d;
35,577,531✔
1951
}
1952

1953
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,219,856✔
1954
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1955
  double l) const
1956
{
1957
  if (i == 0) {
145,219,856✔
1958

1959
    return std::min(
142,591,814✔
1960
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,295,907✔
1961
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,591,814✔
1962

1963
  } else if (i == 1) {
73,923,949✔
1964

1965
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
1966
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1967
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
1968
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1969

1970
  } else {
1971
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1972
  }
1973
}
1974

1975
int CylindricalMesh::set_grid()
433✔
1976
{
1977
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
1978
    static_cast<int>(grid_[1].size()) - 1,
433✔
1979
    static_cast<int>(grid_[2].size()) - 1};
433✔
1980

1981
  for (const auto& g : grid_) {
1,732✔
1982
    if (g.size() < 2) {
1,299!
UNCOV
1983
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
1984
                 "must each have at least 2 points");
UNCOV
1985
      return OPENMC_E_INVALID_ARGUMENT;
×
1986
    }
1987
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,299!
1988
        g.end()) {
1,299!
UNCOV
1989
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
1990
                 "cylindrical meshes must be sorted and unique.");
UNCOV
1991
      return OPENMC_E_INVALID_ARGUMENT;
×
1992
    }
1993
  }
1994
  if (grid_[0].front() < 0.0) {
433!
UNCOV
1995
    set_errmsg("r-grid for "
×
1996
               "cylindrical meshes must start at r >= 0.");
UNCOV
1997
    return OPENMC_E_INVALID_ARGUMENT;
×
1998
  }
1999
  if (grid_[1].front() < 0.0) {
433!
UNCOV
2000
    set_errmsg("phi-grid for "
×
2001
               "cylindrical meshes must start at phi >= 0.");
UNCOV
2002
    return OPENMC_E_INVALID_ARGUMENT;
×
2003
  }
2004
  if (grid_[1].back() > 2.0 * PI) {
433!
UNCOV
2005
    set_errmsg("phi-grids for "
×
2006
               "cylindrical meshes must end with theta <= 2*pi.");
2007

UNCOV
2008
    return OPENMC_E_INVALID_ARGUMENT;
×
2009
  }
2010

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

2013
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2014
    origin_[2] + grid_[2].front()};
433✔
2015
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2016
    origin_[2] + grid_[2].back()};
433✔
2017

2018
  return 0;
433✔
2019
}
2020

2021
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,273✔
2022
{
2023
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2024
}
2025

UNCOV
2026
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2027
  Position plot_ll, Position plot_ur) const
2028
{
UNCOV
2029
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2030

2031
  // Figure out which axes lie in the plane of the plot.
2032
  array<vector<double>, 2> axis_lines;
2033
  return {axis_lines[0], axis_lines[1]};
2034
}
2035

2036
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2037
{
2038
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2039
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2040
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2041
  write_dataset(mesh_group, "origin", origin_);
374✔
2042
}
374✔
2043

2044
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2045
{
2046
  double r_i = grid_[0][ijk[0] - 1];
792✔
2047
  double r_o = grid_[0][ijk[0]];
792✔
2048

2049
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2050
  double phi_o = grid_[1][ijk[1]];
792✔
2051

2052
  double z_i = grid_[2][ijk[2] - 1];
792✔
2053
  double z_o = grid_[2][ijk[2]];
792✔
2054

2055
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2056
}
2057

2058
//==============================================================================
2059
// SphericalMesh implementation
2060
//==============================================================================
2061

2062
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2063
  : PeriodicStructuredMesh {node}
345✔
2064
{
2065
  n_dimension_ = 3;
345✔
2066

2067
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2068
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2069
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2070
  origin_ = get_node_position(node, "origin");
345✔
2071

2072
  if (int err = set_grid()) {
345!
UNCOV
2073
    fatal_error(openmc_err_msg);
×
2074
  }
2075
}
345✔
2076

2077
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2078
{
2079
  n_dimension_ = 3;
11✔
2080

2081
  read_dataset(group, "r_grid", grid_[0]);
11✔
2082
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2083
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2084
  read_dataset(group, "origin", origin_);
11✔
2085

2086
  if (int err = set_grid()) {
11!
UNCOV
2087
    fatal_error(openmc_err_msg);
×
2088
  }
2089
}
11✔
2090

2091
const std::string SphericalMesh::mesh_type = "spherical";
2092

2093
std::string SphericalMesh::get_mesh_type() const
385✔
2094
{
2095
  return mesh_type;
385✔
2096
}
2097

2098
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2099
  Position r, bool& in_mesh) const
2100
{
2101
  r = local_coords(r);
68,592,128✔
2102

2103
  Position mapped_r;
68,592,128✔
2104
  mapped_r[0] = r.norm();
68,592,128✔
2105

2106
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2107
    mapped_r[1] = 0.0;
2108
    mapped_r[2] = 0.0;
2109
  } else {
2110
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2111
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2112
    if (mapped_r[2] < 0)
68,592,128✔
2113
      mapped_r[2] += 2 * M_PI;
34,268,685✔
2114
  }
2115

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

2118
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2119
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2120

2121
  return idx;
68,592,128✔
2122
}
2123

2124
Position SphericalMesh::sample_element(
110✔
2125
  const MeshIndex& ijk, uint64_t* seed) const
2126
{
2127
  double r_min = this->r(ijk[0] - 1);
110✔
2128
  double r_max = this->r(ijk[0]);
110✔
2129

2130
  double theta_min = this->theta(ijk[1] - 1);
110✔
2131
  double theta_max = this->theta(ijk[1]);
110✔
2132

2133
  double phi_min = this->phi(ijk[2] - 1);
110✔
2134
  double phi_max = this->phi(ijk[2]);
110✔
2135

2136
  double cos_theta =
110✔
2137
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2138
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2139
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2140
  double r_min_cub = std::pow(r_min, 3);
110✔
2141
  double r_max_cub = std::pow(r_max, 3);
110✔
2142
  // might be faster to do rejection here?
2143
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2144

2145
  double x = r * std::cos(phi) * sin_theta;
110✔
2146
  double y = r * std::sin(phi) * sin_theta;
110✔
2147
  double z = r * cos_theta;
110✔
2148

2149
  return origin_ + Position(x, y, z);
110✔
2150
}
2151

2152
double SphericalMesh::find_r_crossing(
444,010,820✔
2153
  const Position& r, const Direction& u, double l, int shell) const
2154
{
2155
  if ((shell < 0) || (shell > shape_[0]))
444,010,820✔
2156
    return INFTY;
2157

2158
  // solve |r+s*u| = r0
2159
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2160
  const double r0 = grid_[0][shell];
404,389,733✔
2161
  if (isclose(r0, 0.0, 0.0, FP_PRECISION))
404,389,733✔
2162
    return INFTY;
2163
  const double p = r.dot(u);
396,711,216✔
2164
  double R = r.norm();
396,711,216✔
2165
  double D = p * p - (R - r0) * (R + r0);
396,711,216✔
2166

2167
  // Particle is already on the shell surface; avoid spurious crossing
2168
  if (isclose(R, r0, RADIAL_MESH_TOL, FP_PRECISION))
396,711,216✔
2169
    return INFTY;
2170

2171
  if (D >= 0.0) {
386,002,562✔
2172
    D = std::sqrt(D);
358,125,614✔
2173
    // Check -p - D first because it is always smaller as -p + D
2174
    if (-p - D > l)
358,125,614✔
2175
      return -p - D;
2176
    if (-p + D > l)
293,803,642✔
2177
      return -p + D;
177,256,596✔
2178
  }
2179

2180
  return INFTY;
2181
}
2182

2183
double SphericalMesh::find_theta_crossing(
110,161,348✔
2184
  const Position& r, const Direction& u, double l, int shell) const
2185
{
2186
  // Theta grid is [0, π], thus there is no real surface to cross
2187
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2188
    return INFTY;
2189

2190
  shell = sanitize_theta(shell);
38,358,540✔
2191

2192
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2193
  // yields
2194
  // a*s^2 + 2*b*s + c == 0 with
2195
  // a = cos(theta)^2 - u.z * u.z
2196
  // b = r*u * cos(theta)^2 - u.z * r.z
2197
  // c = r*r * cos(theta)^2 - r.z^2
2198

2199
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2200
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2201
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2202

2203
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2204
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2205
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2206

2207
  // if factor of s^2 is zero, direction of flight is parallel to theta
2208
  // surface
2209
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2210
    // if b vanishes, direction of flight is within theta surface and crossing
2211
    // is not possible
2212
    if (std::abs(b) < FP_PRECISION)
482,548!
2213
      return INFTY;
2214

UNCOV
2215
    const double s = -0.5 * c / b;
×
2216
    // Check if solution is in positive direction of flight and has correct
2217
    // sign
2218
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
UNCOV
2219
      return s;
×
2220

2221
    // no crossing is possible
2222
    return INFTY;
2223
  }
2224

2225
  const double p = b / a;
37,875,992✔
2226
  double D = p * p - c / a;
37,875,992✔
2227

2228
  if (D < 0.0)
37,875,992✔
2229
    return INFTY;
2230

2231
  D = std::sqrt(D);
26,921,004✔
2232

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

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

2244
  return INFTY;
2245
}
2246

2247
double SphericalMesh::find_phi_crossing(
111,750,826✔
2248
  const Position& r, const Direction& u, double l, int shell) const
2249
{
2250
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2251
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2252
    return INFTY;
2253

2254
  shell = sanitize_phi(shell);
39,948,018✔
2255

2256
  const double p0 = grid_[2][shell];
39,948,018✔
2257

2258
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2259
  // => x(s) * cos(p0) = y(s) * sin(p0)
2260
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2261
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2262

2263
  const double c0 = std::cos(p0);
39,948,018✔
2264
  const double s0 = std::sin(p0);
39,948,018✔
2265

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

2268
  // Check if direction of flight is not parallel to phi surface
2269
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2270
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2271
    // Check if solution is in positive direction of flight and crosses the
2272
    // correct phi surface (not -phi)
2273
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2274
      return s;
17,579,452✔
2275
  }
2276

2277
  return INFTY;
2278
}
2279

2280
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,961,497✔
2281
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2282
  double l) const
2283
{
2284

2285
  if (i == 0) {
332,961,497✔
2286
    return std::min(
444,010,820✔
2287
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
222,005,410✔
2288
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
444,010,820✔
2289

2290
  } else if (i == 1) {
110,956,087✔
2291
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2292
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2293
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2294
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2295

2296
  } else {
2297
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2298
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2299
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2300
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2301
  }
2302
}
2303

2304
int SphericalMesh::set_grid()
378✔
2305
{
2306
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2307
    static_cast<int>(grid_[1].size()) - 1,
378✔
2308
    static_cast<int>(grid_[2].size()) - 1};
378✔
2309

2310
  for (const auto& g : grid_) {
1,512✔
2311
    if (g.size() < 2) {
1,134!
UNCOV
2312
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2313
                 "must each have at least 2 points");
UNCOV
2314
      return OPENMC_E_INVALID_ARGUMENT;
×
2315
    }
2316
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,134!
2317
        g.end()) {
1,134!
UNCOV
2318
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2319
                 "spherical meshes must be sorted and unique.");
UNCOV
2320
      return OPENMC_E_INVALID_ARGUMENT;
×
2321
    }
2322
    if (g.front() < 0.0) {
1,134!
UNCOV
2323
      set_errmsg("r-, theta-, and phi- grids for "
×
2324
                 "spherical meshes must start at v >= 0.");
UNCOV
2325
      return OPENMC_E_INVALID_ARGUMENT;
×
2326
    }
2327
  }
2328
  if (grid_[1].back() > PI) {
378!
UNCOV
2329
    set_errmsg("theta-grids for "
×
2330
               "spherical meshes must end with theta <= pi.");
2331

UNCOV
2332
    return OPENMC_E_INVALID_ARGUMENT;
×
2333
  }
2334
  if (grid_[2].back() > 2 * PI) {
378!
UNCOV
2335
    set_errmsg("phi-grids for "
×
2336
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2337
    return OPENMC_E_INVALID_ARGUMENT;
×
2338
  }
2339

2340
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2341
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2342

2343
  double r = grid_[0].back();
378✔
2344
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2345
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2346

2347
  return 0;
378✔
2348
}
2349

2350
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,384✔
2351
{
2352
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2353
}
2354

UNCOV
2355
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2356
  Position plot_ll, Position plot_ur) const
2357
{
UNCOV
2358
  fatal_error("Plot of spherical Mesh not implemented");
×
2359

2360
  // Figure out which axes lie in the plane of the plot.
2361
  array<vector<double>, 2> axis_lines;
2362
  return {axis_lines[0], axis_lines[1]};
2363
}
2364

2365
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2366
{
2367
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2368
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2369
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2370
  write_dataset(mesh_group, "origin", origin_);
319✔
2371
}
319✔
2372

2373
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2374
{
2375
  double r_i = grid_[0][ijk[0] - 1];
935✔
2376
  double r_o = grid_[0][ijk[0]];
935✔
2377

2378
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2379
  double theta_o = grid_[1][ijk[1]];
935✔
2380

2381
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2382
  double phi_o = grid_[2][ijk[2]];
935✔
2383

2384
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2385
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2386
}
2387

2388
//==============================================================================
2389
// Helper functions for the C API
2390
//==============================================================================
2391

2392
int check_mesh(int32_t index)
6,380✔
2393
{
2394
  if (index < 0 || index >= model::meshes.size()) {
6,380!
2395
    set_errmsg("Index in meshes array is out of bounds.");
×
UNCOV
2396
    return OPENMC_E_OUT_OF_BOUNDS;
×
2397
  }
2398
  return 0;
2399
}
2400

2401
template<class T>
2402
int check_mesh_type(int32_t index)
1,100✔
2403
{
2404
  if (int err = check_mesh(index))
1,100!
2405
    return err;
2406

2407
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2408
  if (!mesh) {
1,100!
2409
    set_errmsg("This function is not valid for input mesh.");
×
UNCOV
2410
    return OPENMC_E_INVALID_TYPE;
×
2411
  }
2412
  return 0;
2413
}
2414

2415
template<class T>
2416
bool is_mesh_type(int32_t index)
2417
{
2418
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2419
  return mesh;
2420
}
2421

2422
//==============================================================================
2423
// C API functions
2424
//==============================================================================
2425

2426
// Return the type of mesh as a C string
2427
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,474✔
2428
{
2429
  if (int err = check_mesh(index))
1,474!
2430
    return err;
2431

2432
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,474✔
2433

2434
  return 0;
1,474✔
2435
}
2436

2437
//! Extend the meshes array by n elements
2438
extern "C" int openmc_extend_meshes(
253✔
2439
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2440
{
2441
  if (index_start)
253!
2442
    *index_start = model::meshes.size();
253✔
2443
  std::string mesh_type;
253✔
2444

2445
  for (int i = 0; i < n; ++i) {
506✔
2446
    if (RegularMesh::mesh_type == type) {
253✔
2447
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2448
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2449
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2450
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2451
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2452
    } else if (SphericalMesh::mesh_type == type) {
22!
2453
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2454
    } else {
UNCOV
2455
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2456
    }
2457
  }
2458
  if (index_end)
253!
UNCOV
2459
    *index_end = model::meshes.size() - 1;
×
2460

2461
  return 0;
253✔
2462
}
253✔
2463

2464
//! Adds a new unstructured mesh to OpenMC
UNCOV
2465
extern "C" int openmc_add_unstructured_mesh(
×
2466
  const char filename[], const char library[], int* id)
2467
{
2468
  std::string lib_name(library);
×
2469
  std::string mesh_file(filename);
×
UNCOV
2470
  bool valid_lib = false;
×
2471

2472
#ifdef OPENMC_DAGMC_ENABLED
2473
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2474
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2475
    valid_lib = true;
2476
  }
2477
#endif
2478

2479
#ifdef OPENMC_LIBMESH_ENABLED
2480
  if (lib_name == LibMesh::mesh_lib_type) {
×
2481
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2482
    valid_lib = true;
2483
  }
2484
#endif
2485

2486
  if (!valid_lib) {
×
UNCOV
2487
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2488
                           "by this build of OpenMC",
2489
      lib_name));
UNCOV
2490
    return OPENMC_E_INVALID_ARGUMENT;
×
2491
  }
2492

2493
  // auto-assign new ID
2494
  model::meshes.back()->set_id(-1);
×
2495
  *id = model::meshes.back()->id_;
2496

2497
  return 0;
UNCOV
2498
}
×
2499

2500
//! Return the index in the meshes array of a mesh with a given ID
2501
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2502
{
2503
  auto pair = model::mesh_map.find(id);
429!
2504
  if (pair == model::mesh_map.end()) {
429!
2505
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
UNCOV
2506
    return OPENMC_E_INVALID_ID;
×
2507
  }
2508
  *index = pair->second;
429✔
2509
  return 0;
429✔
2510
}
2511

2512
//! Return the ID of a mesh
2513
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,805✔
2514
{
2515
  if (int err = check_mesh(index))
2,805!
2516
    return err;
2517
  *id = model::meshes[index]->id_;
2,805✔
2518
  return 0;
2,805✔
2519
}
2520

2521
//! Set the ID of a mesh
2522
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2523
{
2524
  if (int err = check_mesh(index))
253!
2525
    return err;
2526
  model::meshes[index]->id_ = id;
253✔
2527
  model::mesh_map[id] = index;
253✔
2528
  return 0;
253✔
2529
}
2530

2531
//! Get the number of elements in a mesh
2532
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
275✔
2533
{
2534
  if (int err = check_mesh(index))
275!
2535
    return err;
2536
  *n = model::meshes[index]->n_bins();
275✔
2537
  return 0;
275✔
2538
}
2539

2540
//! Get the volume of each element in the mesh
2541
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2542
{
2543
  if (int err = check_mesh(index))
88!
2544
    return err;
2545
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2546
    volumes[i] = model::meshes[index]->volume(i);
880✔
2547
  }
2548
  return 0;
2549
}
2550

2551
//! Get the bounding box of a mesh
2552
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
154✔
2553
{
2554
  if (int err = check_mesh(index))
154!
2555
    return err;
2556

2557
  BoundingBox bbox = model::meshes[index]->bounding_box();
154✔
2558

2559
  // set lower left corner values
2560
  ll[0] = bbox.min.x;
154✔
2561
  ll[1] = bbox.min.y;
154✔
2562
  ll[2] = bbox.min.z;
154✔
2563

2564
  // set upper right corner values
2565
  ur[0] = bbox.max.x;
154✔
2566
  ur[1] = bbox.max.y;
154✔
2567
  ur[2] = bbox.max.z;
154✔
2568
  return 0;
154✔
2569
}
2570

2571
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
187✔
2572
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2573
{
2574
  if (int err = check_mesh(index))
187!
2575
    return err;
2576

2577
  try {
187✔
2578
    model::meshes[index]->material_volumes(
187✔
2579
      nx, ny, nz, table_size, materials, volumes, bboxes);
2580
  } catch (const std::exception& e) {
11!
2581
    set_errmsg(e.what());
11✔
2582
    if (starts_with(e.what(), "Mesh")) {
11!
2583
      return OPENMC_E_GEOMETRY;
11✔
2584
    } else {
UNCOV
2585
      return OPENMC_E_ALLOCATE;
×
2586
    }
2587
  }
11✔
2588

2589
  return 0;
2590
}
2591

2592
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2593
  Position width, int basis, int* pixels, int32_t* data)
2594
{
2595
  if (int err = check_mesh(index))
44!
2596
    return err;
2597
  const auto& mesh = model::meshes[index].get();
44!
2598

2599
  int pixel_width = pixels[0];
44✔
2600
  int pixel_height = pixels[1];
44✔
2601

2602
  // get pixel size
2603
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2604
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2605

2606
  // setup basis indices and initial position centered on pixel
2607
  int in_i, out_i;
44✔
2608
  Position xyz = origin;
44✔
2609
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2610
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2611
  switch (basis_enum) {
44!
2612
  case PlotBasis::xy:
2613
    in_i = 0;
2614
    out_i = 1;
2615
    break;
2616
  case PlotBasis::xz:
2617
    in_i = 0;
2618
    out_i = 2;
2619
    break;
2620
  case PlotBasis::yz:
2621
    in_i = 1;
2622
    out_i = 2;
2623
    break;
2624
  default:
×
UNCOV
2625
    UNREACHABLE();
×
2626
  }
2627

2628
  // set initial position
2629
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2630
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2631

2632
#pragma omp parallel
24✔
2633
  {
20✔
2634
    Position r = xyz;
20✔
2635

2636
#pragma omp for
2637
    for (int y = 0; y < pixel_height; y++) {
420✔
2638
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2639
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2640
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2641
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2642
      }
2643
    }
2644
  }
2645

2646
  return 0;
44✔
2647
}
2648

2649
//! Get the dimension of a regular mesh
2650
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2651
  int32_t index, int** dims, int* n)
2652
{
2653
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2654
    return err;
2655
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2656
  *dims = mesh->shape_.data();
11✔
2657
  *n = mesh->n_dimension_;
11✔
2658
  return 0;
11✔
2659
}
2660

2661
//! Set the dimension of a regular mesh
2662
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2663
  int32_t index, int n, const int* dims)
2664
{
2665
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2666
    return err;
2667
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2668

2669
  // Copy dimension
2670
  mesh->n_dimension_ = n;
187✔
2671
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2672
  return 0;
187✔
2673
}
2674

2675
//! Get the regular mesh parameters
2676
extern "C" int openmc_regular_mesh_get_params(
209✔
2677
  int32_t index, double** ll, double** ur, double** width, int* n)
2678
{
2679
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2680
    return err;
2681
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2682

2683
  if (m->lower_left_.empty()) {
209!
2684
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2685
    return OPENMC_E_ALLOCATE;
×
2686
  }
2687

2688
  *ll = m->lower_left_.data();
209✔
2689
  *ur = m->upper_right_.data();
209✔
2690
  *width = m->width_.data();
209✔
2691
  *n = m->n_dimension_;
209✔
2692
  return 0;
209✔
2693
}
2694

2695
//! Set the regular mesh parameters
2696
extern "C" int openmc_regular_mesh_set_params(
220✔
2697
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2698
{
2699
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2700
    return err;
2701
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2702

2703
  if (m->n_dimension_ == -1) {
220!
2704
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
UNCOV
2705
    return OPENMC_E_UNASSIGNED;
×
2706
  }
2707

2708
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2709
  if (ll && ur) {
220✔
2710
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2711
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2712
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2713
  } else if (ll && width) {
22✔
2714
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2715
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2716
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2717
  } else if (ur && width) {
11!
2718
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2719
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2720
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2721
  } else {
2722
    set_errmsg("At least two parameters must be specified.");
×
UNCOV
2723
    return OPENMC_E_INVALID_ARGUMENT;
×
2724
  }
2725

2726
  // Set material volumes
2727

2728
  // TODO: incorporate this into method in RegularMesh that can be called from
2729
  // here and from constructor
2730
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2731
  m->element_volume_ = 1.0;
220✔
2732
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2733
    m->element_volume_ *= m->width_[i];
660✔
2734
  }
2735

2736
  return 0;
2737
}
220✔
2738

2739
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2740
template<class C>
2741
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2742
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2743
  const int nz)
2744
{
2745
  if (int err = check_mesh_type<C>(index))
88!
2746
    return err;
2747

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

2750
  m->n_dimension_ = 3;
88✔
2751

2752
  m->grid_[0].reserve(nx);
88✔
2753
  m->grid_[1].reserve(ny);
88✔
2754
  m->grid_[2].reserve(nz);
88✔
2755

2756
  for (int i = 0; i < nx; i++) {
572✔
2757
    m->grid_[0].push_back(grid_x[i]);
484✔
2758
  }
2759
  for (int i = 0; i < ny; i++) {
341✔
2760
    m->grid_[1].push_back(grid_y[i]);
253✔
2761
  }
2762
  for (int i = 0; i < nz; i++) {
319✔
2763
    m->grid_[2].push_back(grid_z[i]);
231✔
2764
  }
2765

2766
  int err = m->set_grid();
88✔
2767
  return err;
88✔
2768
}
2769

2770
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2771
template<class C>
2772
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2773
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2774
{
2775
  if (int err = check_mesh_type<C>(index))
385!
2776
    return err;
2777
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2778

2779
  if (m->lower_left_.empty()) {
385!
2780
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2781
    return OPENMC_E_ALLOCATE;
×
2782
  }
2783

2784
  *grid_x = m->grid_[0].data();
385✔
2785
  *nx = m->grid_[0].size();
385✔
2786
  *grid_y = m->grid_[1].data();
385✔
2787
  *ny = m->grid_[1].size();
385✔
2788
  *grid_z = m->grid_[2].data();
385✔
2789
  *nz = m->grid_[2].size();
385✔
2790

2791
  return 0;
385✔
2792
}
2793

2794
//! Get the rectilinear mesh grid
2795
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2796
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2797
{
2798
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2799
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2800
}
2801

2802
//! Set the rectilienar mesh parameters
2803
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2804
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2805
  const double* grid_z, const int nz)
2806
{
2807
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2808
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2809
}
2810

2811
//! Get the cylindrical mesh grid
2812
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2813
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2814
{
2815
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2816
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2817
}
2818

2819
//! Set the cylindrical mesh parameters
2820
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2821
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2822
  const double* grid_z, const int nz)
2823
{
2824
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2825
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2826
}
2827

2828
//! Get the spherical mesh grid
2829
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2830
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2831
{
2832

2833
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2834
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2835
  ;
121✔
2836
}
2837

2838
//! Set the spherical mesh parameters
2839
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2840
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2841
  const double* grid_z, const int nz)
2842
{
2843
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2844
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2845
}
2846

2847
#ifdef OPENMC_DAGMC_ENABLED
2848

2849
const std::string MOABMesh::mesh_lib_type = "moab";
2850

2851
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2852
{
2853
  initialize();
24✔
2854
}
24!
2855

2856
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2857
{
2858
  initialize();
×
2859
}
×
2860

2861
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2862
  : UnstructuredMesh()
×
2863
{
2864
  n_dimension_ = 3;
2865
  filename_ = filename;
×
2866
  set_length_multiplier(length_multiplier);
×
2867
  initialize();
×
2868
}
×
2869

2870
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2871
{
2872
  mbi_ = external_mbi;
1✔
2873
  filename_ = "unknown (external file)";
1✔
2874
  this->initialize();
1✔
2875
}
1!
2876

2877
void MOABMesh::initialize()
25✔
2878
{
2879

2880
  // Create the MOAB interface and load data from file
2881
  this->create_interface();
25✔
2882

2883
  // Initialise MOAB error code
2884
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2885

2886
  // Set the dimension
2887
  n_dimension_ = 3;
25✔
2888

2889
  // set member range of tetrahedral entities
2890
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2891
  if (rval != moab::MB_SUCCESS) {
25!
2892
    fatal_error("Failed to get all tetrahedral elements");
2893
  }
2894

2895
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2896
    warning("Non-tetrahedral elements found in unstructured "
×
2897
            "mesh file: " +
2898
            filename_);
2899
  }
2900

2901
  // set member range of vertices
2902
  int vertex_dim = 0;
25✔
2903
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2904
  if (rval != moab::MB_SUCCESS) {
25!
2905
    fatal_error("Failed to get all vertex handles");
2906
  }
2907

2908
  // make an entity set for all tetrahedra
2909
  // this is used for convenience later in output
2910
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2911
  if (rval != moab::MB_SUCCESS) {
25!
2912
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2913
  }
2914

2915
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2916
  if (rval != moab::MB_SUCCESS) {
25!
2917
    fatal_error("Failed to add tetrahedra to an entity set.");
2918
  }
2919

2920
  if (length_multiplier_ > 0.0) {
25!
2921
    // get the connectivity of all tets
2922
    moab::Range adj;
×
2923
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
2924
    if (rval != moab::MB_SUCCESS) {
×
2925
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2926
    }
2927
    // scale all vertex coords by multiplier (done individually so not all
2928
    // coordinates are in memory twice at once)
2929
    for (auto vert : adj) {
×
2930
      // retrieve coords
2931
      std::array<double, 3> coord;
2932
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
2933
      if (rval != moab::MB_SUCCESS) {
×
2934
        fatal_error("Could not get coordinates of vertex.");
2935
      }
2936
      // scale coords
2937
      for (auto& c : coord) {
×
2938
        c *= length_multiplier_;
2939
      }
2940
      // set new coords
2941
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2942
      if (rval != moab::MB_SUCCESS) {
×
2943
        fatal_error("Failed to set new vertex coordinates");
2944
      }
2945
    }
2946
  }
2947

2948
  // Determine bounds of mesh
2949
  this->determine_bounds();
25✔
2950
}
25✔
2951

2952
void MOABMesh::prepare_for_point_location()
21✔
2953
{
2954
  // if the KDTree has already been constructed, do nothing
2955
  if (kdtree_)
21!
2956
    return;
2957

2958
  // build acceleration data structures
2959
  compute_barycentric_data(ehs_);
21✔
2960
  build_kdtree(ehs_);
21✔
2961
}
2962

2963
void MOABMesh::create_interface()
25✔
2964
{
2965
  // Do not create a MOAB instance if one is already in memory
2966
  if (mbi_)
25✔
2967
    return;
2968

2969
  // create MOAB instance
2970
  mbi_ = std::make_shared<moab::Core>();
24!
2971

2972
  // load unstructured mesh file
2973
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
2974
  if (rval != moab::MB_SUCCESS) {
24!
2975
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2976
  }
2977
}
2978

2979
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
2980
{
2981
  moab::Range all_tris;
21✔
2982
  int adj_dim = 2;
21✔
2983
  write_message("Getting tet adjacencies...", 7);
21✔
2984
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
2985
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
2986
  if (rval != moab::MB_SUCCESS) {
21!
2987
    fatal_error("Failed to get adjacent triangles for tets");
2988
  }
2989

2990
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
2991
    warning("Non-triangle elements found in tet adjacencies in "
×
2992
            "unstructured mesh file: " +
2993
            filename_);
×
2994
  }
2995

2996
  // combine into one range
2997
  moab::Range all_tets_and_tris;
21✔
2998
  all_tets_and_tris.merge(all_tets);
21✔
2999
  all_tets_and_tris.merge(all_tris);
21✔
3000

3001
  // create a kd-tree instance
3002
  write_message(
21✔
3003
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3004
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3005

3006
  // Determine what options to use
3007
  std::ostringstream options_stream;
21✔
3008
  if (options_.empty()) {
21✔
3009
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3010
  } else {
3011
    options_stream << options_;
16✔
3012
  }
3013
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3014

3015
  // Build the k-d tree
3016
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3017
  if (rval != moab::MB_SUCCESS) {
21!
3018
    fatal_error("Failed to construct KDTree for the "
3019
                "unstructured mesh file: " +
3020
                filename_);
×
3021
  }
3022
}
21✔
3023

3024
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3025
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3026
{
3027
  hits.clear();
1,543,584!
3028

3029
  moab::ErrorCode rval;
1,543,584✔
3030
  vector<moab::EntityHandle> tris;
1,543,584✔
3031
  // get all intersections with triangles in the tet mesh
3032
  // (distances are relative to the start point, not the previous
3033
  // intersection)
3034
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3035
    dir.array(), start.array(), tris, hits, 0, track_len);
3036
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3037
    fatal_error(
3038
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3039
  }
3040

3041
  // remove duplicate intersection distances
3042
  std::unique(hits.begin(), hits.end());
1,543,584✔
3043

3044
  // sorts by first component of std::pair by default
3045
  std::sort(hits.begin(), hits.end());
1,543,584✔
3046
}
1,543,584✔
3047

3048
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3049
  vector<int>& bins, vector<double>& lengths) const
3050
{
3051
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3052
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3053
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3054
  dir.normalize();
1,543,584✔
3055

3056
  double track_len = (end - start).length();
1,543,584✔
3057
  if (track_len == 0.0)
1,543,584!
3058
    return;
721,692✔
3059

3060
  start -= TINY_BIT * dir;
1,543,584✔
3061
  end += TINY_BIT * dir;
1,543,584✔
3062

3063
  vector<double> hits;
1,543,584✔
3064
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3065

3066
  bins.clear();
1,543,584!
3067
  lengths.clear();
1,543,584!
3068

3069
  // if there are no intersections the track may lie entirely
3070
  // within a single tet. If this is the case, apply entire
3071
  // score to that tet and return.
3072
  if (hits.size() == 0) {
1,543,584✔
3073
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3074
    int bin = this->get_bin(midpoint);
721,692✔
3075
    if (bin != -1) {
721,692✔
3076
      bins.push_back(bin);
242,866✔
3077
      lengths.push_back(1.0);
242,866✔
3078
    }
3079
    return;
721,692✔
3080
  }
3081

3082
  // for each segment in the set of tracks, try to look up a tet
3083
  // at the midpoint of the segment
3084
  Position current = r0;
3085
  double last_dist = 0.0;
3086
  for (const auto& hit : hits) {
5,516,161✔
3087
    // get the segment length
3088
    double segment_length = hit - last_dist;
4,694,269✔
3089
    last_dist = hit;
4,694,269✔
3090
    // find the midpoint of this segment
3091
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3092
    // try to find a tet for this position
3093
    int bin = this->get_bin(midpoint);
4,694,269✔
3094

3095
    // determine the start point for this segment
3096
    current = r0 + u * hit;
4,694,269✔
3097

3098
    if (bin == -1) {
4,694,269✔
3099
      continue;
20,522✔
3100
    }
3101

3102
    bins.push_back(bin);
4,673,747✔
3103
    lengths.push_back(segment_length / track_len);
4,673,747✔
3104
  }
3105

3106
  // tally remaining portion of track after last hit if
3107
  // the last segment of the track is in the mesh but doesn't
3108
  // reach the other side of the tet
3109
  if (hits.back() < track_len) {
821,892!
3110
    Position segment_start = r0 + u * hits.back();
821,892✔
3111
    double segment_length = track_len - hits.back();
821,892✔
3112
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3113
    int bin = this->get_bin(midpoint);
821,892✔
3114
    if (bin != -1) {
821,892✔
3115
      bins.push_back(bin);
766,509✔
3116
      lengths.push_back(segment_length / track_len);
766,509✔
3117
    }
3118
  }
3119
};
1,543,584✔
3120

3121
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3122
{
3123
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3124
  // find the leaf of the kd-tree for this position
3125
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3126
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3127
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3128
    return 0;
3129
  }
3130

3131
  // retrieve the tet elements of this leaf
3132
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3133
  moab::Range tets;
6,305,335✔
3134
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3135
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3136
    warning("MOAB error finding tets.");
×
3137
  }
3138

3139
  // loop over the tets in this leaf, returning the containing tet if found
3140
  for (const auto& tet : tets) {
260,211,273✔
3141
    if (point_in_tet(pos, tet)) {
260,208,426✔
3142
      return tet;
6,302,488✔
3143
    }
3144
  }
3145

3146
  // if no tet is found, return an invalid handle
3147
  return 0;
2,847✔
3148
}
14,634,464✔
3149

3150
double MOABMesh::volume(int bin) const
167,880✔
3151
{
3152
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3153
}
3154

3155
std::string MOABMesh::library() const
34✔
3156
{
3157
  return mesh_lib_type;
34✔
3158
}
3159

3160
// Sample position within a tet for MOAB type tets
3161
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3162
{
3163

3164
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3165

3166
  // Get vertex coordinates for MOAB tet
3167
  const moab::EntityHandle* conn1;
200,410✔
3168
  int conn1_size;
200,410✔
3169
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3170
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3171
    fatal_error(fmt::format(
3172
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3173
      conn1_size));
3174
  }
3175
  moab::CartVect p[4];
200,410✔
3176
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3177
  if (rval != moab::MB_SUCCESS) {
200,410!
3178
    fatal_error("Failed to get tet coords");
3179
  }
3180

3181
  std::array<Position, 4> tet_verts;
200,410✔
3182
  for (int i = 0; i < 4; i++) {
1,002,050✔
3183
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3184
  }
3185
  // Samples position within tet using Barycentric stuff
3186
  return this->sample_tet(tet_verts, seed);
200,410✔
3187
}
3188

3189
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3190
{
3191
  vector<moab::EntityHandle> conn;
167,880✔
3192
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3193
  if (rval != moab::MB_SUCCESS) {
167,880!
3194
    fatal_error("Failed to get tet connectivity");
3195
  }
3196

3197
  moab::CartVect p[4];
167,880✔
3198
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3199
  if (rval != moab::MB_SUCCESS) {
167,880!
3200
    fatal_error("Failed to get tet coords");
3201
  }
3202

3203
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3204
}
167,880✔
3205

3206
int MOABMesh::get_bin(Position r) const
7,317,232✔
3207
{
3208
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3209
  if (tet == 0) {
7,317,232✔
3210
    return -1;
3211
  } else {
3212
    return get_bin_from_ent_handle(tet);
6,302,488✔
3213
  }
3214
}
3215

3216
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3217
{
3218
  moab::ErrorCode rval;
21✔
3219

3220
  baryc_data_.clear();
21!
3221
  baryc_data_.resize(tets.size());
21✔
3222

3223
  // compute the barycentric data for each tet element
3224
  // and store it as a 3x3 matrix
3225
  for (auto& tet : tets) {
239,757✔
3226
    vector<moab::EntityHandle> verts;
239,736✔
3227
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3228
    if (rval != moab::MB_SUCCESS) {
239,736!
3229
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3230
    }
3231

3232
    moab::CartVect p[4];
239,736✔
3233
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3234
    if (rval != moab::MB_SUCCESS) {
239,736!
3235
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3236
    }
3237

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

3240
    // invert now to avoid this cost later
3241
    a = a.transpose().inverse();
239,736✔
3242
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3243
  }
239,736✔
3244
}
21✔
3245

3246
bool MOABMesh::point_in_tet(
260,208,426✔
3247
  const moab::CartVect& r, moab::EntityHandle tet) const
3248
{
3249

3250
  moab::ErrorCode rval;
260,208,426✔
3251

3252
  // get tet vertices
3253
  vector<moab::EntityHandle> verts;
260,208,426✔
3254
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3255
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3256
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3257
    return false;
3258
  }
3259

3260
  // first vertex is used as a reference point for the barycentric data -
3261
  // retrieve its coordinates
3262
  moab::CartVect p_zero;
260,208,426✔
3263
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3264
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3265
    warning("Failed to get coordinates of a vertex in "
×
3266
            "unstructured mesh: " +
3267
            filename_);
×
3268
    return false;
3269
  }
3270

3271
  // look up barycentric data
3272
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3273
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3274

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

3277
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3278
          bary_coords[2] >= 0.0 &&
318,957,185✔
3279
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3280
}
260,208,426✔
3281

3282
int MOABMesh::get_bin_from_index(int idx) const
3283
{
3284
  if (idx >= n_bins()) {
×
3285
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3286
  }
3287
  return ehs_[idx] - ehs_[0];
3288
}
3289

3290
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3291
{
3292
  int bin = get_bin(r);
3293
  *in_mesh = bin != -1;
3294
  return bin;
3295
}
3296

3297
int MOABMesh::get_index_from_bin(int bin) const
3298
{
3299
  return bin;
3300
}
3301

3302
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3303
  Position plot_ll, Position plot_ur) const
3304
{
3305
  // TODO: Implement mesh lines
3306
  return {};
3307
}
3308

3309
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3310
{
3311
  int idx = vert - verts_[0];
815,520✔
3312
  if (idx >= n_vertices()) {
815,520!
3313
    fatal_error(
3314
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3315
  }
3316
  return idx;
815,520✔
3317
}
3318

3319
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3320
{
3321
  int bin = eh - ehs_[0];
266,750,650✔
3322
  if (bin >= n_bins()) {
266,750,650!
3323
    fatal_error(fmt::format("Invalid bin: {}", bin));
3324
  }
3325
  return bin;
266,750,650✔
3326
}
3327

3328
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3329
{
3330
  if (bin >= n_bins()) {
572,170!
3331
    fatal_error(fmt::format("Invalid bin index: ", bin));
3332
  }
3333
  return ehs_[0] + bin;
572,170✔
3334
}
3335

3336
int MOABMesh::n_bins() const
267,526,773✔
3337
{
3338
  return ehs_.size();
267,526,773✔
3339
}
3340

3341
int MOABMesh::n_surface_bins() const
3342
{
3343
  // collect all triangles in the set of tets for this mesh
3344
  moab::Range tris;
×
3345
  moab::ErrorCode rval;
3346
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3347
  if (rval != moab::MB_SUCCESS) {
×
3348
    warning("Failed to get all triangles in the mesh instance");
×
3349
    return -1;
3350
  }
3351
  return 2 * tris.size();
×
3352
}
3353

3354
Position MOABMesh::centroid(int bin) const
3355
{
3356
  moab::ErrorCode rval;
3357

3358
  auto tet = this->get_ent_handle_from_bin(bin);
3359

3360
  // look up the tet connectivity
3361
  vector<moab::EntityHandle> conn;
×
3362
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3363
  if (rval != moab::MB_SUCCESS) {
×
3364
    warning("Failed to get connectivity of a mesh element.");
×
3365
    return {};
3366
  }
3367

3368
  // get the coordinates
3369
  vector<moab::CartVect> coords(conn.size());
×
3370
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3371
  if (rval != moab::MB_SUCCESS) {
×
3372
    warning("Failed to get the coordinates of a mesh element.");
×
3373
    return {};
3374
  }
3375

3376
  // compute the centroid of the element vertices
3377
  moab::CartVect centroid(0.0, 0.0, 0.0);
3378
  for (const auto& coord : coords) {
×
3379
    centroid += coord;
3380
  }
3381
  centroid /= double(coords.size());
3382

3383
  return {centroid[0], centroid[1], centroid[2]};
3384
}
3385

3386
int MOABMesh::n_vertices() const
845,874✔
3387
{
3388
  return verts_.size();
845,874✔
3389
}
3390

3391
Position MOABMesh::vertex(int id) const
86,227✔
3392
{
3393

3394
  moab::ErrorCode rval;
86,227✔
3395

3396
  moab::EntityHandle vert = verts_[id];
86,227✔
3397

3398
  moab::CartVect coords;
86,227✔
3399
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3400
  if (rval != moab::MB_SUCCESS) {
86,227!
3401
    fatal_error("Failed to get the coordinates of a vertex.");
3402
  }
3403

3404
  return {coords[0], coords[1], coords[2]};
86,227✔
3405
}
3406

3407
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3408
{
3409
  moab::ErrorCode rval;
203,880✔
3410

3411
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3412

3413
  // look up the tet connectivity
3414
  vector<moab::EntityHandle> conn;
203,880✔
3415
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3416
  if (rval != moab::MB_SUCCESS) {
203,880!
3417
    fatal_error("Failed to get connectivity of a mesh element.");
3418
    return {};
3419
  }
3420

3421
  std::vector<int> verts(4);
203,880✔
3422
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3423
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3424
  }
3425

3426
  return verts;
203,880✔
3427
}
203,880✔
3428

3429
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3430
  std::string score) const
3431
{
3432
  moab::ErrorCode rval;
3433
  // add a tag to the mesh
3434
  // all scores are treated as a single value
3435
  // with an uncertainty
3436
  moab::Tag value_tag;
3437

3438
  // create the value tag if not present and get handle
3439
  double default_val = 0.0;
3440
  auto val_string = score + "_mean";
3441
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3442
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3443
  if (rval != moab::MB_SUCCESS) {
×
3444
    auto msg =
3445
      fmt::format("Could not create or retrieve the value tag for the score {}"
3446
                  " on unstructured mesh {}",
3447
        score, id_);
×
3448
    fatal_error(msg);
3449
  }
3450

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

3464
  // return the populated tag handles
3465
  return {value_tag, error_tag};
3466
}
3467

3468
void MOABMesh::add_score(const std::string& score)
3469
{
3470
  auto score_tags = get_score_tags(score);
×
3471
  tag_names_.push_back(score);
3472
}
3473

3474
void MOABMesh::remove_scores()
3475
{
3476
  for (const auto& name : tag_names_) {
×
3477
    auto value_name = name + "_mean";
3478
    moab::Tag tag;
3479
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3480
    if (rval != moab::MB_SUCCESS)
×
3481
      return;
3482

3483
    rval = mbi_->tag_delete(tag);
×
3484
    if (rval != moab::MB_SUCCESS) {
×
3485
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3486
                             " on unstructured mesh {}",
3487
        name, id_);
×
3488
      fatal_error(msg);
3489
    }
3490

3491
    auto std_dev_name = name + "_std_dev";
×
3492
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3493
    if (rval != moab::MB_SUCCESS) {
×
3494
      auto msg =
3495
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3496
                    " on unstructured mesh {}",
3497
          name, id_);
×
3498
    }
3499

3500
    rval = mbi_->tag_delete(tag);
×
3501
    if (rval != moab::MB_SUCCESS) {
×
3502
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3503
                             " on unstructured mesh {}",
3504
        name, id_);
×
3505
      fatal_error(msg);
3506
    }
3507
  }
3508
  tag_names_.clear();
3509
}
3510

3511
void MOABMesh::set_score_data(const std::string& score,
3512
  const vector<double>& values, const vector<double>& std_dev)
3513
{
3514
  auto score_tags = this->get_score_tags(score);
×
3515

3516
  moab::ErrorCode rval;
3517
  // set the score value
3518
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3519
  if (rval != moab::MB_SUCCESS) {
×
3520
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3521
                           "on unstructured mesh {}",
3522
      score, id_);
3523
    warning(msg);
×
3524
  }
3525

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

3536
void MOABMesh::write(const std::string& base_filename) const
3537
{
3538
  // add extension to the base name
3539
  auto filename = base_filename + ".vtk";
3540
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3541
  filename = settings::path_output + filename;
×
3542

3543
  // write the tetrahedral elements of the mesh only
3544
  // to avoid clutter from zero-value data on other
3545
  // elements during visualization
3546
  moab::ErrorCode rval;
3547
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3548
  if (rval != moab::MB_SUCCESS) {
×
3549
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3550
    warning(msg);
×
3551
  }
3552
}
3553

3554
#endif
3555

3556
#ifdef OPENMC_LIBMESH_ENABLED
3557

3558
const std::string LibMesh::mesh_lib_type = "libmesh";
3559

3560
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
23✔
3561
{
3562
  // filename_ and length_multiplier_ will already be set by the
3563
  // UnstructuredMesh constructor
3564
  set_mesh_pointer_from_filename(filename_);
23✔
3565
  set_length_multiplier(length_multiplier_);
23✔
3566
  initialize();
23✔
3567
}
23✔
3568

3569
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3570
{
3571
  // filename_ and length_multiplier_ will already be set by the
3572
  // UnstructuredMesh constructor
3573
  set_mesh_pointer_from_filename(filename_);
×
3574
  set_length_multiplier(length_multiplier_);
×
3575
  initialize();
×
3576
}
3577

3578
// create the mesh from a pointer to a libMesh Mesh
3579
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3580
{
3581
  if (!input_mesh.is_replicated()) {
×
3582
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3583
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3584
  }
3585

3586
  m_ = &input_mesh;
3587
  set_length_multiplier(length_multiplier);
×
3588
  initialize();
×
3589
}
3590

3591
// create the mesh from an input file
3592
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3593
{
3594
  n_dimension_ = 3;
3595
  set_mesh_pointer_from_filename(filename);
×
3596
  set_length_multiplier(length_multiplier);
×
3597
  initialize();
×
3598
}
3599

3600
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
23✔
3601
{
3602
  filename_ = filename;
23✔
3603
  unique_m_ =
23✔
3604
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
23✔
3605
  m_ = unique_m_.get();
23✔
3606
  m_->read(filename_);
23✔
3607
}
23✔
3608

3609
// build a libMesh equation system for storing values
3610
void LibMesh::build_eqn_sys()
15✔
3611
{
3612
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
15✔
3613
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
15✔
3614
  libMesh::ExplicitSystem& eq_sys =
15✔
3615
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
15✔
3616
}
15✔
3617

3618
// intialize from mesh file
3619
void LibMesh::initialize()
23✔
3620
{
3621
  if (!settings::libmesh_comm) {
23!
3622
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3623
                "communicator.");
3624
  }
3625

3626
  // assuming that unstructured meshes used in OpenMC are 3D
3627
  n_dimension_ = 3;
23✔
3628

3629
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3630
  // Otherwise assume that it is prepared by its owning application
3631
  if (unique_m_) {
23!
3632
    m_->prepare_for_use();
23✔
3633
  }
3634

3635
  // ensure that the loaded mesh is 3 dimensional
3636
  if (m_->mesh_dimension() != n_dimension_) {
23!
3637
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3638
                            "mesh is not a 3D mesh.",
3639
      filename_));
3640
  }
3641

3642
  for (int i = 0; i < num_threads(); i++) {
69✔
3643
    pl_.emplace_back(m_->sub_point_locator());
46✔
3644
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46✔
3645
    pl_.back()->enable_out_of_mesh_mode();
46✔
3646
  }
3647

3648
  // store first element in the mesh to use as an offset for bin indices
3649
  auto first_elem = *m_->elements_begin();
46✔
3650
  first_element_id_ = first_elem->id();
23✔
3651

3652
  // bounding box for the mesh for quick rejection checks
3653
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
23!
3654
  libMesh::Point ll = bbox_.min();
23!
3655
  libMesh::Point ur = bbox_.max();
23!
3656
  if (length_multiplier_ > 0.0) {
23!
3657
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3658
      length_multiplier_ * ll(2)};
3659
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3660
      length_multiplier_ * ur(2)};
3661
  } else {
3662
    lower_left_ = {ll(0), ll(1), ll(2)};
23✔
3663
    upper_right_ = {ur(0), ur(1), ur(2)};
23✔
3664
  }
3665
}
23✔
3666

3667
// Sample position within a tet for LibMesh type tets
3668
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3669
{
3670
  const auto& elem = get_element_from_bin(bin);
400,820✔
3671
  // Get tet vertex coordinates from LibMesh
3672
  std::array<Position, 4> tet_verts;
400,820✔
3673
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3674
    auto node_ref = elem.node_ref(i);
1,603,280✔
3675
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3676
  }
1,603,280✔
3677
  // Samples position within tet using Barycentric coordinates
3678
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3679
  if (length_multiplier_ > 0.0) {
400,820!
3680
    return length_multiplier_ * sampled_position;
3681
  } else {
3682
    return sampled_position;
400,820✔
3683
  }
3684
}
3685

3686
Position LibMesh::centroid(int bin) const
3687
{
3688
  const auto& elem = this->get_element_from_bin(bin);
3689
  auto centroid = elem.vertex_average();
3690
  if (length_multiplier_ > 0.0) {
×
3691
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3692
  } else {
3693
    return {centroid(0), centroid(1), centroid(2)};
3694
  }
3695
}
3696

3697
int LibMesh::n_vertices() const
39,978✔
3698
{
3699
  return m_->n_nodes();
39,978✔
3700
}
3701

3702
Position LibMesh::vertex(int vertex_id) const
39,942✔
3703
{
3704
  const auto node_ref = m_->node_ref(vertex_id);
39,942✔
3705
  if (length_multiplier_ > 0.0) {
39,942!
3706
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3707
  } else {
3708
    return {node_ref(0), node_ref(1), node_ref(2)};
39,942✔
3709
  }
3710
}
39,942✔
3711

3712
std::vector<int> LibMesh::connectivity(int elem_id) const
265,856✔
3713
{
3714
  std::vector<int> conn;
265,856✔
3715
  const auto* elem_ptr = m_->elem_ptr(elem_id);
265,856✔
3716
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,337,280✔
3717
    conn.push_back(elem_ptr->node_id(i));
1,071,424✔
3718
  }
3719
  return conn;
265,856✔
3720
}
3721

3722
std::string LibMesh::library() const
33✔
3723
{
3724
  return mesh_lib_type;
33✔
3725
}
3726

3727
int LibMesh::n_bins() const
1,784,407✔
3728
{
3729
  return m_->n_elem();
1,784,407✔
3730
}
3731

3732
int LibMesh::n_surface_bins() const
3733
{
3734
  int n_bins = 0;
3735
  for (int i = 0; i < this->n_bins(); i++) {
×
3736
    const libMesh::Elem& e = get_element_from_bin(i);
3737
    n_bins += e.n_faces();
3738
    // if this is a boundary element, it will only be visited once,
3739
    // the number of surface bins is incremented to
3740
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3741
      // null neighbor pointer indicates a boundary face
3742
      if (!neighbor_ptr) {
×
3743
        n_bins++;
3744
      }
3745
    }
3746
  }
3747
  return n_bins;
3748
}
3749

3750
void LibMesh::add_score(const std::string& var_name)
15✔
3751
{
3752
  if (!equation_systems_) {
15!
3753
    build_eqn_sys();
15✔
3754
  }
3755

3756
  // check if this is a new variable
3757
  std::string value_name = var_name + "_mean";
15✔
3758
  if (!variable_map_.count(value_name)) {
15✔
3759
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3760
    auto var_num =
15✔
3761
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
15✔
3762
    variable_map_[value_name] = var_num;
15✔
3763
  }
3764

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

3775
void LibMesh::remove_scores()
15✔
3776
{
3777
  if (equation_systems_) {
15!
3778
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3779
    eqn_sys.clear();
15✔
3780
    variable_map_.clear();
15✔
3781
  }
3782
}
15✔
3783

3784
void LibMesh::set_score_data(const std::string& var_name,
15✔
3785
  const vector<double>& values, const vector<double>& std_dev)
3786
{
3787
  if (!equation_systems_) {
15!
3788
    build_eqn_sys();
3789
  }
3790

3791
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
15✔
3792

3793
  if (!eqn_sys.is_initialized()) {
15!
3794
    equation_systems_->init();
15✔
3795
  }
3796

3797
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
15✔
3798

3799
  // look up the value variable
3800
  std::string value_name = var_name + "_mean";
15✔
3801
  unsigned int value_num = variable_map_.at(value_name);
15✔
3802
  // look up the std dev variable
3803
  std::string std_dev_name = var_name + "_std_dev";
15✔
3804
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
15✔
3805

3806
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
195,757✔
3807
       it++) {
3808
    if (!(*it)->active()) {
97,856!
3809
      continue;
3810
    }
3811

3812
    auto bin = get_bin_from_element(*it);
97,856✔
3813

3814
    // set value
3815
    vector<libMesh::dof_id_type> value_dof_indices;
97,856✔
3816
    dof_map.dof_indices(*it, value_dof_indices, value_num);
97,856✔
3817
    assert(value_dof_indices.size() == 1);
97,856✔
3818
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
97,856✔
3819

3820
    // set std dev
3821
    vector<libMesh::dof_id_type> std_dev_dof_indices;
97,856✔
3822
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
97,856✔
3823
    assert(std_dev_dof_indices.size() == 1);
97,856✔
3824
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
97,856✔
3825
  }
97,871✔
3826
}
15✔
3827

3828
void LibMesh::write(const std::string& filename) const
15✔
3829
{
3830
  write_message(fmt::format(
15✔
3831
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
15✔
3832
  libMesh::ExodusII_IO exo(*m_);
15✔
3833
  std::set<std::string> systems_out = {eq_system_name_};
30!
3834
  exo.write_discontinuous_exodusII(
15✔
3835
    filename + ".e", *equation_systems_, &systems_out);
30✔
3836
}
15✔
3837

3838
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3839
  vector<int>& bins, vector<double>& lengths) const
3840
{
3841
  // TODO: Implement triangle crossings here
3842
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3843
}
3844

3845
int LibMesh::get_bin(Position r) const
2,340,604✔
3846
{
3847
  // look-up a tet using the point locator
3848
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3849

3850
  if (length_multiplier_ > 0.0) {
2,340,604!
3851
    // Scale the point down
3852
    p /= length_multiplier_;
2,340,604✔
3853
  }
3854

3855
  // quick rejection check
3856
  if (!bbox_.contains_point(p)) {
2,340,604✔
3857
    return -1;
3858
  }
3859

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

3862
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3863
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3864
}
2,340,604✔
3865

3866
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,518,434✔
3867
{
3868
  int bin = elem->id() - first_element_id_;
1,518,434✔
3869
  if (bin >= n_bins() || bin < 0) {
1,518,434!
3870
    fatal_error(fmt::format("Invalid bin: {}", bin));
3871
  }
3872
  return bin;
1,518,434✔
3873
}
3874

3875
std::pair<vector<double>, vector<double>> LibMesh::plot(
3876
  Position plot_ll, Position plot_ur) const
3877
{
3878
  return {};
3879
}
3880

3881
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
765,460✔
3882
{
3883
  return m_->elem_ref(bin);
765,460✔
3884
}
3885

3886
double LibMesh::volume(int bin) const
364,640✔
3887
{
3888
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
364,640✔
3889
         length_multiplier_ * length_multiplier_;
364,640✔
3890
}
3891

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

3919
int AdaptiveLibMesh::n_bins() const
3920
{
3921
  return num_active_;
3922
}
3923

3924
void AdaptiveLibMesh::add_score(const std::string& var_name)
3925
{
3926
  warning(fmt::format(
×
3927
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3928
    this->id_));
3929
}
3930

3931
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3932
  const vector<double>& values, const vector<double>& std_dev)
3933
{
3934
  warning(fmt::format(
×
3935
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3936
    this->id_));
3937
}
3938

3939
void AdaptiveLibMesh::write(const std::string& filename) const
3940
{
3941
  warning(fmt::format(
×
3942
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3943
    this->id_));
3944
}
3945

3946
int AdaptiveLibMesh::get_bin(Position r) const
3947
{
3948
  // look-up a tet using the point locator
3949
  libMesh::Point p(r.x, r.y, r.z);
×
3950

3951
  if (length_multiplier_ > 0.0) {
×
3952
    // Scale the point down
3953
    p /= length_multiplier_;
3954
  }
3955

3956
  // quick rejection check
3957
  if (!bbox_.contains_point(p)) {
×
3958
    return -1;
3959
  }
3960

3961
  const auto& point_locator = pl_.at(thread_num());
×
3962

3963
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3964
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3965
}
3966

3967
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3968
{
3969
  int bin = elem_to_bin_map_[elem->id()];
3970
  if (bin >= n_bins() || bin < 0) {
×
3971
    fatal_error(fmt::format("Invalid bin: {}", bin));
3972
  }
3973
  return bin;
3974
}
3975

3976
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3977
{
3978
  return m_->elem_ref(bin_to_elem_map_.at(bin));
3979
}
3980

3981
#endif // OPENMC_LIBMESH_ENABLED
3982

3983
//==============================================================================
3984
// Non-member functions
3985
//==============================================================================
3986

3987
void read_meshes(pugi::xml_node root)
12,639✔
3988
{
3989
  std::unordered_set<int> mesh_ids;
12,639✔
3990

3991
  for (auto node : root.children("mesh")) {
15,624✔
3992
    // Check to make sure multiple meshes in the same file don't share IDs
3993
    int id = std::stoi(get_node_value(node, "id"));
5,970✔
3994
    if (contains(mesh_ids, id)) {
5,970!
UNCOV
3995
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
3996
                              "'{}' in the same input file",
3997
        id));
3998
    }
3999
    mesh_ids.insert(id);
2,985✔
4000

4001
    // If we've already read a mesh with the same ID in a *different* file,
4002
    // assume it is the same here
4003
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
2,985!
4004
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
UNCOV
4005
      continue;
×
4006
    }
4007

4008
    std::string mesh_type;
2,985✔
4009
    if (check_for_node(node, "type")) {
2,985✔
4010
      mesh_type = get_node_value(node, "type", true, true);
948✔
4011
    } else {
4012
      mesh_type = "regular";
2,037✔
4013
    }
4014

4015
    // determine the mesh library to use
4016
    std::string mesh_lib;
2,985✔
4017
    if (check_for_node(node, "library")) {
2,985✔
4018
      mesh_lib = get_node_value(node, "library", true, true);
47!
4019
    }
4020

4021
    Mesh::create(node, mesh_type, mesh_lib);
2,985✔
4022
  }
2,985✔
4023
}
12,639✔
4024

4025
void read_meshes(hid_t group)
22✔
4026
{
4027
  std::unordered_set<int> mesh_ids;
22✔
4028

4029
  std::vector<int> ids;
22✔
4030
  read_attribute(group, "ids", ids);
22✔
4031

4032
  for (auto id : ids) {
55✔
4033

4034
    // Check to make sure multiple meshes in the same file don't share IDs
4035
    if (contains(mesh_ids, id)) {
66!
UNCOV
4036
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4037
                              "'{}' in the same HDF5 input file",
4038
        id));
4039
    }
4040
    mesh_ids.insert(id);
33✔
4041

4042
    // If we've already read a mesh with the same ID in a *different* file,
4043
    // assume it is the same here
4044
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33!
4045
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4046
      continue;
33✔
4047
    }
4048

4049
    std::string name = fmt::format("mesh {}", id);
×
UNCOV
4050
    hid_t mesh_group = open_group(group, name.c_str());
×
4051

4052
    std::string mesh_type;
×
4053
    if (object_exists(mesh_group, "type")) {
×
UNCOV
4054
      read_dataset(mesh_group, "type", mesh_type);
×
4055
    } else {
UNCOV
4056
      mesh_type = "regular";
×
4057
    }
4058

4059
    // determine the mesh library to use
4060
    std::string mesh_lib;
×
4061
    if (object_exists(mesh_group, "library")) {
×
UNCOV
4062
      read_dataset(mesh_group, "library", mesh_lib);
×
4063
    }
4064

4065
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
UNCOV
4066
  }
×
4067
}
44✔
4068

4069
void meshes_to_hdf5(hid_t group)
7,049✔
4070
{
4071
  // Write number of meshes
4072
  hid_t meshes_group = create_group(group, "meshes");
7,049✔
4073
  int32_t n_meshes = model::meshes.size();
7,049✔
4074
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,049✔
4075

4076
  if (n_meshes > 0) {
7,049✔
4077
    // Write IDs of meshes
4078
    vector<int> ids;
2,170✔
4079
    for (const auto& m : model::meshes) {
4,919✔
4080
      m->to_hdf5(meshes_group);
2,749✔
4081
      ids.push_back(m->id_);
2,749✔
4082
    }
4083
    write_attribute(meshes_group, "ids", ids);
2,170✔
4084
  }
2,170✔
4085

4086
  close_group(meshes_group);
7,049✔
4087
}
7,049✔
4088

4089
void free_memory_mesh()
8,287✔
4090
{
4091
  model::meshes.clear();
8,287✔
4092
  model::mesh_map.clear();
8,287✔
4093
}
8,287✔
4094

4095
extern "C" int n_meshes()
308✔
4096
{
4097
  return model::meshes.size();
308✔
4098
}
4099

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

© 2026 Coveralls, Inc