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

openmc-dev / openmc / 30082591782

24 Jul 2026 09:26AM UTC coverage: 81.336% (-0.08%) from 81.413%
30082591782

Pull #4026

github

web-flow
Merge d3b3c7684 into 01790598d
Pull Request #4026: Add domain decomposition for random ray solver

19231 of 27986 branches covered (68.72%)

Branch coverage included in aggregate %.

1186 of 1209 new or added lines in 12 files covered. (98.1%)

415 existing lines in 10 files now uncovered.

61115 of 70797 relevant lines covered (86.32%)

49017206.19 hits per line

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

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

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

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

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

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

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

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

58
namespace openmc {
59

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

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

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

74
namespace model {
75

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

79
} // namespace model
80

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

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

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

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

115
//! Atomic compare-and-swap for signed 32-bit integer
116
//
117
//! \param[in,out] ptr Pointer to value to update
118
//! \param[in,out] expected Value to compare to
119
//! \param[in] desired If comparison is successful, value to update to
120
//! \return True if the comparison was successful and the value was updated
121
inline bool atomic_cas_int32(int32_t* ptr, int32_t& expected, int32_t desired)
1,568✔
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,568✔
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,829,461✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
37,952✔
146
  return out;
147
}
148

149
inline void atomic_update_double(double* ptr, double value, bool is_min)
38,829,312✔
150
{
151
#if defined(__GNUC__) || defined(__clang__)
152
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
38,829,312✔
153
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
38,829,312✔
154
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
38,829,312✔
155
  double current = bit_cast_value<double>(current_bits);
38,829,312✔
156
  while (is_min ? (value < current) : (value > current)) {
38,829,461✔
157
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
37,952✔
158
    uint64_t expected_bits = current_bits;
37,952✔
159
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
37,952✔
160
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
161
      return;
38,829,312✔
162
    }
163
    current_bits = expected_bits;
149✔
164
    current = bit_cast_value<double>(current_bits);
149✔
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,414,656✔
188
{
189
  atomic_update_double(ptr, value, false);
6,471,552✔
190
}
6,471,552✔
191

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

197
namespace detail {
198

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

203
void MaterialVolumes::add_volume(
9,124,939✔
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,124,939!
214
    // Determine slot to check, making sure it is positive
215
    int slot = (index_material + attempt) % table_size_;
9,124,939✔
216
    if (slot < 0)
9,124,939✔
217
      slot += table_size_;
5,873,290✔
218
    int32_t* slot_ptr = &this->materials(index_elem, slot);
9,124,939✔
219

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

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

238
    // Slot appears to be empty; attempt to claim
239
    if (current_val == EMPTY) {
1,568!
240
      // Attempt compare-and-swap from EMPTY to index_material
241
      int32_t expected_val = EMPTY;
1,568✔
242
      bool claimed_slot =
1,568✔
243
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,568✔
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,568!
248
#pragma omp atomic
864✔
249
        this->volumes(index_elem, slot) += volume;
1,568✔
250
        if (bbox) {
1,568✔
251
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
168✔
252
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
168✔
253
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
168✔
254
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
168✔
255
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
168✔
256
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
168✔
257
        }
258
        return;
1,568✔
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,442✔
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,442✔
338
    model::meshes.push_back(make_unique<RegularMesh>(dataset));
2,526✔
339
  } else if (mesh_type == RectilinearMesh::mesh_type) {
916✔
340
    model::meshes.push_back(make_unique<RectilinearMesh>(dataset));
122✔
341
  } else if (mesh_type == CylindricalMesh::mesh_type) {
794✔
342
    model::meshes.push_back(make_unique<CylindricalMesh>(dataset));
400✔
343
  } else if (mesh_type == SphericalMesh::mesh_type) {
394✔
344
    model::meshes.push_back(make_unique<SphericalMesh>(dataset));
345✔
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,442✔
364

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

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

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

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

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

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

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

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

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

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

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

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

432
//! Default (Cartesian) axis labels used for surface bin labels.
433
std::array<const char*, 3> Mesh::axis_labels() const
428,252✔
434
{
435
  return {"x", "y", "z"};
428,252✔
436
}
437

438
//! Build the surface component of a mesh surface tally bin label.
439
//! surf_index: 0=out/min, 1=in/min, 2=out/max, 3=in/max
440
std::string Mesh::surface_bin_label(int surf_index) const
1,398,188✔
441
{
442
  auto labels = this->axis_labels();
1,398,188✔
443
  int dim = surf_index / 4;
1,398,188✔
444
  int code = surf_index % 4;
1,398,188✔
445
  bool incoming = (code == 1) || (code == 3);
1,398,188✔
446
  bool max = (code == 2) || (code == 3);
1,398,188✔
447
  return fmt::format(" {}, {}-{}", incoming ? "Incoming" : "Outgoing",
1,398,188✔
448
    labels[dim], max ? "max" : "min");
2,796,376✔
449
}
450

UNCOV
451
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
×
452
  int32_t* materials, double* volumes) const
453
{
UNCOV
454
  this->material_volumes(nx, ny, nz, table_size, materials, volumes, nullptr);
×
UNCOV
455
}
×
456

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

473
  Timer timer;
209✔
474
  timer.start();
209✔
475

476
  // Create object for keeping track of materials/volumes
477
  detail::MaterialVolumes result(materials, volumes, bboxes, table_size);
209✔
478
  bool compute_bboxes = bboxes != nullptr;
209✔
479

480
  // Determine bounding box
481
  auto bbox = this->bounding_box();
209✔
482

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

485
  // Determine effective width of rays
486
  Position width = bbox.max - bbox.min;
209✔
487
  width.x = (nx > 0) ? width.x / nx : 0.0;
209✔
488
  width.y = (ny > 0) ? width.y / ny : 0.0;
209✔
489
  width.z = (nz > 0) ? width.z / nz : 0.0;
209✔
490

491
  // Set flag for mesh being contained within model
492
  bool out_of_model = false;
209✔
493

494
#pragma omp parallel
114✔
495
  {
95✔
496
    // Preallocate vector for mesh indices and length fractions and particle
497
    vector<int> bins;
95✔
498
    vector<double> length_fractions;
95✔
499
    Particle p;
95✔
500

501
    SourceSite site;
95✔
502
    site.E = 1.0;
95✔
503
    site.particle = ParticleType::neutron();
95✔
504

505
    for (int axis = 0; axis < 3; ++axis) {
380✔
506
      // Set starting position and direction
507
      site.r = {0.0, 0.0, 0.0};
285✔
508
      site.r[axis] = bbox.min[axis];
285✔
509
      site.u = {0.0, 0.0, 0.0};
285✔
510
      site.u[axis] = 1.0;
285✔
511

512
      // Determine width of rays and number of rays in other directions
513
      int ax1 = (axis + 1) % 3;
285✔
514
      int ax2 = (axis + 2) % 3;
285✔
515
      double min1 = bbox.min[ax1];
285✔
516
      double min2 = bbox.min[ax2];
285✔
517
      double d1 = width[ax1];
285✔
518
      double d2 = width[ax2];
285✔
519
      int n1 = n_rays[ax1];
285✔
520
      int n2 = n_rays[ax2];
285✔
521
      if (n1 == 0 || n2 == 0) {
285✔
522
        continue;
60✔
523
      }
524

525
      // Divide rays in first direction over MPI processes by computing starting
526
      // and ending indices
527
      int min_work = n1 / mpi::n_procs;
225✔
528
      int remainder = n1 % mpi::n_procs;
225✔
529
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
225!
530
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
225!
531
      int i1_end = i1_start + n1_local;
225✔
532

533
      // Loop over rays on face of bounding box
534
#pragma omp for collapse(2)
535
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
17,600✔
536
        for (int i2 = 0; i2 < n2; ++i2) {
3,080,220✔
537
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,062,845✔
538
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,062,845✔
539

540
          p.from_source(&site);
3,062,845✔
541

542
          // Determine particle's location
543
          if (!exhaustive_find_cell(p)) {
3,062,845✔
544
            out_of_model = true;
39,930✔
545
            continue;
39,930✔
546
          }
547

548
          // Set birth cell attribute
549
          if (p.cell_born() == C_NONE)
3,022,915!
550
            p.cell_born() = p.lowest_coord().cell();
3,022,915✔
551

552
          // Initialize last cells from current cell
553
          for (int j = 0; j < p.n_coord(); ++j) {
6,045,830✔
554
            p.cell_last(j) = p.coord(j).cell();
3,022,915✔
555
          }
556
          p.n_coord_last() = p.n_coord();
3,022,915✔
557

558
          while (true) {
4,826,243✔
559
            // Ray trace from r_start to r_end
560
            Position r0 = p.r();
3,924,579✔
561
            double max_distance = bbox.max[axis] - r0[axis];
3,924,579✔
562

563
            // Find the distance to the nearest boundary
564
            BoundaryInfo boundary = distance_to_boundary(p);
3,924,579✔
565

566
            // Advance particle forward
567
            double distance = std::min(boundary.distance(), max_distance);
3,924,579✔
568
            p.move_distance(distance);
3,924,579✔
569

570
            // Determine what mesh elements were crossed by particle
571
            bins.clear();
3,924,579✔
572
            length_fractions.clear();
3,924,579✔
573
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
3,924,579✔
574

575
            // Add volumes to any mesh elements that were crossed
576
            int i_material = p.material();
3,924,579✔
577
            if (i_material != C_NONE) {
3,924,579✔
578
              i_material = model::materials[i_material]->id();
1,246,437✔
579
            }
580
            double cumulative_frac = 0.0;
3,924,579✔
581
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
8,067,808✔
582
              int mesh_index = bins[i_bin];
4,143,229✔
583
              double length = distance * length_fractions[i_bin];
4,143,229✔
584
              double volume = length * d1 * d2;
4,143,229✔
585

586
              if (compute_bboxes) {
4,143,229✔
587
                double axis_start = r0[axis] + distance * cumulative_frac;
2,937,144✔
588
                double axis_end = axis_start + length;
2,937,144✔
589
                cumulative_frac += length_fractions[i_bin];
2,937,144✔
590

591
                Position contrib_min = site.r;
2,937,144✔
592
                Position contrib_max = site.r;
2,937,144✔
593

594
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,937,144✔
595
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,937,144✔
596
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,937,144✔
597
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,937,144✔
598
                contrib_min[axis] = std::min(axis_start, axis_end);
2,937,144!
599
                contrib_max[axis] = std::max(axis_start, axis_end);
5,874,288!
600

601
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,937,144✔
602
                contrib_bbox &= bbox;
2,937,144✔
603

604
                result.add_volume(
2,937,144✔
605
                  mesh_index, i_material, volume, &contrib_bbox);
606
              } else {
607
                // Add volume to result
608
                result.add_volume(mesh_index, i_material, volume);
1,206,085✔
609
              }
610
            }
611

612
            if (distance == max_distance)
3,924,579✔
613
              break;
614

615
            // cross next geometric surface
616
            for (int j = 0; j < p.n_coord(); ++j) {
1,803,328✔
617
              p.cell_last(j) = p.coord(j).cell();
901,664✔
618
            }
619
            p.n_coord_last() = p.n_coord();
901,664✔
620

621
            // Set surface that particle is on and adjust coordinate levels
622
            p.surface() = boundary.surface();
901,664✔
623
            p.n_coord() = boundary.coord_level();
901,664✔
624

625
            if (boundary.lattice_translation()[0] != 0 ||
901,664!
626
                boundary.lattice_translation()[1] != 0 ||
901,664!
627
                boundary.lattice_translation()[2] != 0) {
901,664!
628
              // Particle crosses lattice boundary
629
              cross_lattice(p, boundary);
×
630
            } else {
631
              // Particle crosses surface
632
              const auto& surf {model::surfaces[p.surface_index()].get()};
901,664✔
633
              p.cross_surface(*surf);
901,664✔
634
            }
635
          }
901,664✔
636
        }
637
      }
638
    }
639
  }
95✔
640

641
  // Check for errors
642
  if (out_of_model) {
209✔
643
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
644
  } else if (result.table_full()) {
198!
UNCOV
645
    throw std::runtime_error("Maximum number of materials for mesh material "
×
UNCOV
646
                             "volume calculation insufficient.");
×
647
  }
648

649
  // Compute time for raytracing
650
  double t_raytrace = timer.elapsed();
198✔
651

652
#ifdef OPENMC_MPI
653
  // Combine results from multiple MPI processes
654
  if (mpi::n_procs > 1) {
72!
655
    int total = this->n_bins() * table_size;
656
    int total_bbox = total * 6;
657
    if (mpi::master) {
×
658
      // Allocate temporary buffer for receiving data
659
      vector<int32_t> mats(total);
660
      vector<double> vols(total);
×
661
      vector<double> recv_bboxes;
×
662
      if (compute_bboxes) {
×
663
        recv_bboxes.resize(total_bbox);
×
664
      }
665

666
      for (int i = 1; i < mpi::n_procs; ++i) {
×
667
        // Receive material indices and volumes from process i
668
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
669
          MPI_STATUS_IGNORE);
670
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
671
          MPI_STATUS_IGNORE);
672
        if (compute_bboxes) {
×
673
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
674
            mpi::intracomm, MPI_STATUS_IGNORE);
675
        }
676

677
        // Combine with existing results; we can call thread unsafe version of
678
        // add_volume because each thread is operating on a different element
679
#pragma omp for
680
        for (int index_elem = 0; index_elem < n_bins(); ++index_elem) {
×
681
          for (int k = 0; k < table_size; ++k) {
×
682
            int index = index_elem * table_size + k;
683
            if (mats[index] != EMPTY) {
×
684
              if (compute_bboxes) {
×
685
                int bbox_index = index * 6;
686
                BoundingBox slot_bbox {
687
                  {recv_bboxes[bbox_index + 0], recv_bboxes[bbox_index + 1],
×
688
                    recv_bboxes[bbox_index + 2]},
689
                  {recv_bboxes[bbox_index + 3], recv_bboxes[bbox_index + 4],
×
690
                    recv_bboxes[bbox_index + 5]}};
×
691
                result.add_volume_unsafe(
692
                  index_elem, mats[index], vols[index], &slot_bbox);
×
693
              } else {
694
                result.add_volume_unsafe(index_elem, mats[index], vols[index]);
×
695
              }
696
            }
697
          }
698
        }
699
      }
700
    } else {
701
      // Send material indices and volumes to process 0
702
      MPI_Send(materials, total, MPI_INT32_T, 0, mpi::rank, mpi::intracomm);
703
      MPI_Send(volumes, total, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
704
      if (compute_bboxes) {
×
705
        MPI_Send(bboxes, total_bbox, MPI_DOUBLE, 0, mpi::rank, mpi::intracomm);
706
      }
707
    }
708
  }
709

710
  // Report time for MPI communication
711
  double t_mpi = timer.elapsed() - t_raytrace;
72✔
712
#else
713
  double t_mpi = 0.0;
108✔
714
#endif
715

716
  // Normalize based on known volumes of elements
717
  for (int i = 0; i < this->n_bins(); ++i) {
1,111✔
718
    // Estimated total volume in element i
719
    double volume = 0.0;
720
    for (int j = 0; j < table_size; ++j) {
8,349✔
721
      volume += result.volumes(i, j);
7,436✔
722
    }
723
    // Renormalize volumes based on known volume of element i
724
    double norm = this->volume(i) / volume;
913✔
725
    for (int j = 0; j < table_size; ++j) {
8,349✔
726
      result.volumes(i, j) *= norm;
7,436✔
727
    }
728
  }
729

730
  // Get total time and normalization time
731
  timer.stop();
198✔
732
  double t_total = timer.elapsed();
198✔
733
  double t_norm = t_total - t_raytrace - t_mpi;
198✔
734

735
  // Show timing statistics
736
  if (settings::verbosity < 7 || !mpi::master)
198!
737
    return;
44✔
738
  header("Timing Statistics", 7);
154✔
739
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
154✔
740
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
154✔
741
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
154✔
742
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
154✔
743
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
308✔
744
    n_total / t_raytrace);
154✔
745
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
224✔
746
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
154✔
747
  std::fflush(stdout);
154✔
748
}
749

