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

openmc-dev / openmc / 26783682952

01 Jun 2026 09:39PM UTC coverage: 81.37% (+0.04%) from 81.333%
26783682952

Pull #3948

github

web-flow
Merge 4c502fee3 into 111eb7706
Pull Request #3948: Fix get_index_in_direction for regular meshes

18031 of 26121 branches covered (69.03%)

Branch coverage included in aggregate %.

30 of 32 new or added lines in 9 files covered. (93.75%)

533 existing lines in 14 files now uncovered.

59192 of 68782 relevant lines covered (86.06%)

48604925.37 hits per line

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

70.38
/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/memory.h"
32
#include "openmc/message_passing.h"
33
#include "openmc/openmp_interface.h"
34
#include "openmc/output.h"
35
#include "openmc/particle_data.h"
36
#include "openmc/plot.h"
37
#include "openmc/random_dist.h"
38
#include "openmc/search.h"
39
#include "openmc/settings.h"
40
#include "openmc/string_utils.h"
41
#include "openmc/tallies/filter.h"
42
#include "openmc/tallies/tally.h"
43
#include "openmc/timer.h"
44
#include "openmc/volume_calc.h"
45
#include "openmc/xml_interface.h"
46

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

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

58
namespace openmc {
59

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

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

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

74
namespace model {
75

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

79
} // namespace model
80

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

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

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

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

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

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

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

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

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

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

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

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

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

197
namespace detail {
198

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

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

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

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

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

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

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

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

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

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

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

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

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

326
} // namespace detail
327

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

556
            // Add volumes to any mesh elements that were crossed
557
            int i_material = p.material();
3,865,155✔
558
            if (i_material != C_NONE) {
3,865,155✔
559
              i_material = model::materials[i_material]->id();
1,216,725✔
560
            }
561
            double cumulative_frac = 0.0;
3,865,155✔
562
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
7,948,960✔
563
              int mesh_index = bins[i_bin];
4,083,805✔
564
              double length = distance * length_fractions[i_bin];
4,083,805✔
565
              double volume = length * d1 * d2;
4,083,805✔
566

567
              if (compute_bboxes) {
4,083,805✔
568
                double axis_start = r0[axis] + distance * cumulative_frac;
2,877,720✔
569
                double axis_end = axis_start + length;
2,877,720✔
570
                cumulative_frac += length_fractions[i_bin];
2,877,720✔
571

572
                Position contrib_min = site.r;
2,877,720✔
573
                Position contrib_max = site.r;
2,877,720✔
574

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

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

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

593
            if (distance == max_distance)
3,865,155✔
594
              break;
595

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

761
  if (n_dimension_ > 2) {
5,160,280✔
762
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,144,341✔
763
  } else if (n_dimension_ > 1) {
15,939✔
764
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
15,664✔
765
  } else {
766
    return fmt::format("Mesh Index ({})", ijk[0]);
275✔
767
  }
768
}
769

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

965
  int num_elem_skipped = 0;
34✔
966

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

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

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

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

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

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

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

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

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

1033
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1034
      in_mesh = false;
105,112,662✔
1035
  }
1036
  return ijk;
1,583,413,687✔
1037
}
1038

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

1053
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
7,814,495✔
1054
{
1055
  MeshIndex ijk;
7,814,495✔
1056
  if (n_dimension_ == 1) {
7,814,495✔
1057
    ijk[0] = bin + 1;
275✔
1058
  } else if (n_dimension_ == 2) {
7,814,220✔
1059
    ijk[0] = bin % shape_[0] + 1;
15,664✔
1060
    ijk[1] = bin / shape_[0] + 1;
15,664✔
1061
  } else if (n_dimension_ == 3) {
7,798,556!
1062
    ijk[0] = bin % shape_[0] + 1;
7,798,556✔
1063
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
7,798,556✔
1064
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
7,798,556✔
1065
  }
1066
  return ijk;
7,814,495✔
1067
}
1068

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

1077
  // Convert indices to bin
1078
  return get_bin_from_indices(ijk);
387,399,315✔
1079
}
1080

1081
int StructuredMesh::n_bins() const
1,137,913✔
1082
{
1083
  return std::accumulate(
2,275,826✔
1084
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
1,137,913✔
1085
}
1086

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

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

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

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

1106
    // determine scoring bin for entropy mesh
NEW
1107
    int mesh_bin = get_bin(site.r, site.u);
×
1108

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

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

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

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

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

1138
  return counts;
×
1139
}
×
1140

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

1154
  // Compute the length of the entire track.
1155
  double total_distance = (r1 - r0).norm();
1,211,798,159✔
1156
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,211,798,159✔
1157
    return;
1158

1159
  // keep a copy of the original global position to pass to get_indices,
1160
  // which performs its own transformation to local coordinates
1161
  Position global_r = r0;
1,167,729,875✔
1162
  Position local_r = local_coords(r0);
1,167,729,875✔
1163

1164
  const int n = n_dimension_;
1,167,729,875✔
1165

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

1169
  // Position is r = r0 + u * traveled_distance, start at r0
1170
  double traveled_distance {0.0};
1,167,729,875✔
1171

1172
  // Calculate index of current cell. Offset the position a tiny bit in
1173
  // direction of flight
1174
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, u, in_mesh);
1,167,729,875✔
1175

1176
  // if track is very short, assume that it is completely inside one cell.
1177
  // Only the current cell will score and no surfaces
1178
  if (total_distance < 2 * TINY_BIT) {
1,167,729,875✔
1179
    if (in_mesh) {
361,843✔
1180
      tally.track(ijk, 1.0);
361,359✔
1181
    }
1182
    return;
361,843✔
1183
  }
1184

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

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

1194
    if (in_mesh) {
1,965,241,007✔
1195

1196
      // find surface with minimal distance to current position
1197
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,876,324,099✔
1198
                     distances.begin();
1,876,324,099✔
1199

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

1205
      // update position and leave, if we have reached end position
1206
      traveled_distance = distances[k].distance;
1,876,324,099✔
1207
      if (traveled_distance >= total_distance)
1,876,324,099✔
1208
        return;
1209

1210
      // If we have not reached r1, we have hit a surface. Tally outward
1211
      // current
1212
      tally.surface(ijk, k, distances[k].max_surface, false);
790,608,575✔
1213

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

1220
      // Check if we have left the interior of the mesh
1221
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
797,515,353✔
1222

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

1228
    } else { // not inside mesh
1229

1230
      // For all directions outside the mesh, find the distance that we need
1231
      // to travel to reach the next surface. Use the largest distance, as
1232
      // only this will cross all outer surfaces.
1233
      int k_max {-1};
1234
      for (int k = 0; k < n; ++k) {
354,223,266✔
1235
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
265,306,358✔
1236
            (distances[k].distance > traveled_distance)) {
96,924,823✔
1237
          traveled_distance = distances[k].distance;
1238
          k_max = k;
1239
        }
1240
      }
1241
      // Assure some distance is traveled
1242
      if (k_max == -1) {
88,916,908✔
1243
        traveled_distance += TINY_BIT;
110✔
1244
      }
1245

1246
      // If r1 is not inside the mesh, exit here
1247
      if (traveled_distance >= total_distance)
88,916,908✔
1248
        return;
1249

1250
      // Calculate the new cell index and update all distances to next
1251
      // surfaces.
1252
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, u, in_mesh);
7,264,400✔
1253
      for (int k = 0; k < n; ++k) {
28,849,062✔
1254
        distances[k] =
21,584,662✔
1255
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,584,662✔
1256
      }
1257

1258
      // If inside the mesh, Tally inward current
1259
      if (in_mesh && k_max >= 0)
7,264,400!
1260
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
768,273,108✔
1261
    }
1262
  }
1263
}
1264

1265
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,099,670,594✔
1266
  vector<int>& bins, vector<double>& lengths) const
1267
{
1268

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

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

1289
  // Perform the mesh raytrace with the helper class.
1290
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,099,670,594✔
1291
}
1,099,670,594✔
1292

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

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

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

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

1324
//==============================================================================
1325
// RegularMesh implementation
1326
//==============================================================================
1327

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

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

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

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

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

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

1363
  } else if (upper_right_.size() > 0) {
2,329!
1364

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

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

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

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

1387
  element_volume_ = 1.0;
2,375✔
1388
  for (int i = 0; i < n_dimension_; i++) {
8,953✔
1389
    element_volume_ *= width_[i];
6,578✔
1390
  }
1391
  return 0;
1392
}
2,375✔
1393

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

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

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

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

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

1424
  } else if (check_for_node(node, "upper_right")) {
2,318!
1425

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

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

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

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

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

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

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

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

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

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

1473
int RegularMesh::get_index_in_direction(double r, double u, int i) const
2,147,483,647✔
1474
{
1475
  int idx = std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1476

1477
  // If on upper boundary with positive direction, use next index
1478
  if (r == lower_left_[i] + width_[i] * idx) {
2,147,483,647✔
1479
    if (u > 0.0) {
278,828✔
1480
      idx++;
146,492✔
1481
    }
1482
  }
1483

1484
  return idx;
2,147,483,647✔
1485
}
1486

1487
const std::string RegularMesh::mesh_type = "regular";
1488

1489
std::string RegularMesh::get_mesh_type() const
3,478✔
1490
{
1491
  return mesh_type;
3,478✔
1492
}
1493

1494
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,863,794,552✔
1495
{
1496
  return lower_left_[i] + ijk[i] * width_[i];
1,863,794,552✔
1497
}
1498

1499
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,794,714,351✔
1500
{
1501
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,794,714,351✔
1502
}
1503

1504
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1505
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1506
  double l) const
1507
{
1508
  MeshDistance d;
2,147,483,647✔
1509
  d.next_index = ijk[i];
2,147,483,647✔
1510
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1511
    return d;
15,240,792✔
1512

1513
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1514
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1515
    d.next_index++;
1,859,473,730✔
1516
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,859,473,730✔
1517
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,813,385,042✔
1518
    d.next_index--;
1,790,393,529✔
1519
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,790,393,529✔
1520
  }
1521

1522
  return d;
2,147,483,647✔
1523
}
1524

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

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

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

1563
  return {axis_lines[0], axis_lines[1]};
44✔
1564
}
1565

1566
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,323✔
1567
{
1568
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,323✔
1569
  write_dataset(mesh_group, "lower_left", lower_left_);
2,323✔
1570
  write_dataset(mesh_group, "upper_right", upper_right_);
2,323✔
1571
  write_dataset(mesh_group, "width", width_);
2,323✔
1572
}
2,323✔
1573

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

1581
  // Create array of zeros
1582
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1583
  bool outside_ = false;
2,892✔
1584

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

1588
    // determine scoring bin for entropy mesh
1589
    int mesh_bin = get_bin(site.r, site.u);
7,667,451✔
1590

1591
    // if outside mesh, skip particle
1592
    if (mesh_bin < 0) {
7,667,451!
UNCOV
1593
      outside_ = true;
×
1594
      continue;
×
1595
    }
1596

1597
    // Add to appropriate bin