750
void Mesh::to_hdf5(hid_t group) const
3,368✔
751
{
752
  // Create group for mesh
753
  std::string group_name = fmt::format("mesh {}", id_);
3,368✔
754
  hid_t mesh_group = create_group(group, group_name.c_str());
3,368✔
755

756
  // Write mesh type
757
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,368✔
758

759
  // Write mesh ID
760
  write_attribute(mesh_group, "id", id_);
3,368✔
761

762
  // Write mesh name
763
  write_dataset(mesh_group, "name", name_);
3,368✔
764

765
  // Write mesh data
766
  this->to_hdf5_inner(mesh_group);
3,368✔
767

768
  // Close group
769
  close_group(mesh_group);
3,368✔
770
}
3,368✔
771

772
//==============================================================================
773
// Structured Mesh implementation
774
//==============================================================================
775

776
std::string StructuredMesh::bin_label(int bin) const
5,315,732✔
777
{
778
  MeshIndex ijk = get_indices_from_bin(bin);
5,315,732✔
779

780
  if (n_dimension_ > 2) {
5,315,732✔
781
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,299,133✔
782
  } else if (n_dimension_ > 1) {
16,599✔
783
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
16,236✔
784
  } else {
785
    return fmt::format("Mesh Index ({})", ijk[0]);
363✔
786
  }
787
}
788

789
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,938✔
790
{
791
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,938✔
792
}
793

794
Position StructuredMesh::sample_element(
1,438,198✔
795
  const MeshIndex& ijk, uint64_t* seed) const