1598
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1599
  }
1600

1601
  // Create reduced count data
1602
  auto counts = tensor::zeros<double>(shape);
7,820✔
1603
  int total = cnt.size();
7,820✔
1604

1605
#ifdef OPENMC_MPI
1606
  // collect values from all processors
1607
  MPI_Reduce(
2,892✔
1608
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1609

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

1620
  return counts;
7,820✔
1621
}
7,820✔
1622

1623
double RegularMesh::volume(const MeshIndex& ijk) const
1,123,862✔
1624
{
1625
  return element_volume_;
1,123,862✔
1626
}
1627

1628
//==============================================================================
1629
// RectilinearMesh implementation
1630
//==============================================================================
1631

1632
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133✔
1633
{
1634
  n_dimension_ = 3;
133✔
1635

1636
  grid_[0] = get_node_array<double>(node, "x_grid");
133✔
1637
  grid_[1] = get_node_array<double>(node, "y_grid");
133✔
1638
  grid_[2] = get_node_array<double>(node, "z_grid");
133✔
1639

1640
  if (int err = set_grid()) {
133!
UNCOV
1641
    fatal_error(openmc_err_msg);
×
1642
  }
1643
}
133✔
1644

1645
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1646
{
1647
  n_dimension_ = 3;
11✔
1648

1649
  read_dataset(group, "x_grid", grid_[0]);
11✔
1650
  read_dataset(group, "y_grid", grid_[1]);
11✔
1651
  read_dataset(group, "z_grid", grid_[2]);
11✔
1652

1653
  if (int err = set_grid()) {
11!
UNCOV
1654
    fatal_error(openmc_err_msg);
×
1655
  }
1656
}
11✔
1657

1658
const std::string RectilinearMesh::mesh_type = "rectilinear";
1659

1660
std::string RectilinearMesh::get_mesh_type() const
275✔
1661
{
1662
  return mesh_type;
275✔
1663
}
1664

1665
double RectilinearMesh::positive_grid_boundary(
26,505,963✔
1666
  const MeshIndex& ijk, int i) const
1667
{
1668
  return grid_[i][ijk[i]];
26,505,963✔
1669
}
1670

1671
double RectilinearMesh::negative_grid_boundary(
25,739,406✔
1672
  const MeshIndex& ijk, int i) const
1673
{
1674
  return grid_[i][ijk[i] - 1];
25,739,406✔
1675
}
1676

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

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

1697
int RectilinearMesh::set_grid()
188✔
1698
{
1699
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
188✔
1700
    static_cast<int>(grid_[1].size()) - 1,
188✔
1701
    static_cast<int>(grid_[2].size()) - 1};
188✔
1702

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

1717
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
188✔
1718
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
188✔
1719

1720
  return 0;
188✔
1721
}
1722

1723
int RectilinearMesh::get_index_in_direction(double r, double u, int i) const
74,109,046✔
1724
{
1725
  int idx = lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,109,046✔
1726

1727
  // If on lower boundary with negative direction, use previous index
1728
  if (r == grid_[i][idx - 1]) {
74,109,046✔
1729
    if (u < 0) {
22✔
1730
      idx--;
11✔
1731
    }
1732
  }
1733

1734
  // If on upper boundary with positive direction, use next index
1735
  if (r == grid_[i][idx]) {
74,109,046✔
1736
    if (u > 0) {
6,809✔
1737
      idx++;
22✔
1738
    }
1739
  }
1740

1741
  return idx;
74,109,046✔
1742
}
1743

1744
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11✔
1745
  Position plot_ll, Position plot_ur) const
1746
{
1747
  // Figure out which axes lie in the plane of the plot.
1748
  array<int, 2> axes {-1, -1};
11✔
1749
  if (plot_ur.z == plot_ll.z) {
11!
UNCOV
1750
    axes = {0, 1};
×
1751
  } else if (plot_ur.y == plot_ll.y) {
11!
1752
    axes = {0, 2};
11✔
UNCOV
1753
  } else if (plot_ur.x == plot_ll.x) {
×
1754
    axes = {1, 2};
×
1755
  } else {
UNCOV
1756
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1757
  }
1758

1759
  // Get the coordinates of the mesh lines along both of the axes.
1760
  array<vector<double>, 2> axis_lines;
1761
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1762
    int axis = axes[i_ax];
22✔
1763
    vector<double>& lines {axis_lines[i_ax]};
22✔
1764

1765
    for (auto coord : grid_[axis]) {
110✔
1766
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1767
        lines.push_back(coord);
88✔
1768
    }
1769
  }
1770

1771
  return {axis_lines[0], axis_lines[1]};
22✔
1772
}
1773

1774
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
110✔
1775
{
1776
  write_dataset(mesh_group, "x_grid", grid_[0]);
110✔
1777
  write_dataset(mesh_group, "y_grid", grid_[1]);
110✔
1778
  write_dataset(mesh_group, "z_grid", grid_[2]);
110✔
1779
}
110✔
1780

1781
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1782
{
1783
  double vol {1.0};
132✔
1784

1785
  for (int i = 0; i < n_dimension_; i++) {
528✔
1786
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1787
  }
1788
  return vol;
132✔
1789
}
1790

1791
//==============================================================================
1792
// CylindricalMesh implementation
1793
//==============================================================================
1794

1795
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
400✔
1796
  : PeriodicStructuredMesh {node}
400✔
1797
{
1798
  n_dimension_ = 3;
400✔
1799
  grid_[0] = get_node_array<double>(node, "r_grid");
400✔
1800
  grid_[1] = get_node_array<double>(node, "phi_grid");
400✔
1801
  grid_[2] = get_node_array<double>(node, "z_grid");
400✔
1802
  origin_ = get_node_position(node, "origin");
400✔
1803

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

1809
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1810
{
1811
  n_dimension_ = 3;
11✔
1812
  read_dataset(group, "r_grid", grid_[0]);
11✔
1813
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1814
  read_dataset(group, "z_grid", grid_[2]);
11✔
1815
  read_dataset(group, "origin", origin_);
11✔
1816

1817
  if (int err = set_grid()) {
11!
UNCOV
1818
    fatal_error(openmc_err_msg);
×
1819
  }
1820
}
11✔
1821

1822
const std::string CylindricalMesh::mesh_type = "cylindrical";
1823

1824
std::string CylindricalMesh::get_mesh_type() const
484✔
1825
{
1826
  return mesh_type;
484✔
1827
}
1828

1829
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,091✔
1830
  Position r, Direction u, bool& in_mesh) const
1831
{
1832
  r = local_coords(r);
47,732,091✔
1833

1834
  Position mapped_r;
47,732,091✔
1835
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,091✔
1836
  mapped_r[2] = r[2];
47,732,091✔
1837

1838
  if (mapped_r[0] < FP_PRECISION) {
47,732,091!
1839
    mapped_r[1] = 0.0;
1840
  } else {
1841
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,091✔
1842
    if (mapped_r[1] < 0)
47,732,091✔
1843
      mapped_r[1] += 2 * M_PI;
23,874,862✔
1844
  }
1845

1846
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, u, in_mesh);
47,732,091✔
1847

1848
  idx[1] = sanitize_phi(idx[1]);
47,732,091✔
1849

1850
  return idx;
47,732,091✔
1851
}
1852

1853
Position CylindricalMesh::sample_element(
88,110✔
1854
  const MeshIndex& ijk, uint64_t* seed) const
1855
{
1856
  double r_min = this->r(ijk[0] - 1);
88,110✔
1857
  double r_max = this->r(ijk[0]);
88,110✔
1858

1859
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1860
  double phi_max = this->phi(ijk[1]);
88,110✔
1861

1862
  double z_min = this->z(ijk[2] - 1);
88,110✔
1863
  double z_max = this->z(ijk[2]);
88,110✔
1864

1865
  double r_min_sq = r_min * r_min;
88,110✔
1866
  double r_max_sq = r_max * r_max;
88,110✔
1867
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1868
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1869
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1870

1871
  double x = r * std::cos(phi);
88,110✔
1872
  double y = r * std::sin(phi);
88,110✔
1873

1874
  return origin_ + Position(x, y, z);
88,110✔
1875
}
1876

1877
double CylindricalMesh::find_r_crossing(
142,587,080✔
1878
  const Position& r, const Direction& u, double l, int shell) const
1879
{
1880

1881
  if ((shell < 0) || (shell > shape_[0]))
142,587,080!
1882
    return INFTY;
1883

1884
  // solve r.x^2 + r.y^2 == r0^2
1885
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1886
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1887

1888
  const double r0 = grid_[0][shell];
124,673,183✔
1889
  if (r0 == 0.0)
124,673,183✔
1890
    return INFTY;
1891

1892
  const double denominator = u.x * u.x + u.y * u.y;
117,537,109✔
1893

1894
  // Direction of flight is in z-direction. Will never intersect r.
1895
  if (std::abs(denominator) < FP_PRECISION)
117,537,109✔
1896
    return INFTY;
1897

1898
  // inverse of dominator to help the compiler to speed things up
1899
  const double inv_denominator = 1.0 / denominator;
117,478,149✔
1900

1901
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,478,149✔
1902
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,478,149✔
1903
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,478,149✔
1904

1905
  if (D < 0.0)
117,478,149✔
1906
    return INFTY;
1907

1908
  D = std::sqrt(D);
107,742,027✔
1909

1910
  // Particle is already on the shell surface; avoid spurious crossing
1911
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,742,027✔
1912
    return INFTY;
1913

1914
  // Check -p - D first because it is always smaller as -p + D
1915
  if (-p - D > l)
101,108,653✔
1916
    return -p - D;
1917
  if (-p + D > l)
80,901,059✔
1918
    return -p + D;
50,077,872✔
1919

1920
  return INFTY;
1921
}
1922

1923
double CylindricalMesh::find_phi_crossing(
74,456,404✔
1924
  const Position& r, const Direction& u, double l, int shell) const
1925
{
1926
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1927
  if (full_phi_ && (shape_[1] == 1))
74,456,404✔
1928
    return INFTY;
1929

1930
  shell = sanitize_phi(shell);
43,970,718✔
1931

1932
  const double p0 = grid_[1][shell];
43,970,718✔
1933

1934
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1935
  // => x(s) * cos(p0) = y(s) * sin(p0)
1936
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1937
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1938

1939
  const double c0 = std::cos(p0);
43,970,718✔
1940
  const double s0 = std::sin(p0);
43,970,718✔
1941

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

1944
  // Check if direction of flight is not parallel to phi surface
1945
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1946
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1947
    // Check if solution is in positive direction of flight and crosses the
1948
    // correct phi surface (not -phi)
1949
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1950
      return s;
20,219,859✔
1951
  }
1952

1953
  return INFTY;
1954
}
1955

1956
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,747✔
1957
  const Position& r, const Direction& u, double l, int shell) const
1958
{
1959
  MeshDistance d;
36,695,747✔
1960
  d.next_index = shell;
36,695,747✔
1961

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

1966
  d.max_surface = (u.z > 0.0);
35,577,531✔
1967
  if (d.max_surface && (shell <= shape_[2])) {
35,577,531✔
1968
    d.next_index += 1;
16,875,892✔
1969
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,892✔
1970
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1971
    d.next_index -= 1;
16,846,225✔
1972
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1973
  }
1974
  return d;
35,577,531✔
1975
}
1976

1977
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,217,489✔
1978
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1979
  double l) const
1980
{
1981
  if (i == 0) {
145,217,489✔
1982

1983
    return std::min(
142,587,080✔
1984
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,293,540✔
1985
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,587,080✔
1986

1987
  } else if (i == 1) {
73,923,949✔
1988

1989
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,202✔
1990
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,202✔
1991
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,202✔
1992
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,404✔
1993

1994
  } else {
1995
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,747✔
1996
  }
1997
}
1998

1999
int CylindricalMesh::set_grid()
433✔
2000
{
2001
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
433✔
2002
    static_cast<int>(grid_[1].size()) - 1,
433✔
2003
    static_cast<int>(grid_[2].size()) - 1};
433✔
2004

2005
  for (const auto& g : grid_) {
1,732✔
2006
    if (g.size() < 2) {
1,299!
UNCOV
2007
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2008
                 "must each have at least 2 points");
UNCOV
2009
      return OPENMC_E_INVALID_ARGUMENT;
×
2010
    }
2011
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,299!
2012
        g.end()) {
1,299!
UNCOV
2013
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2014
                 "cylindrical meshes must be sorted and unique.");
UNCOV
2015
      return OPENMC_E_INVALID_ARGUMENT;
×
2016
    }
2017
  }
2018
  if (grid_[0].front() < 0.0) {
433!
UNCOV
2019
    set_errmsg("r-grid for "
×
2020
               "cylindrical meshes must start at r >= 0.");
UNCOV
2021
    return OPENMC_E_INVALID_ARGUMENT;
×
2022
  }
2023
  if (grid_[1].front() < 0.0) {
433!
UNCOV
2024
    set_errmsg("phi-grid for "
×
2025
               "cylindrical meshes must start at phi >= 0.");
UNCOV
2026
    return OPENMC_E_INVALID_ARGUMENT;
×
2027
  }
2028
  if (grid_[1].back() > 2.0 * PI) {
433!
UNCOV
2029
    set_errmsg("phi-grids for "
×
2030
               "cylindrical meshes must end with theta <= 2*pi.");
2031

UNCOV
2032
    return OPENMC_E_INVALID_ARGUMENT;
×
2033
  }
2034

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

2037
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
433✔
2038
    origin_[2] + grid_[2].front()};
433✔
2039
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
433✔
2040
    origin_[2] + grid_[2].back()};
433✔
2041

2042
  return 0;
433✔
2043
}
2044

2045
int CylindricalMesh::get_index_in_direction(double r, double u, int i) const
143,196,273✔
2046
{
2047
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,273✔
2048
}
2049

UNCOV
2050
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2051
  Position plot_ll, Position plot_ur) const
2052
{
UNCOV
2053
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2054

2055
  // Figure out which axes lie in the plane of the plot.
2056
  array<vector<double>, 2> axis_lines;
2057
  return {axis_lines[0], axis_lines[1]};
2058
}
2059

2060
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
374✔
2061
{
2062
  write_dataset(mesh_group, "r_grid", grid_[0]);
374✔
2063
  write_dataset(mesh_group, "phi_grid", grid_[1]);
374✔
2064
  write_dataset(mesh_group, "z_grid", grid_[2]);
374✔
2065
  write_dataset(mesh_group, "origin", origin_);
374✔
2066
}
374✔
2067

2068
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2069
{
2070
  double r_i = grid_[0][ijk[0] - 1];
792✔
2071
  double r_o = grid_[0][ijk[0]];
792✔
2072

2073
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2074
  double phi_o = grid_[1][ijk[1]];
792✔
2075

2076
  double z_i = grid_[2][ijk[2] - 1];
792✔
2077
  double z_o = grid_[2][ijk[2]];
792✔
2078

2079
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2080
}
2081

2082
//==============================================================================
2083
// SphericalMesh implementation
2084
//==============================================================================
2085

2086
SphericalMesh::SphericalMesh(pugi::xml_node node)
345✔
2087
  : PeriodicStructuredMesh {node}
345✔
2088
{
2089
  n_dimension_ = 3;
345✔
2090

2091
  grid_[0] = get_node_array<double>(node, "r_grid");
345✔
2092
  grid_[1] = get_node_array<double>(node, "theta_grid");
345✔
2093
  grid_[2] = get_node_array<double>(node, "phi_grid");
345✔
2094
  origin_ = get_node_position(node, "origin");
345✔
2095

2096
  if (int err = set_grid()) {
345!
UNCOV
2097
    fatal_error(openmc_err_msg);
×
2098
  }
2099
}
345✔
2100

2101
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2102
{
2103
  n_dimension_ = 3;
11✔
2104

2105
  read_dataset(group, "r_grid", grid_[0]);
11✔
2106
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2107
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2108
  read_dataset(group, "origin", origin_);
11✔
2109

2110
  if (int err = set_grid()) {
11!
UNCOV
2111
    fatal_error(openmc_err_msg);
×
2112
  }
2113
}
11✔
2114

2115
const std::string SphericalMesh::mesh_type = "spherical";
2116

2117
std::string SphericalMesh::get_mesh_type() const
385✔
2118
{
2119
  return mesh_type;
385✔
2120
}
2121

2122
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,128✔
2123
  Position r, Direction u, bool& in_mesh) const
2124
{
2125
  r = local_coords(r);
68,592,128✔
2126

2127
  Position mapped_r;
68,592,128✔
2128
  mapped_r[0] = r.norm();
68,592,128✔
2129

2130
  if (mapped_r[0] < FP_PRECISION) {
68,592,128!
2131
    mapped_r[1] = 0.0;
2132
    mapped_r[2] = 0.0;
2133
  } else {
2134
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,128✔
2135
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,128✔
2136
    if (mapped_r[2] < 0)
68,592,128✔
2137
      mapped_r[2] += 2 * M_PI;
34,268,685✔
2138
  }
2139

2140
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, u, in_mesh);
68,592,128✔
2141

2142
  idx[1] = sanitize_theta(idx[1]);
68,592,128✔
2143
  idx[2] = sanitize_phi(idx[2]);
68,592,128✔
2144

2145
  return idx;
68,592,128✔
2146
}
2147

2148
Position SphericalMesh::sample_element(
110✔
2149
  const MeshIndex& ijk, uint64_t* seed) const
2150
{
2151
  double r_min = this->r(ijk[0] - 1);
110✔
2152
  double r_max = this->r(ijk[0]);
110✔
2153

2154
  double theta_min = this->theta(ijk[1] - 1);
110✔
2155
  double theta_max = this->theta(ijk[1]);
110✔
2156

2157
  double phi_min = this->phi(ijk[2] - 1);
110✔
2158
  double phi_max = this->phi(ijk[2]);
110✔
2159

2160
  double cos_theta =
110✔
2161
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2162
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2163
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2164
  double r_min_cub = std::pow(r_min, 3);
110✔
2165
  double r_max_cub = std::pow(r_max, 3);
110✔
2166
  // might be faster to do rejection here?
2167
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2168

2169
  double x = r * std::cos(phi) * sin_theta;
110✔
2170
  double y = r * std::sin(phi) * sin_theta;
110✔
2171
  double z = r * cos_theta;
110✔
2172

2173
  return origin_ + Position(x, y, z);
110✔
2174
}
2175

2176
double SphericalMesh::find_r_crossing(
443,974,630✔
2177
  const Position& r, const Direction& u, double l, int shell) const
2178
{
2179
  if ((shell < 0) || (shell > shape_[0]))
443,974,630✔
2180
    return INFTY;
2181

2182
  // solve |r+s*u| = r0
2183
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2184
  const double r0 = grid_[0][shell];
404,353,543✔
2185
  if (r0 == 0.0)
404,353,543✔
2186
    return INFTY;
2187
  const double p = r.dot(u);
396,675,026✔
2188
  double R = r.norm();
396,675,026✔
2189
  double D = p * p - (R - r0) * (R + r0);
396,675,026✔
2190

2191
  // Particle is already on the shell surface; avoid spurious crossing
2192
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,675,026✔
2193
    return INFTY;
2194

2195
  if (D >= 0.0) {
385,966,372✔
2196
    D = std::sqrt(D);
358,089,424✔
2197
    // Check -p - D first because it is always smaller as -p + D
2198
    if (-p - D > l)
358,089,424✔
2199
      return -p - D;
2200
    if (-p + D > l)
293,777,792✔
2201
      return -p + D;
177,238,501✔
2202
  }
2203

2204
  return INFTY;
2205
}
2206

2207
double SphericalMesh::find_theta_crossing(
110,161,348✔
2208
  const Position& r, const Direction& u, double l, int shell) const
2209
{
2210
  // Theta grid is [0, π], thus there is no real surface to cross
2211
  if (full_theta_ && (shape_[1] == 1))
110,161,348✔
2212
    return INFTY;
2213

2214
  shell = sanitize_theta(shell);
38,358,540✔
2215

2216
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2217
  // yields
2218
  // a*s^2 + 2*b*s + c == 0 with
2219
  // a = cos(theta)^2 - u.z * u.z
2220
  // b = r*u * cos(theta)^2 - u.z * r.z
2221
  // c = r*r * cos(theta)^2 - r.z^2
2222

2223
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2224
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2225
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2226

2227
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2228
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2229
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2230

2231
  // if factor of s^2 is zero, direction of flight is parallel to theta
2232
  // surface
2233
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2234
    // if b vanishes, direction of flight is within theta surface and crossing
2235
    // is not possible
2236
    if (std::abs(b) < FP_PRECISION)
482,548!
2237
      return INFTY;
2238

UNCOV
2239
    const double s = -0.5 * c / b;
×
2240
    // Check if solution is in positive direction of flight and has correct
2241
    // sign
UNCOV
2242
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
2243
      return s;
×
2244

2245
    // no crossing is possible
2246
    return INFTY;
2247
  }
2248

2249
  const double p = b / a;
37,875,992✔
2250
  double D = p * p - c / a;
37,875,992✔
2251

2252
  if (D < 0.0)
37,875,992✔
2253
    return INFTY;
2254

2255
  D = std::sqrt(D);
26,921,004✔
2256

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

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

2268
  return INFTY;
2269
}
2270

2271
double SphericalMesh::find_phi_crossing(
111,750,826✔
2272
  const Position& r, const Direction& u, double l, int shell) const