796
{
797
  // lookup the lower/upper bounds for the mesh element
798
  double x_min = negative_grid_boundary(ijk, 0);
1,438,198✔
799
  double x_max = positive_grid_boundary(ijk, 0);
1,438,198✔
800

801
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,438,198!
802
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,438,198!
803

804
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,438,198!
805
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,438,198!
806

807
  return {x_min + (x_max - x_min) * prn(seed),
1,438,198✔
808
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,438,198✔
809
}
810

811
//==============================================================================
812
// Unstructured Mesh implementation
813
//==============================================================================
814

815
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
49!
816
{
817
  n_dimension_ = 3;
49✔
818

819
  // check the mesh type
820
  if (check_for_node(node, "type")) {
49!
821
    auto temp = get_node_value(node, "type", true, true);
49!
822
    if (temp != mesh_type) {
49!
UNCOV
823
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
824
    }
825
  }
49✔
826

827
  // check if a length unit multiplier was specified
828
  if (check_for_node(node, "length_multiplier")) {
49!
UNCOV
829
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
830
  }
831

832
  // get the filename of the unstructured mesh to load
833
  if (check_for_node(node, "filename")) {
49!
834
    filename_ = get_node_value(node, "filename");
49!
835
    if (!file_exists(filename_)) {
49!
UNCOV
836
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
837
    }
838
  } else {
UNCOV
839
    fatal_error(fmt::format(
×
840
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
841
  }
842

843
  if (check_for_node(node, "options")) {
49!
844
    options_ = get_node_value(node, "options");
16!
845
  }
846

847
  // check if mesh tally data should be written with
848
  // statepoint files
849
  if (check_for_node(node, "output")) {
49!
850
    output_ = get_node_value_bool(node, "output");
×
851
  }
852
}
49✔
853

854
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
855
{
856
  n_dimension_ = 3;
×
857

858
  // check the mesh type
UNCOV
859
  if (object_exists(group, "type")) {
×
860
    std::string temp;
×
861
    read_dataset(group, "type", temp);
×
UNCOV
862
    if (temp != mesh_type) {
×
UNCOV
863
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
864
    }
865
  }
×
866

867
  // check if a length unit multiplier was specified
UNCOV
868
  if (object_exists(group, "length_multiplier")) {
×
UNCOV
869
    read_dataset(group, "length_multiplier", length_multiplier_);
×
870
  }
871

872
  // get the filename of the unstructured mesh to load
873
  if (object_exists(group, "filename")) {
×
UNCOV
874
    read_dataset(group, "filename", filename_);
×
UNCOV
875
    if (!file_exists(filename_)) {
×
UNCOV
876
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
877
    }
878
  } else {
UNCOV
879
    fatal_error(fmt::format(
×
UNCOV
880
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
881
  }
882

UNCOV
883
  if (attribute_exists(group, "options")) {
×
UNCOV
884
    read_attribute(group, "options", options_);
×
885
  }
886

887
  // check if mesh tally data should be written with
888
  // statepoint files
UNCOV
889
  if (attribute_exists(group, "output")) {
×
UNCOV
890
    read_attribute(group, "output", output_);
×
891
  }
UNCOV
892
}
×
893

894
void UnstructuredMesh::determine_bounds()
25✔
895
{
896
  double xmin = INFTY;
25✔
897
  double ymin = INFTY;
25✔
898
  double zmin = INFTY;
25✔
899
  double xmax = -INFTY;
25✔
900
  double ymax = -INFTY;
25✔
901
  double zmax = -INFTY;
25✔
902
  int n = this->n_vertices();
25✔
903
  for (int i = 0; i < n; ++i) {
55,951✔
904
    auto v = this->vertex(i);
55,926✔
905
    xmin = std::min(v.x, xmin);
55,926✔
906
    ymin = std::min(v.y, ymin);
55,926✔
907
    zmin = std::min(v.z, zmin);
55,926✔
908
    xmax = std::max(v.x, xmax);
55,926✔
909
    ymax = std::max(v.y, ymax);
55,926✔
910
    zmax = std::max(v.z, zmax);
79,911✔
911
  }
912
  lower_left_ = {xmin, ymin, zmin};
25✔
913
  upper_right_ = {xmax, ymax, zmax};
25✔
914
}
25✔
915

916
Position UnstructuredMesh::sample_tet(
601,230✔
917
  std::array<Position, 4> coords, uint64_t* seed) const
918
{
919
  // Uniform distribution
920
  double s = prn(seed);
601,230✔
921
  double t = prn(seed);
601,230✔
922
  double u = prn(seed);
601,230✔
923

924
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
925
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
926
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
927
  if (s + t > 1) {
601,230✔
928
    s = 1.0 - s;
300,882✔
929
    t = 1.0 - t;
300,882✔
930
  }
931
  if (s + t + u > 1) {
601,230✔
932
    if (t + u > 1) {
400,122✔
933
      double old_t = t;
200,373✔
934
      t = 1.0 - u;
200,373✔
935
      u = 1.0 - s - old_t;
200,373✔
936
    } else if (t + u <= 1) {
199,749!
937
      double old_s = s;
199,749✔
938
      s = 1.0 - t - u;
199,749✔
939
      u = old_s + t + u - 1;
199,749✔
940
    }
941
  }
942
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,803,690✔
943
         u * (coords[3] - coords[0]) + coords[0];
601,230✔
944
}
945

946
const std::string UnstructuredMesh::mesh_type = "unstructured";
947

948
std::string UnstructuredMesh::get_mesh_type() const
34✔
949
{
950
  return mesh_type;
34✔
951
}
952

UNCOV
953
void UnstructuredMesh::surface_bins_crossed(
×
954
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
955
{
UNCOV
956
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
957
}
958

959
std::string UnstructuredMesh::bin_label(int bin) const
207,736✔
960
{
961
  return fmt::format("Mesh Index ({})", bin);
207,736✔
962
};
963

964
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
34✔
965
{
966
  write_dataset(mesh_group, "filename", filename_);
34!
967
  write_dataset(mesh_group, "library", this->library());
34!
968
  if (!options_.empty()) {
34✔
969
    write_attribute(mesh_group, "options", options_);
8✔
970
  }
971

972
  if (length_multiplier_ > 0.0)
34!
UNCOV
973
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
974

975
  // write vertex coordinates
976
  tensor::Tensor<double> vertices(
34✔
977
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
34✔
978
  for (int i = 0; i < this->n_vertices(); i++) {
72,939!
979
    auto v = this->vertex(i);
72,905!
980
    vertices.slice(i) = {v.x, v.y, v.z};
145,810!
981
  }
982
  write_dataset(mesh_group, "vertices", vertices);
34!
983

984
  int num_elem_skipped = 0;
34✔
985

986
  // write element types and connectivity
987
  vector<double> volumes;
34!
988
  tensor::Tensor<int> connectivity(
34✔
989
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
34!
990
  tensor::Tensor<int> elem_types(
34✔
991
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
34!
992
  for (int i = 0; i < this->n_bins(); i++) {
351,770!
993
    auto conn = this->connectivity(i);
351,736!
994

995
    volumes.emplace_back(this->volume(i));
351,736!
996

997
    // write linear tet element
998
    if (conn.size() == 4) {
351,736✔
999
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
347,736!
1000
      connectivity.slice(i) = {
347,736!
1001
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
695,472!
1002
      // write linear hex element
1003
    } else if (conn.size() == 8) {
4,000!
1004
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
4,000!
1005
      connectivity.slice(i) = {
4,000!
1006
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
8,000!
1007
    } else {
UNCOV
1008
      num_elem_skipped++;
×
UNCOV
1009
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
UNCOV
1010
      connectivity.slice(i) = -1;
×
1011
    }
1012
  }
351,736✔
1013

1014
  // warn users that some elements were skipped
1015
  if (num_elem_skipped > 0) {
34!
UNCOV
1016
    warning(fmt::format("The connectivity of {} elements "
×
1017
                        "on mesh {} were not written "
1018
                        "because they are not of type linear tet/hex.",
1019
      num_elem_skipped, this->id_));
×
1020
  }
1021

1022
  write_dataset(mesh_group, "volumes", volumes);
34!
1023
  write_dataset(mesh_group, "connectivity", connectivity);
34!
1024
  write_dataset(mesh_group, "element_types", elem_types);
34!
1025
}
102✔
1026

1027
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
25✔
1028
{
1029
  length_multiplier_ = length_multiplier;
25✔
1030
}
25✔
1031

1032
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1033
{
1034
  auto conn = connectivity(bin);
120,000✔
1035

1036
  if (conn.size() == 4)
120,000!
1037
    return ElementType::LINEAR_TET;
UNCOV
1038
  else if (conn.size() == 8)
×
1039
    return ElementType::LINEAR_HEX;
1040
  else
UNCOV
1041
    return ElementType::UNSUPPORTED;
×
1042
}
120,000✔
1043

1044
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,803,996,735✔
1045
  Position r, bool& in_mesh) const
1046
{
1047
  MeshIndex ijk;
1,803,996,735✔
1048
  in_mesh = true;
1,803,996,735✔
1049
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1050
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1051

1052
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1053
      in_mesh = false;
102,839,607✔
1054
  }
1055
  return ijk;
1,803,996,735✔
1056
}
1057

1058
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647✔
1059
{
1060
  switch (n_dimension_) {
2,147,483,647!
1061
  case 1:
880,627✔
1062
    return ijk[0] - 1;
880,627✔
1063
  case 2:
149,522,373✔
1064
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
149,522,373✔
1065
  case 3:
2,147,483,647✔
1066
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,147,483,647✔
UNCOV
1067
  default:
×
UNCOV
1068
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1069
  }
1070
}
1071

1072
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,088,607✔
1073
{
1074
  MeshIndex ijk;
8,088,607✔
1075
  if (n_dimension_ == 1) {
8,088,607✔
1076
    ijk[0] = bin + 1;
363✔
1077
  } else if (n_dimension_ == 2) {
8,088,244✔
1078
    ijk[0] = bin % shape_[0] + 1;
16,236✔
1079
    ijk[1] = bin / shape_[0] + 1;
16,236✔
1080
  } else if (n_dimension_ == 3) {
8,072,008!
1081
    ijk[0] = bin % shape_[0] + 1;
8,072,008✔
1082
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,072,008✔
1083
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,072,008✔
1084
  }
1085
  return ijk;
8,088,607✔
1086
}
1087

1088
int StructuredMesh::get_bin(Position r) const
578,841,324✔
1089
{
1090
  // Determine indices
1091
  bool in_mesh;
578,841,324✔
1092
  MeshIndex ijk = get_indices(r, in_mesh);
578,841,324✔
1093
  if (!in_mesh)
578,841,324✔
1094
    return -1;
1095

1096
  // Convert indices to bin
1097
  return get_bin_from_indices(ijk);
557,747,167✔
1098
}
1099

1100
int StructuredMesh::n_bins() const
1,259,322✔
1101
{
1102
  // Bin indices are stored as 32-bit ints in the tally system.
1103
  int64_t n = 1;
1,259,322✔
1104
  for (int i = 0; i < n_dimension_; ++i)
5,036,828✔
1105
    n *= shape_[i];
3,777,506✔
1106
  if (n > std::numeric_limits<int>::max()) {
1,259,322!
UNCOV
1107
    fatal_error(fmt::format(
×
UNCOV
1108
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1109
  }
1110
  return static_cast<int>(n);
1,259,322✔
1111
}
1112

1113
int StructuredMesh::n_surface_bins() const
436✔
1114
{
1115
  // Surface bin indices are stored as 32-bit ints in the tally system.
1116
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
436✔
1117
  if (n > std::numeric_limits<int>::max()) {
436!
UNCOV
1118
    fatal_error(fmt::format(
×
UNCOV
1119
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1120
  }
1121
  return static_cast<int>(n);
436✔
1122
}
1123

1124
tensor::Tensor<double> StructuredMesh::count_sites(
×
1125
  const SourceSite* bank, int64_t length, bool* outside) const
1126
{
1127
  // Determine shape of array for counts
UNCOV
1128
  std::size_t m = this->n_bins();
×
1129
  vector<std::size_t> shape = {m};
×
1130

1131
  // Create array of zeros
UNCOV
1132
  auto cnt = tensor::zeros<double>(shape);
×
1133
  bool outside_ = false;
1134

UNCOV
1135
  for (int64_t i = 0; i < length; i++) {
×
UNCOV
1136
    const auto& site = bank[i];
×
1137

1138
    // determine scoring bin for entropy mesh
UNCOV
1139
    int mesh_bin = get_bin(site.r);
×
1140

1141
    // if outside mesh, skip particle
UNCOV
1142
    if (mesh_bin < 0) {
×
UNCOV
1143
      outside_ = true;
×
UNCOV
1144
      continue;
×
1145
    }
1146

1147
    // Add to appropriate bin
UNCOV
1148
    cnt(mesh_bin) += site.wgt;
×
1149
  }
1150

1151
  // Create reduced count data
1152
  auto counts = tensor::zeros<double>(shape);
×
UNCOV
1153
  int total = cnt.size();
×
1154

1155
#ifdef OPENMC_MPI
1156
  // collect values from all processors
1157
  MPI_Reduce(
×
1158
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1159

1160
  // Check if there were sites outside the mesh for any processor
1161
  if (outside) {
×
1162
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1163
  }
1164
#else
1165
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1166
  if (outside)
×
1167
    *outside = outside_;
1168
#endif
1169

UNCOV
1170
  return counts;
×
UNCOV
1171
}
×
1172

1173
// raytrace through the mesh. The template class T will do the tallying.
1174
// A modern optimizing compiler can recognize the noop method of T and
1175
// eliminate that call entirely.
1176
template<class T>
1177
void StructuredMesh::raytrace_mesh(
1,272,326,095✔
1178
  Position r0, Position r1, const Direction& u, T tally) const
1179
{
1180
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1181
  // enable/disable tally calls for now, T template type needs to provide both
1182
  // surface and track methods, which might be empty. modern optimizing
1183
  // compilers will (hopefully) eliminate the complete code (including
1184
  // calculation of parameters) but for the future: be explicit
1185

1186
  // Compute the length of the entire track.
1187
  double total_distance = (r1 - r0).norm();
1,272,326,095✔
1188
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,272,326,095✔
1189
    return;
1190

1191
  // keep a copy of the original global position to pass to get_indices,
1192
  // which performs its own transformation to local coordinates
1193
  Position global_r = r0;
1,217,979,583✔
1194
  Position local_r = local_coords(r0);
1,217,979,583✔
1195

1196
  const int n = n_dimension_;
1,217,979,583✔
1197

1198
  // Flag if position is inside the mesh
1199
  bool in_mesh;
1200

1201
  // Position is r = r0 + u * traveled_distance, start at r0
1202
  double traveled_distance {0.0};
1,217,979,583✔
1203

1204
  // Calculate index of current cell. Offset the position a tiny bit in
1205
  // direction of flight
1206
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,217,979,583✔
1207

1208
  // if track is very short, assume that it is completely inside one cell.
1209
  // Only the current cell will score and no surfaces
1210
  if (total_distance < 2 * TINY_BIT) {
1,217,979,583✔
1211
    if (in_mesh) {
685,802✔
1212
      tally.track(ijk, 1.0);
685,318✔
1213
    }
1214
    return;
685,802✔
1215
  }
1216

1217
  // Calculate initial distances to next surfaces in all three dimensions
1218
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1219
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1220
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1221
  }
1222

1223
  // Loop until r = r1 is eventually reached
1224
  while (true) {
1225

1226
    if (in_mesh) {
2,085,643,610✔
1227

1228
      // find surface with minimal distance to current position
1229
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,999,176,598✔
1230
                     distances.begin();
1,999,176,598✔
1231

1232
      // Tally track length delta since last step
1233
      tally.track(ijk,
1,999,176,598✔
1234
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1235
          total_distance);
1236

1237
      // update position and leave, if we have reached end position
1238
      traveled_distance = distances[k].distance;
1,999,176,598✔
1239
      if (traveled_distance >= total_distance)
1,999,176,598✔
1240
        return;
1241

1242
      // If we have not reached r1, we have hit a surface. Tally outward
1243
      // current
1244
      tally.surface(ijk, k, distances[k].max_surface, false);
861,174,001✔
1245

1246
      // Update cell and calculate distance to next surface in k-direction.
1247
      // The two other directions are still valid!
1248
      ijk[k] = distances[k].next_index;
861,174,001✔
1249
      distances[k] =
861,174,001✔
1250
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
861,174,001✔
1251

1252
      // Check if we have left the interior of the mesh
1253
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
868,026,100✔
1254

1255
      // If we are still inside the mesh, tally inward current for the next
1256
      // cell
1257
      if (in_mesh)
29,576,976✔
1258
        tally.surface(ijk, k, !distances[k].max_surface, true);
866,933,601✔
1259

1260
    } else { // not inside mesh
1261

1262
      // For all directions outside the mesh, find the distance that we need
1263
      // to travel to reach the next surface. Use the largest distance, as
1264
      // only this will cross all outer surfaces.
1265
      int k_max {-1};
1266
      for (int k = 0; k < n; ++k) {
344,399,086✔
1267
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
257,932,074✔
1268
            (distances[k].distance > traveled_distance)) {
94,474,927✔
1269
          traveled_distance = distances[k].distance;
1270
          k_max = k;
1271
        }
1272
      }
1273
      // Assure some distance is traveled
1274
      if (k_max == -1) {
86,467,012✔
1275
        traveled_distance += TINY_BIT;
110✔
1276
      }
1277

1278
      // If r1 is not inside the mesh, exit here
1279
      if (traveled_distance >= total_distance)
86,467,012✔
1280
        return;
1281

1282
      // Calculate the new cell index and update all distances to next
1283
      // surfaces.
1284
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
7,175,828✔
1285
      for (int k = 0; k < n; ++k) {
28,494,774✔
1286
        distances[k] =
21,318,946✔
1287
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
21,318,946✔
1288
      }
1289

1290
      // If inside the mesh, Tally inward current
1291
      if (in_mesh && k_max >= 0)
7,175,828!
1292
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
838,749,885✔
1293
    }
1294
  }
1295
}
1296

1297
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,160,198,464✔
1298
  vector<int>& bins, vector<double>& lengths) const
1299
{
1300

1301
  // Helper tally class.
1302
  // stores a pointer to the mesh class and references to bins and lengths
1303
  // parameters. Performs the actual tally through the track method.
1304
  struct TrackAggregator {
1,160,198,464✔
1305
    TrackAggregator(
1,160,198,464✔
1306
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1307
      : mesh(_mesh), bins(_bins), lengths(_lengths)
1,160,198,464✔
1308
    {}
1309
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1310
    void track(const MeshIndex& ijk, double l) const
1,859,817,220✔
1311
    {
1312
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,859,817,220✔
1313
      lengths.push_back(l);
1,859,817,220✔
1314
    }
1,859,817,220✔
1315

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

1321
  // Perform the mesh raytrace with the helper class.
1322
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,160,198,464✔
1323
}
1,160,198,464✔
1324

1325
void StructuredMesh::surface_bins_crossed(
112,127,631✔
1326
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1327
{
1328

1329
  // Helper tally class.
1330
  // stores a pointer to the mesh class and a reference to the bins parameter.
1331
  // Performs the actual tally through the surface method.
1332
  struct SurfaceAggregator {
112,127,631✔
1333
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,127,631✔
1334
      : mesh(_mesh), bins(_bins)
112,127,631✔
1335
    {}
1336
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
58,159,332✔
1337
    {
1338
      int i_bin =
58,159,332✔
1339
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
58,159,332✔
1340
      if (max)
58,159,332✔
1341
        i_bin += 2;
29,051,517✔
1342
      if (inward)
58,159,332✔
1343
        i_bin += 1;
28,582,356✔
1344
      bins.push_back(i_bin);
58,159,332✔
1345
    }
58,159,332✔
1346
    void track(const MeshIndex& idx, double l) const {}
1347

1348
    const StructuredMesh* mesh;
1349
    vector<int>& bins;
1350
  };
1351

1352
  // Perform the mesh raytrace with the helper class.
1353
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,127,631✔
1354
}
112,127,631✔
1355

1356
//==============================================================================
1357
// RegularMesh implementation
1358
//==============================================================================
1359

1360
int RegularMesh::set_grid()
2,548✔
1361
{
1362
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,548✔
1363

1364
  // Check that dimensions are all greater than zero
1365
  if ((shape <= 0).any()) {
7,644!
UNCOV
1366
    set_errmsg("All entries for a regular mesh dimensions "
×
1367
               "must be positive.");
UNCOV
1368
    return OPENMC_E_INVALID_ARGUMENT;
×
1369
  }
1370

1371
  // Make sure lower_left and dimension match
1372
  if (lower_left_.size() != n_dimension_) {
2,548!
UNCOV
1373
    set_errmsg("Number of entries in lower_left must be the same "
×
1374
               "as the regular mesh dimensions.");
UNCOV
1375
    return OPENMC_E_INVALID_ARGUMENT;
×
1376
  }
1377
  if (width_.size() > 0) {
2,548✔
1378

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

1386
    // Check for negative widths
1387
    if ((width_ < 0.0).any()) {
138!
UNCOV
1388
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
UNCOV
1389
      return OPENMC_E_INVALID_ARGUMENT;
×
1390
    }
1391

1392
    // Set width and upper right coordinate
1393
    upper_right_ = lower_left_ + shape * width_;
138✔
1394

1395
  } else if (upper_right_.size() > 0) {
2,502!
1396

1397
    // Check to ensure upper_right_ has same dimensions
1398
    if (upper_right_.size() != n_dimension_) {
2,502!
UNCOV
1399
      set_errmsg("Number of entries on upper_right must be the "
×
1400
                 "same as the regular mesh dimensions.");
UNCOV
1401
      return OPENMC_E_INVALID_ARGUMENT;
×
1402
    }
1403

1404
    // Check that upper-right is above lower-left
1405
    if ((upper_right_ < lower_left_).any()) {
7,506!
UNCOV
1406
      set_errmsg(
×
1407
        "The upper_right coordinates of a regular mesh must be greater than "
1408
        "the lower_left coordinates.");
UNCOV
1409
      return OPENMC_E_INVALID_ARGUMENT;
×
1410
    }
1411

1412
    // Set width
1413
    width_ = (upper_right_ - lower_left_) / shape;
7,506✔
1414
  }
1415

1416
  // Set material volumes
1417
  volume_frac_ = 1.0 / shape.prod();
2,548✔
1418

1419
  element_volume_ = 1.0;
2,548✔
1420
  for (int i = 0; i < n_dimension_; i++) {
9,597✔
1421
    element_volume_ *= width_[i];
7,049✔
1422
  }
1423
  return 0;
1424
}
2,548✔
1425

1426
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,511✔
1427
{
1428
  // Determine number of dimensions for mesh
1429
  if (!check_for_node(node, "dimension")) {
2,511!
UNCOV
1430
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1431
  }
1432

1433
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,511✔
1434
  int n = n_dimension_ = shape.size();
2,511!
1435
  if (n != 1 && n != 2 && n != 3) {
2,511!
UNCOV
1436
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1437
  }
1438
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,511✔
1439

1440
  // Check for lower-left coordinates
1441
  if (check_for_node(node, "lower_left")) {
2,511!
1442
    // Read mesh lower-left corner location
1443
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,511✔
1444
  } else {
UNCOV
1445
    fatal_error("Must specify <lower_left> on a mesh.");
×
1446
  }
1447

1448
  if (check_for_node(node, "width")) {
2,511✔
1449
    // Make sure one of upper-right or width were specified
1450
    if (check_for_node(node, "upper_right")) {
46!
UNCOV
1451
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1452
    }
1453

1454
    width_ = get_node_tensor<double>(node, "width");
92✔
1455

1456
  } else if (check_for_node(node, "upper_right")) {
2,465!
1457

1458
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,930✔
1459

1460
  } else {
1461
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1462
  }
1463

1464
  if (int err = set_grid()) {
2,511!
UNCOV
1465
    fatal_error(openmc_err_msg);
×
1466
  }
1467
}
2,511✔
1468

1469
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
37✔
1470
{
1471
  // Determine number of dimensions for mesh
1472
  if (!object_exists(group, "dimension")) {
37!
UNCOV
1473
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1474
  }
1475

1476
  tensor::Tensor<int> shape;
37✔
1477
  read_dataset(group, "dimension", shape);
37✔
1478
  int n = n_dimension_ = shape.size();
37!
1479
  if (n != 1 && n != 2 && n != 3) {
37!
UNCOV
1480
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1481
  }
1482
  std::copy(shape.begin(), shape.end(), shape_.begin());
37✔
1483

1484
  // Check for lower-left coordinates
1485
  if (object_exists(group, "lower_left")) {
37!
1486
    // Read mesh lower-left corner location
1487
    read_dataset(group, "lower_left", lower_left_);
37✔
1488
  } else {
UNCOV
1489
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1490
  }
1491

1492
  if (object_exists(group, "upper_right")) {
37!
1493

1494
    read_dataset(group, "upper_right", upper_right_);
37✔
1495

1496
  } else {
UNCOV
1497
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1498
  }
1499

1500
  if (int err = set_grid()) {
37!
UNCOV
1501
    fatal_error(openmc_err_msg);
×
1502
  }
1503
}
37✔
1504

1505
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1506
{
1507
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1508
}
1509

1510
const std::string RegularMesh::mesh_type = "regular";
1511

1512
std::string RegularMesh::get_mesh_type() const
3,653✔
1513
{
1514
  return mesh_type;
3,653✔
1515
}
1516

1517
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,970,099,975✔
1518
{
1519
  return lower_left_[i] + ijk[i] * width_[i];
1,970,099,975✔
1520
}
1521

1522
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,900,389,637✔
1523
{
1524
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,900,389,637✔
1525
}
1526

1527
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1528
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1529
  double l) const
1530
{
1531
  MeshDistance d;
2,147,483,647✔
1532
  d.next_index = ijk[i];
2,147,483,647✔
1533
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1534
    return d;
15,669,434✔
1535

1536
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1537
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1538
    d.next_index++;
1,965,785,381✔
1539
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,965,785,381✔
1540
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,917,656,587✔
1541
    d.next_index--;
1,896,075,043✔
1542
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,896,075,043✔
1543
  }
1544

1545
  return d;
2,147,483,647✔
1546
}
1547

1548
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22✔
1549
  Position plot_ll, Position plot_ur) const
1550
{
1551
  // Figure out which axes lie in the plane of the plot.
1552
  array<int, 2> axes {-1, -1};
22✔
1553
  if (plot_ur.z == plot_ll.z) {
22!
1554
    axes[0] = 0;
22!
1555
    if (n_dimension_ > 1)
22!
1556
      axes[1] = 1;
22✔
UNCOV
1557
  } else if (plot_ur.y == plot_ll.y) {
×
UNCOV
1558
    axes[0] = 0;
×
UNCOV
1559
    if (n_dimension_ > 2)
×
UNCOV
1560
      axes[1] = 2;
×
UNCOV
1561
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1562
    if (n_dimension_ > 1)
×
UNCOV
1563
      axes[0] = 1;
×
UNCOV
1564
    if (n_dimension_ > 2)
×
UNCOV
1565
      axes[1] = 2;
×
1566
  } else {
UNCOV
1567
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1568
  }
1569

1570
  // Get the coordinates of the mesh lines along both of the axes.
1571
  array<vector<double>, 2> axis_lines;
1572
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66✔
1573
    int axis = axes[i_ax];
44!
1574
    if (axis == -1)
44!
UNCOV
1575
      continue;
×
1576
    auto& lines {axis_lines[i_ax]};
44✔
1577

1578
    double coord = lower_left_[axis];
44✔
1579
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286✔
1580
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242!
1581
        lines.push_back(coord);
242✔
1582
      coord += width_[axis];
242✔
1583
    }
1584
  }
1585

1586
  return {axis_lines[0], axis_lines[1]};
44✔
1587
}
1588

1589
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,498✔
1590
{
1591
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,498✔
1592
  write_dataset(mesh_group, "lower_left", lower_left_);
2,498✔
1593
  write_dataset(mesh_group, "upper_right", upper_right_);
2,498✔
1594
  write_dataset(mesh_group, "width", width_);
2,498✔
1595
}
2,498✔
1596

1597
tensor::Tensor<double> RegularMesh::count_sites(
7,820✔
1598
  const SourceSite* bank, int64_t length, bool* outside) const
1599
{
1600
  // Determine shape of array for counts
1601
  std::size_t m = this->n_bins();
7,820✔
1602
  vector<std::size_t> shape = {m};
7,820✔
1603

1604
  // Create array of zeros
1605
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1606
  bool outside_ = false;
2,892✔
1607

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

1611
    // determine scoring bin for entropy mesh
1612
    int mesh_bin = get_bin(site.r);
7,667,451✔
1613

1614
    // if outside mesh, skip particle
1615
    if (mesh_bin < 0) {
7,667,451!
UNCOV
1616
      outside_ = true;
×
UNCOV
1617
      continue;
×
1618
    }
1619

1620
    // Add to appropriate bin
1621
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1622
  }
1623

1624
  // Create reduced count data
1625
  auto counts = tensor::zeros<double>(shape);
7,820✔
1626
  int total = cnt.size();
7,820✔
1627

1628
#ifdef OPENMC_MPI
1629
  // collect values from all processors
1630
  MPI_Reduce(
2,892✔
1631
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
2,892✔
1632

1633
  // Check if there were sites outside the mesh for any processor
1634
  if (outside) {
2,892!
1635
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892✔
1636
  }
1637
#else
1638
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928✔
1639
  if (outside)
4,928!
1640
    *outside = outside_;
4,928✔
1641
#endif
1642

1643
  return counts;
7,820✔
1644
}
7,820✔
1645

1646
double RegularMesh::volume(const MeshIndex& ijk) const
1,244,598✔
1647
{
1648
  return element_volume_;
1,244,598✔
1649
}
1650

1651
//==============================================================================
1652
// RectilinearMesh implementation
1653
//==============================================================================
1654

1655
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133✔
1656
{
1657
  n_dimension_ = 3;
133✔
1658

1659
  grid_[0] = get_node_array<double>(node, "x_grid");
133✔
1660
  grid_[1] = get_node_array<double>(node, "y_grid");
133✔
1661
  grid_[2] = get_node_array<double>(node, "z_grid");
133✔
1662

1663
  if (int err = set_grid()) {
133!
UNCOV
1664
    fatal_error(openmc_err_msg);
×
1665
  }
1666
}
133✔
1667

1668
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1669
{
1670
  n_dimension_ = 3;
11✔
1671

1672
  read_dataset(group, "x_grid", grid_[0]);
11✔
1673
  read_dataset(group, "y_grid", grid_[1]);
11✔
1674
  read_dataset(group, "z_grid", grid_[2]);
11✔
1675

1676
  if (int err = set_grid()) {
11!
UNCOV
1677
    fatal_error(openmc_err_msg);
×
1678
  }
1679
}
11✔
1680

1681
const std::string RectilinearMesh::mesh_type = "rectilinear";
1682

1683
std::string RectilinearMesh::get_mesh_type() const
286✔
1684
{
1685
  return mesh_type;
286✔
1686
}
1687

1688
double RectilinearMesh::positive_grid_boundary(
26,505,985✔
1689
  const MeshIndex& ijk, int i) const
1690
{
1691
  return grid_[i][ijk[i]];
26,505,985✔
1692
}
1693

1694
double RectilinearMesh::negative_grid_boundary(
25,739,428✔
1695
  const MeshIndex& ijk, int i) const
1696
{
1697
  return grid_[i][ijk[i] - 1];
25,739,428✔
1698
}
1699

1700
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
53,602,131✔
1701
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1702
  double l) const
1703
{
1704
  MeshDistance d;
53,602,131✔
1705
  d.next_index = ijk[i];
53,602,131✔
1706
  if (std::abs(u[i]) < FP_PRECISION)
53,602,131✔
1707
    return d;
571,824✔
1708

1709
  d.max_surface = (u[i] > 0);
53,030,307✔
1710
  if (d.max_surface && (ijk[i] <= shape_[i])) {
53,030,307✔
1711
    d.next_index++;
26,505,985✔
1712
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,505,985✔
1713
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,524,322✔
1714
    d.next_index--;
25,739,428✔
1715
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,739,428✔
1716
  }
1717
  return d;
53,030,307✔
1718
}
1719

1720
int RectilinearMesh::set_grid()
188✔
1721
{
1722
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
188✔
1723
    static_cast<int>(grid_[1].size()) - 1,
188✔
1724
    static_cast<int>(grid_[2].size()) - 1};
188✔
1725

1726
  for (const auto& g : grid_) {
752✔
1727
    if (g.size() < 2) {
564!
UNCOV
1728
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1729
                 "must each have at least 2 points");
UNCOV
1730
      return OPENMC_E_INVALID_ARGUMENT;
×
1731
    }
1732
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
564!
1733
        g.end()) {
564!
UNCOV
1734
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1735
                 "rectilinear meshes must be sorted and unique.");
UNCOV
1736
      return OPENMC_E_INVALID_ARGUMENT;
×
1737
    }
1738
  }
1739

1740
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
188✔
1741
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
188✔
1742

1743
  return 0;
188✔
1744
}
1745

1746
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,108,925✔
1747
{
1748
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,108,925✔
1749
}
1750

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

1766
  // Get the coordinates of the mesh lines along both of the axes.
1767
  array<vector<double>, 2> axis_lines;
1768
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33✔
1769
    int axis = axes[i_ax];
22✔
1770
    vector<double>& lines {axis_lines[i_ax]};
22✔
1771

1772
    for (auto coord : grid_[axis]) {
110✔
1773
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88!
1774
        lines.push_back(coord);
88✔
1775
    }
1776
  }
1777

1778
  return {axis_lines[0], axis_lines[1]};
22✔
1779
}
1780

1781
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
121✔
1782
{
1783
  write_dataset(mesh_group, "x_grid", grid_[0]);
121✔
1784
  write_dataset(mesh_group, "y_grid", grid_[1]);
121✔
1785
  write_dataset(mesh_group, "z_grid", grid_[2]);
121✔
1786
}
121✔
1787

1788
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1789
{
1790
  double vol {1.0};
132✔
1791

1792
  for (int i = 0; i < n_dimension_; i++) {
528✔
1793
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396✔
1794
  }
1795
  return vol;
132✔
1796
}
1797

1798
//==============================================================================
1799
// CylindricalMesh implementation
1800
//==============================================================================
1801

1802
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
411✔
1803
  : PeriodicStructuredMesh {node}
411✔
1804
{
1805
  n_dimension_ = 3;
411✔
1806
  grid_[0] = get_node_array<double>(node, "r_grid");
411✔
1807
  grid_[1] = get_node_array<double>(node, "phi_grid");
411✔
1808
  grid_[2] = get_node_array<double>(node, "z_grid");
411✔
1809
  origin_ = get_node_position(node, "origin");
411✔
1810

1811
  if (int err = set_grid()) {
411!
UNCOV
1812
    fatal_error(openmc_err_msg);
×
1813
  }
1814
}
411✔
1815

1816
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
1817
{
1818
  n_dimension_ = 3;
11✔
1819
  read_dataset(group, "r_grid", grid_[0]);
11✔
1820
  read_dataset(group, "phi_grid", grid_[1]);
11✔
1821
  read_dataset(group, "z_grid", grid_[2]);
11✔
1822
  read_dataset(group, "origin", origin_);
11✔
1823

1824
  if (int err = set_grid()) {
11!
UNCOV
1825
    fatal_error(openmc_err_msg);
×
1826
  }
1827
}
11✔
1828

1829
const std::string CylindricalMesh::mesh_type = "cylindrical";
1830

1831
std::string CylindricalMesh::get_mesh_type() const
495✔
1832
{
1833
  return mesh_type;
495✔
1834
}
1835

1836
std::array<const char*, 3> CylindricalMesh::axis_labels() const
646,536✔
1837
{
1838
  return {"r", "phi", "z"};
646,536✔
1839
}
1840

1841
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,732,102✔
1842
  Position r, bool& in_mesh) const
1843
{
1844
  r = local_coords(r);
47,732,102✔
1845

1846
  Position mapped_r;
47,732,102✔
1847
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,102✔
1848
  mapped_r[2] = r[2];
47,732,102✔
1849

1850
  if (mapped_r[0] < FP_PRECISION) {
47,732,102!
1851
    mapped_r[1] = 0.0;
1852
  } else {
1853
    mapped_r[1] = std::atan2(r.y, r.x);
47,732,102✔
1854
    if (mapped_r[1] < 0)
47,732,102✔
1855
      mapped_r[1] += 2 * PI;
23,874,862✔
1856
  }
1857

1858
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,732,102✔
1859

1860
  idx[1] = sanitize_phi(idx[1]);
47,732,102✔
1861

1862
  return idx;
47,732,102✔
1863
}
1864

1865
Position CylindricalMesh::sample_element(
88,110✔
1866
  const MeshIndex& ijk, uint64_t* seed) const
1867
{
1868
  double r_min = this->r(ijk[0] - 1);
88,110✔
1869
  double r_max = this->r(ijk[0]);
88,110✔
1870

1871
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1872
  double phi_max = this->phi(ijk[1]);
88,110✔
1873

1874
  double z_min = this->z(ijk[2] - 1);
88,110✔
1875
  double z_max = this->z(ijk[2]);
88,110✔
1876

1877
  double r_min_sq = r_min * r_min;
88,110✔
1878
  double r_max_sq = r_max * r_max;
88,110✔
1879
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110✔
1880
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110✔
1881
  double z = uniform_distribution(z_min, z_max, seed);
88,110✔
1882

1883
  double x = r * std::cos(phi);
88,110✔
1884
  double y = r * std::sin(phi);
88,110✔
1885

1886
  return origin_ + Position(x, y, z);
88,110✔
1887
}
1888

1889
double CylindricalMesh::find_r_crossing(
142,589,936✔
1890
  const Position& r, const Direction& u, double l, int shell) const
1891
{
1892

1893
  if ((shell < 0) || (shell > shape_[0]))
142,589,936!
1894
    return INFTY;
1895

1896
  // solve r.x^2 + r.y^2 == r0^2
1897
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1898
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1899

1900
  const double r0 = grid_[0][shell];
124,675,883✔
1901
  if (r0 == 0.0)
124,675,883✔
1902
    return INFTY;
1903

1904
  const double denominator = u.x * u.x + u.y * u.y;
117,539,798✔
1905

1906
  // Direction of flight is in z-direction. Will never intersect r.
1907
  if (std::abs(denominator) < FP_PRECISION)
117,539,798✔
1908
    return INFTY;
1909

1910
  // inverse of dominator to help the compiler to speed things up
1911
  const double inv_denominator = 1.0 / denominator;
117,480,838✔
1912

1913
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,480,838✔
1914
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,480,838✔
1915
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,480,838✔
1916

1917
  if (D < 0.0)
117,480,838✔
1918
    return INFTY;
1919

1920
  D = std::sqrt(D);
107,744,716✔
1921

1922
  // Particle is already on the shell surface; avoid spurious crossing
1923
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,744,716✔
1924
    return INFTY;
1925

1926
  // Check -p - D first because it is always smaller as -p + D
1927
  if (-p - D > l)
101,111,342✔
1928
    return -p - D;
1929
  if (-p + D > l)
80,903,726✔
1930
    return -p + D;
50,079,144✔
1931

1932
  return INFTY;
1933
}
1934

1935
double CylindricalMesh::find_phi_crossing(
74,456,426✔
1936
  const Position& r, const Direction& u, double l, int shell) const
1937
{
1938
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
1939
  if (full_phi_ && (shape_[1] == 1))
74,456,426✔
1940
    return INFTY;
1941

1942
  shell = sanitize_phi(shell);
43,970,718✔
1943

1944
  const double p0 = grid_[1][shell];
43,970,718✔
1945

1946
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1947
  // => x(s) * cos(p0) = y(s) * sin(p0)
1948
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1949
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1950

1951
  const double c0 = std::cos(p0);
43,970,718✔
1952
  const double s0 = std::sin(p0);
43,970,718✔
1953

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

1956
  // Check if direction of flight is not parallel to phi surface
1957
  if (std::abs(denominator) > FP_PRECISION) {
43,970,718✔
1958
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,709,974✔
1959
    // Check if solution is in positive direction of flight and crosses the
1960
    // correct phi surface (not -phi)
1961
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,709,974✔
1962
      return s;
20,219,859✔
1963
  }
1964

1965
  return INFTY;
1966
}
1967

1968
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,695,758✔
1969
  const Position& r, const Direction& u, double l, int shell) const