2273
{
2274
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2275
  if (full_phi_ && (shape_[2] == 1))
111,750,826✔
2276
    return INFTY;
2277

2278
  shell = sanitize_phi(shell);
39,948,018✔
2279

2280
  const double p0 = grid_[2][shell];
39,948,018✔
2281

2282
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2283
  // => x(s) * cos(p0) = y(s) * sin(p0)
2284
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2285
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2286

2287
  const double c0 = std::cos(p0);
39,948,018✔
2288
  const double s0 = std::sin(p0);
39,948,018✔
2289

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

2292
  // Check if direction of flight is not parallel to phi surface
2293
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2294
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2295
    // Check if solution is in positive direction of flight and crosses the
2296
    // correct phi surface (not -phi)
2297
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2298
      return s;
17,579,452✔
2299
  }
2300

2301
  return INFTY;
2302
}
2303

2304
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,943,402✔
2305
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2306
  double l) const
2307
{
2308

2309
  if (i == 0) {
332,943,402✔
2310
    return std::min(
443,974,630✔
2311
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,987,315✔
2312
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,974,630✔
2313

2314
  } else if (i == 1) {
110,956,087✔
2315
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,674✔
2316
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,674✔
2317
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,674✔
2318
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,348✔
2319

2320
  } else {
2321
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,413✔
2322
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,413✔
2323
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,413✔
2324
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,826✔
2325
  }
2326
}
2327

2328
int SphericalMesh::set_grid()
378✔
2329
{
2330
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
378✔
2331
    static_cast<int>(grid_[1].size()) - 1,
378✔
2332
    static_cast<int>(grid_[2].size()) - 1};
378✔
2333

2334
  for (const auto& g : grid_) {
1,512✔
2335
    if (g.size() < 2) {
1,134!
UNCOV
2336
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2337
                 "must each have at least 2 points");
UNCOV
2338
      return OPENMC_E_INVALID_ARGUMENT;
×
2339
    }
2340
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,134!
2341
        g.end()) {
1,134!
UNCOV
2342
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2343
                 "spherical meshes must be sorted and unique.");
UNCOV
2344
      return OPENMC_E_INVALID_ARGUMENT;
×
2345
    }
2346
    if (g.front() < 0.0) {
1,134!
UNCOV
2347
      set_errmsg("r-, theta-, and phi- grids for "
×
2348
                 "spherical meshes must start at v >= 0.");
UNCOV
2349
      return OPENMC_E_INVALID_ARGUMENT;
×
2350
    }
2351
  }
2352
  if (grid_[1].back() > PI) {
378!
UNCOV
2353
    set_errmsg("theta-grids for "
×
2354
               "spherical meshes must end with theta <= pi.");
2355

UNCOV
2356
    return OPENMC_E_INVALID_ARGUMENT;
×
2357
  }
2358
  if (grid_[2].back() > 2 * PI) {
378!
UNCOV
2359
    set_errmsg("phi-grids for "
×
2360
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2361
    return OPENMC_E_INVALID_ARGUMENT;
×
2362
  }
2363

2364
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
378!
2365
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
378✔
2366

2367
  double r = grid_[0].back();
378✔
2368
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
378✔
2369
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
378✔
2370

2371
  return 0;
378✔
2372
}
2373

2374
int SphericalMesh::get_index_in_direction(double r, double u, int i) const
205,776,384✔
2375
{
2376
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,384✔
2377
}
2378

UNCOV
2379
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2380
  Position plot_ll, Position plot_ur) const
2381
{
UNCOV
2382
  fatal_error("Plot of spherical Mesh not implemented");
×
2383

2384
  // Figure out which axes lie in the plane of the plot.
2385
  array<vector<double>, 2> axis_lines;
2386
  return {axis_lines[0], axis_lines[1]};
2387
}
2388

2389
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
319✔
2390
{
2391
  write_dataset(mesh_group, "r_grid", grid_[0]);
319✔
2392
  write_dataset(mesh_group, "theta_grid", grid_[1]);
319✔
2393
  write_dataset(mesh_group, "phi_grid", grid_[2]);
319✔
2394
  write_dataset(mesh_group, "origin", origin_);
319✔
2395
}
319✔
2396

2397
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2398
{
2399
  double r_i = grid_[0][ijk[0] - 1];
935✔
2400
  double r_o = grid_[0][ijk[0]];
935✔
2401

2402
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2403
  double theta_o = grid_[1][ijk[1]];
935✔
2404

2405
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2406
  double phi_o = grid_[2][ijk[2]];
935✔
2407

2408
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2409
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2410
}
2411

2412
//==============================================================================
2413
// Helper functions for the C API
2414
//==============================================================================
2415

2416
int check_mesh(int32_t index)
6,490✔
2417
{
2418
  if (index < 0 || index >= model::meshes.size()) {
6,490!
UNCOV
2419
    set_errmsg("Index in meshes array is out of bounds.");
×
2420
    return OPENMC_E_OUT_OF_BOUNDS;
×
2421
  }
2422
  return 0;
2423
}
2424

2425
template<class T>
2426
int check_mesh_type(int32_t index)
1,100✔
2427
{
2428
  if (int err = check_mesh(index))
1,100!
2429
    return err;
2430

2431
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2432
  if (!mesh) {
1,100!
UNCOV
2433
    set_errmsg("This function is not valid for input mesh.");
×
2434
    return OPENMC_E_INVALID_TYPE;
×
2435
  }
2436
  return 0;
2437
}
2438

2439
template<class T>
2440
bool is_mesh_type(int32_t index)
2441
{
2442
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2443
  return mesh;
2444
}
2445

2446
//==============================================================================
2447
// C API functions
2448
//==============================================================================
2449

2450
// Return the type of mesh as a C string
2451
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2452
{
2453
  if (int err = check_mesh(index))
1,496!
2454
    return err;
2455

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

2458
  return 0;
1,496✔
2459
}
2460

2461
//! Extend the meshes array by n elements
2462
extern "C" int openmc_extend_meshes(
253✔
2463
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2464
{
2465
  if (index_start)
253!
2466
    *index_start = model::meshes.size();
253✔
2467
  std::string mesh_type;
253✔
2468

2469
  for (int i = 0; i < n; ++i) {
506✔
2470
    if (RegularMesh::mesh_type == type) {
253✔
2471
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2472
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2473
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2474
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2475
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2476
    } else if (SphericalMesh::mesh_type == type) {
22!
2477
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2478
    } else {
UNCOV
2479
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2480
    }
2481
  }
2482
  if (index_end)
253!
UNCOV
2483
    *index_end = model::meshes.size() - 1;
×
2484

2485
  return 0;
253✔
2486
}
253✔
2487

2488
//! Adds a new unstructured mesh to OpenMC
UNCOV
2489
extern "C" int openmc_add_unstructured_mesh(
×
2490
  const char filename[], const char library[], int* id)
2491
{
UNCOV
2492
  std::string lib_name(library);
×
2493
  std::string mesh_file(filename);
×
2494
  bool valid_lib = false;
×
2495

2496
#ifdef OPENMC_DAGMC_ENABLED
2497
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2498
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2499
    valid_lib = true;
2500
  }
2501
#endif
2502

2503
#ifdef OPENMC_LIBMESH_ENABLED
2504
  if (lib_name == LibMesh::mesh_lib_type) {
×
2505
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2506
    valid_lib = true;
2507
  }
2508
#endif
2509

UNCOV
2510
  if (!valid_lib) {
×
2511
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2512
                           "by this build of OpenMC",
2513
      lib_name));
UNCOV
2514
    return OPENMC_E_INVALID_ARGUMENT;
×
2515
  }
2516

2517
  // auto-assign new ID
2518
  model::meshes.back()->set_id(-1);
×
2519
  *id = model::meshes.back()->id_;
2520

2521
  return 0;
UNCOV
2522
}
×
2523

2524
//! Return the index in the meshes array of a mesh with a given ID
2525
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2526
{
2527
  auto pair = model::mesh_map.find(id);
429!
2528
  if (pair == model::mesh_map.end()) {
429!
UNCOV
2529
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
2530
    return OPENMC_E_INVALID_ID;
×
2531
  }
2532
  *index = pair->second;
429✔
2533
  return 0;
429✔
2534
}
2535

2536
//! Return the ID of a mesh
2537
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,827✔
2538
{
2539
  if (int err = check_mesh(index))
2,827!
2540
    return err;
2541
  *id = model::meshes[index]->id_;
2,827✔
2542
  return 0;
2,827✔
2543
}
2544

2545
//! Set the ID of a mesh
2546
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2547
{
2548
  if (int err = check_mesh(index))
253!
2549
    return err;
2550
  model::meshes[index]->id_ = id;
253✔
2551
  model::mesh_map[id] = index;
253✔
2552
  return 0;
253✔
2553
}
2554

2555
//! Get the number of elements in a mesh
2556
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2557
{
2558
  if (int err = check_mesh(index))
297!
2559
    return err;
2560
  *n = model::meshes[index]->n_bins();
297✔
2561
  return 0;
297✔
2562
}
2563

2564
//! Get the volume of each element in the mesh
2565
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2566
{
2567
  if (int err = check_mesh(index))
88!
2568
    return err;
2569
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2570
    volumes[i] = model::meshes[index]->volume(i);
880✔
2571
  }
2572
  return 0;
2573
}
2574

2575
//! Get the bounding box of a mesh
2576
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2577
{
2578
  if (int err = check_mesh(index))
176!
2579
    return err;
2580

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

2583
  // set lower left corner values
2584
  ll[0] = bbox.min.x;
176✔
2585
  ll[1] = bbox.min.y;
176✔
2586
  ll[2] = bbox.min.z;
176✔
2587

2588
  // set upper right corner values
2589
  ur[0] = bbox.max.x;
176✔
2590
  ur[1] = bbox.max.y;
176✔
2591
  ur[2] = bbox.max.z;
176✔
2592
  return 0;
176✔
2593
}
2594

2595
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2596
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2597
{
2598
  if (int err = check_mesh(index))
209!
2599
    return err;
2600

2601
  try {
209✔
2602
    model::meshes[index]->material_volumes(
209✔
2603
      nx, ny, nz, table_size, materials, volumes, bboxes);
2604
  } catch (const std::exception& e) {
11!
2605
    set_errmsg(e.what());
11✔
2606
    if (starts_with(e.what(), "Mesh")) {
11!
2607
      return OPENMC_E_GEOMETRY;
11✔
2608
    } else {
UNCOV
2609
      return OPENMC_E_ALLOCATE;
×
2610
    }
2611
  }
11✔
2612

2613
  return 0;
2614
}
2615

2616
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2617
  Position width, int basis, int* pixels, int32_t* data)