1970
{
1971
  MeshDistance d;
36,695,758✔
1972
  d.next_index = shell;
36,695,758✔
1973

1974
  // Direction of flight is within xy-plane. Will never intersect z.
1975
  if (std::abs(u.z) < FP_PRECISION)
36,695,758✔
1976
    return d;
1,118,216✔
1977

1978
  d.max_surface = (u.z > 0.0);
35,577,542✔
1979
  if (d.max_surface && (shell <= shape_[2])) {
35,577,542✔
1980
    d.next_index += 1;
16,875,903✔
1981
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,875,903✔
1982
  } else if (!d.max_surface && (shell > 0)) {
18,701,639✔
1983
    d.next_index -= 1;
16,846,225✔
1984
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,846,225✔
1985
  }
1986
  return d;
35,577,542✔
1987
}
1988

1989
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,939✔
1990
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1991
  double l) const
1992
{
1993
  if (i == 0) {
145,218,939✔
1994

1995
    return std::min(
142,589,936✔
1996
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,968✔
1997
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,589,936✔
1998

1999
  } else if (i == 1) {
73,923,971✔
2000

2001
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,228,213✔
2002
                      find_phi_crossing(r0, u, l, ijk[i])),
37,228,213✔
2003
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,228,213✔
2004
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,456,426✔
2005

2006
  } else {
2007
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,758✔
2008
  }
2009
}
2010

2011
int CylindricalMesh::set_grid()
444✔
2012
{
2013
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
444✔
2014
    static_cast<int>(grid_[1].size()) - 1,
444✔
2015
    static_cast<int>(grid_[2].size()) - 1};
444✔
2016

2017
  for (const auto& g : grid_) {
1,776✔
2018
    if (g.size() < 2) {
1,332!
UNCOV
2019
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2020
                 "must each have at least 2 points");
UNCOV
2021
      return OPENMC_E_INVALID_ARGUMENT;
×
2022
    }
2023
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,332!
2024
        g.end()) {
1,332!
UNCOV
2025
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2026
                 "cylindrical meshes must be sorted and unique.");
UNCOV
2027
      return OPENMC_E_INVALID_ARGUMENT;
×
2028
    }
2029
  }
2030
  if (grid_[0].front() < 0.0) {
444!
UNCOV
2031
    set_errmsg("r-grid for "
×
2032
               "cylindrical meshes must start at r >= 0.");
UNCOV
2033
    return OPENMC_E_INVALID_ARGUMENT;
×
2034
  }
2035
  if (grid_[1].front() < 0.0) {
444!
UNCOV
2036
    set_errmsg("phi-grid for "
×
2037
               "cylindrical meshes must start at phi >= 0.");
2038
    return OPENMC_E_INVALID_ARGUMENT;
×
2039
  }
2040
  if (grid_[1].back() > 2.0 * PI) {
444!
2041
    set_errmsg("phi-grids for "
×
2042
               "cylindrical meshes must end with theta <= 2*pi.");
2043

UNCOV
2044
    return OPENMC_E_INVALID_ARGUMENT;
×
2045
  }
2046

2047
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
444!
2048

2049
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
444✔
2050
    origin_[2] + grid_[2].front()};
444✔
2051
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
444✔
2052
    origin_[2] + grid_[2].back()};
444✔
2053

2054
  return 0;
444✔
2055
}
2056

2057
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,196,306✔
2058
{
2059
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,196,306✔
2060
}
2061

UNCOV
2062
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2063
  Position plot_ll, Position plot_ur) const
2064
{
UNCOV
2065
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2066

2067
  // Figure out which axes lie in the plane of the plot.
2068
  array<vector<double>, 2> axis_lines;
2069
  return {axis_lines[0], axis_lines[1]};
2070
}
2071

2072
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
385✔
2073
{
2074
  write_dataset(mesh_group, "r_grid", grid_[0]);
385✔
2075
  write_dataset(mesh_group, "phi_grid", grid_[1]);
385✔
2076
  write_dataset(mesh_group, "z_grid", grid_[2]);
385✔
2077
  write_dataset(mesh_group, "origin", origin_);
385✔
2078
}
385✔
2079

2080
double CylindricalMesh::volume(const MeshIndex& ijk) const
792✔
2081
{
2082
  double r_i = grid_[0][ijk[0] - 1];
792✔
2083
  double r_o = grid_[0][ijk[0]];
792✔
2084

2085
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2086
  double phi_o = grid_[1][ijk[1]];
792✔
2087

2088
  double z_i = grid_[2][ijk[2] - 1];
792✔
2089
  double z_o = grid_[2][ijk[2]];
792✔
2090

2091
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2092
}
2093

2094
//==============================================================================
2095
// SphericalMesh implementation
2096
//==============================================================================
2097

2098
SphericalMesh::SphericalMesh(pugi::xml_node node)
356✔
2099
  : PeriodicStructuredMesh {node}
356✔
2100
{
2101
  n_dimension_ = 3;
356✔
2102

2103
  grid_[0] = get_node_array<double>(node, "r_grid");
356✔
2104
  grid_[1] = get_node_array<double>(node, "theta_grid");
356✔
2105
  grid_[2] = get_node_array<double>(node, "phi_grid");
356✔
2106
  origin_ = get_node_position(node, "origin");
356✔
2107

2108
  if (int err = set_grid()) {
356!
UNCOV
2109
    fatal_error(openmc_err_msg);
×
2110
  }
2111
}
356✔
2112

2113
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2114
{
2115
  n_dimension_ = 3;
11✔
2116

2117
  read_dataset(group, "r_grid", grid_[0]);
11✔
2118
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2119
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2120
  read_dataset(group, "origin", origin_);
11✔
2121

2122
  if (int err = set_grid()) {
11!
UNCOV
2123
    fatal_error(openmc_err_msg);
×
2124
  }
2125
}
11✔
2126

2127
const std::string SphericalMesh::mesh_type = "spherical";
2128

2129
std::string SphericalMesh::get_mesh_type() const
396✔
2130
{
2131
  return mesh_type;
396✔
2132
}
2133

2134
std::array<const char*, 3> SphericalMesh::axis_labels() const
323,400✔
2135
{
2136
  return {"r", "theta", "phi"};
323,400✔
2137
}
2138

2139
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,592,139✔
2140
  Position r, bool& in_mesh) const
2141
{
2142
  r = local_coords(r);
68,592,139✔
2143

2144
  Position mapped_r;
68,592,139✔
2145
  mapped_r[0] = r.norm();
68,592,139✔
2146

2147
  if (mapped_r[0] < FP_PRECISION) {
68,592,139!
2148
    mapped_r[1] = 0.0;
2149
    mapped_r[2] = 0.0;
2150
  } else {
2151
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,592,139✔
2152
    mapped_r[2] = std::atan2(r.y, r.x);
68,592,139✔
2153
    if (mapped_r[2] < 0)
68,592,139✔
2154
      mapped_r[2] += 2 * PI;
34,268,685✔
2155
  }
2156

2157
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,592,139✔
2158

2159
  idx[1] = sanitize_theta(idx[1]);
68,592,139✔
2160
  idx[2] = sanitize_phi(idx[2]);
68,592,139✔
2161

2162
  return idx;
68,592,139✔
2163
}
2164