2618
{
2619
  if (int err = check_mesh(index))
44!
2620
    return err;
2621
  const auto& mesh = model::meshes[index].get();
44!
2622

2623
  int pixel_width = pixels[0];
44✔
2624
  int pixel_height = pixels[1];
44✔
2625

2626
  // get pixel size
2627
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2628
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2629

2630
  // setup basis indices and initial position centered on pixel
2631
  int in_i, out_i;
44✔
2632
  Position xyz = origin;
44✔
2633
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2634
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2635
  switch (basis_enum) {
44!
2636
  case PlotBasis::xy:
2637
    in_i = 0;
2638
    out_i = 1;
2639
    break;
2640
  case PlotBasis::xz:
2641
    in_i = 0;
2642
    out_i = 2;
2643
    break;
2644
  case PlotBasis::yz:
2645
    in_i = 1;
2646
    out_i = 2;
2647
    break;
UNCOV
2648
  default:
×
2649
    UNREACHABLE();
×
2650
  }
2651

2652
  // set initial position
2653
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2654
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2655

2656
#pragma omp parallel
24✔
2657
  {
20✔
2658
    Position r = xyz;
20✔
2659
    Direction placeholder_u = Direction(1.0, 0.0, 0.0);
20✔
2660

2661
#pragma omp for
2662
    for (int y = 0; y < pixel_height; y++) {
420✔
2663
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2664
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2665
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2666
        data[pixel_width * y + x] = mesh->get_bin(r, placeholder_u);
8,000✔
2667
      }
2668
    }
2669
  }
2670

2671
  return 0;
44✔
2672
}
2673

2674
//! Get the dimension of a regular mesh
2675
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2676
  int32_t index, int** dims, int* n)
2677
{
2678
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2679
    return err;
2680
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2681
  *dims = mesh->shape_.data();
11✔
2682
  *n = mesh->n_dimension_;
11✔
2683
  return 0;
11✔
2684
}
2685

2686
//! Set the dimension of a regular mesh
2687
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2688
  int32_t index, int n, const int* dims)
2689
{
2690
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2691
    return err;
2692
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2693

2694
  // Copy dimension
2695
  mesh->n_dimension_ = n;
187✔
2696
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2697
  return 0;
187✔
2698
}
2699

2700
//! Get the regular mesh parameters
2701
extern "C" int openmc_regular_mesh_get_params(
209✔
2702
  int32_t index, double** ll, double** ur, double** width, int* n)
2703
{
2704
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2705
    return err;
2706
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2707

2708
  if (m->lower_left_.empty()) {
209!
UNCOV
2709
    set_errmsg("Mesh parameters have not been set.");
×
2710
    return OPENMC_E_ALLOCATE;
×
2711
  }
2712

2713
  *ll = m->lower_left_.data();
209✔
2714
  *ur = m->upper_right_.data();
209✔
2715
  *width = m->width_.data();
209✔
2716
  *n = m->n_dimension_;
209✔
2717
  return 0;
209✔
2718
}
2719

2720
//! Set the regular mesh parameters
2721
extern "C" int openmc_regular_mesh_set_params(
220✔
2722
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2723
{
2724
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2725
    return err;
2726
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2727

2728
  if (m->n_dimension_ == -1) {
220!
UNCOV
2729
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
2730
    return OPENMC_E_UNASSIGNED;
×
2731
  }
2732

2733
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2734
  if (ll && ur) {
220✔
2735
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2736
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2737
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2738
  } else if (ll && width) {
22✔
2739
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2740
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2741
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2742
  } else if (ur && width) {
11!
2743
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2744
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2745
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2746
  } else {
UNCOV
2747
    set_errmsg("At least two parameters must be specified.");
×
2748
    return OPENMC_E_INVALID_ARGUMENT;
×
2749
  }
2750

2751
  // Set material volumes
2752

2753
  // TODO: incorporate this into method in RegularMesh that can be called from
2754
  // here and from constructor
2755
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2756
  m->element_volume_ = 1.0;
220✔
2757
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2758
    m->element_volume_ *= m->width_[i];
660✔
2759
  }
2760

2761
  return 0;
2762
}
220✔
2763

2764
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2765
template<class C>
2766
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2767
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2768
  const int nz)
2769
{
2770
  if (int err = check_mesh_type<C>(index))
88!
2771
    return err;
2772

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

2775
  m->n_dimension_ = 3;
88✔
2776

2777
  m->grid_[0].reserve(nx);
88✔
2778
  m->grid_[1].reserve(ny);
88✔
2779
  m->grid_[2].reserve(nz);
88✔
2780

2781
  for (int i = 0; i < nx; i++) {
572✔
2782
    m->grid_[0].push_back(grid_x[i]);
484✔
2783
  }
2784
  for (int i = 0; i < ny; i++) {
341✔
2785
    m->grid_[1].push_back(grid_y[i]);
253✔
2786
  }
2787
  for (int i = 0; i < nz; i++) {
319✔
2788
    m->grid_[2].push_back(grid_z[i]);
231✔
2789
  }
2790

2791
  int err = m->set_grid();
88✔
2792
  return err;
88✔
2793
}
2794

2795
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2796
template<class C>
2797
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2798
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2799
{
2800
  if (int err = check_mesh_type<C>(index))
385!
2801
    return err;
2802
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2803

2804
  if (m->lower_left_.empty()) {
385!
UNCOV
2805
    set_errmsg("Mesh parameters have not been set.");
×
2806
    return OPENMC_E_ALLOCATE;
×
2807
  }
2808

2809
  *grid_x = m->grid_[0].data();
385✔
2810
  *nx = m->grid_[0].size();
385✔
2811
  *grid_y = m->grid_[1].data();
385✔
2812
  *ny = m->grid_[1].size();
385✔
2813
  *grid_z = m->grid_[2].data();
385✔
2814
  *nz = m->grid_[2].size();
385✔
2815

2816
  return 0;
385✔
2817
}
2818

2819
//! Get the rectilinear mesh grid
2820
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2821
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2822
{
2823
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2824
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2825
}
2826

2827
//! Set the rectilienar mesh parameters
2828
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
44✔
2829
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2830
  const double* grid_z, const int nz)
2831
{
2832
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
44✔
2833
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44✔
2834
}
2835

2836
//! Get the cylindrical mesh grid
2837
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2838
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2839
{
2840
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2841
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2842
}
2843

2844
//! Set the cylindrical mesh parameters
2845
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2846
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2847
  const double* grid_z, const int nz)
2848
{
2849
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2850
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2851
}
2852

2853
//! Get the spherical mesh grid
2854
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2855
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2856
{
2857

2858
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2859
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2860
  ;
121✔
2861
}
2862

2863
//! Set the spherical mesh parameters
2864
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2865
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2866
  const double* grid_z, const int nz)
2867
{
2868
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2869
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2870
}
2871

2872
#ifdef OPENMC_DAGMC_ENABLED
2873

2874
const std::string MOABMesh::mesh_lib_type = "moab";
2875

2876
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2877
{
2878
  initialize();
24✔
2879
}
24!
2880

2881
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2882
{
2883
  initialize();
×
2884
}
×
2885

2886
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2887
  : UnstructuredMesh()
×
2888
{
2889
  n_dimension_ = 3;
2890
  filename_ = filename;
×
2891
  set_length_multiplier(length_multiplier);
×
2892
  initialize();
×
2893
}
×
2894

2895
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2896
{
2897
  mbi_ = external_mbi;
1✔
2898
  filename_ = "unknown (external file)";
1✔
2899
  this->initialize();
1✔
2900
}
1!
2901

2902
void MOABMesh::initialize()
25✔
2903
{
2904

2905
  // Create the MOAB interface and load data from file
2906
  this->create_interface();
25✔
2907

2908
  // Initialise MOAB error code
2909
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2910

2911
  // Set the dimension
2912
  n_dimension_ = 3;
25✔
2913

2914
  // set member range of tetrahedral entities
2915
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2916
  if (rval != moab::MB_SUCCESS) {
25!
2917
    fatal_error("Failed to get all tetrahedral elements");
2918
  }
2919

2920
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2921
    warning("Non-tetrahedral elements found in unstructured "
×
2922
            "mesh file: " +
2923
            filename_);
2924
  }
2925

2926
  // set member range of vertices
2927
  int vertex_dim = 0;
25✔
2928
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2929
  if (rval != moab::MB_SUCCESS) {
25!
2930
    fatal_error("Failed to get all vertex handles");
2931
  }
2932

2933
  // make an entity set for all tetrahedra
2934
  // this is used for convenience later in output
2935
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2936
  if (rval != moab::MB_SUCCESS) {
25!
2937
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2938
  }
2939

2940
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2941
  if (rval != moab::MB_SUCCESS) {
25!
2942
    fatal_error("Failed to add tetrahedra to an entity set.");
2943
  }
2944

2945
  if (length_multiplier_ > 0.0) {
25!
2946
    // get the connectivity of all tets
2947
    moab::Range adj;
×
2948
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
2949
    if (rval != moab::MB_SUCCESS) {
×
2950
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2951
    }
2952
    // scale all vertex coords by multiplier (done individually so not all
2953
    // coordinates are in memory twice at once)
2954
    for (auto vert : adj) {
×
2955
      // retrieve coords
2956
      std::array<double, 3> coord;
2957
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
2958
      if (rval != moab::MB_SUCCESS) {
×
2959
        fatal_error("Could not get coordinates of vertex.");
2960
      }
2961
      // scale coords
2962
      for (auto& c : coord) {
×
2963
        c *= length_multiplier_;
2964
      }
2965
      // set new coords
2966
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2967
      if (rval != moab::MB_SUCCESS) {
×
2968
        fatal_error("Failed to set new vertex coordinates");
2969
      }
2970
    }
2971
  }
2972

2973
  // Determine bounds of mesh
2974
  this->determine_bounds();
25✔
2975
}
25✔
2976

2977
void MOABMesh::prepare_for_point_location()
21✔
2978
{
2979
  // if the KDTree has already been constructed, do nothing
2980
  if (kdtree_)
21!
2981
    return;
2982

2983
  // build acceleration data structures
2984
  compute_barycentric_data(ehs_);
21✔
2985
  build_kdtree(ehs_);
21✔
2986
}
2987

2988
void MOABMesh::create_interface()
25✔
2989
{
2990
  // Do not create a MOAB instance if one is already in memory
2991
  if (mbi_)
25✔
2992
    return;
2993

2994
  // create MOAB instance
2995
  mbi_ = std::make_shared<moab::Core>();
24!
2996

2997
  // load unstructured mesh file
2998
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
2999
  if (rval != moab::MB_SUCCESS) {
24!
3000
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3001
  }
3002
}
3003

3004
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
3005
{
3006
  moab::Range all_tris;
21✔
3007
  int adj_dim = 2;
21✔
3008
  write_message("Getting tet adjacencies...", 7);
21✔
3009
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
3010
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3011
  if (rval != moab::MB_SUCCESS) {
21!
3012
    fatal_error("Failed to get adjacent triangles for tets");
3013
  }
3014

3015
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3016
    warning("Non-triangle elements found in tet adjacencies in "
×
3017
            "unstructured mesh file: " +
3018
            filename_);
×
3019
  }
3020

3021
  // combine into one range
3022
  moab::Range all_tets_and_tris;
21✔
3023
  all_tets_and_tris.merge(all_tets);
21✔
3024
  all_tets_and_tris.merge(all_tris);
21✔
3025

3026
  // create a kd-tree instance