2165
Position SphericalMesh::sample_element(
110✔
2166
  const MeshIndex& ijk, uint64_t* seed) const
2167
{
2168
  double r_min = this->r(ijk[0] - 1);
110✔
2169
  double r_max = this->r(ijk[0]);
110✔
2170

2171
  double theta_min = this->theta(ijk[1] - 1);
110✔
2172
  double theta_max = this->theta(ijk[1]);
110✔
2173

2174
  double phi_min = this->phi(ijk[2] - 1);
110✔
2175
  double phi_max = this->phi(ijk[2]);
110✔
2176

2177
  double cos_theta =
110✔
2178
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110✔
2179
  double sin_theta = std::sin(std::acos(cos_theta));
110✔
2180
  double phi = uniform_distribution(phi_min, phi_max, seed);
110✔
2181
  double r_min_cub = std::pow(r_min, 3);
110✔
2182
  double r_max_cub = std::pow(r_max, 3);
110✔
2183
  // might be faster to do rejection here?
2184
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110✔
2185

2186
  double x = r * std::cos(phi) * sin_theta;
110✔
2187
  double y = r * std::sin(phi) * sin_theta;
110✔
2188
  double z = r * cos_theta;
110✔
2189

2190
  return origin_ + Position(x, y, z);
110✔
2191
}
2192

2193
double SphericalMesh::find_r_crossing(
443,989,172✔
2194
  const Position& r, const Direction& u, double l, int shell) const
2195
{
2196
  if ((shell < 0) || (shell > shape_[0]))
443,989,172✔
2197
    return INFTY;
2198

2199
  // solve |r+s*u| = r0
2200
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2201
  const double r0 = grid_[0][shell];
404,368,074✔
2202
  if (r0 == 0.0)
404,368,074✔
2203
    return INFTY;
2204
  const double p = r.dot(u);
396,689,546✔
2205
  double R = r.norm();
396,689,546✔
2206
  double D = p * p - (R - r0) * (R + r0);
396,689,546✔
2207

2208
  // Particle is already on the shell surface; avoid spurious crossing
2209
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,689,546✔
2210
    return INFTY;
2211

2212
  if (D >= 0.0) {
385,980,892✔
2213
    D = std::sqrt(D);
358,103,944✔
2214
    // Check -p - D first because it is always smaller as -p + D
2215
    if (-p - D > l)
358,103,944✔
2216
      return -p - D;
2217
    if (-p + D > l)
293,788,176✔
2218
      return -p + D;
177,245,761✔
2219
  }
2220

2221
  return INFTY;
2222
}
2223

2224
double SphericalMesh::find_theta_crossing(
110,161,370✔
2225
  const Position& r, const Direction& u, double l, int shell) const
2226
{
2227
  // Theta grid is [0, π], thus there is no real surface to cross
2228
  if (full_theta_ && (shape_[1] == 1))
110,161,370✔
2229
    return INFTY;
2230

2231
  shell = sanitize_theta(shell);
38,358,540✔
2232

2233
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2234
  // yields
2235
  // a*s^2 + 2*b*s + c == 0 with
2236
  // a = cos(theta)^2 - u.z * u.z
2237
  // b = r*u * cos(theta)^2 - u.z * r.z
2238
  // c = r*r * cos(theta)^2 - r.z^2
2239

2240
  const double cos_t = std::cos(grid_[1][shell]);
38,358,540✔
2241
  const bool sgn = std::signbit(cos_t);
38,358,540✔
2242
  const double cos_t_2 = cos_t * cos_t;
38,358,540✔
2243

2244
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2245
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2246
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2247

2248
  // if factor of s^2 is zero, direction of flight is parallel to theta
2249
  // surface
2250
  if (std::abs(a) < FP_PRECISION) {
38,358,540✔
2251
    // if b vanishes, direction of flight is within theta surface and crossing
2252
    // is not possible
2253
    if (std::abs(b) < FP_PRECISION)
482,548!
2254
      return INFTY;
2255

UNCOV
2256
    const double s = -0.5 * c / b;
×
2257
    // Check if solution is in positive direction of flight and has correct
2258
    // sign
UNCOV
2259
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
UNCOV
2260
      return s;
×
2261

2262
    // no crossing is possible
2263
    return INFTY;
2264
  }
2265

2266
  const double p = b / a;
37,875,992✔
2267
  double D = p * p - c / a;
37,875,992✔
2268

2269
  if (D < 0.0)
37,875,992✔
2270
    return INFTY;
2271

2272
  D = std::sqrt(D);
26,921,004✔
2273

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

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

2285
  return INFTY;
2286
}
2287

2288
double SphericalMesh::find_phi_crossing(
111,750,848✔
2289
  const Position& r, const Direction& u, double l, int shell) const
2290
{
2291
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2292
  if (full_phi_ && (shape_[2] == 1))
111,750,848✔
2293
    return INFTY;
2294

2295
  shell = sanitize_phi(shell);
39,948,018✔
2296

2297
  const double p0 = grid_[2][shell];
39,948,018✔
2298

2299
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2300
  // => x(s) * cos(p0) = y(s) * sin(p0)
2301
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2302
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2303

2304
  const double c0 = std::cos(p0);
39,948,018✔
2305
  const double s0 = std::sin(p0);
39,948,018✔
2306

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

2309
  // Check if direction of flight is not parallel to phi surface
2310
  if (std::abs(denominator) > FP_PRECISION) {
39,948,018✔
2311
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,714,026✔
2312
    // Check if solution is in positive direction of flight and crosses the
2313
    // correct phi surface (not -phi)
2314
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,714,026✔
2315
      return s;
17,579,452✔
2316
  }
2317

2318
  return INFTY;
2319
}
2320

2321
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,950,695✔
2322
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2323
  double l) const
2324
{
2325

2326
  if (i == 0) {
332,950,695✔
2327
    return std::min(
443,989,172✔
2328
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,994,586✔
2329
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,989,172✔
2330

2331
  } else if (i == 1) {
110,956,109✔
2332
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,080,685✔
2333
                      find_theta_crossing(r0, u, l, ijk[i])),
55,080,685✔
2334
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,080,685✔
2335
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,161,370✔
2336

2337
  } else {
2338
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,875,424✔
2339
                      find_phi_crossing(r0, u, l, ijk[i])),
55,875,424✔
2340
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,875,424✔
2341
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,750,848✔
2342
  }
2343
}
2344

2345
int SphericalMesh::set_grid()
389✔
2346
{
2347
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
389✔
2348
    static_cast<int>(grid_[1].size()) - 1,
389✔
2349
    static_cast<int>(grid_[2].size()) - 1};
389✔
2350

2351
  for (const auto& g : grid_) {
1,556✔
2352
    if (g.size() < 2) {
1,167!
UNCOV
2353
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2354
                 "must each have at least 2 points");
UNCOV
2355
      return OPENMC_E_INVALID_ARGUMENT;
×
2356
    }
2357
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,167!
2358
        g.end()) {
1,167!
UNCOV
2359
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2360
                 "spherical meshes must be sorted and unique.");
UNCOV
2361
      return OPENMC_E_INVALID_ARGUMENT;
×
2362
    }
2363
    if (g.front() < 0.0) {
1,167!
UNCOV
2364
      set_errmsg("r-, theta-, and phi- grids for "
×
2365
                 "spherical meshes must start at v >= 0.");
UNCOV
2366
      return OPENMC_E_INVALID_ARGUMENT;
×
2367
    }
2368
  }
2369
  if (grid_[1].back() > PI) {
389!
2370
    set_errmsg("theta-grids for "
×
2371
               "spherical meshes must end with theta <= pi.");
2372

UNCOV
2373
    return OPENMC_E_INVALID_ARGUMENT;
×
2374
  }
2375
  if (grid_[2].back() > 2 * PI) {
389!
UNCOV
2376
    set_errmsg("phi-grids for "
×
2377
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2378
    return OPENMC_E_INVALID_ARGUMENT;
×
2379
  }
2380

2381
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
389!
2382
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
389✔
2383

2384
  double r = grid_[0].back();
389✔
2385
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
389✔
2386
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
389✔
2387

2388
  return 0;
389✔
2389
}
2390

2391
int SphericalMesh::get_index_in_direction(double r, int i) const
205,776,417✔
2392
{
2393
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,776,417✔
2394
}
2395

UNCOV
2396
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2397
  Position plot_ll, Position plot_ur) const
2398
{
UNCOV
2399
  fatal_error("Plot of spherical Mesh not implemented");
×
2400

2401
  // Figure out which axes lie in the plane of the plot.
2402
  array<vector<double>, 2> axis_lines;
2403
  return {axis_lines[0], axis_lines[1]};
2404
}
2405

2406
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
330✔
2407
{
2408
  write_dataset(mesh_group, "r_grid", grid_[0]);
330✔
2409
  write_dataset(mesh_group, "theta_grid", grid_[1]);
330✔
2410
  write_dataset(mesh_group, "phi_grid", grid_[2]);
330✔
2411
  write_dataset(mesh_group, "origin", origin_);
330✔
2412
}
330✔
2413

2414
double SphericalMesh::volume(const MeshIndex& ijk) const
935✔
2415
{
2416
  double r_i = grid_[0][ijk[0] - 1];
935✔
2417
  double r_o = grid_[0][ijk[0]];
935✔
2418

2419
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2420
  double theta_o = grid_[1][ijk[1]];
935✔
2421

2422
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2423
  double phi_o = grid_[2][ijk[2]];
935✔
2424

2425
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870✔
2426
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935✔
2427
}
2428

2429
//==============================================================================
2430
// Helper functions for the C API
2431
//==============================================================================
2432

2433
int check_mesh(int32_t index)
6,490✔
2434
{
2435
  if (index < 0 || index >= model::meshes.size()) {
6,490!
UNCOV
2436
    set_errmsg("Index in meshes array is out of bounds.");
×
UNCOV
2437
    return OPENMC_E_OUT_OF_BOUNDS;
×
2438
  }
2439
  return 0;
2440
}
2441

2442
template<class T>
2443
int check_mesh_type(int32_t index)
1,100✔
2444
{
2445
  if (int err = check_mesh(index))
1,100!
2446
    return err;
2447

2448
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,100!
2449
  if (!mesh) {
1,100!
UNCOV
2450
    set_errmsg("This function is not valid for input mesh.");
×
UNCOV
2451
    return OPENMC_E_INVALID_TYPE;
×
2452
  }
2453
  return 0;
2454
}
2455

2456
template<class T>
2457
bool is_mesh_type(int32_t index)
2458
{
2459
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2460
  return mesh;
2461
}
2462

2463
//==============================================================================
2464
// C API functions
2465
//==============================================================================
2466

2467
// Return the type of mesh as a C string
2468
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,496✔
2469
{
2470
  if (int err = check_mesh(index))
1,496!
2471
    return err;
2472

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

2475
  return 0;
1,496✔
2476
}
2477

2478
//! Extend the meshes array by n elements
2479
extern "C" int openmc_extend_meshes(
253✔
2480
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2481
{
2482
  if (index_start)
253!
2483
    *index_start = model::meshes.size();
253✔
2484
  std::string mesh_type;
253✔
2485

2486
  for (int i = 0; i < n; ++i) {
506✔
2487
    if (RegularMesh::mesh_type == type) {
253✔
2488
      model::meshes.push_back(make_unique<RegularMesh>());
165✔
2489
    } else if (RectilinearMesh::mesh_type == type) {
88✔
2490
      model::meshes.push_back(make_unique<RectilinearMesh>());
44✔
2491
    } else if (CylindricalMesh::mesh_type == type) {
44✔
2492
      model::meshes.push_back(make_unique<CylindricalMesh>());
22✔
2493
    } else if (SphericalMesh::mesh_type == type) {
22!
2494
      model::meshes.push_back(make_unique<SphericalMesh>());
22✔
2495
    } else {
UNCOV
2496
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2497
    }
2498
  }
2499
  if (index_end)
253!
UNCOV
2500
    *index_end = model::meshes.size() - 1;
×
2501

2502
  return 0;
253✔
2503
}
253✔
2504

2505
//! Adds a new unstructured mesh to OpenMC
UNCOV
2506
extern "C" int openmc_add_unstructured_mesh(
×
2507
  const char filename[], const char library[], int* id)
2508
{
UNCOV
2509
  std::string lib_name(library);
×
2510
  std::string mesh_file(filename);
×
UNCOV
2511
  bool valid_lib = false;
×
2512

2513
#ifdef OPENMC_DAGMC_ENABLED
2514
  if (lib_name == MOABMesh::mesh_lib_type) {
×
2515
    model::meshes.push_back(std::move(make_unique<MOABMesh>(mesh_file)));
×
2516
    valid_lib = true;
2517
  }
2518
#endif
2519

2520
#ifdef OPENMC_LIBMESH_ENABLED
2521
  if (lib_name == LibMesh::mesh_lib_type) {
×
2522
    model::meshes.push_back(std::move(make_unique<LibMesh>(mesh_file)));
×
2523
    valid_lib = true;
2524
  }
2525
#endif
2526

UNCOV
2527
  if (!valid_lib) {
×
UNCOV
2528
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2529
                           "by this build of OpenMC",
2530
      lib_name));
UNCOV
2531
    return OPENMC_E_INVALID_ARGUMENT;
×
2532
  }
2533

2534
  // auto-assign new ID
2535
  model::meshes.back()->set_id(-1);
×
2536
  *id = model::meshes.back()->id_;
2537

2538
  return 0;
UNCOV
2539
}
×
2540

2541
//! Return the index in the meshes array of a mesh with a given ID
2542
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
429✔
2543
{
2544
  auto pair = model::mesh_map.find(id);
429!
2545
  if (pair == model::mesh_map.end()) {
429!
UNCOV
2546
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
×
UNCOV
2547
    return OPENMC_E_INVALID_ID;
×
2548
  }
2549
  *index = pair->second;
429✔
2550
  return 0;
429✔
2551
}
2552

2553
//! Return the ID of a mesh
2554
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
2,827✔
2555
{
2556
  if (int err = check_mesh(index))
2,827!
2557
    return err;
2558
  *id = model::meshes[index]->id_;
2,827✔
2559
  return 0;
2,827✔
2560
}
2561

2562
//! Set the ID of a mesh
2563
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
253✔
2564
{
2565
  if (int err = check_mesh(index))
253!
2566
    return err;
2567
  model::meshes[index]->id_ = id;
253✔
2568
  model::mesh_map[id] = index;
253✔
2569
  return 0;
253✔
2570
}
2571

2572
//! Get the number of elements in a mesh
2573
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
297✔
2574
{
2575
  if (int err = check_mesh(index))
297!
2576
    return err;
2577
  *n = model::meshes[index]->n_bins();
297✔
2578
  return 0;
297✔
2579
}
2580

2581
//! Get the volume of each element in the mesh
2582
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88✔
2583
{
2584
  if (int err = check_mesh(index))
88!
2585
    return err;
2586
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968✔
2587
    volumes[i] = model::meshes[index]->volume(i);
880✔
2588
  }
2589
  return 0;
2590
}
2591

2592
//! Get the bounding box of a mesh
2593
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176✔
2594
{
2595
  if (int err = check_mesh(index))
176!
2596
    return err;
2597

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

2600
  // set lower left corner values
2601
  ll[0] = bbox.min.x;
176✔
2602
  ll[1] = bbox.min.y;
176✔
2603
  ll[2] = bbox.min.z;
176✔
2604

2605
  // set upper right corner values
2606
  ur[0] = bbox.max.x;
176✔
2607
  ur[1] = bbox.max.y;
176✔
2608
  ur[2] = bbox.max.z;
176✔
2609
  return 0;
176✔
2610
}
2611

2612
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
209✔
2613
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2614
{
2615
  if (int err = check_mesh(index))
209!
2616
    return err;
2617

2618
  try {
209✔
2619
    model::meshes[index]->material_volumes(
209✔
2620
      nx, ny, nz, table_size, materials, volumes, bboxes);
2621
  } catch (const std::exception& e) {
11!
2622
    set_errmsg(e.what());
11✔
2623
    if (starts_with(e.what(), "Mesh")) {
11!
2624
      return OPENMC_E_GEOMETRY;
11✔
2625
    } else {
UNCOV
2626
      return OPENMC_E_ALLOCATE;
×
2627
    }
2628
  }
11✔
2629

2630
  return 0;
2631
}
2632