3027
  write_message(
21✔
3028
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3029
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3030

3031
  // Determine what options to use
3032
  std::ostringstream options_stream;
21✔
3033
  if (options_.empty()) {
21✔
3034
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3035
  } else {
3036
    options_stream << options_;
16✔
3037
  }
3038
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3039

3040
  // Build the k-d tree
3041
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3042
  if (rval != moab::MB_SUCCESS) {
21!
3043
    fatal_error("Failed to construct KDTree for the "
3044
                "unstructured mesh file: " +
3045
                filename_);
×
3046
  }
3047
}
21✔
3048

3049
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3050
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3051
{
3052
  hits.clear();
1,543,584!
3053

3054
  moab::ErrorCode rval;
1,543,584✔
3055
  vector<moab::EntityHandle> tris;
1,543,584✔
3056
  // get all intersections with triangles in the tet mesh
3057
  // (distances are relative to the start point, not the previous
3058
  // intersection)
3059
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3060
    dir.array(), start.array(), tris, hits, 0, track_len);
3061
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3062
    fatal_error(
3063
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3064
  }
3065

3066
  // remove duplicate intersection distances
3067
  std::unique(hits.begin(), hits.end());
1,543,584✔
3068

3069
  // sorts by first component of std::pair by default
3070
  std::sort(hits.begin(), hits.end());
1,543,584✔
3071
}
1,543,584✔
3072

3073
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3074
  vector<int>& bins, vector<double>& lengths) const
3075
{
3076
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3077
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3078
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3079
  dir.normalize();
1,543,584✔
3080

3081
  double track_len = (end - start).length();
1,543,584✔
3082
  if (track_len == 0.0)
1,543,584!
3083
    return;
721,692✔
3084

3085
  start -= TINY_BIT * dir;
1,543,584✔
3086
  end += TINY_BIT * dir;
1,543,584✔
3087

3088
  vector<double> hits;
1,543,584✔
3089
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3090

3091
  bins.clear();
1,543,584!
3092
  lengths.clear();
1,543,584!
3093

3094
  // if there are no intersections the track may lie entirely
3095
  // within a single tet. If this is the case, apply entire
3096
  // score to that tet and return.
3097
  if (hits.size() == 0) {
1,543,584✔
3098
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3099
    int bin = this->get_bin(midpoint, u);
721,692✔
3100
    if (bin != -1) {
721,692✔
3101
      bins.push_back(bin);
242,866✔
3102
      lengths.push_back(1.0);
242,866✔
3103
    }
3104
    return;
721,692✔
3105
  }
3106

3107
  // for each segment in the set of tracks, try to look up a tet
3108
  // at the midpoint of the segment
3109
  Position current = r0;
3110
  double last_dist = 0.0;
3111
  for (const auto& hit : hits) {
5,516,161✔
3112
    // get the segment length
3113
    double segment_length = hit - last_dist;
4,694,269✔
3114
    last_dist = hit;
4,694,269✔
3115
    // find the midpoint of this segment
3116
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3117
    // try to find a tet for this position
3118
    int bin = this->get_bin(midpoint, u);
4,694,269✔
3119

3120
    // determine the start point for this segment
3121
    current = r0 + u * hit;
4,694,269✔
3122

3123
    if (bin == -1) {
4,694,269✔
3124
      continue;
20,522✔
3125
    }
3126

3127
    bins.push_back(bin);
4,673,747✔
3128
    lengths.push_back(segment_length / track_len);
4,673,747✔
3129
  }
3130

3131
  // tally remaining portion of track after last hit if
3132
  // the last segment of the track is in the mesh but doesn't
3133
  // reach the other side of the tet
3134
  if (hits.back() < track_len) {
821,892!
3135
    Position segment_start = r0 + u * hits.back();
821,892✔
3136
    double segment_length = track_len - hits.back();
821,892✔
3137
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3138
    int bin = this->get_bin(midpoint, u);
821,892✔
3139
    if (bin != -1) {
821,892✔
3140
      bins.push_back(bin);
766,509✔
3141
      lengths.push_back(segment_length / track_len);
766,509✔
3142
    }
3143
  }
3144
};
1,543,584✔
3145

3146
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3147
{
3148
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3149
  // find the leaf of the kd-tree for this position
3150
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3151
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3152
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3153
    return 0;
3154
  }
3155

3156
  // retrieve the tet elements of this leaf
3157
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3158
  moab::Range tets;
6,305,335✔
3159
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3160
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3161
    warning("MOAB error finding tets.");
×
3162
  }
3163

3164
  // loop over the tets in this leaf, returning the containing tet if found
3165
  for (const auto& tet : tets) {
260,211,273✔
3166
    if (point_in_tet(pos, tet)) {
260,208,426✔
3167
      return tet;
6,302,488✔
3168
    }
3169
  }
3170

3171
  // if no tet is found, return an invalid handle
3172
  return 0;
2,847✔
3173
}
14,634,464✔
3174

3175
double MOABMesh::volume(int bin) const
167,880✔
3176
{
3177
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3178
}
3179

3180
std::string MOABMesh::library() const
34✔
3181
{
3182
  return mesh_lib_type;
34✔
3183
}
3184

3185
// Sample position within a tet for MOAB type tets
3186
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3187
{
3188

3189
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3190

3191
  // Get vertex coordinates for MOAB tet
3192
  const moab::EntityHandle* conn1;
200,410✔
3193
  int conn1_size;
200,410✔
3194
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3195
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3196
    fatal_error(fmt::format(
3197
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3198
      conn1_size));
3199
  }
3200
  moab::CartVect p[4];
200,410✔
3201
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3202
  if (rval != moab::MB_SUCCESS) {
200,410!
3203
    fatal_error("Failed to get tet coords");
3204
  }
3205

3206
  std::array<Position, 4> tet_verts;
200,410✔
3207
  for (int i = 0; i < 4; i++) {
1,002,050✔
3208
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3209
  }
3210
  // Samples position within tet using Barycentric stuff
3211
  return this->sample_tet(tet_verts, seed);
200,410✔
3212
}
3213

3214
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3215
{
3216
  vector<moab::EntityHandle> conn;
167,880✔
3217
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3218
  if (rval != moab::MB_SUCCESS) {
167,880!
3219
    fatal_error("Failed to get tet connectivity");
3220
  }
3221

3222
  moab::CartVect p[4];
167,880✔
3223
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3224
  if (rval != moab::MB_SUCCESS) {
167,880!
3225
    fatal_error("Failed to get tet coords");
3226
  }
3227

3228
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3229
}
167,880✔
3230

3231
int MOABMesh::get_bin(Position r, Direction u) const
7,317,232✔
3232
{
3233
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3234
  if (tet == 0) {
7,317,232✔
3235
    return -1;
3236
  } else {
3237
    return get_bin_from_ent_handle(tet);
6,302,488✔
3238
  }
3239
}
3240

3241
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3242
{
3243
  moab::ErrorCode rval;
21✔
3244

3245
  baryc_data_.clear();
21!
3246
  baryc_data_.resize(tets.size());
21✔
3247

3248
  // compute the barycentric data for each tet element
3249
  // and store it as a 3x3 matrix
3250
  for (auto& tet : tets) {
239,757✔
3251
    vector<moab::EntityHandle> verts;
239,736✔
3252
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3253
    if (rval != moab::MB_SUCCESS) {
239,736!
3254
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3255
    }
3256

3257
    moab::CartVect p[4];
239,736✔
3258
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3259
    if (rval != moab::MB_SUCCESS) {
239,736!
3260
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3261
    }
3262

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

3265
    // invert now to avoid this cost later
3266
    a = a.transpose().inverse();
239,736✔
3267
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3268
  }
239,736✔
3269
}
21✔
3270

3271
bool MOABMesh::point_in_tet(
260,208,426✔
3272
  const moab::CartVect& r, moab::EntityHandle tet) const
3273
{
3274

3275
  moab::ErrorCode rval;
260,208,426✔
3276

3277
  // get tet vertices
3278
  vector<moab::EntityHandle> verts;
260,208,426✔
3279
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3280
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3281
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3282
    return false;
3283
  }
3284

3285
  // first vertex is used as a reference point for the barycentric data -
3286
  // retrieve its coordinates
3287
  moab::CartVect p_zero;
260,208,426✔
3288
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3289
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3290
    warning("Failed to get coordinates of a vertex in "
×
3291
            "unstructured mesh: " +
3292
            filename_);
×
3293
    return false;
3294
  }
3295

3296
  // look up barycentric data
3297
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3298
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3299

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

3302
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3303
          bary_coords[2] >= 0.0 &&
318,957,185✔
3304
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3305
}
260,208,426✔
3306

3307
int MOABMesh::get_bin_from_index(int idx) const
3308
{
3309
  if (idx >= n_bins()) {
×
3310
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3311
  }
3312
  return ehs_[idx] - ehs_[0];
3313
}
3314

3315
int MOABMesh::get_index(
3316
  const Position& r, const Direction& u, bool* in_mesh) const
3317
{
3318
  int bin = get_bin(r, u);
3319
  *in_mesh = bin != -1;
3320
  return bin;
3321
}
3322

3323
int MOABMesh::get_index_from_bin(int bin) const
3324
{
3325
  return bin;
3326
}
3327

3328
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3329
  Position plot_ll, Position plot_ur) const
3330
{
3331
  // TODO: Implement mesh lines
3332
  return {};
3333
}
3334