2633
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44✔
2634
  Position width, int basis, int* pixels, int32_t* data)
2635
{
2636
  if (int err = check_mesh(index))
44!
2637
    return err;
2638
  const auto& mesh = model::meshes[index].get();
44!
2639

2640
  int pixel_width = pixels[0];
44✔
2641
  int pixel_height = pixels[1];
44✔
2642

2643
  // get pixel size
2644
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44✔
2645
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44✔
2646

2647
  // setup basis indices and initial position centered on pixel
2648
  int in_i, out_i;
44✔
2649
  Position xyz = origin;
44✔
2650
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44✔
2651
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44✔
2652
  switch (basis_enum) {
44!
2653
  case PlotBasis::xy:
2654
    in_i = 0;
2655
    out_i = 1;
2656
    break;
2657
  case PlotBasis::xz:
2658
    in_i = 0;
2659
    out_i = 2;
2660
    break;
2661
  case PlotBasis::yz:
2662
    in_i = 1;
2663
    out_i = 2;
2664
    break;
UNCOV
2665
  default:
×
UNCOV
2666
    UNREACHABLE();
×
2667
  }
2668

2669
  // set initial position
2670
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44✔
2671
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44✔
2672

2673
#pragma omp parallel
24✔
2674
  {
20✔
2675
    Position r = xyz;
20✔
2676

2677
#pragma omp for
2678
    for (int y = 0; y < pixel_height; y++) {
420✔
2679
      r[out_i] = xyz[out_i] - out_pixel * y;
400✔
2680
      for (int x = 0; x < pixel_width; x++) {
8,400✔
2681
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000✔
2682
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000✔
2683
      }
2684
    }
2685
  }
2686

2687
  return 0;
44✔
2688
}
2689

2690
//! Get the dimension of a regular mesh
2691
extern "C" int openmc_regular_mesh_get_dimension(
11✔
2692
  int32_t index, int** dims, int* n)
2693
{
2694
  if (int err = check_mesh_type<RegularMesh>(index))
11!
2695
    return err;
2696
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
11!
2697
  *dims = mesh->shape_.data();
11✔
2698
  *n = mesh->n_dimension_;
11✔
2699
  return 0;
11✔
2700
}
2701

2702
//! Set the dimension of a regular mesh
2703
extern "C" int openmc_regular_mesh_set_dimension(
187✔
2704
  int32_t index, int n, const int* dims)
2705
{
2706
  if (int err = check_mesh_type<RegularMesh>(index))
187!
2707
    return err;
2708
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
187!
2709

2710
  // Copy dimension
2711
  mesh->n_dimension_ = n;
187✔
2712
  std::copy(dims, dims + n, mesh->shape_.begin());
187✔
2713
  return 0;
187✔
2714
}
2715

2716
//! Get the regular mesh parameters
2717
extern "C" int openmc_regular_mesh_get_params(
209✔
2718
  int32_t index, double** ll, double** ur, double** width, int* n)
2719
{
2720
  if (int err = check_mesh_type<RegularMesh>(index))
209!
2721
    return err;
2722
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
209!
2723

2724
  if (m->lower_left_.empty()) {
209!
UNCOV
2725
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2726
    return OPENMC_E_ALLOCATE;
×
2727
  }
2728

2729
  *ll = m->lower_left_.data();
209✔
2730
  *ur = m->upper_right_.data();
209✔
2731
  *width = m->width_.data();
209✔
2732
  *n = m->n_dimension_;
209✔
2733
  return 0;
209✔
2734
}
2735

2736
//! Set the regular mesh parameters
2737
extern "C" int openmc_regular_mesh_set_params(
220✔
2738
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2739
{
2740
  if (int err = check_mesh_type<RegularMesh>(index))
220!
2741
    return err;
2742
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
220!
2743

2744
  if (m->n_dimension_ == -1) {
220!
UNCOV
2745
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
UNCOV
2746
    return OPENMC_E_UNASSIGNED;
×
2747
  }
2748

2749
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
220✔
2750
  if (ll && ur) {
220✔
2751
    m->lower_left_ = tensor::Tensor<double>(ll, n);
198✔
2752
    m->upper_right_ = tensor::Tensor<double>(ur, n);
198✔
2753
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
792✔
2754
  } else if (ll && width) {
22✔
2755
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11✔
2756
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2757
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44✔
2758
  } else if (ur && width) {
11!
2759
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11✔
2760
    m->width_ = tensor::Tensor<double>(width, n);
11✔
2761
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44✔
2762
  } else {
UNCOV
2763
    set_errmsg("At least two parameters must be specified.");
×
UNCOV
2764
    return OPENMC_E_INVALID_ARGUMENT;
×
2765
  }
2766

2767
  // Set material volumes
2768

2769
  // TODO: incorporate this into method in RegularMesh that can be called from
2770
  // here and from constructor
2771
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
220✔
2772
  m->element_volume_ = 1.0;
220✔
2773
  for (int i = 0; i < m->n_dimension_; i++) {
880✔
2774
    m->element_volume_ *= m->width_[i];
660✔
2775
  }
2776

2777
  return 0;
2778
}
220✔
2779

2780
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2781
template<class C>
2782
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
88✔
2783
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2784
  const int nz)
2785
{
2786
  if (int err = check_mesh_type<C>(index))
88!
2787
    return err;
2788

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

2791
  m->n_dimension_ = 3;
88✔
2792

2793
  m->grid_[0].reserve(nx);
88✔
2794
  m->grid_[1].reserve(ny);
88✔
2795
  m->grid_[2].reserve(nz);
88✔
2796

2797
  for (int i = 0; i < nx; i++) {
572✔
2798
    m->grid_[0].push_back(grid_x[i]);
484✔
2799
  }
2800
  for (int i = 0; i < ny; i++) {
341✔
2801
    m->grid_[1].push_back(grid_y[i]);
253✔
2802
  }
2803
  for (int i = 0; i < nz; i++) {
319✔
2804
    m->grid_[2].push_back(grid_z[i]);
231✔
2805
  }
2806

2807
  int err = m->set_grid();
88✔
2808
  return err;
88✔
2809
}
2810

2811
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2812
template<class C>
2813
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
385✔
2814
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2815
{
2816
  if (int err = check_mesh_type<C>(index))
385!
2817
    return err;
2818
  C* m = dynamic_cast<C*>(model::meshes[index].get());
385!
2819

2820
  if (m->lower_left_.empty()) {
385!
UNCOV
2821
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2822
    return OPENMC_E_ALLOCATE;
×
2823
  }
2824

2825
  *grid_x = m->grid_[0].data();
385✔
2826
  *nx = m->grid_[0].size();
385✔
2827
  *grid_y = m->grid_[1].data();
385✔
2828
  *ny = m->grid_[1].size();
385✔
2829
  *grid_z = m->grid_[2].data();
385✔
2830
  *nz = m->grid_[2].size();
385✔
2831

2832
  return 0;
385✔
2833
}
2834

2835
//! Get the rectilinear mesh grid
2836
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
143✔
2837
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2838
{
2839
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
143✔
2840
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143✔
2841
}
2842

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

2852
//! Get the cylindrical mesh grid
2853
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2854
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2855
{
2856
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
121✔
2857
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2858
}
2859

2860
//! Set the cylindrical mesh parameters
2861
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
22✔
2862
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2863
  const double* grid_z, const int nz)
2864
{
2865
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
22✔
2866
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2867
}
2868

2869
//! Get the spherical mesh grid
2870
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
121✔
2871
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2872
{
2873

2874
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2875
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2876
  ;
121✔
2877
}
2878

2879
//! Set the spherical mesh parameters
2880
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
22✔
2881
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2882
  const double* grid_z, const int nz)
2883
{
2884
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
22✔
2885
    index, grid_x, nx, grid_y, ny, grid_z, nz);
22✔
2886
}
2887

2888
#ifdef OPENMC_DAGMC_ENABLED
2889

2890
const std::string MOABMesh::mesh_lib_type = "moab";
2891

2892
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2893
{
2894
  initialize();
24✔
2895
}
24!
2896

2897
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2898
{
2899
  initialize();
×
2900
}
×
2901

2902
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2903
  : UnstructuredMesh()
×
2904
{
2905
  n_dimension_ = 3;
2906
  filename_ = filename;
×
2907
  set_length_multiplier(length_multiplier);
×
2908
  initialize();
×
2909
}
×
2910

2911
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1✔
2912
{
2913
  mbi_ = external_mbi;
1✔
2914
  filename_ = "unknown (external file)";
1✔
2915
  this->initialize();
1✔
2916
}
1!
2917

2918
void MOABMesh::initialize()
25✔
2919
{
2920

2921
  // Create the MOAB interface and load data from file
2922
  this->create_interface();
25✔
2923

2924
  // Initialise MOAB error code
2925
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2926

2927
  // Set the dimension
2928
  n_dimension_ = 3;
25✔
2929

2930
  // set member range of tetrahedral entities
2931
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
25✔
2932
  if (rval != moab::MB_SUCCESS) {
25!
2933
    fatal_error("Failed to get all tetrahedral elements");
2934
  }
2935

2936
  if (!ehs_.all_of_type(moab::MBTET)) {
25!
2937
    warning("Non-tetrahedral elements found in unstructured "
×
2938
            "mesh file: " +
2939
            filename_);
2940
  }
2941

2942
  // set member range of vertices
2943
  int vertex_dim = 0;
25✔
2944
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
25✔
2945
  if (rval != moab::MB_SUCCESS) {
25!
2946
    fatal_error("Failed to get all vertex handles");
2947
  }
2948

2949
  // make an entity set for all tetrahedra
2950
  // this is used for convenience later in output
2951
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
25✔
2952
  if (rval != moab::MB_SUCCESS) {
25!
2953
    fatal_error("Failed to create an entity set for the tetrahedral elements");
2954
  }
2955

2956
  rval = mbi_->add_entities(tetset_, ehs_);
25✔
2957
  if (rval != moab::MB_SUCCESS) {
25!
2958
    fatal_error("Failed to add tetrahedra to an entity set.");
2959
  }
2960

2961
  if (length_multiplier_ > 0.0) {
25!
2962
    // get the connectivity of all tets
2963
    moab::Range adj;
×
2964
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
×
2965
    if (rval != moab::MB_SUCCESS) {
×
2966
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
2967
    }
2968
    // scale all vertex coords by multiplier (done individually so not all
2969
    // coordinates are in memory twice at once)
2970
    for (auto vert : adj) {
×
2971
      // retrieve coords
2972
      std::array<double, 3> coord;
2973
      rval = mbi_->get_coords(&vert, 1, coord.data());
×
2974
      if (rval != moab::MB_SUCCESS) {
×
2975
        fatal_error("Could not get coordinates of vertex.");
2976
      }
2977
      // scale coords
2978
      for (auto& c : coord) {
×
2979
        c *= length_multiplier_;
2980
      }
2981
      // set new coords
2982
      rval = mbi_->set_coords(&vert, 1, coord.data());
×
2983
      if (rval != moab::MB_SUCCESS) {
×
2984
        fatal_error("Failed to set new vertex coordinates");
2985
      }
2986
    }
2987
  }
2988

2989
  // Determine bounds of mesh
2990
  this->determine_bounds();
25✔
2991
}
25✔
2992

2993
void MOABMesh::prepare_for_point_location()
21✔
2994
{
2995
  // if the KDTree has already been constructed, do nothing
2996
  if (kdtree_)
21!
2997
    return;
2998

2999
  // build acceleration data structures
3000
  compute_barycentric_data(ehs_);
21✔
3001
  build_kdtree(ehs_);
21✔
3002
}
3003

3004
void MOABMesh::create_interface()
25✔
3005
{
3006
  // Do not create a MOAB instance if one is already in memory
3007
  if (mbi_)
25✔
3008
    return;
3009

3010
  // create MOAB instance
3011
  mbi_ = std::make_shared<moab::Core>();
24!
3012

3013
  // load unstructured mesh file
3014
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
24✔
3015
  if (rval != moab::MB_SUCCESS) {
24!
3016
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3017
  }
3018
}
3019

3020
void MOABMesh::build_kdtree(const moab::Range& all_tets)
21✔
3021
{
3022
  moab::Range all_tris;
21✔
3023
  int adj_dim = 2;
21✔
3024
  write_message("Getting tet adjacencies...", 7);
21✔
3025
  moab::ErrorCode rval = mbi_->get_adjacencies(
21✔
3026
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3027
  if (rval != moab::MB_SUCCESS) {
21!
3028
    fatal_error("Failed to get adjacent triangles for tets");
3029
  }
3030

3031
  if (!all_tris.all_of_type(moab::MBTRI)) {
21!
3032
    warning("Non-triangle elements found in tet adjacencies in "
×
3033
            "unstructured mesh file: " +
3034
            filename_);
×
3035
  }
3036

3037
  // combine into one range
3038
  moab::Range all_tets_and_tris;
21✔
3039
  all_tets_and_tris.merge(all_tets);
21✔
3040
  all_tets_and_tris.merge(all_tris);
21✔
3041

3042
  // create a kd-tree instance
3043
  write_message(
21✔
3044
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
21✔
3045
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
21✔
3046

3047
  // Determine what options to use
3048
  std::ostringstream options_stream;
21✔
3049
  if (options_.empty()) {
21✔
3050
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
5✔
3051
  } else {
3052
    options_stream << options_;
16✔
3053
  }
3054
  moab::FileOptions file_opts(options_stream.str().c_str());
21✔
3055

3056
  // Build the k-d tree
3057
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
21✔
3058
  if (rval != moab::MB_SUCCESS) {
21!
3059
    fatal_error("Failed to construct KDTree for the "
3060
                "unstructured mesh file: " +
3061
                filename_);
×
3062
  }
3063
}
21✔
3064

3065
void MOABMesh::intersect_track(const moab::CartVect& start,
1,543,584✔
3066
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3067
{
3068
  hits.clear();
1,543,584!
3069

3070
  moab::ErrorCode rval;
1,543,584✔
3071
  vector<moab::EntityHandle> tris;
1,543,584✔
3072
  // get all intersections with triangles in the tet mesh
3073
  // (distances are relative to the start point, not the previous
3074
  // intersection)
3075
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,543,584✔
3076
    dir.array(), start.array(), tris, hits, 0, track_len);
3077
  if (rval != moab::MB_SUCCESS) {
1,543,584!
3078
    fatal_error(
3079
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3080
  }
3081

3082
  // remove duplicate intersection distances
3083
  std::unique(hits.begin(), hits.end());
1,543,584✔
3084

3085
  // sorts by first component of std::pair by default
3086
  std::sort(hits.begin(), hits.end());
1,543,584✔
3087
}
1,543,584✔
3088

3089
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,543,584✔
3090
  vector<int>& bins, vector<double>& lengths) const
3091
{
3092
  moab::CartVect start(r0.x, r0.y, r0.z);
1,543,584✔
3093
  moab::CartVect end(r1.x, r1.y, r1.z);
1,543,584✔
3094
  moab::CartVect dir(u.x, u.y, u.z);
1,543,584✔
3095
  dir.normalize();
1,543,584✔
3096

3097
  double track_len = (end - start).length();
1,543,584✔
3098
  if (track_len == 0.0)
1,543,584!
3099
    return;
721,692✔
3100

3101
  start -= TINY_BIT * dir;
1,543,584✔
3102
  end += TINY_BIT * dir;
1,543,584✔
3103

3104
  vector<double> hits;
1,543,584✔
3105
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3106

3107
  bins.clear();
1,543,584!
3108
  lengths.clear();
1,543,584!
3109

3110
  // if there are no intersections the track may lie entirely
3111
  // within a single tet. If this is the case, apply entire
3112
  // score to that tet and return.
3113
  if (hits.size() == 0) {
1,543,584✔
3114
    Position midpoint = r0 + u * (track_len * 0.5);
721,692✔
3115
    int bin = this->get_bin(midpoint);
721,692✔
3116
    if (bin != -1) {
721,692✔
3117
      bins.push_back(bin);
242,866✔
3118
      lengths.push_back(1.0);
242,866✔
3119
    }
3120
    return;
721,692✔
3121
  }
3122

3123
  // for each segment in the set of tracks, try to look up a tet
3124
  // at the midpoint of the segment
3125
  Position current = r0;
3126
  double last_dist = 0.0;
3127
  for (const auto& hit : hits) {
5,516,161✔
3128
    // get the segment length
3129
    double segment_length = hit - last_dist;
4,694,269✔
3130
    last_dist = hit;
4,694,269✔
3131
    // find the midpoint of this segment
3132
    Position midpoint = current + u * (segment_length * 0.5);
4,694,269✔
3133
    // try to find a tet for this position
3134
    int bin = this->get_bin(midpoint);
4,694,269✔
3135

3136
    // determine the start point for this segment
3137
    current = r0 + u * hit;
4,694,269✔
3138

3139
    if (bin == -1) {
4,694,269✔
3140
      continue;
20,522✔
3141
    }
3142

3143
    bins.push_back(bin);
4,673,747✔
3144
    lengths.push_back(segment_length / track_len);
4,673,747✔
3145
  }
3146

3147
  // tally remaining portion of track after last hit if
3148
  // the last segment of the track is in the mesh but doesn't
3149
  // reach the other side of the tet
3150
  if (hits.back() < track_len) {
821,892!
3151
    Position segment_start = r0 + u * hits.back();
821,892✔
3152
    double segment_length = track_len - hits.back();
821,892✔
3153
    Position midpoint = segment_start + u * (segment_length * 0.5);
821,892✔
3154
    int bin = this->get_bin(midpoint);
821,892✔
3155
    if (bin != -1) {
821,892✔
3156
      bins.push_back(bin);
766,509✔
3157
      lengths.push_back(segment_length / track_len);
766,509✔
3158
    }
3159
  }
3160
};
1,543,584✔
3161

3162
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,317,232✔
3163
{
3164
  moab::CartVect pos(r.x, r.y, r.z);
7,317,232✔
3165
  // find the leaf of the kd-tree for this position
3166
  moab::AdaptiveKDTreeIter kdtree_iter;
7,317,232✔
3167
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,317,232✔
3168
  if (rval != moab::MB_SUCCESS) {
7,317,232✔
3169
    return 0;
3170
  }
3171

3172
  // retrieve the tet elements of this leaf
3173
  moab::EntityHandle leaf = kdtree_iter.handle();
6,305,335✔
3174
  moab::Range tets;
6,305,335✔
3175
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,305,335✔
3176
  if (rval != moab::MB_SUCCESS) {
6,305,335!
3177
    warning("MOAB error finding tets.");
×
3178
  }
3179

3180
  // loop over the tets in this leaf, returning the containing tet if found
3181
  for (const auto& tet : tets) {
260,211,273✔
3182
    if (point_in_tet(pos, tet)) {
260,208,426✔
3183
      return tet;
6,302,488✔
3184
    }
3185
  }
3186

3187
  // if no tet is found, return an invalid handle
3188
  return 0;
2,847✔
3189
}
14,634,464✔
3190

3191
double MOABMesh::volume(int bin) const
167,880✔
3192
{
3193
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3194
}
3195

3196
std::string MOABMesh::library() const
34✔
3197
{
3198
  return mesh_lib_type;
34✔
3199
}
3200

3201
// Sample position within a tet for MOAB type tets
3202
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410✔
3203
{
3204

3205
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3206

3207
  // Get vertex coordinates for MOAB tet
3208
  const moab::EntityHandle* conn1;
200,410✔
3209
  int conn1_size;
200,410✔
3210
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410✔
3211
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410!
3212
    fatal_error(fmt::format(
3213
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3214
      conn1_size));
3215
  }
3216
  moab::CartVect p[4];
200,410✔
3217
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410✔
3218
  if (rval != moab::MB_SUCCESS) {
200,410!
3219
    fatal_error("Failed to get tet coords");
3220
  }
3221

3222
  std::array<Position, 4> tet_verts;
200,410✔
3223
  for (int i = 0; i < 4; i++) {
1,002,050✔
3224
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640✔
3225
  }
3226
  // Samples position within tet using Barycentric stuff
3227
  return this->sample_tet(tet_verts, seed);
200,410✔
3228
}
3229

3230
double MOABMesh::tet_volume(moab::EntityHandle tet) const
167,880✔
3231
{
3232
  vector<moab::EntityHandle> conn;
167,880✔
3233
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
167,880✔
3234
  if (rval != moab::MB_SUCCESS) {
167,880!
3235
    fatal_error("Failed to get tet connectivity");
3236
  }
3237

3238
  moab::CartVect p[4];
167,880✔
3239
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
167,880✔
3240
  if (rval != moab::MB_SUCCESS) {
167,880!
3241
    fatal_error("Failed to get tet coords");
3242
  }
3243

3244
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3245
}
167,880✔
3246

3247
int MOABMesh::get_bin(Position r) const
7,317,232✔
3248
{
3249
  moab::EntityHandle tet = get_tet(r);
7,317,232✔
3250
  if (tet == 0) {
7,317,232✔
3251
    return -1;
3252
  } else {
3253
    return get_bin_from_ent_handle(tet);
6,302,488✔
3254
  }
3255
}
3256

3257
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3258
{
3259
  moab::ErrorCode rval;
21✔
3260

3261
  baryc_data_.clear();
21!
3262
  baryc_data_.resize(tets.size());
21✔
3263

3264
  // compute the barycentric data for each tet element
3265
  // and store it as a 3x3 matrix
3266
  for (auto& tet : tets) {
239,757✔
3267
    vector<moab::EntityHandle> verts;
239,736✔
3268
    rval = mbi_->get_connectivity(&tet, 1, verts);
239,736✔
3269
    if (rval != moab::MB_SUCCESS) {
239,736!
3270
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3271
    }
3272

3273
    moab::CartVect p[4];
239,736✔
3274
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
239,736✔
3275
    if (rval != moab::MB_SUCCESS) {
239,736!
3276
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3277
    }
3278

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

3281
    // invert now to avoid this cost later
3282
    a = a.transpose().inverse();
239,736✔
3283
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
239,736✔
3284
  }
239,736✔
3285
}
21✔
3286

3287
bool MOABMesh::point_in_tet(
260,208,426✔
3288
  const moab::CartVect& r, moab::EntityHandle tet) const
3289
{
3290

3291
  moab::ErrorCode rval;
260,208,426✔
3292

3293
  // get tet vertices
3294
  vector<moab::EntityHandle> verts;
260,208,426✔
3295
  rval = mbi_->get_connectivity(&tet, 1, verts);
260,208,426✔
3296
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3297
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3298
    return false;
3299
  }
3300

3301
  // first vertex is used as a reference point for the barycentric data -
3302
  // retrieve its coordinates
3303
  moab::CartVect p_zero;
260,208,426✔
3304
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
260,208,426✔
3305
  if (rval != moab::MB_SUCCESS) {
260,208,426!
3306
    warning("Failed to get coordinates of a vertex in "
×
3307
            "unstructured mesh: " +
3308
            filename_);
×
3309
    return false;
3310
  }
3311

3312
  // look up barycentric data
3313
  int idx = get_bin_from_ent_handle(tet);
260,208,426✔
3314
  const moab::Matrix3& a_inv = baryc_data_[idx];
260,208,426✔
3315

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

3318
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
161,208,987✔
3319
          bary_coords[2] >= 0.0 &&
318,957,185✔
3320
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,688,225✔
3321
}
260,208,426✔
3322

3323
int MOABMesh::get_bin_from_index(int idx) const
3324
{
3325
  if (idx >= n_bins()) {
×
3326
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3327
  }
3328
  return ehs_[idx] - ehs_[0];
3329
}
3330

3331
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3332
{
3333
  int bin = get_bin(r);
3334
  *in_mesh = bin != -1;
3335
  return bin;
3336
}
3337

3338
int MOABMesh::get_index_from_bin(int bin) const
3339
{
3340
  return bin;
3341
}
3342

3343
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3344
  Position plot_ll, Position plot_ur) const
3345
{
3346
  // TODO: Implement mesh lines
3347
  return {};
3348
}
3349

3350
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
815,520✔
3351
{
3352
  int idx = vert - verts_[0];
815,520✔
3353
  if (idx >= n_vertices()) {
815,520!
3354
    fatal_error(
3355
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3356
  }
3357
  return idx;
815,520✔
3358
}
3359

3360
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
266,750,650✔
3361
{
3362
  int bin = eh - ehs_[0];
266,750,650✔
3363
  if (bin >= n_bins()) {
266,750,650!
3364
    fatal_error(fmt::format("Invalid bin: {}", bin));
3365
  }
3366
  return bin;
266,750,650✔
3367
}
3368

3369
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
572,170✔
3370
{
3371
  if (bin >= n_bins()) {
572,170!
3372
    fatal_error(fmt::format("Invalid bin index: ", bin));
3373
  }
3374
  return ehs_[0] + bin;
572,170✔
3375
}
3376

3377
int MOABMesh::n_bins() const
267,526,773✔
3378
{
3379
  return ehs_.size();
267,526,773✔
3380
}
3381

3382
int MOABMesh::n_surface_bins() const
3383
{
3384
  // collect all triangles in the set of tets for this mesh
3385
  moab::Range tris;
×
3386
  moab::ErrorCode rval;
3387
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3388
  if (rval != moab::MB_SUCCESS) {
×
3389
    warning("Failed to get all triangles in the mesh instance");
×
3390
    return -1;
3391
  }
3392
  return 2 * tris.size();
×
3393
}
3394

3395
Position MOABMesh::centroid(int bin) const
3396
{
3397
  moab::ErrorCode rval;
3398

3399
  auto tet = this->get_ent_handle_from_bin(bin);
3400

3401
  // look up the tet connectivity
3402
  vector<moab::EntityHandle> conn;
×
3403
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3404
  if (rval != moab::MB_SUCCESS) {
×
3405
    warning("Failed to get connectivity of a mesh element.");
×
3406
    return {};
3407
  }
3408

3409
  // get the coordinates
3410
  vector<moab::CartVect> coords(conn.size());
×
3411
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3412
  if (rval != moab::MB_SUCCESS) {
×
3413
    warning("Failed to get the coordinates of a mesh element.");
×
3414
    return {};
3415
  }
3416

3417
  // compute the centroid of the element vertices
3418
  moab::CartVect centroid(0.0, 0.0, 0.0);
3419
  for (const auto& coord : coords) {
×
3420
    centroid += coord;
3421
  }
3422
  centroid /= double(coords.size());
3423

3424
  return {centroid[0], centroid[1], centroid[2]};
3425
}
3426

3427
int MOABMesh::n_vertices() const
845,874✔
3428
{
3429
  return verts_.size();
845,874✔
3430
}
3431

3432
Position MOABMesh::vertex(int id) const
86,227✔
3433
{
3434

3435
  moab::ErrorCode rval;
86,227✔
3436

3437
  moab::EntityHandle vert = verts_[id];
86,227✔
3438

3439
  moab::CartVect coords;
86,227✔
3440
  rval = mbi_->get_coords(&vert, 1, coords.array());
86,227✔
3441
  if (rval != moab::MB_SUCCESS) {
86,227!
3442
    fatal_error("Failed to get the coordinates of a vertex.");
3443
  }
3444

3445
  return {coords[0], coords[1], coords[2]};
86,227✔
3446
}
3447

3448
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3449
{
3450
  moab::ErrorCode rval;
203,880✔
3451

3452
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3453

3454
  // look up the tet connectivity
3455
  vector<moab::EntityHandle> conn;
203,880✔
3456
  rval = mbi_->get_connectivity(&tet, 1, conn);
203,880✔
3457
  if (rval != moab::MB_SUCCESS) {
203,880!
3458
    fatal_error("Failed to get connectivity of a mesh element.");
3459
    return {};
3460
  }
3461

3462
  std::vector<int> verts(4);
203,880✔
3463
  for (int i = 0; i < verts.size(); i++) {
1,019,400✔
3464
    verts[i] = get_vert_idx_from_handle(conn[i]);
815,520✔
3465
  }
3466

3467
  return verts;
203,880✔
3468
}
203,880✔
3469

3470
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3471
  std::string score) const
3472
{
3473
  moab::ErrorCode rval;
3474
  // add a tag to the mesh
3475
  // all scores are treated as a single value
3476
  // with an uncertainty
3477
  moab::Tag value_tag;
3478

3479
  // create the value tag if not present and get handle
3480
  double default_val = 0.0;
3481
  auto val_string = score + "_mean";
3482
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3483
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3484
  if (rval != moab::MB_SUCCESS) {
×
3485
    auto msg =
3486
      fmt::format("Could not create or retrieve the value tag for the score {}"
3487
                  " on unstructured mesh {}",
3488
        score, id_);
×
3489
    fatal_error(msg);
3490
  }
3491

3492
  // create the std dev tag if not present and get handle
3493
  moab::Tag error_tag;
3494
  std::string err_string = score + "_std_dev";
×
3495
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3496
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3497
  if (rval != moab::MB_SUCCESS) {
×
3498
    auto msg =
3499
      fmt::format("Could not create or retrieve the error tag for the score {}"
3500
                  " on unstructured mesh {}",
3501
        score, id_);
×
3502
    fatal_error(msg);
3503
  }
3504

3505
  // return the populated tag handles
3506
  return {value_tag, error_tag};
3507
}
3508

3509
void MOABMesh::add_score(const std::string& score)
3510
{
3511
  auto score_tags = get_score_tags(score);
×
3512
  tag_names_.push_back(score);
3513
}
3514

3515
void MOABMesh::remove_scores()
3516
{
3517
  for (const auto& name : tag_names_) {
×
3518
    auto value_name = name + "_mean";
3519
    moab::Tag tag;
3520
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3521
    if (rval != moab::MB_SUCCESS)
×
3522
      return;
3523

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

3532
    auto std_dev_name = name + "_std_dev";
×
3533
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3534
    if (rval != moab::MB_SUCCESS) {
×
3535
      auto msg =
3536
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3537
                    " on unstructured mesh {}",
3538
          name, id_);
×
3539
    }
3540

3541
    rval = mbi_->tag_delete(tag);
×
3542
    if (rval != moab::MB_SUCCESS) {
×
3543
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3544
                             " on unstructured mesh {}",
3545
        name, id_);
×
3546
      fatal_error(msg);
3547
    }
3548
  }
3549
  tag_names_.clear();
3550
}
3551

3552
void MOABMesh::set_score_data(const std::string& score,
3553
  const vector<double>& values, const vector<double>& std_dev)
3554
{
3555
  auto score_tags = this->get_score_tags(score);
×
3556

3557
  moab::ErrorCode rval;
3558
  // set the score value
3559
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3560
  if (rval != moab::MB_SUCCESS) {
×
3561
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3562
                           "on unstructured mesh {}",
3563
      score, id_);
3564
    warning(msg);
×
3565
  }
3566

3567
  // set the error value
3568
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3569
  if (rval != moab::MB_SUCCESS) {
×
3570
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3571
                           "on unstructured mesh {}",
3572
      score, id_);
3573
    warning(msg);
×
3574
  }
3575
}
3576

3577
void MOABMesh::write(const std::string& base_filename) const
3578
{
3579
  // add extension to the base name
3580
  auto filename = base_filename + ".vtk";
3581
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3582
  filename = settings::path_output + filename;
×
3583

3584
  // write the tetrahedral elements of the mesh only
3585
  // to avoid clutter from zero-value data on other
3586
  // elements during visualization
3587
  moab::ErrorCode rval;
3588
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3589
  if (rval != moab::MB_SUCCESS) {
×
3590
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3591
    warning(msg);
×
3592
  }
3593
}
3594

3595
#endif
3596

3597
#ifdef OPENMC_LIBMESH_ENABLED
3598

3599
const std::string LibMesh::mesh_lib_type = "libmesh";
3600

3601
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25✔
3602
{
3603
  // filename_ and length_multiplier_ will already be set by the
3604
  // UnstructuredMesh constructor
3605
  set_mesh_pointer_from_filename(filename_);
25✔
3606
  set_length_multiplier(length_multiplier_);
25✔
3607
  initialize();
25✔
3608
}
25✔
3609

3610
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3611
{
3612
  // filename_ and length_multiplier_ will already be set by the
3613
  // UnstructuredMesh constructor
3614
  set_mesh_pointer_from_filename(filename_);
×
3615
  set_length_multiplier(length_multiplier_);
×
3616
  initialize();
×
3617
}
3618