3335
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3336
{
3337
  int idx = vert - verts_[0];
815,520✔
3338
  if (idx >= n_vertices()) {
815,520!
3339
    fatal_error(
3340
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3341
  }
3342
  return idx;
815,520✔
3343
}
3344

3345
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3346
{
3347
  int bin = eh - ehs_[0];
266,750,650✔
3348
  if (bin >= n_bins()) {
266,750,650!
3349
    fatal_error(fmt::format("Invalid bin: {}", bin));
3350
  }
3351
  return bin;
266,750,650✔
3352
}
3353

3354
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3355
{
3356
  if (bin >= n_bins()) {
572,170!
3357
    fatal_error(fmt::format("Invalid bin index: ", bin));
3358
  }
3359
  return ehs_[0] + bin;
572,170✔
3360
}
3361

3362
int MOABMesh::n_bins() const
267,526,773✔
3363
{
3364
  return ehs_.size();
267,526,773✔
3365
}
3366

3367
int MOABMesh::n_surface_bins() const
3368
{
3369
  // collect all triangles in the set of tets for this mesh
3370
  moab::Range tris;
×
3371
  moab::ErrorCode rval;
3372
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3373
  if (rval != moab::MB_SUCCESS) {
×
3374
    warning("Failed to get all triangles in the mesh instance");
×
3375
    return -1;
3376
  }
3377
  return 2 * tris.size();
×
3378
}
3379

3380
Position MOABMesh::centroid(int bin) const
3381
{
3382
  moab::ErrorCode rval;
3383

3384
  auto tet = this->get_ent_handle_from_bin(bin);
3385

3386
  // look up the tet connectivity
3387
  vector<moab::EntityHandle> conn;
×
3388
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3389
  if (rval != moab::MB_SUCCESS) {
×
3390
    warning("Failed to get connectivity of a mesh element.");
×
3391
    return {};
3392
  }
3393

3394
  // get the coordinates
3395
  vector<moab::CartVect> coords(conn.size());
×
3396
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3397
  if (rval != moab::MB_SUCCESS) {
×
3398
    warning("Failed to get the coordinates of a mesh element.");
×
3399
    return {};
3400
  }
3401

3402
  // compute the centroid of the element vertices
3403
  moab::CartVect centroid(0.0, 0.0, 0.0);
3404
  for (const auto& coord : coords) {
×
3405
    centroid += coord;
3406
  }
3407
  centroid /= double(coords.size());
3408

3409
  return {centroid[0], centroid[1], centroid[2]};
3410
}
3411

3412
int MOABMesh::n_vertices() const
845,874✔
3413
{
3414
  return verts_.size();
845,874✔
3415
}
3416

3417
Position MOABMesh::vertex(int id) const
86,227✔
3418
{
3419

3420
  moab::ErrorCode rval;
86,227✔
3421

3422
  moab::EntityHandle vert = verts_[id];
86,227✔
3423

3424
  moab::CartVect coords;
86,227✔
3425
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3426
  if (rval != moab::MB_SUCCESS) {
86,227!
3427
    fatal_error("Failed to get the coordinates of a vertex.");
3428
  }
3429

3430
  return {coords[0], coords[1], coords[2]};
86,227✔
3431
}
3432

3433
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3434
{
3435
  moab::ErrorCode rval;
203,880✔
3436

3437
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3438

3439
  // look up the tet connectivity
3440
  vector<moab::EntityHandle> conn;
203,880✔
3441
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3442
  if (rval != moab::MB_SUCCESS) {
203,880!
3443
    fatal_error("Failed to get connectivity of a mesh element.");
3444
    return {};
3445
  }
3446

3447
  std::vector<int> verts(4);
203,880✔
3448
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3449
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3450
  }
3451

3452
  return verts;
203,880✔
3453
}
203,880✔
3454

3455
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3456
  std::string score) const
3457
{
3458
  moab::ErrorCode rval;
3459
  // add a tag to the mesh
3460
  // all scores are treated as a single value
3461
  // with an uncertainty
3462
  moab::Tag value_tag;
3463

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

3477
  // create the std dev tag if not present and get handle
3478
  moab::Tag error_tag;
3479
  std::string err_string = score + "_std_dev";
×
3480
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3481
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3482
  if (rval != moab::MB_SUCCESS) {
×
3483
    auto msg =
3484
      fmt::format("Could not create or retrieve the error tag for the score {}"
3485
                  " on unstructured mesh {}",
3486
        score, id_);
×
3487
    fatal_error(msg);
3488
  }
3489

3490
  // return the populated tag handles
3491
  return {value_tag, error_tag};
3492
}
3493

3494
void MOABMesh::add_score(const std::string& score)
3495
{
3496
  auto score_tags = get_score_tags(score);
×
3497
  tag_names_.push_back(score);
3498
}
3499

3500
void MOABMesh::remove_scores()
3501
{
3502
  for (const auto& name : tag_names_) {
×
3503
    auto value_name = name + "_mean";
3504
    moab::Tag tag;
3505
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3506
    if (rval != moab::MB_SUCCESS)
×
3507
      return;
3508

3509
    rval = mbi_->tag_delete(tag);
×
3510
    if (rval != moab::MB_SUCCESS) {
×
3511
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3512
                             " on unstructured mesh {}",
3513
        name, id_);
×
3514
      fatal_error(msg);
3515
    }
3516

3517
    auto std_dev_name = name + "_std_dev";
×
3518
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3519
    if (rval != moab::MB_SUCCESS) {
×
3520
      auto msg =
3521
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3522
                    " on unstructured mesh {}",
3523
          name, id_);
×
3524
    }
3525

3526
    rval = mbi_->tag_delete(tag);
×
3527
    if (rval != moab::MB_SUCCESS) {
×
3528
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3529
                             " on unstructured mesh {}",
3530
        name, id_);
×
3531
      fatal_error(msg);
3532
    }
3533
  }
3534
  tag_names_.clear();
3535
}
3536

3537
void MOABMesh::set_score_data(const std::string& score,
3538
  const vector<double>& values, const vector<double>& std_dev)
3539
{
3540
  auto score_tags = this->get_score_tags(score);
×
3541

3542
  moab::ErrorCode rval;
3543
  // set the score value
3544
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3545
  if (rval != moab::MB_SUCCESS) {
×
3546
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3547
                           "on unstructured mesh {}",
3548
      score, id_);
3549
    warning(msg);
×
3550
  }
3551

3552
  // set the error value
3553
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3554
  if (rval != moab::MB_SUCCESS) {
×
3555
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3556
                           "on unstructured mesh {}",
3557
      score, id_);
3558
    warning(msg);
×
3559
  }
3560
}
3561

3562
void MOABMesh::write(const std::string& base_filename) const
3563
{
3564
  // add extension to the base name
3565
  auto filename = base_filename + ".vtk";
3566
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3567
  filename = settings::path_output + filename;
×
3568

3569
  // write the tetrahedral elements of the mesh only
3570
  // to avoid clutter from zero-value data on other
3571
  // elements during visualization
3572
  moab::ErrorCode rval;
3573
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3574
  if (rval != moab::MB_SUCCESS) {
×
3575
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3576
    warning(msg);
×
3577
  }
3578
}
3579

3580
#endif
3581

3582
#ifdef OPENMC_LIBMESH_ENABLED
3583

3584
const std::string LibMesh::mesh_lib_type = "libmesh";
3585

3586
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3587
{
3588
  // filename_ and length_multiplier_ will already be set by the
3589
  // UnstructuredMesh constructor
3590
  set_mesh_pointer_from_filename(filename_);
25✔
3591
  set_length_multiplier(length_multiplier_);
25✔
3592
  initialize();
25✔
3593
}
25✔
3594

3595
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3596
{
3597
  // filename_ and length_multiplier_ will already be set by the
3598
  // UnstructuredMesh constructor
3599
  set_mesh_pointer_from_filename(filename_);
×
3600
  set_length_multiplier(length_multiplier_);
×
3601
  initialize();
×
3602
}
3603

3604
// create the mesh from a pointer to a libMesh Mesh
3605
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3606
{
3607
  if (!input_mesh.is_replicated()) {
×
3608
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3609
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3610
  }
3611

3612
  m_ = &input_mesh;
3613
  set_length_multiplier(length_multiplier);
×
3614
  initialize();
×
3615
}
3616

3617
// create the mesh from an input file
3618
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3619
{
3620
  n_dimension_ = 3;
3621
  set_mesh_pointer_from_filename(filename);
×
3622
  set_length_multiplier(length_multiplier);
×
3623
  initialize();
×
3624
}
3625

3626
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3627
{
3628
  filename_ = filename;
25✔
3629
  unique_m_ =
25✔
3630
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3631
  m_ = unique_m_.get();
25✔
3632
  m_->read(filename_);
25✔
3633
}
25✔
3634

3635
// build a libMesh equation system for storing values
3636
void LibMesh::build_eqn_sys()
17✔
3637
{
3638
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3639
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3640
  libMesh::ExplicitSystem& eq_sys =
17✔
3641
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3642
}
17✔
3643

3644
// intialize from mesh file
3645
void LibMesh::initialize()
25✔
3646
{
3647
  if (!settings::libmesh_comm) {
25!
3648
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3649
                "communicator.");
3650
  }
3651

3652
  // assuming that unstructured meshes used in OpenMC are 3D
3653
  n_dimension_ = 3;
25✔
3654

3655
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3656
  // Otherwise assume that it is prepared by its owning application
3657
  if (unique_m_) {
25!
3658
    m_->prepare_for_use();
25✔
3659
  }
3660

3661
  // ensure that the loaded mesh is 3 dimensional
3662
  if (m_->mesh_dimension() != n_dimension_) {
25!
3663
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3664
                            "mesh is not a 3D mesh.",
3665
      filename_));
3666
  }
3667

3668
  for (int i = 0; i < num_threads(); i++) {
75✔
3669
    pl_.emplace_back(m_->sub_point_locator());
50✔
3670
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
50✔
3671
    pl_.back()->enable_out_of_mesh_mode();
50✔
3672
  }
3673

3674
  // store first element in the mesh to use as an offset for bin indices
3675
  auto first_elem = *m_->elements_begin();
50✔
3676
  first_element_id_ = first_elem->id();
25✔
3677

3678
  // bounding box for the mesh for quick rejection checks
3679
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3680
  libMesh::Point ll = bbox_.min();
25!
3681
  libMesh::Point ur = bbox_.max();
25!
3682
  if (length_multiplier_ > 0.0) {
25!
3683
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3684
      length_multiplier_ * ll(2)};
3685
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3686
      length_multiplier_ * ur(2)};
3687
  } else {
3688
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3689
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3690
  }
3691
}
25✔
3692

3693
// Sample position within a tet for LibMesh type tets
3694
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3695
{
3696
  const auto& elem = get_element_from_bin(bin);
400,820✔
3697
  // Get tet vertex coordinates from LibMesh
3698
  std::array<Position, 4> tet_verts;
400,820✔
3699
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3700
    auto node_ref = elem.node_ref(i);
1,603,280✔
3701
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3702
  }
1,603,280✔
3703
  // Samples position within tet using Barycentric coordinates
3704
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3705
  if (length_multiplier_ > 0.0) {
400,820!
3706
    return length_multiplier_ * sampled_position;
3707
  } else {
3708
    return sampled_position;
400,820✔
3709
  }
3710
}
3711

3712
Position LibMesh::centroid(int bin) const
3713
{
3714
  const auto& elem = this->get_element_from_bin(bin);
3715
  auto centroid = elem.vertex_average();
3716
  if (length_multiplier_ > 0.0) {
×
3717
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3718
  } else {
3719
    return {centroid(0), centroid(1), centroid(2)};
3720
  }
3721
}
3722

3723
int LibMesh::n_vertices() const
42,644✔
3724
{
3725
  return m_->n_nodes();
42,644✔
3726
}
3727

3728
Position LibMesh::vertex(int vertex_id) const
42,604✔
3729
{
3730
  const auto node_ref = m_->node_ref(vertex_id);
42,604✔
3731
  if (length_multiplier_ > 0.0) {
42,604!
3732
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
×
3733
  } else {
3734
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3735
  }
3736
}
42,604✔
3737

3738
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3739
{
3740
  std::vector<int> conn;
267,856✔
3741
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3742
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3743
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3744
  }
3745
  return conn;
267,856✔
3746
}
3747

3748
std::string LibMesh::library() const
37✔
3749
{
3750
  return mesh_lib_type;
37✔
3751
}
3752

3753
int LibMesh::n_bins() const
1,788,419✔
3754
{
3755
  return m_->n_elem();
1,788,419✔
3756
}
3757