3619
// create the mesh from a pointer to a libMesh Mesh
3620
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3621
{
3622
  if (!input_mesh.is_replicated()) {
×
3623
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3624
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3625
  }
3626

3627
  m_ = &input_mesh;
3628
  set_length_multiplier(length_multiplier);
×
3629
  initialize();
×
3630
}
3631

3632
// create the mesh from an input file
3633
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
×
3634
{
3635
  n_dimension_ = 3;
3636
  set_mesh_pointer_from_filename(filename);
×
3637
  set_length_multiplier(length_multiplier);
×
3638
  initialize();
×
3639
}
3640

3641
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
25✔
3642
{
3643
  filename_ = filename;
25✔
3644
  unique_m_ =
25✔
3645
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
25✔
3646
  m_ = unique_m_.get();
25✔
3647
  m_->read(filename_);
25✔
3648
}
25✔
3649

3650
// build a libMesh equation system for storing values
3651
void LibMesh::build_eqn_sys()
17✔
3652
{
3653
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17✔
3654
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17✔
3655
  libMesh::ExplicitSystem& eq_sys =
17✔
3656
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17✔
3657
}
17✔
3658

3659
// intialize from mesh file
3660
void LibMesh::initialize()
25✔
3661
{
3662
  if (!settings::libmesh_comm) {
25!
3663
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3664
                "communicator.");
3665
  }
3666

3667
  // assuming that unstructured meshes used in OpenMC are 3D
3668
  n_dimension_ = 3;
25✔
3669

3670
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3671
  // Otherwise assume that it is prepared by its owning application
3672
  if (unique_m_) {
25!
3673
    m_->prepare_for_use();
25✔
3674
  }
3675

3676
  // ensure that the loaded mesh is 3 dimensional
3677
  if (m_->mesh_dimension() != n_dimension_) {
25!
3678
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3679
                            "mesh is not a 3D mesh.",
3680
      filename_));
3681
  }
3682

3683
  for (int i = 0; i < num_threads(); i++) {
69✔
3684
    pl_.emplace_back(m_->sub_point_locator());
44✔
3685
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
44✔
3686
    pl_.back()->enable_out_of_mesh_mode();
44✔
3687
  }
3688

3689
  // store first element in the mesh to use as an offset for bin indices
3690
  auto first_elem = *m_->elements_begin();
50✔
3691
  first_element_id_ = first_elem->id();
25✔
3692

3693
  // bounding box for the mesh for quick rejection checks
3694
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
25!
3695
  libMesh::Point ll = bbox_.min();
25!
3696
  libMesh::Point ur = bbox_.max();
25!
3697
  if (length_multiplier_ > 0.0) {
25!
3698
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3699
      length_multiplier_ * ll(2)};
3700
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3701
      length_multiplier_ * ur(2)};
3702
  } else {
3703
    lower_left_ = {ll(0), ll(1), ll(2)};
25✔
3704
    upper_right_ = {ur(0), ur(1), ur(2)};
25✔
3705
  }
3706
}
25✔
3707

3708
// Sample position within a tet for LibMesh type tets
3709
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820✔
3710
{
3711
  const auto& elem = get_element_from_bin(bin);
400,820✔
3712
  // Get tet vertex coordinates from LibMesh
3713
  std::array<Position, 4> tet_verts;
400,820✔
3714
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100✔
3715
    const auto& node_ref = elem.node_ref(i);
1,603,280✔
3716
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280✔
3717
  }
3718
  // Samples position within tet using Barycentric coordinates
3719
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820✔
3720
  if (length_multiplier_ > 0.0) {
400,820!
3721
    return length_multiplier_ * sampled_position;
3722
  } else {
3723
    return sampled_position;
400,820✔
3724
  }
3725
}
3726

3727
Position LibMesh::centroid(int bin) const
3728
{
3729
  const auto& elem = this->get_element_from_bin(bin);
3730
  auto centroid = elem.vertex_average();
3731
  if (length_multiplier_ > 0.0) {
×
3732
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3733
  } else {
3734
    return {centroid(0), centroid(1), centroid(2)};
3735
  }
3736
}
3737

3738
int LibMesh::n_vertices() const
42,644✔
3739
{
3740
  return m_->n_nodes();
42,644✔
3741
}
3742

3743
Position LibMesh::vertex(int vertex_id) const
42,604✔
3744
{
3745
  const auto& node_ref = m_->node_ref(vertex_id);
42,604✔
3746
  if (length_multiplier_ > 0.0) {
42,604!
3747
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3748
  } else {
3749
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604✔
3750
  }
3751
}
3752

3753
std::vector<int> LibMesh::connectivity(int elem_id) const
267,856✔
3754
{
3755
  std::vector<int> conn;
267,856✔
3756
  const auto* elem_ptr = m_->elem_ptr(elem_id);
267,856✔
3757
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,355,280✔
3758
    conn.push_back(elem_ptr->node_id(i));
1,087,424✔
3759
  }
3760
  return conn;
267,856✔
3761
}
3762

3763
std::string LibMesh::library() const
37✔
3764
{
3765
  return mesh_lib_type;
37✔
3766
}
3767

3768
int LibMesh::n_bins() const
1,788,419✔
3769
{
3770
  return m_->n_elem();
1,788,419✔
3771
}
3772

3773
int LibMesh::n_surface_bins() const
3774
{
3775
  int n_bins = 0;
3776
  for (int i = 0; i < this->n_bins(); i++) {
×
3777
    const libMesh::Elem& e = get_element_from_bin(i);
3778
    n_bins += e.n_faces();
3779
    // if this is a boundary element, it will only be visited once,
3780
    // the number of surface bins is incremented to
3781
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3782
      // null neighbor pointer indicates a boundary face
3783
      if (!neighbor_ptr) {
×
3784
        n_bins++;
3785
      }
3786
    }
3787
  }
3788
  return n_bins;
3789
}
3790

3791
void LibMesh::add_score(const std::string& var_name)
17✔
3792
{
3793
  if (!equation_systems_) {
17!
3794
    build_eqn_sys();
17✔
3795
  }
3796

3797
  // check if this is a new variable
3798
  std::string value_name = var_name + "_mean";
17✔
3799
  if (!variable_map_.count(value_name)) {
17✔
3800
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3801
    auto var_num =
17✔
3802
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3803
    variable_map_[value_name] = var_num;
17✔
3804
  }
3805

3806
  std::string std_dev_name = var_name + "_std_dev";
17✔
3807
  // check if this is a new variable
3808
  if (!variable_map_.count(std_dev_name)) {
17✔
3809
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3810
    auto var_num =
17✔
3811
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17✔
3812
    variable_map_[std_dev_name] = var_num;
17✔
3813
  }
3814
}
17✔
3815

3816
void LibMesh::remove_scores()
17✔
3817
{
3818
  if (equation_systems_) {
17!
3819
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3820
    eqn_sys.clear();
17✔
3821
    variable_map_.clear();
17✔
3822
  }
3823
}
17✔
3824

3825
void LibMesh::set_score_data(const std::string& var_name,
17✔
3826
  const vector<double>& values, const vector<double>& std_dev)
3827
{
3828
  if (!equation_systems_) {
17!
3829
    build_eqn_sys();
3830
  }
3831

3832
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3833

3834
  if (!eqn_sys.is_initialized()) {
17!
3835
    equation_systems_->init();
17✔
3836
  }
3837

3838
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3839

3840
  // look up the value variable
3841
  std::string value_name = var_name + "_mean";
17✔
3842
  unsigned int value_num = variable_map_.at(value_name);
17✔
3843
  // look up the std dev variable
3844
  std::string std_dev_name = var_name + "_std_dev";
17✔
3845
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17✔
3846

3847
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763✔
3848
       it++) {
3849
    if (!(*it)->active()) {
99,856!
3850
      continue;
3851
    }
3852

3853
    auto bin = get_bin_from_element(*it);
99,856✔
3854

3855
    // set value
3856
    vector<libMesh::dof_id_type> value_dof_indices;
99,856✔
3857
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856✔
3858
    assert(value_dof_indices.size() == 1);
99,856✔
3859
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856✔
3860

3861
    // set std dev
3862
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856✔
3863
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856✔
3864
    assert(std_dev_dof_indices.size() == 1);
99,856✔
3865
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856✔
3866
  }
99,873✔
3867
}
17✔
3868

3869
void LibMesh::write(const std::string& filename) const
17✔
3870
{
3871
  write_message(fmt::format(
17✔
3872
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3873
  libMesh::ExodusII_IO exo(*m_);
17✔
3874
  std::set<std::string> systems_out = {eq_system_name_};
34!
3875
  exo.write_discontinuous_exodusII(
17✔
3876
    filename + ".e", *equation_systems_, &systems_out);
34✔
3877
}
17✔
3878

3879
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3880
  vector<int>& bins, vector<double>& lengths) const
3881
{
3882
  // TODO: Implement triangle crossings here
3883
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3884
}
3885

3886
int LibMesh::get_bin(Position r) const
2,340,604✔
3887
{
3888
  // look-up a tet using the point locator
3889
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3890

3891
  if (length_multiplier_ > 0.0) {
2,340,604!
3892
    // Scale the point down
3893
    p /= length_multiplier_;
2,340,604✔
3894
  }
3895

3896
  // quick rejection check
3897
  if (!bbox_.contains_point(p)) {
2,340,604✔
3898
    return -1;
3899
  }
3900

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

3903
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3904
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3905
}
2,340,604✔
3906

3907
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3908
{
3909
  int bin = elem->id() - first_element_id_;
1,520,434✔
3910
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3911
    fatal_error(fmt::format("Invalid bin: {}", bin));
3912
  }
3913
  return bin;
1,520,434✔
3914
}
3915

3916
std::pair<vector<double>, vector<double>> LibMesh::plot(
3917
  Position plot_ll, Position plot_ur) const
3918
{
3919
  return {};
3920
}
3921

3922
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3923
{
3924
  return m_->elem_ref(bin);
769,460✔
3925
}
3926

3927
double LibMesh::volume(int bin) const
368,640✔
3928
{
3929
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3930
         length_multiplier_ * length_multiplier_;
368,640✔
3931
}
3932

3933
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
3934
  double length_multiplier,
3935
  const std::set<libMesh::subdomain_id_type>& block_ids)
3936
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
3937
    block_restrict_(!block_ids_.empty()),
×
3938
    num_active_(
×
3939
      block_restrict_
3940
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
3941
            m_->active_subdomain_set_elements_end(block_ids_))
×
3942
        : m_->n_active_elem())
×
3943
{
3944
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
3945
  // contiguous in ID space, so we need to map from bin indices (defined over
3946
  // active elements) to global dof ids
3947
  bin_to_elem_map_.reserve(num_active_);
×
3948
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
3949
  auto begin = block_restrict_
3950
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
3951
                 : m_->active_elements_begin();
×
3952
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
3953
                             : m_->active_elements_end();
×
3954
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
3955
    bin_to_elem_map_.push_back(elem->id());
×
3956
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
3957
  }
3958
}
3959

3960
int AdaptiveLibMesh::n_bins() const
3961
{
3962
  return num_active_;
3963
}
3964

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

3972
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3973
  const vector<double>& values, const vector<double>& std_dev)
3974
{
3975
  warning(fmt::format(
×
3976
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3977
    this->id_));
3978
}
3979

3980
void AdaptiveLibMesh::write(const std::string& filename) const
3981
{
3982
  warning(fmt::format(
×
3983
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3984
    this->id_));
3985
}
3986

3987
int AdaptiveLibMesh::get_bin(Position r) const
3988
{
3989
  // look-up a tet using the point locator
3990
  libMesh::Point p(r.x, r.y, r.z);
×
3991

3992
  if (length_multiplier_ > 0.0) {
×
3993
    // Scale the point down
3994
    p /= length_multiplier_;
3995
  }
3996

3997
  // quick rejection check
3998
  if (!bbox_.contains_point(p)) {
×
3999
    return -1;
4000
  }
4001

4002
  const auto& point_locator = pl_.at(thread_num());
×
4003

4004
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4005
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4006
}
4007

4008
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4009
{
4010
  int bin = elem_to_bin_map_[elem->id()];
4011
  if (bin >= n_bins() || bin < 0) {
×
4012
    fatal_error(fmt::format("Invalid bin: {}", bin));
4013
  }
4014
  return bin;
4015
}
4016

4017
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4018
{
4019
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4020
}
4021

4022
#endif // OPENMC_LIBMESH_ENABLED
4023

4024
//==============================================================================
4025
// Non-member functions
4026
//==============================================================================
4027

4028
void read_meshes(pugi::xml_node root)
14,016✔
4029
{
4030
  std::unordered_set<int> mesh_ids;
14,016✔
4031

4032
  for (auto node : root.children("mesh")) {
17,432✔
4033
    // Check to make sure multiple meshes in the same file don't share IDs
4034
    int id = std::stoi(get_node_value(node, "id"));
6,832✔
4035
    if (contains(mesh_ids, id)) {
6,832!
UNCOV
4036
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4037
                              "'{}' in the same input file",
4038
        id));
4039
    }
4040
    mesh_ids.insert(id);
3,416✔
4041

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

4049
    std::string mesh_type;
3,416✔
4050
    if (check_for_node(node, "type")) {
3,416✔
4051
      mesh_type = get_node_value(node, "type", true, true);
983✔
4052
    } else {
4053
      mesh_type = "regular";
2,433✔
4054
    }
4055

4056
    // determine the mesh library to use
4057
    std::string mesh_lib;
3,416✔
4058
    if (check_for_node(node, "library")) {
3,416✔
4059
      mesh_lib = get_node_value(node, "library", true, true);
49!
4060
    }
4061

4062
    Mesh::create(node, mesh_type, mesh_lib);
3,416✔
4063
  }
3,416✔
4064
}
14,016✔
4065

4066
void read_meshes(hid_t group)
48✔
4067
{
4068
  std::unordered_set<int> mesh_ids;
48✔
4069

4070
  std::vector<int> ids;
48✔
4071
  read_attribute(group, "ids", ids);
48✔
4072

4073
  for (auto id : ids) {
107✔
4074

4075
    // Check to make sure multiple meshes in the same file don't share IDs
4076
    if (contains(mesh_ids, id)) {
118!
UNCOV
4077
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4078
                              "'{}' in the same HDF5 input file",
4079
        id));
4080
    }
4081
    mesh_ids.insert(id);
59✔
4082

4083
    // If we've already read a mesh with the same ID in a *different* file,
4084
    // assume it is the same here
4085
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
59✔
4086
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33✔
4087
      continue;
33✔
4088
    }
4089

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

4093
    std::string mesh_type;
26✔
4094
    if (object_exists(mesh_group, "type")) {
26!
4095
      read_dataset(mesh_group, "type", mesh_type);
26✔
4096
    } else {
UNCOV
4097
      mesh_type = "regular";
×
4098
    }
4099

4100
    // determine the mesh library to use
4101
    std::string mesh_lib;
26✔
4102
    if (object_exists(mesh_group, "library")) {
26!
UNCOV
4103
      read_dataset(mesh_group, "library", mesh_lib);
×
4104
    }
4105

4106
    Mesh::create(mesh_group, mesh_type, mesh_lib);
26✔
4107
  }
26✔
4108
}
96✔
4109

4110
void meshes_to_hdf5(hid_t group)
7,855✔
4111
{
4112
  // Write number of meshes
4113
  hid_t meshes_group = create_group(group, "meshes");
7,855✔
4114
  int32_t n_meshes = model::meshes.size();
7,855✔
4115
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,855✔
4116

4117
  if (n_meshes > 0) {
7,855✔
4118
    // Write IDs of meshes
4119
    vector<int> ids;
2,436✔
4120
    for (const auto& m : model::meshes) {
5,616✔
4121
      m->to_hdf5(meshes_group);
3,180✔
4122
      ids.push_back(m->id_);
3,180✔
4123
    }
4124
    write_attribute(meshes_group, "ids", ids);
2,436✔
4125
  }
2,436✔
4126

4127
  close_group(meshes_group);
7,855✔
4128
}
7,855✔
4129

4130
void free_memory_mesh()
9,148✔
4131
{
4132
  model::meshes.clear();
9,148✔
4133
  model::mesh_map.clear();
9,148✔
4134
}
9,148✔
4135

4136
extern "C" int n_meshes()
308✔
4137
{
4138
  return model::meshes.size();
308✔
4139
}
4140

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

© 2026 Coveralls, Inc