3758
int LibMesh::n_surface_bins() const
3759
{
3760
  int n_bins = 0;
3761
  for (int i = 0; i < this->n_bins(); i++) {
×
3762
    const libMesh::Elem& e = get_element_from_bin(i);
3763
    n_bins += e.n_faces();
3764
    // if this is a boundary element, it will only be visited once,
3765
    // the number of surface bins is incremented to
3766
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3767
      // null neighbor pointer indicates a boundary face
3768
      if (!neighbor_ptr) {
×
3769
        n_bins++;
3770
      }
3771
    }
3772
  }
3773
  return n_bins;
3774
}
3775

3776
void LibMesh::add_score(const std::string& var_name)
17✔
3777
{
3778
  if (!equation_systems_) {
17!
3779
    build_eqn_sys();
17✔
3780
  }
3781

3782
  // check if this is a new variable
3783
  std::string value_name = var_name + "_mean";
17✔
3784
  if (!variable_map_.count(value_name)) {
17✔
3785
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3786
    auto var_num =
17✔
3787
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3788
    variable_map_[value_name] = var_num;
17✔
3789
  }
3790

3791
  std::string std_dev_name = var_name + "_std_dev";
17✔
3792
  // check if this is a new variable
3793
  if (!variable_map_.count(std_dev_name)) {
17✔
3794
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3795
    auto var_num =
17✔
3796
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3797
    variable_map_[std_dev_name] = var_num;
17✔
3798
  }
3799
}
17✔
3800

3801
void LibMesh::remove_scores()
17✔
3802
{
3803
  if (equation_systems_) {
17!
3804
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3805
    eqn_sys.clear();
17✔
3806
    variable_map_.clear();
17✔
3807
  }
3808
}
17✔
3809

3810
void LibMesh::set_score_data(const std::string& var_name,
17✔
3811
  const vector<double>& values, const vector<double>& std_dev)
3812
{
3813
  if (!equation_systems_) {
17!
3814
    build_eqn_sys();
3815
  }
3816

3817
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3818

3819
  if (!eqn_sys.is_initialized()) {
17!
3820
    equation_systems_->init();
17✔
3821
  }
3822

3823
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3824

3825
  // look up the value variable
3826
  std::string value_name = var_name + "_mean";
17✔
3827
  unsigned int value_num = variable_map_.at(value_name);
17✔
3828
  // look up the std dev variable
3829
  std::string std_dev_name = var_name + "_std_dev";
17✔
3830
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3831

3832
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3833
       it++) {
3834
    if (!(*it)->active()) {
99,856!
3835
      continue;
3836
    }
3837

3838
    auto bin = get_bin_from_element(*it);
99,856✔
3839

3840
    // set value
3841
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3842
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3843
    assert(value_dof_indices.size() == 1);
99,856✔
3844
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3845

3846
    // set std dev
3847
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3848
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3849
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3850
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3851
  }
99,873✔
3852
}
17✔
3853

3854
void LibMesh::write(const std::string& filename) const
17✔
3855
{
3856
  write_message(fmt::format(
17✔
3857
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3858
  libMesh::ExodusII_IO exo(*m_);
17✔
3859
  std::set<std::string> systems_out = {eq_system_name_};
34!
3860
  exo.write_discontinuous_exodusII(
17✔
3861
    filename + ".e", *equation_systems_, &systems_out);
34✔
3862
}
17✔
3863

3864
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3865
  vector<int>& bins, vector<double>& lengths) const
3866
{
3867
  // TODO: Implement triangle crossings here
3868
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3869
}
3870

3871
int LibMesh::get_bin(Position r, Direction u) const
2,340,604✔
3872
{
3873
  // look-up a tet using the point locator
3874
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3875

3876
  if (length_multiplier_ > 0.0) {
2,340,604!
3877
    // Scale the point down
3878
    p /= length_multiplier_;
2,340,604✔
3879
  }
3880

3881
  // quick rejection check
3882
  if (!bbox_.contains_point(p)) {
2,340,604✔
3883
    return -1;
3884
  }
3885

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

3888
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3889
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3890
}
2,340,604✔
3891

3892
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3893
{
3894
  int bin = elem->id() - first_element_id_;
1,520,434✔
3895
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3896
    fatal_error(fmt::format("Invalid bin: {}", bin));
3897
  }
3898
  return bin;
1,520,434✔
3899
}
3900

3901
std::pair<vector<double>, vector<double>> LibMesh::plot(
3902
  Position plot_ll, Position plot_ur) const
3903
{
3904
  return {};
3905
}
3906

3907
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3908
{
3909
  return m_->elem_ref(bin);
769,460✔
3910
}
3911

3912
double LibMesh::volume(int bin) const
368,640✔
3913
{
3914
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3915
         length_multiplier_ * length_multiplier_;
368,640✔
3916
}
3917

3918
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3919
  double length_multiplier,
3920
  const std::set<libMesh::subdomain_id_type>& block_ids)
3921
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3922
    block_restrict_(!block_ids_.empty()),
×
3923
    num_active_(
×
3924
      block_restrict_
3925
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
3926
            m_->active_subdomain_set_elements_end(block_ids_))
×
3927
        : m_->n_active_elem())
×
3928
{
3929
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3930
  // contiguous in ID space, so we need to map from bin indices (defined over
3931
  // active elements) to global dof ids
3932
  bin_to_elem_map_.reserve(num_active_);
×
3933
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3934
  auto begin = block_restrict_
3935
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
3936
                 : m_->active_elements_begin();
×
3937
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
3938
                             : m_->active_elements_end();
×
3939
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
3940
    bin_to_elem_map_.push_back(elem->id());
×
3941
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3942
  }
3943
}
3944

3945
int AdaptiveLibMesh::n_bins() const
3946
{
3947
  return num_active_;
3948
}
3949

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

3957
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3958
  const vector<double>& values, const vector<double>& std_dev)
3959
{
3960
  warning(fmt::format(
×
3961
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3962
    this->id_));
3963
}
3964

3965
void AdaptiveLibMesh::write(const std::string& filename) const
3966
{
3967
  warning(fmt::format(
×
3968
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3969
    this->id_));
3970
}
3971

3972
int AdaptiveLibMesh::get_bin(Position r, Direction u) const
3973
{
3974
  // look-up a tet using the point locator
3975
  libMesh::Point p(r.x, r.y, r.z);
×
3976

3977
  if (length_multiplier_ > 0.0) {
×
3978
    // Scale the point down
3979
    p /= length_multiplier_;
3980
  }
3981

3982
  // quick rejection check
3983
  if (!bbox_.contains_point(p)) {
×
3984
    return -1;
3985
  }
3986

3987
  const auto& point_locator = pl_.at(thread_num());
×
3988

3989
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
3990
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
3991
}
3992

3993
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3994
{
3995
  int bin = elem_to_bin_map_[elem->id()];
3996
  if (bin >= n_bins() || bin < 0) {
×
3997
    fatal_error(fmt::format("Invalid bin: {}", bin));
3998
  }
3999
  return bin;
4000
}
4001

4002
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4003
{
4004
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4005
}
4006

4007
#endif // OPENMC_LIBMESH_ENABLED
4008

4009
//==============================================================================
4010
// Non-member functions
4011
//==============================================================================
4012

4013
void read_meshes(pugi::xml_node root)
13,394✔
4014
{
4015
  std::unordered_set<int> mesh_ids;
13,394✔
4016

4017
  for (auto node : root.children("mesh")) {
16,619✔
4018
    // Check to make sure multiple meshes in the same file don't share IDs
4019
    int id = std::stoi(get_node_value(node, "id"));
6,450✔
4020
    if (contains(mesh_ids, id)) {
6,450!
UNCOV
4021
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4022
                              "'{}' in the same input file",
4023
        id));
4024
    }
4025
    mesh_ids.insert(id);
3,225✔
4026

4027
    // If we've already read a mesh with the same ID in a *different* file,
4028
    // assume it is the same here
4029
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,225!
UNCOV
4030
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4031
      continue;
×
4032
    }
4033

4034
    std::string mesh_type;
3,225✔
4035
    if (check_for_node(node, "type")) {
3,225✔
4036
      mesh_type = get_node_value(node, "type", true, true);
950✔
4037
    } else {
4038
      mesh_type = "regular";
2,275✔
4039
    }
4040

4041
    // determine the mesh library to use
4042
    std::string mesh_lib;
3,225✔
4043
    if (check_for_node(node, "library")) {
3,225✔
4044
      mesh_lib = get_node_value(node, "library", true, true);
49!
4045
    }
4046

4047
    Mesh::create(node, mesh_type, mesh_lib);
3,225✔
4048
  }
3,225✔
4049
}
13,394✔
4050

4051
void read_meshes(hid_t group)
22✔
4052
{
4053
  std::unordered_set<int> mesh_ids;
22✔
4054

4055
  std::vector<int> ids;
22✔
4056
  read_attribute(group, "ids", ids);
22✔
4057

4058
  for (auto id : ids) {
55✔
4059

4060
    // Check to make sure multiple meshes in the same file don't share IDs
4061
    if (contains(mesh_ids, id)) {
66!
UNCOV
4062
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4063
                              "'{}' in the same HDF5 input file",
4064
        id));
4065
    }
4066
    mesh_ids.insert(id);
33✔
4067

4068
    // If we've already read a mesh with the same ID in a *different* file,
4069
    // assume it is the same here
4070
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
33!
4071
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4072
      continue;
33✔
4073
    }
4074

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

UNCOV
4078
    std::string mesh_type;
×
4079
    if (object_exists(mesh_group, "type")) {
×
4080
      read_dataset(mesh_group, "type", mesh_type);
×
4081
    } else {
UNCOV
4082
      mesh_type = "regular";
×
4083
    }
4084

4085
    // determine the mesh library to use
UNCOV
4086
    std::string mesh_lib;
×
4087
    if (object_exists(mesh_group, "library")) {
×
4088
      read_dataset(mesh_group, "library", mesh_lib);
×
4089
    }
4090

UNCOV
4091
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4092
  }
×
4093
}
44✔
4094

4095
void meshes_to_hdf5(hid_t group)
7,624✔
4096
{
4097
  // Write number of meshes
4098
  hid_t meshes_group = create_group(group, "meshes");
7,624✔
4099
  int32_t n_meshes = model::meshes.size();
7,624✔
4100
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,624✔
4101

4102
  if (n_meshes > 0) {
7,624✔
4103
    // Write IDs of meshes
4104
    vector<int> ids;
2,304✔
4105
    for (const auto& m : model::meshes) {
5,253✔
4106
      m->to_hdf5(meshes_group);
2,949✔
4107
      ids.push_back(m->id_);
2,949✔
4108
    }
4109
    write_attribute(meshes_group, "ids", ids);
2,304✔
4110
  }
2,304✔
4111

4112
  close_group(meshes_group);
7,624✔
4113
}
7,624✔
4114

4115
void free_memory_mesh()
8,721✔
4116
{
4117
  model::meshes.clear();
8,721✔
4118
  model::mesh_map.clear();
8,721✔
4119
}
8,721✔
4120

4121
extern "C" int n_meshes()
308✔
4122
{
4123
  return model::meshes.size();
308✔
4124
}
4125

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