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

openmc-dev / openmc / 34416149688

09 Sep 2026 11:15PM UTC coverage: 81.48% (+0.1%) from 81.347%
34416149688

Pull #4087

github

web-flow
Merge 93138e589 into 5260b9a0f
Pull Request #4087: Compute bounding boxes for general planes and tori in C++

18756 of 27197 branches covered (68.96%)

Branch coverage included in aggregate %.

43 of 46 new or added lines in 2 files covered. (93.48%)

959 existing lines in 29 files now uncovered.

60863 of 70519 relevant lines covered (86.31%)

49704801.91 hits per line

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

72.64
/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
// Value used to indicate an empty slot in the hash table. We use -2 because
65
// the value -1 is used to indicate a void material.
66
constexpr int32_t EMPTY = -2;
67

68
namespace model {
69

70
std::unordered_map<int32_t, int32_t> mesh_map;
71
vector<unique_ptr<Mesh>> meshes;
72

73
} // namespace model
74

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

82
//==============================================================================
83
// Helper functions
84
//==============================================================================
85

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

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

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

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

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

134
// Helper function equivalent to std::bit_cast in C++20
135
template<typename To, typename From>
136
inline To bit_cast_value(const From& value)
38,980,305 ✔
137
{
138
  To out;
139
  std::memcpy(&out, &value, sizeof(To));
62,228 ✔
140
  return out;
141
}
142

143
inline void atomic_update_double(double* ptr, double value, bool is_min)
38,980,080 ✔
144
{
145
#if defined(__GNUC__) || defined(__clang__)
146
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
38,980,080 ✔
147
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
38,980,080 ✔
148
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
38,980,080 ✔
149
  double current = bit_cast_value<double>(current_bits);
38,980,080 ✔
150
  while (is_min ? (value < current) : (value > current)) {
38,980,305 ✔
151
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
62,228 ✔
152
    uint64_t expected_bits = current_bits;
62,228 ✔
153
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
62,228 ✔
154
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
155
      return;
38,980,080 ✔
156
    }
157
    current_bits = expected_bits;
225 ✔
158
    current = bit_cast_value<double>(current_bits);
225 ✔
159
  }
160

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

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

181
inline void atomic_max_double(double* ptr, double value)
19,490,040 ✔
182
{
183
  atomic_update_double(ptr, value, false);
6,496,680 ✔
184
}
6,496,680 ✔
185

186
inline void atomic_min_double(double* ptr, double value)
19,490,040 ✔
187
{
188
  atomic_update_double(ptr, value, true);
6,496,680 ✔
189
}
190

191
namespace detail {
192

193
//==============================================================================
194
// MaterialVolumes implementation
195
//==============================================================================
196

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

206
  // Loop for linear probing
207
  for (int attempt = 0; attempt < table_size_; ++attempt) {
9,496,889 !
208
    // Determine slot to check, making sure it is positive
209
    int slot = (index_material + attempt) % table_size_;
9,496,889 ✔
210
    if (slot < 0)
9,496,889 ✔
211
      slot += table_size_;
6,096,250 ✔
212
    int32_t* slot_ptr = &this->materials(index_elem, slot);
9,496,889 ✔
213

214
    // Non-atomic read of current material
215
    int32_t current_val = *slot_ptr;
9,496,889 ✔
216

217
    // Found the desired material; accumulate volume and bbox
218
    if (current_val == index_material) {
9,496,889 ✔
219
#pragma omp atomic
5,427,525 ✔
220
      this->volumes(index_elem, slot) += volume;
9,436,831 ✔
221
      if (bbox) {
9,436,831 ✔
222
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
6,494,921 ✔
223
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
6,494,921 ✔
224
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
6,494,921 ✔
225
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
6,494,921 ✔
226
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
6,494,921 ✔
227
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
6,494,921 ✔
228
      }
229
      return;
9,436,831 ✔
230
    }
231

232
    // Slot appears to be empty; attempt to claim
233
    if (current_val == EMPTY) {
60,058 ✔
234
      // Attempt compare-and-swap from EMPTY to index_material
235
      int32_t expected_val = EMPTY;
3,199 ✔
236
      bool claimed_slot =
3,199 ✔
237
        atomic_cas_int32(slot_ptr, expected_val, index_material);
3,199 ✔
238

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

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

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

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

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

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

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

320
} // namespace detail
321

322
//==============================================================================
323
// Mesh implementation
324
//==============================================================================
325

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

356
  // Map ID to position in vector
357
  model::mesh_map[model::meshes.back()->id_] = model::meshes.size() - 1;
3,465 ✔
358

359
  return model::meshes.back();
3,465 ✔
360
}
361

362
Mesh::Mesh(pugi::xml_node node)
3,516 ✔
363
{
364
  // Read mesh id
365
  id_ = std::stoi(get_node_value(node, "id"));
7,032 ✔
366
  if (check_for_node(node, "name"))
3,516 ✔
367
    name_ = get_node_value(node, "name");
15 ✔
368
}
3,516 ✔
369

370
Mesh::Mesh(hid_t group)
70 ✔
371
{
372
  // Read mesh ID
373
  read_attribute(group, "id", id_);
70 ✔
374

375
  // Read mesh name
376
  if (object_exists(group, "name")) {
70 !
377
    read_dataset(group, "name", name_);
×
378
  }
379
}
70 ✔
380

381
void Mesh::set_id(int32_t id)
444 ✔
382
{
383
  assert(id >= 0 || id == C_NONE);
444 !
384

385
  // Clear entry in mesh map in case one was already assigned
386
  if (id_ != C_NONE) {
444 ✔
387
    model::mesh_map.erase(id_);
22 ✔
388
    id_ = C_NONE;
22 ✔
389
  }
390

391
  // Ensure no other mesh has the same ID
392
  if (model::mesh_map.find(id) != model::mesh_map.end()) {
444 !
393
    throw std::runtime_error {
×
394
      fmt::format("Two meshes have the same ID: {}", id)};
×
395
  }
396

397
  // If no ID is specified, auto-assign the next ID in the sequence
398
  if (id == C_NONE) {
444 ✔
399
    id = 0;
1 ✔
400
    for (const auto& m : model::meshes) {
3 ✔
401
      id = std::max(id, m->id_);
3 ✔
402
    }
403
    ++id;
1 ✔
404
  }
405

406
  // Update ID and entry in the mesh map
407
  id_ = id;
444 ✔
408

409
  // find the index of this mesh in the model::meshes vector
410
  // (search in reverse because this mesh was likely just added to the vector)
411
  auto it = std::find_if(model::meshes.rbegin(), model::meshes.rend(),
888 ✔
412
    [this](const std::unique_ptr<Mesh>& mesh) { return mesh.get() == this; });
899 !
413

414
  model::mesh_map[id] = std::distance(model::meshes.begin(), it.base()) - 1;
444 ✔
415
}
444 ✔
416

417
vector<double> Mesh::volumes() const
331 ✔
418
{
419
  vector<double> volumes(n_bins());
331 ✔
420
  for (int i = 0; i < n_bins(); i++) {
1,243,675 ✔
421
    volumes[i] = this->volume(i);
1,243,344 ✔
422
  }
423
  return volumes;
331 ✔
424
}
×
425

426
//! Default (Cartesian) axis labels used for surface bin labels.
427
std::array<const char*, 3> Mesh::axis_labels() const
428,252 ✔
428
{
429
  return {"x", "y", "z"};
428,252 ✔
430
}
431

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

445
void Mesh::material_volumes(int nx, int ny, int nz, int table_size,
×
446
  int32_t* materials, double* volumes) const
447
{
448
  this->material_volumes(nx, ny, nz, table_size, materials, volumes, nullptr);
×
449
}
×
450

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

467
  Timer timer;
232 ✔
468
  timer.start();
232 ✔
469

470
  // Create object for keeping track of materials/volumes
471
  detail::MaterialVolumes result(materials, volumes, bboxes, table_size);
232 ✔
472
  bool compute_bboxes = bboxes != nullptr;
232 ✔
473

474
  // Determine bounding box
475
  auto bbox = this->bounding_box();
232 ✔
476

477
  std::array<int, 3> n_rays = {nx, ny, nz};
232 ✔
478

479
  // Determine effective width of rays
480
  Position width = bbox.max - bbox.min;
232 ✔
481
  width.x = (nx > 0) ? width.x / nx : 0.0;
232 ✔
482
  width.y = (ny > 0) ? width.y / ny : 0.0;
232 ✔
483
  width.z = (nz > 0) ? width.z / nz : 0.0;
232 ✔
484

485
#pragma omp parallel
127 ✔
486
  {
105 ✔
487
    // Preallocate vector for mesh indices and length fractions and particle
488
    vector<int> bins;
105 ✔
489
    vector<double> length_fractions;
105 ✔
490
    Particle p;
105 ✔
491

492
    SourceSite site;
105 ✔
493
    site.E = 1.0;
105 ✔
494
    site.particle = ParticleType::neutron();
105 ✔
495

496
    bool verbose = settings::verbosity >= 10;
105 ✔
497

498
    // Save the cells occupied immediately before a boundary crossing.
499
    auto save_cell_state = [&p]() {
8,738,569 ✔
500
      for (int j = 0; j < p.n_coord(); ++j) {
17,477,138 ✔
501
        p.cell_last(j) = p.coord(j).cell();
8,738,569 ✔
502
      }
503
      p.n_coord_last() = p.n_coord();
8,738,569 ✔
504
    };
8,738,674 ✔
505

506
    // Initialize cell history after locating a ray inside the model.
507
    auto initialize_cell_state = [&p, &save_cell_state]() {
6,700,951 ✔
508
      if (p.cell_born() == C_NONE)
6,700,951 !
509
        p.cell_born() = p.lowest_coord().cell();
6,700,951 ✔
510

511
      save_cell_state();
6,700,951 ✔
512
    };
6,701,056 ✔
513

514
    // Reset a failed coordinate search while preserving position and direction.
515
    auto reset_geometry_state = [&p]() {
178,472 ✔
516
      Position r = p.r();
178,472 ✔
517
      Direction u = p.u();
178,472 ✔
518
      p.init_from_r_u(r, u);
178,472 ✔
519
      p.coord(0).universe() = model::root_universe;
178,472 ✔
520
    };
178,577 ✔
521

522
    for (int axis = 0; axis < 3; ++axis) {
420 ✔
523
      // Set starting position and direction
524
      site.r = {0.0, 0.0, 0.0};
315 ✔
525
      site.r[axis] = bbox.min[axis];
315 ✔
526
      site.u = {0.0, 0.0, 0.0};
315 ✔
527
      site.u[axis] = 1.0;
315 ✔
528

529
      // Determine width of rays and number of rays in other directions
530
      int ax1 = (axis + 1) % 3;
315 ✔
531
      int ax2 = (axis + 2) % 3;
315 ✔
532
      double min1 = bbox.min[ax1];
315 ✔
533
      double min2 = bbox.min[ax2];
315 ✔
534
      double d1 = width[ax1];
315 ✔
535
      double d2 = width[ax2];
315 ✔
536
      int n1 = n_rays[ax1];
315 ✔
537
      int n2 = n_rays[ax2];
315 ✔
538
      if (n1 == 0 || n2 == 0) {
315 ✔
539
        continue;
60 ✔
540
      }
541

542
      // Divide rays in first direction over MPI processes by computing starting
543
      // and ending indices
544
      int min_work = n1 / mpi::n_procs;
255 ✔
545
      int remainder = n1 % mpi::n_procs;
255 ✔
546
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
255 !
547
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
255 !
548
      int i1_end = i1_start + n1_local;
255 ✔
549

550
      // Add the contribution from a ray segment. The positions used here are
551
      // kept separate from the particle position because the latter is moved a
552
      // tiny distance across each surface for robust geometry searches.
553
      auto add_segment = [&](const Position& r0, const Position& r1,
8,879,703 ✔
554
                           int i_material) {
555
        double distance = r1[axis] - r0[axis];
8,879,703 ✔
556
        if (distance <= 0.0)
8,879,703 !
557
          return;
558

559
        bins.clear();
8,879,703 ✔
560
        length_fractions.clear();
8,879,703 ✔
561
        this->bins_crossed(r0, r1, site.u, bins, length_fractions);
34,866,423 ✔
562

563
        double cumulative_frac = 0.0;
8,879,703 ✔
564
        for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
18,319,732 ✔
565
          int mesh_index = bins[i_bin];
9,440,029 ✔
566
          double length = distance * length_fractions[i_bin];
9,440,029 ✔
567
          double volume = length * d1 * d2;
35,426,749 ✔
568

569
          if (compute_bboxes) {
9,440,029 ✔
570
            double axis_start = r0[axis] + distance * cumulative_frac;
6,496,680 ✔
571
            double axis_end = axis_start + length;
6,496,680 ✔
572
            cumulative_frac += length_fractions[i_bin];
6,496,680 ✔
573

574
            Position contrib_min = site.r;
6,496,680 ✔
575
            Position contrib_max = site.r;
6,496,680 ✔
576

577
            contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
6,496,680 ✔
578
            contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
6,496,680 ✔
579
            contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
6,496,680 ✔
580
            contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
6,496,680 ✔
581
            contrib_min[axis] = std::min(axis_start, axis_end);
6,496,680 !
582
            contrib_max[axis] = std::max(axis_start, axis_end);
12,993,360 !
583

584
            BoundingBox contrib_bbox {contrib_min, contrib_max};
6,496,680 ✔
585
            contrib_bbox &= bbox;
6,496,680 ✔
586

587
            result.add_volume(mesh_index, i_material, volume, &contrib_bbox);
6,496,680 ✔
588
          } else {
589
            result.add_volume(mesh_index, i_material, volume);
2,943,349 ✔
590
          }
591
        }
592
      };
255 ✔
593

594
      // Loop over rays on face of bounding box
595
#pragma omp for collapse(2)
596
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
18,230 ✔
597
        for (int i2 = 0; i2 < n2; ++i2) {
3,092,820 ✔
598
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
3,074,845 ✔
599
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
3,074,845 ✔
600

601
          p.from_source(&site);
3,074,845 ✔
602

603
          // Set the physical endpoint of this ray at the far mesh face.
604
          Position r_mesh_end = site.r;
3,074,845 ✔
605
          r_mesh_end[axis] = bbox.max[axis];
3,074,845 ✔
606

607
          // Determine particle's location
608
          bool inside_model = exhaustive_find_cell(p, verbose);
3,074,845 ✔
609

610
          if (inside_model) {
3,074,845 ✔
611
            initialize_cell_state();
3,028,915 ✔
612
          } else {
613
            // Clear any partial descent into nested universes before searching
614
            // for the first root-universe boundary from undefined space.
615
            reset_geometry_state();
45,930 ✔
616
          }
617

618
          // Physical position through which volume has been accumulated. This
619
          // differs by TINY_BIT from p.r() after crossing a surface.
620
          Position r_scored = site.r;
3,074,845 ✔
621

622
          while (r_scored[axis] < r_mesh_end[axis]) {
4,024,889 !
623
            if (!inside_model) {
4,024,889 ✔
624
              // The ray is outside the model. Advance to the next surface of
625
              // any cell in the root universe, as is done for ray-traced
626
              // plots. Undefined space traversed along the way is void.
627
              Position r0 = p.r();
81,080 ✔
628
              p.advance_to_boundary_from_void();
81,080 ✔
629

630
              // If no model surface lies before the mesh edge, score the
631
              // remaining exterior interval as void and finish the ray.
632
              double distance_to_mesh_end = r_mesh_end[axis] - r0[axis];
81,080 ✔
633
              if (p.boundary().surface() == SURFACE_NONE ||
81,080 ✔
634
                  p.boundary().distance() >= distance_to_mesh_end) {
35,150 !
635
                add_segment(r_scored, r_mesh_end, MATERIAL_VOID);
45,930 ✔
636
                break;
45,930 ✔
637
              }
638

639
              // Determine the physical position of the model boundary.
640
              Position r_boundary = r0 + p.boundary().distance() * p.u();
35,150 ✔
641

642
              // Score the exterior interval and record its physical endpoint.
643
              add_segment(r_scored, r_boundary, MATERIAL_VOID);
35,150 ✔
644
              r_scored = r_boundary;
35,150 ✔
645

646
              // Check whether advancing through the surface entered the model.
647
              inside_model = exhaustive_find_cell(p, verbose);
35,150 ✔
648
              if (inside_model) {
35,150 ✔
649
                initialize_cell_state();
16,950 ✔
650
              } else {
651
                // Clear any partial coordinate search before looking for the
652
                // next surface from undefined space.
653
                reset_geometry_state();
18,200 ✔
654
              }
655
              continue;
35,150 ✔
656
            }
35,150 ✔
657

658
            // Find the distance to the nearest boundary
659
            BoundaryInfo boundary = distance_to_boundary(p);
3,943,809 ✔
660

661
            // Convert the material index to a user-facing ID
662
            int i_material = p.material();
3,943,809 ✔
663
            if (i_material != C_NONE) {
3,943,809 ✔
664
              i_material = model::materials[i_material]->id();
1,282,527 ✔
665
            }
666

667
            // If no model boundary lies before the mesh edge, score the
668
            // remaining material interval and finish the ray.
669
            double distance_to_mesh_end = r_mesh_end[axis] - p.r()[axis];
3,943,809 ✔
670
            if (boundary.distance() >= distance_to_mesh_end) {
3,943,809 ✔
671
              add_segment(r_scored, r_mesh_end, i_material);
3,028,915 ✔
672
              break;
673
            }
674

675
            // Determine the physical position of the model boundary.
676
            Position r_boundary = p.r() + boundary.distance() * p.u();
914,894 ✔
677

678
            // Score the material interval and record its physical endpoint.
679
            add_segment(r_scored, r_boundary, i_material);
914,894 ✔
680
            r_scored = r_boundary;
914,894 ✔
681

682
            // Cross the next geometric surface. The small forward movement
683
            // and neighbor-list search mirror Ray::trace, allowing a failed
684
            // search to mean that the ray has left the model rather than that
685
            // a transport particle has been lost.
686
            save_cell_state();
914,894 ✔
687

688
            // Move just beyond the surface to make the next search robust.
689
            p.move_distance(boundary.distance() + TINY_BIT);
914,894 ✔
690

691
            // Set surface that particle is on and adjust coordinate levels
692
            p.surface() = boundary.surface();
914,894 ✔
693
            p.n_coord() = boundary.coord_level();
914,894 ✔
694

695
            // Update the geometry state according to the boundary type.
696
            if (boundary.lattice_translation()[0] != 0 ||
914,894 !
697
                boundary.lattice_translation()[1] != 0 ||
914,894 !
698
                boundary.lattice_translation()[2] != 0) {
914,894 !
699
              // Particle crosses lattice boundary
700
              cross_lattice(p, boundary, verbose);
×
701
              inside_model = true;
702
            } else {
703
              // Search for the cell on the opposite side of a surface.
704
              inside_model = neighbor_list_find_cell(p, verbose);
914,894 ✔
705
            }
706

707
            // Treat a failed cell search as a transition to exterior void.
708
            if (!inside_model) {
914,894 ✔
709
              // Reset the geometry state so the next iteration can search for
710
              // another disjoint portion of the model.
711
              reset_geometry_state();
16,950 ✔
712
            }
713
          }
714
        }
715
      }
716
    }
717
  }
105 ✔
718

719
  // Check for errors
720
  if (result.table_full()) {
232 !
UNCOV
721
    throw std::runtime_error("Maximum number of materials for mesh material "
×
UNCOV
722
                             "volume calculation insufficient.");
×
723
  }
724

725
  // Compute time for raytracing
726
  double t_raytrace = timer.elapsed();
232 ✔
727

728
#ifdef OPENMC_MPI
729
  // Combine results from multiple MPI processes
730
  if (mpi::n_procs > 1) {
85 !
731
    int total = this->n_bins() * table_size;
732
    int total_bbox = total * 6;
733
    if (mpi::master) {
×
734
      // Allocate temporary buffer for receiving data
735
      vector<int32_t> mats(total);
736
      vector<double> vols(total);
×
737
      vector<double> recv_bboxes;
×
738
      if (compute_bboxes) {
×
739
        recv_bboxes.resize(total_bbox);
×
740
      }
741

742
      for (int i = 1; i < mpi::n_procs; ++i) {
×
743
        // Receive material indices and volumes from process i
744
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
745
          MPI_STATUS_IGNORE);
746
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
747
          MPI_STATUS_IGNORE);
748
        if (compute_bboxes) {
×
749
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
750
            mpi::intracomm, MPI_STATUS_IGNORE);
751
        }
752

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

786
  // Report time for MPI communication
787
  double t_mpi = timer.elapsed() - t_raytrace;
85 ✔
788
#else
789
  double t_mpi = 0.0;
126 ✔
790
#endif
791

792
  // Normalize based on known volumes of elements
793
  for (int i = 0; i < this->n_bins(); ++i) {
2,591 ✔
794
    // Estimated total volume in element i
795
    double volume = 0.0;
796
    for (int j = 0; j < table_size; ++j) {
15,731 ✔
797
      volume += result.volumes(i, j);
13,372 ✔
798
    }
799
    // Renormalize volumes based on known volume of element i
800
    double norm = this->volume(i) / volume;
2,359 ✔
801
    for (int j = 0; j < table_size; ++j) {
15,731 ✔
802
      result.volumes(i, j) *= norm;
13,372 ✔
803
    }
804
  }
805

806
  // Get total time and normalization time
807
  timer.stop();
232 ✔
808
  double t_total = timer.elapsed();
232 ✔
809
  double t_norm = t_total - t_raytrace - t_mpi;
232 ✔
810

811
  // Show timing statistics
812
  if (settings::verbosity < 7 || !mpi::master)
232 !
813
    return;
55 ✔
814
  header("Timing Statistics", 7);
177 ✔
815
  fmt::print(" Total time elapsed            = {:.4e} seconds\n", t_total);
177 ✔
816
  fmt::print("   Ray tracing                 = {:.4e} seconds\n", t_raytrace);
177 ✔
817
  fmt::print("   MPI communication           = {:.4e} seconds\n", t_mpi);
177 ✔
818
  fmt::print("   Normalization               = {:.4e} seconds\n", t_norm);
177 ✔
819
  fmt::print(" Calculation rate              = {:.4e} rays/seconds\n",
354 ✔
820
    n_total / t_raytrace);
177 ✔
821
  fmt::print(" Calculation rate (per thread) = {:.4e} rays/seconds\n",
257 ✔
822
    n_total / (t_raytrace * mpi::n_procs * num_threads()));
177 ✔
823
  std::fflush(stdout);
177 ✔
824
}
825

826
void Mesh::to_hdf5(hid_t group) const
3,415 ✔
827
{
828
  // Create group for mesh
829
  std::string group_name = fmt::format("mesh {}", id_);
3,415 ✔
830
  hid_t mesh_group = create_group(group, group_name.c_str());
3,415 ✔
831

832
  // Write mesh type
833
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,415 ✔
834

835
  // Write mesh ID
836
  write_attribute(mesh_group, "id", id_);
3,415 ✔
837

838
  // Write mesh name
839
  write_dataset(mesh_group, "name", name_);
3,415 ✔
840

841
  // Write mesh data
842
  this->to_hdf5_inner(mesh_group);
3,415 ✔
843

844
  // Close group
845
  close_group(mesh_group);
3,415 ✔
846
}
3,415 ✔
847

848
//==============================================================================
849
// Structured Mesh implementation
850
//==============================================================================
851

852
std::string StructuredMesh::bin_label(int bin) const
5,315,732 ✔
853
{
854
  MeshIndex ijk = get_indices_from_bin(bin);
5,315,732 ✔
855

856
  if (n_dimension_ > 2) {
5,315,732 ✔
857
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,299,133 ✔
858
  } else if (n_dimension_ > 1) {
16,599 ✔
859
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
16,236 ✔
860
  } else {
861
    return fmt::format("Mesh Index ({})", ijk[0]);
363 ✔
862
  }
863
}
864

865
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
3,125 ✔
866
{
867
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
3,125 ✔
868
}
869

870
Position StructuredMesh::sample_element(
1,438,198 ✔
871
  const MeshIndex& ijk, uint64_t* seed) const
872
{
873
  // lookup the lower/upper bounds for the mesh element
874
  double x_min = negative_grid_boundary(ijk, 0);
1,438,198 ✔
875
  double x_max = positive_grid_boundary(ijk, 0);
1,438,198 ✔
876

877
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,438,198 !
878
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,438,198 !
879

880
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,438,198 !
881
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,438,198 !
882

883
  return {x_min + (x_max - x_min) * prn(seed),
1,438,198 ✔
884
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,438,198 ✔
885
}
886

887
//==============================================================================
888
// Unstructured Mesh implementation
889
//==============================================================================
890

891
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
49 !
892
{
893
  n_dimension_ = 3;
49 ✔
894

895
  // check the mesh type
896
  if (check_for_node(node, "type")) {
49 !
897
    auto temp = get_node_value(node, "type", true, true);
49 !
898
    if (temp != mesh_type) {
49 !
UNCOV
899
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
900
    }
901
  }
49 ✔
902

903
  // check if a length unit multiplier was specified
904
  if (check_for_node(node, "length_multiplier")) {
49 !
UNCOV
905
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
906
  }
907

908
  // get the filename of the unstructured mesh to load
909
  if (check_for_node(node, "filename")) {
49 !
910
    filename_ = get_node_value(node, "filename");
49 !
911
    if (!file_exists(filename_)) {
49 !
UNCOV
912
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
913
    }
914
  } else {
UNCOV
915
    fatal_error(fmt::format(
×
UNCOV
916
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
917
  }
918

919
  if (check_for_node(node, "options")) {
49 !
920
    options_ = get_node_value(node, "options");
16 !
921
  }
922

923
  // check if mesh tally data should be written with
924
  // statepoint files
925
  if (check_for_node(node, "output")) {
49 !
UNCOV
926
    output_ = get_node_value_bool(node, "output");
×
927
  }
928
}
49 ✔
929

UNCOV
930
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
931
{
UNCOV
932
  n_dimension_ = 3;
×
933

934
  // check the mesh type
UNCOV
935
  if (object_exists(group, "type")) {
×
UNCOV
936
    std::string temp;
×
UNCOV
937
    read_dataset(group, "type", temp);
×
UNCOV
938
    if (temp != mesh_type) {
×
UNCOV
939
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
940
    }
UNCOV
941
  }
×
942

943
  // check if a length unit multiplier was specified
UNCOV
944
  if (object_exists(group, "length_multiplier")) {
×
UNCOV
945
    read_dataset(group, "length_multiplier", length_multiplier_);
×
946
  }
947

948
  // get the filename of the unstructured mesh to load
UNCOV
949
  if (object_exists(group, "filename")) {
×
950
    read_dataset(group, "filename", filename_);
×
UNCOV
951
    if (!file_exists(filename_)) {
×
UNCOV
952
      fatal_error("Mesh file '" + filename_ + "' does not exist!");
×
953
    }
954
  } else {
UNCOV
955
    fatal_error(fmt::format(
×
UNCOV
956
      "No filename supplied for unstructured mesh with ID: {}", id_));
×
957
  }
958

UNCOV
959
  if (attribute_exists(group, "options")) {
×
UNCOV
960
    read_attribute(group, "options", options_);
×
961
  }
962

963
  // check if mesh tally data should be written with
964
  // statepoint files
UNCOV
965
  if (attribute_exists(group, "output")) {
×
UNCOV
966
    read_attribute(group, "output", output_);
×
967
  }
UNCOV
968
}
×
969

970
void UnstructuredMesh::determine_bounds()
26 ✔
971
{
972
  double xmin = INFTY;
26 ✔
973
  double ymin = INFTY;
26 ✔
974
  double zmin = INFTY;
26 ✔
975
  double xmax = -INFTY;
26 ✔
976
  double ymax = -INFTY;
26 ✔
977
  double zmax = -INFTY;
26 ✔
978
  int n = this->n_vertices();
26 ✔
979
  for (int i = 0; i < n; ++i) {
58,283 ✔
980
    auto v = this->vertex(i);
58,257 ✔
981
    xmin = std::min(v.x, xmin);
58,257 ✔
982
    ymin = std::min(v.y, ymin);
58,257 ✔
983
    zmin = std::min(v.z, zmin);
58,257 ✔
984
    xmax = std::max(v.x, xmax);
58,257 ✔
985
    ymax = std::max(v.y, ymax);
58,257 ✔
986
    zmax = std::max(v.z, zmax);
83,242 ✔
987
  }
988
  lower_left_ = {xmin, ymin, zmin};
26 ✔
989
  upper_right_ = {xmax, ymax, zmax};
26 ✔
990
}
26 ✔
991

992
Position UnstructuredMesh::sample_tet(
601,230 ✔
993
  std::array<Position, 4> coords, uint64_t* seed) const
994
{
995
  // Uniform distribution
996
  double s = prn(seed);
601,230 ✔
997
  double t = prn(seed);
601,230 ✔
998
  double u = prn(seed);
601,230 ✔
999

1000
  // From PyNE implementation of moab tet sampling C. Rocchini & P. Cignoni
1001
  // (2000) Generating Random Points in a Tetrahedron, Journal of Graphics
1002
  // Tools, 5:4, 9-12, DOI: 10.1080/10867651.2000.10487528
1003
  if (s + t > 1) {
601,230 ✔
1004
    s = 1.0 - s;
300,882 ✔
1005
    t = 1.0 - t;
300,882 ✔
1006
  }
1007
  if (s + t + u > 1) {
601,230 ✔
1008
    if (t + u > 1) {
400,122 ✔
1009
      double old_t = t;
200,373 ✔
1010
      t = 1.0 - u;
200,373 ✔
1011
      u = 1.0 - s - old_t;
200,373 ✔
1012
    } else if (t + u <= 1) {
199,749 !
1013
      double old_s = s;
199,749 ✔
1014
      s = 1.0 - t - u;
199,749 ✔
1015
      u = old_s + t + u - 1;
199,749 ✔
1016
    }
1017
  }
1018
  return s * (coords[1] - coords[0]) + t * (coords[2] - coords[0]) +
1,803,690 ✔
1019
         u * (coords[3] - coords[0]) + coords[0];
601,230 ✔
1020
}
1021

1022
const std::string UnstructuredMesh::mesh_type = "unstructured";
1023

1024
std::string UnstructuredMesh::get_mesh_type() const
40 ✔
1025
{
1026
  return mesh_type;
40 ✔
1027
}
1028

UNCOV
1029
void UnstructuredMesh::surface_bins_crossed(
×
1030
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1031
{
1032
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
1033
}
1034

1035
std::string UnstructuredMesh::bin_label(int bin) const
207,736 ✔
1036
{
1037
  return fmt::format("Mesh Index ({})", bin);
207,736 ✔
1038
};
1039

1040
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
37 ✔
1041
{
1042
  write_dataset(mesh_group, "filename", filename_);
37 !
1043
  write_dataset(mesh_group, "library", this->library());
37 !
1044
  if (!options_.empty()) {
37 ✔
1045
    write_attribute(mesh_group, "options", options_);
8 ✔
1046
  }
1047

1048
  if (length_multiplier_ > 0.0)
37 ✔
1049
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
3 ✔
1050

1051
  // write vertex coordinates
1052
  tensor::Tensor<double> vertices(
37 ✔
1053
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
37 ✔
1054
  for (int i = 0; i < this->n_vertices(); i++) {
79,935 !
1055
    auto v = this->vertex(i);
79,898 !
1056
    vertices.slice(i) = {v.x, v.y, v.z};
159,796 !
1057
  }
1058
  write_dataset(mesh_group, "vertices", vertices);
37 !
1059

1060
  int num_elem_skipped = 0;
37 ✔
1061

1062
  // write element types and connectivity
1063
  vector<double> volumes;
37 !
1064
  tensor::Tensor<int> connectivity(
37 ✔
1065
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
37 !
1066
  tensor::Tensor<int> elem_types(
37 ✔
1067
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
37 !
1068
  for (int i = 0; i < this->n_bins(); i++) {
387,773 !
1069
    auto conn = this->connectivity(i);
387,736 !
1070

1071
    volumes.emplace_back(this->volume(i));
387,736 !
1072

1073
    // write linear tet element
1074
    if (conn.size() == 4) {
387,736 ✔
1075
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_TET);
383,736 !
1076
      connectivity.slice(i) = {
383,736 !
1077
        conn[0], conn[1], conn[2], conn[3], -1, -1, -1, -1};
767,472 !
1078
      // write linear hex element
1079
    } else if (conn.size() == 8) {
4,000 !
1080
      elem_types.slice(i) = static_cast<int>(ElementType::LINEAR_HEX);
4,000 !
1081
      connectivity.slice(i) = {
4,000 !
1082
        conn[0], conn[1], conn[2], conn[3], conn[4], conn[5], conn[6], conn[7]};
8,000 !
1083
    } else {
UNCOV
1084
      num_elem_skipped++;
×
UNCOV
1085
      elem_types.slice(i) = static_cast<int>(ElementType::UNSUPPORTED);
×
UNCOV
1086
      connectivity.slice(i) = -1;
×
1087
    }
1088
  }
387,736 ✔
1089

1090
  // warn users that some elements were skipped
1091
  if (num_elem_skipped > 0) {
37 !
UNCOV
1092
    warning(fmt::format("The connectivity of {} elements "
×
1093
                        "on mesh {} were not written "
1094
                        "because they are not of type linear tet/hex.",
UNCOV
1095
      num_elem_skipped, this->id_));
×
1096
  }
1097

1098
  write_dataset(mesh_group, "volumes", volumes);
37 !
1099
  write_dataset(mesh_group, "connectivity", connectivity);
37 !
1100
  write_dataset(mesh_group, "element_types", elem_types);
37 !
1101
}
111 ✔
1102

1103
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
28 ✔
1104
{
1105
  length_multiplier_ = length_multiplier;
28 ✔
1106
}
28 ✔
1107

1108
ElementType UnstructuredMesh::element_type(int bin) const
120,000 ✔
1109
{
1110
  auto conn = connectivity(bin);
120,000 ✔
1111

1112
  if (conn.size() == 4)
120,000 !
1113
    return ElementType::LINEAR_TET;
UNCOV
1114
  else if (conn.size() == 8)
×
1115
    return ElementType::LINEAR_HEX;
1116
  else
UNCOV
1117
    return ElementType::UNSUPPORTED;
×
1118
}
120,000 ✔
1119

1120
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,799,949,334 ✔
1121
  Position r, bool& in_mesh) const
1122
{
1123
  MeshIndex ijk;
1,799,949,334 ✔
1124
  in_mesh = true;
1,799,949,334 ✔
1125
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647 ✔
1126
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647 ✔
1127

1128
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647 ✔
1129
      in_mesh = false;
102,039,409 ✔
1130
  }
1131
  return ijk;
1,799,949,334 ✔
1132
}
1133

1134
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647 ✔
1135
{
1136
  switch (n_dimension_) {
2,147,483,647 !
1137
  case 1:
824,582 ✔
1138
    return ijk[0] - 1;
824,582 ✔
1139
  case 2:
141,543,281 ✔
1140
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
141,543,281 ✔
1141
  case 3:
2,147,483,647 ✔
1142
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,147,483,647 ✔
UNCOV
1143
  default:
×
UNCOV
1144
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1145
  }
1146
}
1147

1148
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
8,090,053 ✔
1149
{
1150
  MeshIndex ijk;
8,090,053 ✔
1151
  if (n_dimension_ == 1) {
8,090,053 ✔
1152
    ijk[0] = bin + 1;
363 ✔
1153
  } else if (n_dimension_ == 2) {
8,089,690 ✔
1154
    ijk[0] = bin % shape_[0] + 1;
16,236 ✔
1155
    ijk[1] = bin / shape_[0] + 1;
16,236 ✔
1156
  } else if (n_dimension_ == 3) {
8,073,454 !
1157
    ijk[0] = bin % shape_[0] + 1;
8,073,454 ✔
1158
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
8,073,454 ✔
1159
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
8,073,454 ✔
1160
  }
1161
  return ijk;
8,090,053 ✔
1162
}
1163

1164
int StructuredMesh::get_bin(Position r) const
604,156,747 ✔
1165
{
1166
  // Determine indices
1167
  bool in_mesh;
604,156,747 ✔
1168
  MeshIndex ijk = get_indices(r, in_mesh);
604,156,747 ✔
1169
  if (!in_mesh)
604,156,747 ✔
1170
    return -1;
1171

1172
  // Convert indices to bin
1173
  return get_bin_from_indices(ijk);
583,098,975 ✔
1174
}
1175

1176
int StructuredMesh::n_bins() const
1,261,179 ✔
1177
{
1178
  // Bin indices are stored as 32-bit ints in the tally system.
1179
  int64_t n = 1;
1,261,179 ✔
1180
  for (int i = 0; i < n_dimension_; ++i)
5,044,212 ✔
1181
    n *= shape_[i];
3,783,033 ✔
1182
  if (n > std::numeric_limits<int>::max()) {
1,261,179 !
UNCOV
1183
    fatal_error(fmt::format(
×
UNCOV
1184
      "Mesh {} has too many bins ({}) for 32-bit tally indexing", id_, n));
×
1185
  }
1186
  return static_cast<int>(n);
1,261,179 ✔
1187
}
1188

1189
int StructuredMesh::n_surface_bins() const
436 ✔
1190
{
1191
  // Surface bin indices are stored as 32-bit ints in the tally system.
1192
  int64_t n = static_cast<int64_t>(n_bins()) * 4 * n_dimension_;
436 ✔
1193
  if (n > std::numeric_limits<int>::max()) {
436 !
UNCOV
1194
    fatal_error(fmt::format(
×
UNCOV
1195
      "Mesh {} has too many surface bins ({}) for tally indexing", id_, n));
×
1196
  }
1197
  return static_cast<int>(n);
436 ✔
1198
}
1199

UNCOV
1200
tensor::Tensor<double> StructuredMesh::count_sites(
×
1201
  const SourceSite* bank, int64_t length, bool* outside) const
1202
{
1203
  // Determine shape of array for counts
UNCOV
1204
  std::size_t m = this->n_bins();
×
UNCOV
1205
  vector<std::size_t> shape = {m};
×
1206

1207
  // Create array of zeros
UNCOV
1208
  auto cnt = tensor::zeros<double>(shape);
×
1209
  bool outside_ = false;
1210

UNCOV
1211
  for (int64_t i = 0; i < length; i++) {
×
UNCOV
1212
    const auto& site = bank[i];
×
1213

1214
    // determine scoring bin for entropy mesh
UNCOV
1215
    int mesh_bin = get_bin(site.r);
×
1216

1217
    // if outside mesh, skip particle
UNCOV
1218
    if (mesh_bin < 0) {
×
UNCOV
1219
      outside_ = true;
×
UNCOV
1220
      continue;
×
1221
    }
1222

1223
    // Add to appropriate bin
UNCOV
1224
    cnt(mesh_bin) += site.wgt;
×
1225
  }
1226

1227
  // Create reduced count data
UNCOV
1228
  auto counts = tensor::zeros<double>(shape);
×
UNCOV
1229
  int total = cnt.size();
×
1230

1231
#ifdef OPENMC_MPI
1232
  // collect values from all processors
1233
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
×
1234

1235
  // Check if there were sites outside the mesh for any processor
1236
  if (outside) {
×
1237
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1238
  }
1239
#else
1240
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1241
  if (outside)
×
1242
    *outside = outside_;
1243
#endif
1244

UNCOV
1245
  return counts;
×
UNCOV
1246
}
×
1247

1248
// raytrace through the mesh. The template class T will do the tallying.
1249
// A modern optimizing compiler can recognize the noop method of T and
1250
// eliminate that call entirely.
1251
template<class T>
1252
void StructuredMesh::raytrace_mesh(
1,188,972,476 ✔
1253
  Position r0, Position r1, const Direction& u, T tally) const
1254
{
1255
  // TODO: when c++-17 is available, use "if constexpr ()" to compile-time
1256
  // enable/disable tally calls for now, T template type needs to provide both
1257
  // surface and track methods, which might be empty. modern optimizing
1258
  // compilers will (hopefully) eliminate the complete code (including
1259
  // calculation of parameters) but for the future: be explicit
1260

1261
  // Compute the length of the entire track.
1262
  double total_distance = (r1 - r0).norm();
1,188,972,476 ✔
1263
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,188,972,476 ✔
1264
    return;
1265

1266
  // keep a copy of the original global position to pass to get_indices,
1267
  // which performs its own transformation to local coordinates
1268
  Position global_r = r0;
1,188,964,083 ✔
1269
  Position local_r = local_coords(r0);
1,188,964,083 ✔
1270

1271
  const int n = n_dimension_;
1,188,964,083 ✔
1272

1273
  // Flag if position is inside the mesh
1274
  bool in_mesh;
1275

1276
  // Position is r = r0 + u * traveled_distance, start at r0
1277
  double traveled_distance {0.0};
1,188,964,083 ✔
1278

1279
  // Calculate index of current cell. Offset the position a tiny bit in
1280
  // direction of flight
1281
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,188,964,083 ✔
1282

1283
  // if track is very short, assume that it is completely inside one cell.
1284
  // Only the current cell will score and no surfaces
1285
  if (total_distance < 2 * TINY_BIT) {
1,188,964,083 ✔
1286
    if (in_mesh) {
675,816 ✔
1287
      tally.track(ijk, 1.0);
675,332 ✔
1288
    }
1289
    return;
675,816 ✔
1290
  }
1291

1292
  // Calculate initial distances to next surfaces in all three dimensions
1293
  std::array<MeshDistance, 3> distances;
2,147,483,647 ✔
1294
  for (int k = 0; k < n; ++k) {
2,147,483,647 ✔
1295
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647 ✔
1296
  }
1297

1298
  // Loop until r = r1 is eventually reached
1299
  while (true) {
1300

1301
    if (in_mesh) {
2,051,110,914 ✔
1302

1303
      // find surface with minimal distance to current position
1304
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,965,363,914 ✔
1305
                     distances.begin();
1,965,363,914 ✔
1306

1307
      // Tally track length delta since last step
1308
      tally.track(ijk,
1,965,363,914 ✔
1309
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647 ✔
1310
          total_distance);
1311

1312
      // update position and leave, if we have reached end position
1313
      traveled_distance = distances[k].distance;
1,965,363,914 ✔
1314
      if (traveled_distance >= total_distance)
1,965,363,914 ✔
1315
        return;
1316

1317
      // If we have not reached r1, we have hit a surface. Tally outward
1318
      // current
1319
      tally.surface(ijk, k, distances[k].max_surface, false);
855,994,143 ✔
1320

1321
      // Update cell and calculate distance to next surface in k-direction.
1322
      // The two other directions are still valid!
1323
      ijk[k] = distances[k].next_index;
855,994,143 ✔
1324
      distances[k] =
855,994,143 ✔
1325
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
855,994,143 ✔
1326

1327
      // Check if we have left the interior of the mesh
1328
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
862,836,689 ✔
1329

1330
      // If we are still inside the mesh, tally inward current for the next
1331
      // cell
1332
      if (in_mesh)
29,487,799 ✔
1333
        tally.surface(ijk, k, !distances[k].max_surface, true);
861,415,021 ✔
1334

1335
    } else { // not inside mesh
1336

1337
      // For all directions outside the mesh, find the distance that we need
1338
      // to travel to reach the next surface. Use the largest distance, as
1339
      // only this will cross all outer surfaces.
1340
      int k_max {-1};
1341
      for (int k = 0; k < n; ++k) {
341,583,124 ✔
1342
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
255,836,124 ✔
1343
            (distances[k].distance > traveled_distance)) {
93,677,182 ✔
1344
          traveled_distance = distances[k].distance;
1345
          k_max = k;
1346
        }
1347
      }
1348
      // Assure some distance is traveled
1349
      if (k_max == -1) {
85,747,000 !
UNCOV
1350
        traveled_distance += TINY_BIT;
×
1351
      }
1352

1353
      // If r1 is not inside the mesh, exit here
1354
      if (traveled_distance >= total_distance)
85,747,000 ✔
1355
        return;
1356

1357
      // Calculate the new cell index and update all distances to next
1358
      // surfaces.
1359
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,828,504 ✔
1360
      for (int k = 0; k < n; ++k) {
27,108,151 ✔
1361
        distances[k] =
20,279,647 ✔
1362
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
20,279,647 ✔
1363
      }
1364

1365
      // If inside the mesh, Tally inward current
1366
      if (in_mesh && k_max >= 0)
6,828,504 !
1367
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
833,310,769 ✔
1368
    }
1369
  }
1370
}
1371

1372
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,076,862,093 ✔
1373
  vector<int>& bins, vector<double>& lengths) const
1374
{
1375

1376
  // Helper tally class.
1377
  // stores a pointer to the mesh class and references to bins and lengths
1378
  // parameters. Performs the actual tally through the track method.
1379
  struct TrackAggregator {
1,076,862,093 ✔
1380
    TrackAggregator(
1,076,862,093 ✔
1381
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1382
      : mesh(_mesh), bins(_bins), lengths(_lengths)
1,076,862,093 ✔
1383
    {}
1384
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1385
    void track(const MeshIndex& ijk, double l) const
1,826,092,989 ✔
1386
    {
1387
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,826,092,989 ✔
1388
      lengths.push_back(l);
1,826,092,989 ✔
1389
    }
1,826,092,989 ✔
1390

1391
    const StructuredMesh* mesh;
1392
    vector<int>& bins;
1393
    vector<double>& lengths;
1394
  };
1395

1396
  // Perform the mesh raytrace with the helper class.
1397
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,076,862,093 ✔
1398
}
1,076,862,093 ✔
1399

1400
void StructuredMesh::surface_bins_crossed(
112,110,383 ✔
1401
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1402
{
1403

1404
  // Helper tally class.
1405
  // stores a pointer to the mesh class and a reference to the bins parameter.
1406
  // Performs the actual tally through the surface method.
1407
  struct SurfaceAggregator {
112,110,383 ✔
1408
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,110,383 ✔
1409
      : mesh(_mesh), bins(_bins)
112,110,383 ✔
1410
    {}
1411
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
57,982,243 ✔
1412
    {
1413
      int i_bin =
57,982,243 ✔
1414
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
57,982,243 ✔
1415
      if (max)
57,982,243 ✔
1416
        i_bin += 2;
28,961,559 ✔
1417
      if (inward)
57,982,243 ✔
1418
        i_bin += 1;
28,494,444 ✔
1419
      bins.push_back(i_bin);
57,982,243 ✔
1420
    }
57,982,243 ✔
1421
    void track(const MeshIndex& idx, double l) const {}
1422

1423
    const StructuredMesh* mesh;
1424
    vector<int>& bins;
1425
  };
1426

1427
  // Perform the mesh raytrace with the helper class.
1428
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,110,383 ✔
1429
}
112,110,383 ✔
1430

1431
//==============================================================================
1432
// RegularMesh implementation
1433
//==============================================================================
1434

1435
int RegularMesh::set_grid()
2,604 ✔
1436
{
1437
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,604 ✔
1438

1439
  // Check that dimensions are all greater than zero
1440
  if ((shape <= 0).any()) {
7,812 !
UNCOV
1441
    set_errmsg("All entries for a regular mesh dimensions "
×
1442
               "must be positive.");
1443
    return OPENMC_E_INVALID_ARGUMENT;
1444
  }
1445

1446
  // Make sure lower_left and dimension match
1447
  if (lower_left_.size() != n_dimension_) {
2,604 !
UNCOV
1448
    set_errmsg("Number of entries in lower_left must be the same "
×
1449
               "as the regular mesh dimensions.");
1450
    return OPENMC_E_INVALID_ARGUMENT;
1451
  }
1452
  if (width_.size() > 0) {
2,604 ✔
1453

1454
    // Check to ensure width has same dimensions
1455
    if (width_.size() != n_dimension_) {
46 !
UNCOV
1456
      set_errmsg("Number of entries on width must be the same as "
×
1457
                 "the regular mesh dimensions.");
1458
      return OPENMC_E_INVALID_ARGUMENT;
1459
    }
1460

1461
    // Check for negative widths
1462
    if ((width_ < 0.0).any()) {
138 !
UNCOV
1463
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1464
      return OPENMC_E_INVALID_ARGUMENT;
1465
    }
1466

1467
    // Set width and upper right coordinate
1468
    upper_right_ = lower_left_ + shape * width_;
138 ✔
1469

1470
  } else if (upper_right_.size() > 0) {
2,558 !
1471

1472
    // Check to ensure upper_right_ has same dimensions
1473
    if (upper_right_.size() != n_dimension_) {
2,558 !
UNCOV
1474
      set_errmsg("Number of entries on upper_right must be the "
×
1475
                 "same as the regular mesh dimensions.");
1476
      return OPENMC_E_INVALID_ARGUMENT;
1477
    }
1478

1479
    // Check that upper-right is above lower-left
1480
    if ((upper_right_ < lower_left_).any()) {
7,674 !
UNCOV
1481
      set_errmsg(
×
1482
        "The upper_right coordinates of a regular mesh must be greater than "
1483
        "the lower_left coordinates.");
1484
      return OPENMC_E_INVALID_ARGUMENT;
1485
    }
1486

1487
    // Set width
1488
    width_ = (upper_right_ - lower_left_) / shape;
7,674 ✔
1489
  }
1490

1491
  // Set material volumes
1492
  volume_frac_ = 1.0 / shape.prod();
2,604 ✔
1493

1494
  element_volume_ = 1.0;
2,604 ✔
1495
  for (int i = 0; i < n_dimension_; i++) {
9,821 ✔
1496
    element_volume_ *= width_[i];
7,217 ✔
1497
  }
1498
  return 0;
1499
}
2,604 ✔
1500

1501
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,567 ✔
1502
{
1503
  // Determine number of dimensions for mesh
1504
  if (!check_for_node(node, "dimension")) {
2,567 !
UNCOV
1505
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1506
  }
1507

1508
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,567 ✔
1509
  int n = n_dimension_ = shape.size();
2,567 !
1510
  if (n != 1 && n != 2 && n != 3) {
2,567 !
UNCOV
1511
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1512
  }
1513
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,567 ✔
1514

1515
  // Check for lower-left coordinates
1516
  if (check_for_node(node, "lower_left")) {
2,567 !
1517
    // Read mesh lower-left corner location
1518
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,567 ✔
1519
  } else {
UNCOV
1520
    fatal_error("Must specify <lower_left> on a mesh.");
×
1521
  }
1522

1523
  if (check_for_node(node, "width")) {
2,567 ✔
1524
    // Make sure one of upper-right or width were specified
1525
    if (check_for_node(node, "upper_right")) {
46 !
UNCOV
1526
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1527
    }
1528

1529
    width_ = get_node_tensor<double>(node, "width");
92 ✔
1530

1531
  } else if (check_for_node(node, "upper_right")) {
2,521 !
1532

1533
    upper_right_ = get_node_tensor<double>(node, "upper_right");
5,042 ✔
1534

1535
  } else {
UNCOV
1536
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1537
  }
1538

1539
  if (int err = set_grid()) {
2,567 !
UNCOV
1540
    fatal_error(get_errmsg());
×
1541
  }
1542
}
2,567 ✔
1543

1544
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
37 ✔
1545
{
1546
  // Determine number of dimensions for mesh
1547
  if (!object_exists(group, "dimension")) {
37 !
UNCOV
1548
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1549
  }
1550

1551
  tensor::Tensor<int> shape;
37 ✔
1552
  read_dataset(group, "dimension", shape);
37 ✔
1553
  int n = n_dimension_ = shape.size();
37 !
1554
  if (n != 1 && n != 2 && n != 3) {
37 !
1555
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1556
  }
1557
  std::copy(shape.begin(), shape.end(), shape_.begin());
37 ✔
1558

1559
  // Check for lower-left coordinates
1560
  if (object_exists(group, "lower_left")) {
37 !
1561
    // Read mesh lower-left corner location
1562
    read_dataset(group, "lower_left", lower_left_);
37 ✔
1563
  } else {
UNCOV
1564
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1565
  }
1566

1567
  if (object_exists(group, "upper_right")) {
37 !
1568

1569
    read_dataset(group, "upper_right", upper_right_);
37 ✔
1570

1571
  } else {
UNCOV
1572
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1573
  }
1574

1575
  if (int err = set_grid()) {
37 !
UNCOV
1576
    fatal_error(get_errmsg());
×
1577
  }
1578
}
37 ✔
1579

1580
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647 ✔
1581
{
1582
  if (r <= lower_left_[i])
2,147,483,647 ✔
1583
    return r == lower_left_[i] ? 1 : 0;
13,716,941 ✔
1584
  if (r >= upper_right_[i])
2,147,483,647 ✔
1585
    return r == upper_right_[i] ? shape_[i] : shape_[i] + 1;
11,319,685 ✔
1586

1587
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647 ✔
1588
}
1589

1590
const std::string RegularMesh::mesh_type = "regular";
1591

1592
std::string RegularMesh::get_mesh_type() const
3,797 ✔
1593
{
1594
  return mesh_type;
3,797 ✔
1595
}
1596

1597
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,926,581,165 ✔
1598
{
1599
  return lower_left_[i] + ijk[i] * width_[i];
1,926,581,165 ✔
1600
}
1601

1602
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,856,483,437 ✔
1603
{
1604
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,856,483,437 ✔
1605
}
1606

1607
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647 ✔
1608
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1609
  double l) const
1610
{
1611
  MeshDistance d;
2,147,483,647 ✔
1612
  d.next_index = ijk[i];
2,147,483,647 ✔
1613
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647 ✔
1614
    return d;
15,841,204 ✔
1615

1616
  d.max_surface = (u[i] > 0);
2,147,483,647 ✔
1617
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647 ✔
1618
    d.next_index++;
1,922,266,571 ✔
1619
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,922,266,571 ✔
1620
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,873,618,015 ✔
1621
    d.next_index--;
1,852,168,843 ✔
1622
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,852,168,843 ✔
1623
  }
1624

1625
  return d;
2,147,483,647 ✔
1626
}
1627

1628
std::pair<vector<double>, vector<double>> RegularMesh::plot(
22 ✔
1629
  Position plot_ll, Position plot_ur) const
1630
{
1631
  // Figure out which axes lie in the plane of the plot.
1632
  array<int, 2> axes {-1, -1};
22 ✔
1633
  if (plot_ur.z == plot_ll.z) {
22 !
1634
    axes[0] = 0;
22 !
1635
    if (n_dimension_ > 1)
22 !
1636
      axes[1] = 1;
22 ✔
UNCOV
1637
  } else if (plot_ur.y == plot_ll.y) {
×
UNCOV
1638
    axes[0] = 0;
×
UNCOV
1639
    if (n_dimension_ > 2)
×
UNCOV
1640
      axes[1] = 2;
×
UNCOV
1641
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1642
    if (n_dimension_ > 1)
×
UNCOV
1643
      axes[0] = 1;
×
UNCOV
1644
    if (n_dimension_ > 2)
×
UNCOV
1645
      axes[1] = 2;
×
1646
  } else {
UNCOV
1647
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1648
  }
1649

1650
  // Get the coordinates of the mesh lines along both of the axes.
1651
  array<vector<double>, 2> axis_lines;
1652
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
66 ✔
1653
    int axis = axes[i_ax];
44 !
1654
    if (axis == -1)
44 !
UNCOV
1655
      continue;
×
1656
    auto& lines {axis_lines[i_ax]};
44 ✔
1657

1658
    double coord = lower_left_[axis];
44 ✔
1659
    for (int i = 0; i < shape_[axis] + 1; ++i) {
286 ✔
1660
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
242 !
1661
        lines.push_back(coord);
242 ✔
1662
      coord += width_[axis];
242 ✔
1663
    }
1664
  }
1665

1666
  return {axis_lines[0], axis_lines[1]};
44 ✔
1667
}
1668

1669
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,509 ✔
1670
{
1671
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,509 ✔
1672
  write_dataset(mesh_group, "lower_left", lower_left_);
2,509 ✔
1673
  write_dataset(mesh_group, "upper_right", upper_right_);
2,509 ✔
1674
  write_dataset(mesh_group, "width", width_);
2,509 ✔
1675
}
2,509 ✔
1676

1677
tensor::Tensor<double> RegularMesh::count_sites(
7,820 ✔
1678
  const SourceSite* bank, int64_t length, bool* outside) const
1679
{
1680
  // Determine shape of array for counts
1681
  std::size_t m = this->n_bins();
7,820 ✔
1682
  vector<std::size_t> shape = {m};
7,820 ✔
1683

1684
  // Create array of zeros
1685
  auto cnt = tensor::zeros<double>(shape);
7,820 ✔
1686
  bool outside_ = false;
2,892 ✔
1687

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

1691
    // determine scoring bin for entropy mesh
1692
    int mesh_bin = get_bin(site.r);
7,667,451 ✔
1693

1694
    // if outside mesh, skip particle
1695
    if (mesh_bin < 0) {
7,667,451 !
UNCOV
1696
      outside_ = true;
×
UNCOV
1697
      continue;
×
1698
    }
1699

1700
    // Add to appropriate bin
1701
    cnt(mesh_bin) += site.wgt;
7,667,451 ✔
1702
  }
1703

1704
  // Create reduced count data
1705
  auto counts = tensor::zeros<double>(shape);
7,820 ✔
1706
  int total = cnt.size();
7,820 ✔
1707

1708
#ifdef OPENMC_MPI
1709
  // collect values from all processors
1710
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
2,892 ✔
1711

1712
  // Check if there were sites outside the mesh for any processor
1713
  if (outside) {
2,892 !
1714
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
2,892 ✔
1715
  }
1716
#else
1717
  std::copy(cnt.data(), cnt.data() + total, counts.data());
4,928 ✔
1718
  if (outside)
4,928 !
1719
    *outside = outside_;
4,928 ✔
1720
#endif
1721

1722
  return counts;
7,820 ✔
1723
}
7,820 ✔
1724

1725
double RegularMesh::volume(const MeshIndex& ijk) const
1,246,044 ✔
1726
{
1727
  return element_volume_;
1,246,044 ✔
1728
}
1729

1730
//==============================================================================
1731
// RectilinearMesh implementation
1732
//==============================================================================
1733

1734
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
133 ✔
1735
{
1736
  n_dimension_ = 3;
133 ✔
1737

1738
  grid_[0] = get_node_array<double>(node, "x_grid");
133 ✔
1739
  grid_[1] = get_node_array<double>(node, "y_grid");
133 ✔
1740
  grid_[2] = get_node_array<double>(node, "z_grid");
133 ✔
1741

1742
  if (int err = set_grid()) {
133 !
UNCOV
1743
    fatal_error(get_errmsg());
×
1744
  }
1745
}
133 ✔
1746

1747
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11 ✔
1748
{
1749
  n_dimension_ = 3;
11 ✔
1750

1751
  read_dataset(group, "x_grid", grid_[0]);
11 ✔
1752
  read_dataset(group, "y_grid", grid_[1]);
11 ✔
1753
  read_dataset(group, "z_grid", grid_[2]);
11 ✔
1754

1755
  if (int err = set_grid()) {
11 !
UNCOV
1756
    fatal_error(get_errmsg());
×
1757
  }
1758
}
11 ✔
1759

1760
const std::string RectilinearMesh::mesh_type = "rectilinear";
1761

1762
std::string RectilinearMesh::get_mesh_type() const
319 ✔
1763
{
1764
  return mesh_type;
319 ✔
1765
}
1766

1767
double RectilinearMesh::positive_grid_boundary(
26,221,162 ✔
1768
  const MeshIndex& ijk, int i) const
1769
{
1770
  return grid_[i][ijk[i]];
26,221,162 ✔
1771
}
1772

1773
double RectilinearMesh::negative_grid_boundary(
25,464,714 ✔
1774
  const MeshIndex& ijk, int i) const
1775
{
1776
  return grid_[i][ijk[i] - 1];
25,464,714 ✔
1777
}
1778

1779
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
52,977,749 ✔
1780
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1781
  double l) const
1782
{
1783
  MeshDistance d;
52,977,749 ✔
1784
  d.next_index = ijk[i];
52,977,749 ✔
1785
  if (std::abs(u[i]) < FP_PRECISION)
52,977,749 ✔
1786
    return d;
571,824 ✔
1787

1788
  d.max_surface = (u[i] > 0);
52,405,925 ✔
1789
  if (d.max_surface && (ijk[i] <= shape_[i])) {
52,405,925 ✔
1790
    d.next_index++;
26,221,162 ✔
1791
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,221,162 ✔
1792
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,184,763 ✔
1793
    d.next_index--;
25,464,714 ✔
1794
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,464,714 ✔
1795
  }
1796
  return d;
52,405,925 ✔
1797
}
1798

1799
int RectilinearMesh::set_grid()
221 ✔
1800
{
1801
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
221 ✔
1802
    static_cast<int>(grid_[1].size()) - 1,
221 ✔
1803
    static_cast<int>(grid_[2].size()) - 1};
221 ✔
1804

1805
  for (const auto& g : grid_) {
884 ✔
1806
    if (g.size() < 2) {
663 !
UNCOV
1807
      set_errmsg("x-, y-, and z- grids for rectilinear meshes "
×
1808
                 "must each have at least 2 points");
1809
      return OPENMC_E_INVALID_ARGUMENT;
×
1810
    }
1811
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
663 !
1812
        g.end()) {
663 !
UNCOV
1813
      set_errmsg("Values in for x-, y-, and z- grids for "
×
1814
                 "rectilinear meshes must be sorted and unique.");
UNCOV
1815
      return OPENMC_E_INVALID_ARGUMENT;
×
1816
    }
1817
  }
1818

1819
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
221 ✔
1820
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
221 ✔
1821

1822
  return 0;
221 ✔
1823
}
1824

1825
int RectilinearMesh::get_index_in_direction(double r, int i) const
73,540,885 ✔
1826
{
1827
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
73,540,885 ✔
1828
}
1829

1830
std::pair<vector<double>, vector<double>> RectilinearMesh::plot(
11 ✔
1831
  Position plot_ll, Position plot_ur) const
1832
{
1833
  // Figure out which axes lie in the plane of the plot.
1834
  array<int, 2> axes {-1, -1};
11 ✔
1835
  if (plot_ur.z == plot_ll.z) {
11 !
UNCOV
1836
    axes = {0, 1};
×
1837
  } else if (plot_ur.y == plot_ll.y) {
11 !
1838
    axes = {0, 2};
11 ✔
UNCOV
1839
  } else if (plot_ur.x == plot_ll.x) {
×
UNCOV
1840
    axes = {1, 2};
×
1841
  } else {
UNCOV
1842
    fatal_error("Can only plot mesh lines on an axis-aligned plot");
×
1843
  }
1844

1845
  // Get the coordinates of the mesh lines along both of the axes.
1846
  array<vector<double>, 2> axis_lines;
1847
  for (int i_ax = 0; i_ax < 2; ++i_ax) {
33 ✔
1848
    int axis = axes[i_ax];
22 ✔
1849
    vector<double>& lines {axis_lines[i_ax]};
22 ✔
1850

1851
    for (auto coord : grid_[axis]) {
110 ✔
1852
      if (coord >= plot_ll[axis] && coord <= plot_ur[axis])
88 !
1853
        lines.push_back(coord);
88 ✔
1854
    }
1855
  }
1856

1857
  return {axis_lines[0], axis_lines[1]};
22 ✔
1858
}
1859

1860
void RectilinearMesh::to_hdf5_inner(hid_t mesh_group) const
132 ✔
1861
{
1862
  write_dataset(mesh_group, "x_grid", grid_[0]);
132 ✔
1863
  write_dataset(mesh_group, "y_grid", grid_[1]);
132 ✔
1864
  write_dataset(mesh_group, "z_grid", grid_[2]);
132 ✔
1865
}
132 ✔
1866

1867
double RectilinearMesh::volume(const MeshIndex& ijk) const
132 ✔
1868
{
1869
  double vol {1.0};
132 ✔
1870

1871
  for (int i = 0; i < n_dimension_; i++) {
528 ✔
1872
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
396 ✔
1873
  }
1874
  return vol;
132 ✔
1875
}
1876

1877
//==============================================================================
1878
// CylindricalMesh implementation
1879
//==============================================================================
1880

1881
CylindricalMesh::CylindricalMesh(pugi::xml_node node)
411 ✔
1882
  : PeriodicStructuredMesh {node}
411 ✔
1883
{
1884
  n_dimension_ = 3;
411 ✔
1885
  grid_[0] = get_node_array<double>(node, "r_grid");
411 ✔
1886
  grid_[1] = get_node_array<double>(node, "phi_grid");
411 ✔
1887
  grid_[2] = get_node_array<double>(node, "z_grid");
411 ✔
1888
  origin_ = get_node_position(node, "origin");
411 ✔
1889

1890
  if (int err = set_grid()) {
411 !
UNCOV
1891
    fatal_error(get_errmsg());
×
1892
  }
1893
}
411 ✔
1894

1895
CylindricalMesh::CylindricalMesh(hid_t group) : PeriodicStructuredMesh {group}
11 ✔
1896
{
1897
  n_dimension_ = 3;
11 ✔
1898
  read_dataset(group, "r_grid", grid_[0]);
11 ✔
1899
  read_dataset(group, "phi_grid", grid_[1]);
11 ✔
1900
  read_dataset(group, "z_grid", grid_[2]);
11 ✔
1901
  read_dataset(group, "origin", origin_);
11 ✔
1902

1903
  if (int err = set_grid()) {
11 !
UNCOV
1904
    fatal_error(get_errmsg());
×
1905
  }
1906
}
11 ✔
1907

1908
const std::string CylindricalMesh::mesh_type = "cylindrical";
1909

1910
std::string CylindricalMesh::get_mesh_type() const
517 ✔
1911
{
1912
  return mesh_type;
517 ✔
1913
}
1914

1915
std::array<const char*, 3> CylindricalMesh::axis_labels() const
646,536 ✔
1916
{
1917
  return {"r", "phi", "z"};
646,536 ✔
1918
}
1919

1920
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,667,686 ✔
1921
  Position r, bool& in_mesh) const
1922
{
1923
  r = local_coords(r);
47,667,686 ✔
1924

1925
  Position mapped_r;
47,667,686 ✔
1926
  mapped_r[0] = std::hypot(r.x, r.y);
47,667,686 ✔
1927
  mapped_r[2] = r[2];
47,667,686 ✔
1928

1929
  if (mapped_r[0] < FP_PRECISION) {
47,667,686 !
1930
    mapped_r[1] = 0.0;
1931
  } else {
1932
    mapped_r[1] = std::atan2(r.y, r.x);
47,667,686 ✔
1933
    if (mapped_r[1] < 0)
47,667,686 ✔
1934
      mapped_r[1] += 2 * PI;
23,854,556 ✔
1935
  }
1936

1937
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
47,667,686 ✔
1938

1939
  idx[1] = sanitize_phi(idx[1]);
47,667,686 ✔
1940

1941
  return idx;
47,667,686 ✔
1942
}
1943

1944
Position CylindricalMesh::sample_element(
88,110 ✔
1945
  const MeshIndex& ijk, uint64_t* seed) const
1946
{
1947
  double r_min = this->r(ijk[0] - 1);
88,110 ✔
1948
  double r_max = this->r(ijk[0]);
88,110 ✔
1949

1950
  double phi_min = this->phi(ijk[1] - 1);
88,110 ✔
1951
  double phi_max = this->phi(ijk[1]);
88,110 ✔
1952

1953
  double z_min = this->z(ijk[2] - 1);
88,110 ✔
1954
  double z_max = this->z(ijk[2]);
88,110 ✔
1955

1956
  double r_min_sq = r_min * r_min;
88,110 ✔
1957
  double r_max_sq = r_max * r_max;
88,110 ✔
1958
  double r = std::sqrt(uniform_distribution(r_min_sq, r_max_sq, seed));
88,110 ✔
1959
  double phi = uniform_distribution(phi_min, phi_max, seed);
88,110 ✔
1960
  double z = uniform_distribution(z_min, z_max, seed);
88,110 ✔
1961

1962
  double x = r * std::cos(phi);
88,110 ✔
1963
  double y = r * std::sin(phi);
88,110 ✔
1964

1965
  return origin_ + Position(x, y, z);
88,110 ✔
1966
}
1967

1968
double CylindricalMesh::find_r_crossing(
142,413,976 ✔
1969
  const Position& r, const Direction& u, double l, int shell) const
1970
{
1971

1972
  if ((shell < 0) || (shell > shape_[0]))
142,413,976 !
1973
    return INFTY;
1974

1975
  // solve r.x^2 + r.y^2 == r0^2
1976
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1977
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1978

1979
  const double r0 = grid_[0][shell];
124,552,490 ✔
1980
  if (r0 == 0.0)
124,552,490 ✔
1981
    return INFTY;
1982

1983
  const double denominator = u.x * u.x + u.y * u.y;
117,416,867 ✔
1984

1985
  // Direction of flight is in z-direction. Will never intersect r.
1986
  if (std::abs(denominator) < FP_PRECISION)
117,416,867 ✔
1987
    return INFTY;
1988

1989
  // inverse of dominator to help the compiler to speed things up
1990
  const double inv_denominator = 1.0 / denominator;
117,357,907 ✔
1991

1992
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,357,907 ✔
1993
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,357,907 ✔
1994
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,357,907 ✔
1995

1996
  if (D < 0.0)
117,357,907 ✔
1997
    return INFTY;
1998

1999
  D = std::sqrt(D);
107,647,305 ✔
2000

2001
  // Particle is already on the shell surface; avoid spurious crossing
2002
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,647,305 ✔
2003
    return INFTY;
2004

2005
  // Check -p - D first because it is always smaller as -p + D
2006
  if (-p - D > l)
101,013,931 ✔
2007
    return -p - D;
2008
  if (-p + D > l)
80,823,684 ✔
2009
    return -p + D;
50,043,731 ✔
2010

2011
  return INFTY;
2012
}
2013

2014
double CylindricalMesh::find_phi_crossing(
74,296,970 ✔
2015
  const Position& r, const Direction& u, double l, int shell) const
2016
{
2017
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2018
  if (full_phi_ && (shape_[1] == 1))
74,296,970 ✔
2019
    return INFTY;
2020

2021
  shell = sanitize_phi(shell);
43,811,262 ✔
2022

2023
  const double p0 = grid_[1][shell];
43,811,262 ✔
2024

2025
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2026
  // => x(s) * cos(p0) = y(s) * sin(p0)
2027
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2028
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2029

2030
  const double c0 = std::cos(p0);
43,811,262 ✔
2031
  const double s0 = std::sin(p0);
43,811,262 ✔
2032

2033
  const double denominator = (u.x * s0 - u.y * c0);
43,811,262 ✔
2034

2035
  // Check if direction of flight is not parallel to phi surface
2036
  if (std::abs(denominator) > FP_PRECISION) {
43,811,262 ✔
2037
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,550,518 ✔
2038
    // Check if solution is in positive direction of flight and crosses the
2039
    // correct phi surface (not -phi)
2040
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,550,518 ✔
2041
      return s;
20,148,227 ✔
2042
  }
2043

2044
  return INFTY;
2045
}
2046

2047
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,620,210 ✔
2048
  const Position& r, const Direction& u, double l, int shell) const
2049
{
2050
  MeshDistance d;
36,620,210 ✔
2051
  d.next_index = shell;
36,620,210 ✔
2052

2053
  // Direction of flight is within xy-plane. Will never intersect z.
2054
  if (std::abs(u.z) < FP_PRECISION)
36,620,210 ✔
2055
    return d;
1,118,216 ✔
2056

2057
  d.max_surface = (u.z > 0.0);
35,501,994 ✔
2058
  if (d.max_surface && (shell <= shape_[2])) {
35,501,994 ✔
2059
    d.next_index += 1;
16,844,971 ✔
2060
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,844,971 ✔
2061
  } else if (!d.max_surface && (shell > 0)) {
18,657,023 ✔
2062
    d.next_index -= 1;
16,811,223 ✔
2063
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,811,223 ✔
2064
  }
2065
  return d;
35,501,994 ✔
2066
}
2067

2068
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
144,975,683 ✔
2069
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2070
  double l) const
2071
{
2072
  if (i == 0) {
144,975,683 ✔
2073

2074
    return std::min(
142,413,976 ✔
2075
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,206,988 ✔
2076
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,413,976 ✔
2077

2078
  } else if (i == 1) {
73,768,695 ✔
2079

2080
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,148,485 ✔
2081
                      find_phi_crossing(r0, u, l, ijk[i])),
37,148,485 ✔
2082
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,148,485 ✔
2083
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,296,970 ✔
2084

2085
  } else {
2086
    return find_z_crossing(r0, u, l, ijk[i]);
36,620,210 ✔
2087
  }
2088
}
2089

2090
int CylindricalMesh::set_grid()
510 ✔
2091
{
2092
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
510 ✔
2093
    static_cast<int>(grid_[1].size()) - 1,
510 ✔
2094
    static_cast<int>(grid_[2].size()) - 1};
510 ✔
2095

2096
  for (const auto& g : grid_) {
2,040 ✔
2097
    if (g.size() < 2) {
1,530 !
UNCOV
2098
      set_errmsg("r-, phi-, and z- grids for cylindrical meshes "
×
2099
                 "must each have at least 2 points");
UNCOV
2100
      return OPENMC_E_INVALID_ARGUMENT;
×
2101
    }
2102
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,530 !
2103
        g.end()) {
1,530 !
UNCOV
2104
      set_errmsg("Values in for r-, phi-, and z- grids for "
×
2105
                 "cylindrical meshes must be sorted and unique.");
2106
      return OPENMC_E_INVALID_ARGUMENT;
×
2107
    }
2108
  }
2109
  if (grid_[0].front() < 0.0) {
510 !
UNCOV
2110
    set_errmsg("r-grid for "
×
2111
               "cylindrical meshes must start at r >= 0.");
UNCOV
2112
    return OPENMC_E_INVALID_ARGUMENT;
×
2113
  }
2114
  if (grid_[1].front() < 0.0) {
510 !
UNCOV
2115
    set_errmsg("phi-grid for "
×
2116
               "cylindrical meshes must start at phi >= 0.");
UNCOV
2117
    return OPENMC_E_INVALID_ARGUMENT;
×
2118
  }
2119
  if (grid_[1].back() > 2.0 * PI) {
510 !
2120
    set_errmsg("phi-grids for "
×
2121
               "cylindrical meshes must end with theta <= 2*pi.");
2122

UNCOV
2123
    return OPENMC_E_INVALID_ARGUMENT;
×
2124
  }
2125

2126
  full_phi_ = (grid_[1].front() == 0.0) && (grid_[1].back() == 2.0 * PI);
510 !
2127

2128
  lower_left_ = {origin_[0] - grid_[0].back(), origin_[1] - grid_[0].back(),
510 ✔
2129
    origin_[2] + grid_[2].front()};
510 ✔
2130
  upper_right_ = {origin_[0] + grid_[0].back(), origin_[1] + grid_[0].back(),
510 ✔
2131
    origin_[2] + grid_[2].back()};
510 ✔
2132

2133
  return 0;
510 ✔
2134
}
2135

2136
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,003,058 ✔
2137
{
2138
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,003,058 ✔
2139
}
2140

UNCOV
2141
std::pair<vector<double>, vector<double>> CylindricalMesh::plot(
×
2142
  Position plot_ll, Position plot_ur) const
2143
{
UNCOV
2144
  fatal_error("Plot of cylindrical Mesh not implemented");
×
2145

2146
  // Figure out which axes lie in the plane of the plot.
2147
  array<vector<double>, 2> axis_lines;
2148
  return {axis_lines[0], axis_lines[1]};
2149
}
2150

2151
void CylindricalMesh::to_hdf5_inner(hid_t mesh_group) const
396 ✔
2152
{
2153
  write_dataset(mesh_group, "r_grid", grid_[0]);
396 ✔
2154
  write_dataset(mesh_group, "phi_grid", grid_[1]);
396 ✔
2155
  write_dataset(mesh_group, "z_grid", grid_[2]);
396 ✔
2156
  write_dataset(mesh_group, "origin", origin_);
396 ✔
2157
}
396 ✔
2158

2159
double CylindricalMesh::volume(const MeshIndex& ijk) const
792 ✔
2160
{
2161
  double r_i = grid_[0][ijk[0] - 1];
792 ✔
2162
  double r_o = grid_[0][ijk[0]];
792 ✔
2163

2164
  double phi_i = grid_[1][ijk[1] - 1];
792 ✔
2165
  double phi_o = grid_[1][ijk[1]];
792 ✔
2166

2167
  double z_i = grid_[2][ijk[2] - 1];
792 ✔
2168
  double z_o = grid_[2][ijk[2]];
792 ✔
2169

2170
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792 ✔
2171
}
2172

2173
//==============================================================================
2174
// SphericalMesh implementation
2175
//==============================================================================
2176

2177
SphericalMesh::SphericalMesh(pugi::xml_node node)
356 ✔
2178
  : PeriodicStructuredMesh {node}
356 ✔
2179
{
2180
  n_dimension_ = 3;
356 ✔
2181

2182
  grid_[0] = get_node_array<double>(node, "r_grid");
356 ✔
2183
  grid_[1] = get_node_array<double>(node, "theta_grid");
356 ✔
2184
  grid_[2] = get_node_array<double>(node, "phi_grid");
356 ✔
2185
  origin_ = get_node_position(node, "origin");
356 ✔
2186

2187
  if (int err = set_grid()) {
356 !
UNCOV
2188
    fatal_error(get_errmsg());
×
2189
  }
2190
}
356 ✔
2191

2192
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11 ✔
2193
{
2194
  n_dimension_ = 3;
11 ✔
2195

2196
  read_dataset(group, "r_grid", grid_[0]);
11 ✔
2197
  read_dataset(group, "theta_grid", grid_[1]);
11 ✔
2198
  read_dataset(group, "phi_grid", grid_[2]);
11 ✔
2199
  read_dataset(group, "origin", origin_);
11 ✔
2200

2201
  if (int err = set_grid()) {
11 !
UNCOV
2202
    fatal_error(get_errmsg());
×
2203
  }
2204
}
11 ✔
2205

2206
const std::string SphericalMesh::mesh_type = "spherical";
2207

2208
std::string SphericalMesh::get_mesh_type() const
418 ✔
2209
{
2210
  return mesh_type;
418 ✔
2211
}
2212

2213
std::array<const char*, 3> SphericalMesh::axis_labels() const
323,400 ✔
2214
{
2215
  return {"r", "theta", "phi"};
323,400 ✔
2216
}
2217

2218
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,528,196 ✔
2219
  Position r, bool& in_mesh) const
2220
{
2221
  r = local_coords(r);
68,528,196 ✔
2222

2223
  Position mapped_r;
68,528,196 ✔
2224
  mapped_r[0] = r.norm();
68,528,196 ✔
2225

2226
  if (mapped_r[0] < FP_PRECISION) {
68,528,196 !
2227
    mapped_r[1] = 0.0;
2228
    mapped_r[2] = 0.0;
2229
  } else {
2230
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,528,196 ✔
2231
    mapped_r[2] = std::atan2(r.y, r.x);
68,528,196 ✔
2232
    if (mapped_r[2] < 0)
68,528,196 ✔
2233
      mapped_r[2] += 2 * PI;
34,249,050 ✔
2234
  }
2235

2236
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
68,528,196 ✔
2237

2238
  idx[1] = sanitize_theta(idx[1]);
68,528,196 ✔
2239
  idx[2] = sanitize_phi(idx[2]);
68,528,196 ✔
2240

2241
  return idx;
68,528,196 ✔
2242
}
2243

2244
Position SphericalMesh::sample_element(
110 ✔
2245
  const MeshIndex& ijk, uint64_t* seed) const
2246
{
2247
  double r_min = this->r(ijk[0] - 1);
110 ✔
2248
  double r_max = this->r(ijk[0]);
110 ✔
2249

2250
  double theta_min = this->theta(ijk[1] - 1);
110 ✔
2251
  double theta_max = this->theta(ijk[1]);
110 ✔
2252

2253
  double phi_min = this->phi(ijk[2] - 1);
110 ✔
2254
  double phi_max = this->phi(ijk[2]);
110 ✔
2255

2256
  double cos_theta =
110 ✔
2257
    uniform_distribution(std::cos(theta_min), std::cos(theta_max), seed);
110 ✔
2258
  double sin_theta = std::sin(std::acos(cos_theta));
110 ✔
2259
  double phi = uniform_distribution(phi_min, phi_max, seed);
110 ✔
2260
  double r_min_cub = std::pow(r_min, 3);
110 ✔
2261
  double r_max_cub = std::pow(r_max, 3);
110 ✔
2262
  // might be faster to do rejection here?
2263
  double r = std::cbrt(uniform_distribution(r_min_cub, r_max_cub, seed));
110 ✔
2264

2265
  double x = r * std::cos(phi) * sin_theta;
110 ✔
2266
  double y = r * std::sin(phi) * sin_theta;
110 ✔
2267
  double z = r * cos_theta;
110 ✔
2268

2269
  return origin_ + Position(x, y, z);
110 ✔
2270
}
2271

2272
double SphericalMesh::find_r_crossing(
443,835,194 ✔
2273
  const Position& r, const Direction& u, double l, int shell) const
2274
{
2275
  if ((shell < 0) || (shell > shape_[0]))
443,835,194 ✔
2276
    return INFTY;
2277

2278
  // solve |r+s*u| = r0
2279
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2280
  const double r0 = grid_[0][shell];
404,273,320 ✔
2281
  if (r0 == 0.0)
404,273,320 ✔
2282
    return INFTY;
2283
  const double p = r.dot(u);
396,594,660 ✔
2284
  double R = r.norm();
396,594,660 ✔
2285
  double D = p * p - (R - r0) * (R + r0);
396,594,660 ✔
2286

2287
  // Particle is already on the shell surface; avoid spurious crossing
2288
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,594,660 ✔
2289
    return INFTY;
2290

2291
  if (D >= 0.0) {
385,886,006 ✔
2292
    D = std::sqrt(D);
358,048,779 ✔
2293
    // Check -p - D first because it is always smaller as -p + D
2294
    if (-p - D > l)
358,048,779 ✔
2295
      return -p - D;
2296
    if (-p + D > l)
293,744,627 ✔
2297
      return -p + D;
177,227,996 ✔
2298
  }
2299

2300
  return INFTY;
2301
}
2302

2303
double SphericalMesh::find_theta_crossing(
110,025,982 ✔
2304
  const Position& r, const Direction& u, double l, int shell) const
2305
{
2306
  // Theta grid is [0, π], thus there is no real surface to cross
2307
  if (full_theta_ && (shape_[1] == 1))
110,025,982 ✔
2308
    return INFTY;
2309

2310
  shell = sanitize_theta(shell);
38,223,152 ✔
2311

2312
  // solving z(s) = cos/theta) * r(s) with r(s) = r+s*u
2313
  // yields
2314
  // a*s^2 + 2*b*s + c == 0 with
2315
  // a = cos(theta)^2 - u.z * u.z
2316
  // b = r*u * cos(theta)^2 - u.z * r.z
2317
  // c = r*r * cos(theta)^2 - r.z^2
2318

2319
  const double cos_t = std::cos(grid_[1][shell]);
38,223,152 ✔
2320
  const bool sgn = std::signbit(cos_t);
38,223,152 ✔
2321
  const double cos_t_2 = cos_t * cos_t;
38,223,152 ✔
2322

2323
  const double a = cos_t_2 - u.z * u.z;
38,223,152 ✔
2324
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,223,152 ✔
2325
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,223,152 ✔
2326

2327
  // if factor of s^2 is zero, direction of flight is parallel to theta
2328
  // surface
2329
  if (std::abs(a) < FP_PRECISION) {
38,223,152 ✔
2330
    // if b vanishes, direction of flight is within theta surface and crossing
2331
    // is not possible
2332
    if (std::abs(b) < FP_PRECISION)
482,548 !
2333
      return INFTY;
2334

UNCOV
2335
    const double s = -0.5 * c / b;
×
2336
    // Check if solution is in positive direction of flight and has correct
2337
    // sign
UNCOV
2338
    if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
×
UNCOV
2339
      return s;
×
2340

2341
    // no crossing is possible
2342
    return INFTY;
2343
  }
2344

2345
  const double p = b / a;
37,740,604 ✔
2346
  double D = p * p - c / a;
37,740,604 ✔
2347

2348
  if (D < 0.0)
37,740,604 ✔
2349
    return INFTY;
2350

2351
  D = std::sqrt(D);
26,823,456 ✔
2352

2353
  // the solution -p-D is always smaller as -p+D : Check this one first
2354
  double s = -p - D;
26,823,456 ✔
2355
  // Check if solution is in positive direction of flight and has correct sign
2356
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
26,823,456 ✔
2357
    return s;
2358

2359
  s = -p + D;
21,564,411 ✔
2360
  // Check if solution is in positive direction of flight and has correct sign
2361
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
21,564,411 ✔
2362
    return s;
10,127,854 ✔
2363

2364
  return INFTY;
2365
}
2366

2367
double SphericalMesh::find_phi_crossing(
111,599,906 ✔
2368
  const Position& r, const Direction& u, double l, int shell) const
2369
{
2370
  // Phi grid is [0, 2Ï€], thus there is no real surface to cross
2371
  if (full_phi_ && (shape_[2] == 1))
111,599,906 ✔
2372
    return INFTY;
2373

2374
  shell = sanitize_phi(shell);
39,797,076 ✔
2375

2376
  const double p0 = grid_[2][shell];
39,797,076 ✔
2377

2378
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2379
  // => x(s) * cos(p0) = y(s) * sin(p0)
2380
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2381
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2382

2383
  const double c0 = std::cos(p0);
39,797,076 ✔
2384
  const double s0 = std::sin(p0);
39,797,076 ✔
2385

2386
  const double denominator = (u.x * s0 - u.y * c0);
39,797,076 ✔
2387

2388
  // Check if direction of flight is not parallel to phi surface
2389
  if (std::abs(denominator) > FP_PRECISION) {
39,797,076 ✔
2390
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,563,084 ✔
2391
    // Check if solution is in positive direction of flight and crosses the
2392
    // correct phi surface (not -phi)
2393
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,563,084 ✔
2394
      return s;
17,512,440 ✔
2395
  }
2396

2397
  return INFTY;
2398
}
2399

2400
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,730,541 ✔
2401
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2402
  double l) const
2403
{
2404

2405
  if (i == 0) {
332,730,541 ✔
2406
    return std::min(
443,835,194 ✔
2407
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,917,597 ✔
2408
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,835,194 ✔
2409

2410
  } else if (i == 1) {
110,812,944 ✔
2411
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,012,991 ✔
2412
                      find_theta_crossing(r0, u, l, ijk[i])),
55,012,991 ✔
2413
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,012,991 ✔
2414
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,025,982 ✔
2415

2416
  } else {
2417
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,799,953 ✔
2418
                      find_phi_crossing(r0, u, l, ijk[i])),
55,799,953 ✔
2419
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,799,953 ✔
2420
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,599,906 ✔
2421
  }
2422
}
2423

2424
int SphericalMesh::set_grid()
455 ✔
2425
{
2426
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
455 ✔
2427
    static_cast<int>(grid_[1].size()) - 1,
455 ✔
2428
    static_cast<int>(grid_[2].size()) - 1};
455 ✔
2429

2430
  for (const auto& g : grid_) {
1,820 ✔
2431
    if (g.size() < 2) {
1,365 !
UNCOV
2432
      set_errmsg("x-, y-, and z- grids for spherical meshes "
×
2433
                 "must each have at least 2 points");
2434
      return OPENMC_E_INVALID_ARGUMENT;
×
2435
    }
2436
    if (std::adjacent_find(g.begin(), g.end(), std::greater_equal<>()) !=
1,365 !
2437
        g.end()) {
1,365 !
UNCOV
2438
      set_errmsg("Values in for r-, theta-, and phi- grids for "
×
2439
                 "spherical meshes must be sorted and unique.");
UNCOV
2440
      return OPENMC_E_INVALID_ARGUMENT;
×
2441
    }
2442
    if (g.front() < 0.0) {
1,365 !
UNCOV
2443
      set_errmsg("r-, theta-, and phi- grids for "
×
2444
                 "spherical meshes must start at v >= 0.");
UNCOV
2445
      return OPENMC_E_INVALID_ARGUMENT;
×
2446
    }
2447
  }
2448
  if (grid_[1].back() > PI) {
455 !
UNCOV
2449
    set_errmsg("theta-grids for "
×
2450
               "spherical meshes must end with theta <= pi.");
2451

UNCOV
2452
    return OPENMC_E_INVALID_ARGUMENT;
×
2453
  }
2454
  if (grid_[2].back() > 2 * PI) {
455 !
UNCOV
2455
    set_errmsg("phi-grids for "
×
2456
               "spherical meshes must end with phi <= 2*pi.");
UNCOV
2457
    return OPENMC_E_INVALID_ARGUMENT;
×
2458
  }
2459

2460
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
455 !
2461
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
455 ✔
2462

2463
  double r = grid_[0].back();
455 ✔
2464
  lower_left_ = {origin_[0] - r, origin_[1] - r, origin_[2] - r};
455 ✔
2465
  upper_right_ = {origin_[0] + r, origin_[1] + r, origin_[2] + r};
455 ✔
2466

2467
  return 0;
455 ✔
2468
}
2469

2470
int SphericalMesh::get_index_in_direction(double r, int i) const
205,584,588 ✔
2471
{
2472
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,584,588 ✔
2473
}
2474

UNCOV
2475
std::pair<vector<double>, vector<double>> SphericalMesh::plot(
×
2476
  Position plot_ll, Position plot_ur) const
2477
{
UNCOV
2478
  fatal_error("Plot of spherical Mesh not implemented");
×
2479

2480
  // Figure out which axes lie in the plane of the plot.
2481
  array<vector<double>, 2> axis_lines;
2482
  return {axis_lines[0], axis_lines[1]};
2483
}
2484

2485
void SphericalMesh::to_hdf5_inner(hid_t mesh_group) const
341 ✔
2486
{
2487
  write_dataset(mesh_group, "r_grid", grid_[0]);
341 ✔
2488
  write_dataset(mesh_group, "theta_grid", grid_[1]);
341 ✔
2489
  write_dataset(mesh_group, "phi_grid", grid_[2]);
341 ✔
2490
  write_dataset(mesh_group, "origin", origin_);
341 ✔
2491
}
341 ✔
2492

2493
double SphericalMesh::volume(const MeshIndex& ijk) const
935 ✔
2494
{
2495
  double r_i = grid_[0][ijk[0] - 1];
935 ✔
2496
  double r_o = grid_[0][ijk[0]];
935 ✔
2497

2498
  double theta_i = grid_[1][ijk[1] - 1];
935 ✔
2499
  double theta_o = grid_[1][ijk[1]];
935 ✔
2500

2501
  double phi_i = grid_[2][ijk[2] - 1];
935 ✔
2502
  double phi_o = grid_[2][ijk[2]];
935 ✔
2503

2504
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
1,870 ✔
2505
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
935 ✔
2506
}
2507

2508
//==============================================================================
2509
// Helper functions for the C API
2510
//==============================================================================
2511

2512
int check_mesh(int32_t index)
8,093 ✔
2513
{
2514
  if (index < 0 || index >= model::meshes.size()) {
8,093 !
UNCOV
2515
    set_errmsg("Index in meshes array is out of bounds.");
×
UNCOV
2516
    return OPENMC_E_OUT_OF_BOUNDS;
×
2517
  }
2518
  return 0;
2519
}
2520

2521
template<class T>
2522
int check_mesh_type(int32_t index)
1,463 ✔
2523
{
2524
  if (int err = check_mesh(index))
1,463 !
2525
    return err;
2526

2527
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
1,463 !
2528
  if (!mesh) {
1,463 !
UNCOV
2529
    set_errmsg("This function is not valid for input mesh.");
×
UNCOV
2530
    return OPENMC_E_INVALID_TYPE;
×
2531
  }
2532
  return 0;
2533
}
2534

2535
template<class T>
2536
bool is_mesh_type(int32_t index)
2537
{
2538
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
2539
  return mesh;
2540
}
2541

2542
//==============================================================================
2543
// C API functions
2544
//==============================================================================
2545

2546
// Return the type of mesh as a C string
2547
extern "C" int openmc_mesh_get_type(int32_t index, char* type)
1,676 ✔
2548
{
2549
  if (int err = check_mesh(index))
1,676 !
2550
    return err;
2551

2552
  std::strcpy(type, model::meshes[index].get()->get_mesh_type().c_str());
1,676 ✔
2553

2554
  return 0;
1,676 ✔
2555
}
2556

2557
//! Extend the meshes array by n elements
2558
extern "C" int openmc_extend_meshes(
418 ✔
2559
  int32_t n, const char* type, int32_t* index_start, int32_t* index_end)
2560
{
2561
  if (index_start)
418 !
2562
    *index_start = model::meshes.size();
418 ✔
2563
  std::string mesh_type;
418 ✔
2564

2565
  for (int i = 0; i < n; ++i) {
836 ✔
2566
    if (RegularMesh::mesh_type == type) {
418 ✔
2567
      model::meshes.push_back(make_unique<RegularMesh>());
253 ✔
2568
    } else if (RectilinearMesh::mesh_type == type) {
165 ✔
2569
      model::meshes.push_back(make_unique<RectilinearMesh>());
77 ✔
2570
    } else if (CylindricalMesh::mesh_type == type) {
88 ✔
2571
      model::meshes.push_back(make_unique<CylindricalMesh>());
44 ✔
2572
    } else if (SphericalMesh::mesh_type == type) {
44 !
2573
      model::meshes.push_back(make_unique<SphericalMesh>());
44 ✔
2574
    } else {
UNCOV
2575
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2576
    }
2577
  }
2578
  if (index_end)
418 !
UNCOV
2579
    *index_end = model::meshes.size() - 1;
×
2580

2581
  return 0;
418 ✔
2582
}
418 ✔
2583

2584
//! Adds a new unstructured mesh to OpenMC with all supported properties
2585
extern "C" int openmc_add_unstructured_mesh(const char filename[],
3 ✔
2586
  const char library[], double length_multiplier, const char options[],
2587
  int32_t id, int32_t* index)
2588
{
2589
  std::string lib_name(library);
3 ✔
2590
  std::string mesh_file(filename);
3 !
2591
  std::string mesh_options(options ? options : "");
6 !
2592
  bool valid_lib = false;
3 ✔
2593

2594
#ifdef OPENMC_DAGMC_ENABLED
2595
  if (lib_name == MOABMesh::mesh_lib_type) {
1 !
2596
    model::meshes.push_back(
1 ✔
2597
      make_unique<MOABMesh>(mesh_file, length_multiplier, mesh_options));
2 ✔
2598
    valid_lib = true;
1 ✔
2599
  }
2600
#endif
2601

2602
#ifdef OPENMC_LIBMESH_ENABLED
2603
  if (lib_name == LibMesh::mesh_lib_type) {
2 !
2604
    model::meshes.push_back(
2 ✔
2605
      make_unique<LibMesh>(mesh_file, length_multiplier, mesh_options));
4 ✔
2606
    valid_lib = true;
2 ✔
2607
  }
2608
#endif
2609

2610
  if (!valid_lib) {
3 ✔
UNCOV
2611
    set_errmsg(fmt::format("Mesh library {} is not supported "
×
2612
                           "by this build of OpenMC",
2613
      lib_name));
UNCOV
2614
    return OPENMC_E_INVALID_ARGUMENT;
×
2615
  }
2616

2617
  model::meshes.back()->set_id(id);
3 ✔
2618
  *index = model::meshes.size() - 1;
3 ✔
2619

2620
  return 0;
3 ✔
2621
}
3 ✔
2622

2623
//! Return the index in the meshes array of a mesh with a given ID
2624
extern "C" int openmc_get_mesh_index(int32_t id, int32_t* index)
652 ✔
2625
{
2626
  auto pair = model::mesh_map.find(id);
652 ✔
2627
  if (pair == model::mesh_map.end()) {
652 ✔
2628
    set_errmsg("No mesh exists with ID=" + std::to_string(id) + ".");
198 ✔
2629
    return OPENMC_E_INVALID_ID;
99 ✔
2630
  }
2631
  *index = pair->second;
553 ✔
2632
  return 0;
553 ✔
2633
}
2634

2635
//! Return the ID of a mesh
2636
extern "C" int openmc_mesh_get_id(int32_t index, int32_t* id)
3,376 ✔
2637
{
2638
  if (int err = check_mesh(index))
3,376 !
2639
    return err;
2640
  *id = model::meshes[index]->id_;
3,376 ✔
2641
  return 0;
3,376 ✔
2642
}
2643

2644
//! Set the ID of a mesh
2645
extern "C" int openmc_mesh_set_id(int32_t index, int32_t id)
418 ✔
2646
{
2647
  if (int err = check_mesh(index))
418 !
2648
    return err;
2649
  model::meshes[index]->set_id(id);
418 ✔
2650
  return 0;
418 ✔
2651
}
2652

2653
//! Return the name of a mesh
2654
extern "C" int openmc_mesh_get_name(int32_t index, const char** name)
55 ✔
2655
{
2656
  if (int err = check_mesh(index))
55 !
2657
    return err;
2658
  *name = model::meshes[index]->name().c_str();
55 ✔
2659
  return 0;
55 ✔
2660
}
2661

2662
//! Set the name of a mesh
2663
extern "C" int openmc_mesh_set_name(int32_t index, const char* name)
113 ✔
2664
{
2665
  if (int err = check_mesh(index))
113 !
2666
    return err;
2667
  model::meshes[index]->set_name(name);
226 ✔
2668
  return 0;
113 ✔
2669
}
2670

2671
//! Get the number of elements in a mesh
2672
extern "C" int openmc_mesh_get_n_elements(int32_t index, size_t* n)
320 ✔
2673
{
2674
  if (int err = check_mesh(index))
320 !
2675
    return err;
2676
  *n = model::meshes[index]->n_bins();
320 ✔
2677
  return 0;
320 ✔
2678
}
2679

2680
//! Get the volume of each element in the mesh
2681
extern "C" int openmc_mesh_get_volumes(int32_t index, double* volumes)
88 ✔
2682
{
2683
  if (int err = check_mesh(index))
88 !
2684
    return err;
2685
  for (int i = 0; i < model::meshes[index]->n_bins(); ++i) {
968 ✔
2686
    volumes[i] = model::meshes[index]->volume(i);
880 ✔
2687
  }
2688
  return 0;
2689
}
2690

2691
//! Get the bounding box of a mesh
2692
extern "C" int openmc_mesh_bounding_box(int32_t index, double* ll, double* ur)
176 ✔
2693
{
2694
  if (int err = check_mesh(index))
176 !
2695
    return err;
2696

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

2699
  // set lower left corner values
2700
  ll[0] = bbox.min.x;
176 ✔
2701
  ll[1] = bbox.min.y;
176 ✔
2702
  ll[2] = bbox.min.z;
176 ✔
2703

2704
  // set upper right corner values
2705
  ur[0] = bbox.max.x;
176 ✔
2706
  ur[1] = bbox.max.y;
176 ✔
2707
  ur[2] = bbox.max.z;
176 ✔
2708
  return 0;
176 ✔
2709
}
2710

2711
extern "C" int openmc_mesh_material_volumes(int32_t index, int nx, int ny,
232 ✔
2712
  int nz, int table_size, int32_t* materials, double* volumes, double* bboxes)
2713
{
2714
  if (int err = check_mesh(index))
232 !
2715
    return err;
2716

2717
  try {
232 ✔
2718
    model::meshes[index]->material_volumes(
232 ✔
2719
      nx, ny, nz, table_size, materials, volumes, bboxes);
UNCOV
2720
  } catch (const std::exception& e) {
×
UNCOV
2721
    set_errmsg(e.what());
×
2722
    if (starts_with(e.what(), "Mesh")) {
×
2723
      return OPENMC_E_GEOMETRY;
2724
    } else {
UNCOV
2725
      return OPENMC_E_ALLOCATE;
×
2726
    }
UNCOV
2727
  }
×
2728

2729
  return 0;
2730
}
2731

2732
extern "C" int openmc_mesh_get_plot_bins(int32_t index, Position origin,
44 ✔
2733
  Position width, int basis, int* pixels, int32_t* data)
2734
{
2735
  if (int err = check_mesh(index))
44 !
2736
    return err;
2737
  const auto& mesh = model::meshes[index].get();
44 !
2738

2739
  int pixel_width = pixels[0];
44 ✔
2740
  int pixel_height = pixels[1];
44 ✔
2741

2742
  // get pixel size
2743
  double in_pixel = (width[0]) / static_cast<double>(pixel_width);
44 ✔
2744
  double out_pixel = (width[1]) / static_cast<double>(pixel_height);
44 ✔
2745

2746
  // setup basis indices and initial position centered on pixel
2747
  int in_i, out_i;
44 ✔
2748
  Position xyz = origin;
44 ✔
2749
  enum class PlotBasis { xy = 1, xz = 2, yz = 3 };
44 ✔
2750
  PlotBasis basis_enum = static_cast<PlotBasis>(basis);
44 ✔
2751
  switch (basis_enum) {
44 !
2752
  case PlotBasis::xy:
2753
    in_i = 0;
2754
    out_i = 1;
2755
    break;
2756
  case PlotBasis::xz:
2757
    in_i = 0;
2758
    out_i = 2;
2759
    break;
2760
  case PlotBasis::yz:
2761
    in_i = 1;
2762
    out_i = 2;
2763
    break;
UNCOV
2764
  default:
×
UNCOV
2765
    UNREACHABLE();
×
2766
  }
2767

2768
  // set initial position
2769
  xyz[in_i] = origin[in_i] - width[0] / 2. + in_pixel / 2.;
44 ✔
2770
  xyz[out_i] = origin[out_i] + width[1] / 2. - out_pixel / 2.;
44 ✔
2771

2772
#pragma omp parallel
24 ✔
2773
  {
20 ✔
2774
    Position r = xyz;
20 ✔
2775

2776
#pragma omp for
2777
    for (int y = 0; y < pixel_height; y++) {
420 ✔
2778
      r[out_i] = xyz[out_i] - out_pixel * y;
400 ✔
2779
      for (int x = 0; x < pixel_width; x++) {
8,400 ✔
2780
        r[in_i] = xyz[in_i] + in_pixel * x;
8,000 ✔
2781
        data[pixel_width * y + x] = mesh->get_bin(r);
8,000 ✔
2782
      }
2783
    }
2784
  }
2785

2786
  return 0;
44 ✔
2787
}
2788

2789
//! Get the dimension of a regular mesh
2790
extern "C" int openmc_regular_mesh_get_dimension(
22 ✔
2791
  int32_t index, int** dims, int* n)
2792
{
2793
  if (int err = check_mesh_type<RegularMesh>(index))
22 !
2794
    return err;
2795
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
22 !
2796
  *dims = mesh->shape_.data();
22 ✔
2797
  *n = mesh->n_dimension_;
22 ✔
2798
  return 0;
22 ✔
2799
}
2800

2801
//! Set the dimension of a regular mesh
2802
extern "C" int openmc_regular_mesh_set_dimension(
275 ✔
2803
  int32_t index, int n, const int* dims)
2804
{
2805
  if (int err = check_mesh_type<RegularMesh>(index))
275 !
2806
    return err;
2807
  RegularMesh* mesh = dynamic_cast<RegularMesh*>(model::meshes[index].get());
275 !
2808

2809
  // Copy dimension
2810
  mesh->n_dimension_ = n;
275 ✔
2811
  std::copy(dims, dims + n, mesh->shape_.begin());
275 ✔
2812
  return 0;
275 ✔
2813
}
2814

2815
//! Get the regular mesh parameters
2816
extern "C" int openmc_regular_mesh_get_params(
231 ✔
2817
  int32_t index, double** ll, double** ur, double** width, int* n)
2818
{
2819
  if (int err = check_mesh_type<RegularMesh>(index))
231 !
2820
    return err;
2821
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
231 !
2822

2823
  if (m->lower_left_.empty()) {
231 !
UNCOV
2824
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2825
    return OPENMC_E_ALLOCATE;
×
2826
  }
2827

2828
  *ll = m->lower_left_.data();
231 ✔
2829
  *ur = m->upper_right_.data();
231 ✔
2830
  *width = m->width_.data();
231 ✔
2831
  *n = m->n_dimension_;
231 ✔
2832
  return 0;
231 ✔
2833
}
2834

2835
//! Set the regular mesh parameters
2836
extern "C" int openmc_regular_mesh_set_params(
308 ✔
2837
  int32_t index, int n, const double* ll, const double* ur, const double* width)
2838
{
2839
  if (int err = check_mesh_type<RegularMesh>(index))
308 !
2840
    return err;
2841
  RegularMesh* m = dynamic_cast<RegularMesh*>(model::meshes[index].get());
308 !
2842

2843
  if (m->n_dimension_ == -1) {
308 !
UNCOV
2844
    set_errmsg("Need to set mesh dimension before setting parameters.");
×
UNCOV
2845
    return OPENMC_E_UNASSIGNED;
×
2846
  }
2847

2848
  vector<std::size_t> shape = {static_cast<std::size_t>(n)};
308 ✔
2849
  if (ll && ur) {
308 ✔
2850
    m->lower_left_ = tensor::Tensor<double>(ll, n);
286 ✔
2851
    m->upper_right_ = tensor::Tensor<double>(ur, n);
286 ✔
2852
    m->width_ = (m->upper_right_ - m->lower_left_) / m->get_shape_tensor();
1,144 ✔
2853
  } else if (ll && width) {
22 ✔
2854
    m->lower_left_ = tensor::Tensor<double>(ll, n);
11 ✔
2855
    m->width_ = tensor::Tensor<double>(width, n);
11 ✔
2856
    m->upper_right_ = m->lower_left_ + m->get_shape_tensor() * m->width_;
44 ✔
2857
  } else if (ur && width) {
11 !
2858
    m->upper_right_ = tensor::Tensor<double>(ur, n);
11 ✔
2859
    m->width_ = tensor::Tensor<double>(width, n);
11 ✔
2860
    m->lower_left_ = m->upper_right_ - m->get_shape_tensor() * m->width_;
44 ✔
2861
  } else {
UNCOV
2862
    set_errmsg("At least two parameters must be specified.");
×
2863
    return OPENMC_E_INVALID_ARGUMENT;
2864
  }
2865

2866
  // Set material volumes
2867

2868
  // TODO: incorporate this into method in RegularMesh that can be called from
2869
  // here and from constructor
2870
  m->volume_frac_ = 1.0 / m->get_shape_tensor().prod();
308 ✔
2871
  m->element_volume_ = 1.0;
308 ✔
2872
  for (int i = 0; i < m->n_dimension_; i++) {
1,210 ✔
2873
    m->element_volume_ *= m->width_[i];
902 ✔
2874
  }
2875

2876
  return 0;
2877
}
308 ✔
2878

2879
//! Set the mesh parameters for rectilinear, cylindrical and spharical meshes
2880
template<class C>
2881
int openmc_structured_mesh_set_grid_impl(int32_t index, const double* grid_x,
165 ✔
2882
  const int nx, const double* grid_y, const int ny, const double* grid_z,
2883
  const int nz)
2884
{
2885
  if (int err = check_mesh_type<C>(index))
165 !
2886
    return err;
2887

2888
  C* m = dynamic_cast<C*>(model::meshes[index].get());
165 !
2889

2890
  m->n_dimension_ = 3;
165 ✔
2891

2892
  m->grid_[0].reserve(nx);
165 ✔
2893
  m->grid_[1].reserve(ny);
165 ✔
2894
  m->grid_[2].reserve(nz);
165 ✔
2895

2896
  for (int i = 0; i < nx; i++) {
1,144 ✔
2897
    m->grid_[0].push_back(grid_x[i]);
979 ✔
2898
  }
2899
  for (int i = 0; i < ny; i++) {
726 ✔
2900
    m->grid_[1].push_back(grid_y[i]);
561 ✔
2901
  }
2902
  for (int i = 0; i < nz; i++) {
671 ✔
2903
    m->grid_[2].push_back(grid_z[i]);
506 ✔
2904
  }
2905

2906
  int err = m->set_grid();
165 ✔
2907
  return err;
165 ✔
2908
}
2909

2910
//! Get the mesh parameters for rectilinear, cylindrical and spherical meshes
2911
template<class C>
2912
int openmc_structured_mesh_get_grid_impl(int32_t index, double** grid_x,
462 ✔
2913
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2914
{
2915
  if (int err = check_mesh_type<C>(index))
462 !
2916
    return err;
2917
  C* m = dynamic_cast<C*>(model::meshes[index].get());
462 !
2918

2919
  if (m->lower_left_.empty()) {
462 !
UNCOV
2920
    set_errmsg("Mesh parameters have not been set.");
×
UNCOV
2921
    return OPENMC_E_ALLOCATE;
×
2922
  }
2923

2924
  *grid_x = m->grid_[0].data();
462 ✔
2925
  *nx = m->grid_[0].size();
462 ✔
2926
  *grid_y = m->grid_[1].data();
462 ✔
2927
  *ny = m->grid_[1].size();
462 ✔
2928
  *grid_z = m->grid_[2].data();
462 ✔
2929
  *nz = m->grid_[2].size();
462 ✔
2930

2931
  return 0;
462 ✔
2932
}
2933

2934
//! Get the rectilinear mesh grid
2935
extern "C" int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x,
176 ✔
2936
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2937
{
2938
  return openmc_structured_mesh_get_grid_impl<RectilinearMesh>(
176 ✔
2939
    index, grid_x, nx, grid_y, ny, grid_z, nz);
176 ✔
2940
}
2941

2942
//! Set the rectilienar mesh parameters
2943
extern "C" int openmc_rectilinear_mesh_set_grid(int32_t index,
77 ✔
2944
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2945
  const double* grid_z, const int nz)
2946
{
2947
  return openmc_structured_mesh_set_grid_impl<RectilinearMesh>(
77 ✔
2948
    index, grid_x, nx, grid_y, ny, grid_z, nz);
77 ✔
2949
}
2950

2951
//! Get the cylindrical mesh grid
2952
extern "C" int openmc_cylindrical_mesh_get_grid(int32_t index, double** grid_x,
143 ✔
2953
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2954
{
2955
  return openmc_structured_mesh_get_grid_impl<CylindricalMesh>(
143 ✔
2956
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143 ✔
2957
}
2958

2959
//! Set the cylindrical mesh parameters
2960
extern "C" int openmc_cylindrical_mesh_set_grid(int32_t index,
44 ✔
2961
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2962
  const double* grid_z, const int nz)
2963
{
2964
  return openmc_structured_mesh_set_grid_impl<CylindricalMesh>(
44 ✔
2965
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44 ✔
2966
}
2967

2968
//! Get the spherical mesh grid
2969
extern "C" int openmc_spherical_mesh_get_grid(int32_t index, double** grid_x,
143 ✔
2970
  int* nx, double** grid_y, int* ny, double** grid_z, int* nz)
2971
{
2972

2973
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
143 ✔
2974
    index, grid_x, nx, grid_y, ny, grid_z, nz);
143 ✔
2975
  ;
143 ✔
2976
}
2977

2978
//! Set the spherical mesh parameters
2979
extern "C" int openmc_spherical_mesh_set_grid(int32_t index,
44 ✔
2980
  const double* grid_x, const int nx, const double* grid_y, const int ny,
2981
  const double* grid_z, const int nz)
2982
{
2983
  return openmc_structured_mesh_set_grid_impl<SphericalMesh>(
44 ✔
2984
    index, grid_x, nx, grid_y, ny, grid_z, nz);
44 ✔
2985
}
2986

2987
template<class T>
2988
int openmc_periodic_mesh_get_origin_impl(int32_t index, double origin[3])
44 ✔
2989
{
2990
  if (int err = check_mesh(index))
44 !
2991
    return err;
2992
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
44 !
2993
  if (!mesh) {
44 !
UNCOV
2994
    set_errmsg("This mesh is not of the expected type.");
×
UNCOV
2995
    return OPENMC_E_INVALID_TYPE;
×
2996
  }
2997
  const auto& mesh_origin = mesh->origin();
44 ✔
2998
  origin[0] = mesh_origin.x;
44 ✔
2999
  origin[1] = mesh_origin.y;
44 ✔
3000
  origin[2] = mesh_origin.z;
44 ✔
3001
  return 0;
44 ✔
3002
}
3003

3004
template<class T>
3005
int openmc_periodic_mesh_set_origin_impl(int32_t index, const double origin[3])
88 ✔
3006
{
3007
  if (int err = check_mesh(index))
88 !
3008
    return err;
3009
  T* mesh = dynamic_cast<T*>(model::meshes[index].get());
88 !
3010
  if (!mesh) {
88 !
UNCOV
3011
    set_errmsg("This mesh is not of the expected type.");
×
UNCOV
3012
    return OPENMC_E_INVALID_TYPE;
×
3013
  }
3014
  return mesh->set_origin({origin[0], origin[1], origin[2]});
88 ✔
3015
}
3016

3017
extern "C" int openmc_cylindrical_mesh_get_origin(
22 ✔
3018
  int32_t index, double origin[3])
3019
{
3020
  return openmc_periodic_mesh_get_origin_impl<CylindricalMesh>(index, origin);
22 ✔
3021
}
3022

3023
extern "C" int openmc_cylindrical_mesh_set_origin(
44 ✔
3024
  int32_t index, const double origin[3])
3025
{
3026
  return openmc_periodic_mesh_set_origin_impl<CylindricalMesh>(index, origin);
44 ✔
3027
}
3028

3029
extern "C" int openmc_spherical_mesh_get_origin(int32_t index, double origin[3])
22 ✔
3030
{
3031
  return openmc_periodic_mesh_get_origin_impl<SphericalMesh>(index, origin);
22 ✔
3032
}
3033

3034
extern "C" int openmc_spherical_mesh_set_origin(
44 ✔
3035
  int32_t index, const double origin[3])
3036
{
3037
  return openmc_periodic_mesh_set_origin_impl<SphericalMesh>(index, origin);
44 ✔
3038
}
3039

3040
#ifdef OPENMC_DAGMC_ENABLED
3041

3042
const std::string MOABMesh::mesh_lib_type = "moab";
3043

3044
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24 ✔
3045
{
3046
  initialize();
24 ✔
3047
}
24 !
3048

3049
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
3050
{
3051
  initialize();
×
3052
}
×
3053

3054
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier,
1 ✔
3055
  const std::string& options)
1 ✔
3056
  : UnstructuredMesh()
1 ✔
3057
{
3058
  n_dimension_ = 3;
1 ✔
3059
  filename_ = filename;
1 ✔
3060
  options_ = options;
1 ✔
3061
  set_length_multiplier(length_multiplier);
1 ✔
3062
  initialize();
1 ✔
3063
}
1 !
3064

3065
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
1 ✔
3066
{
3067
  mbi_ = external_mbi;
1 ✔
3068
  filename_ = "unknown (external file)";
1 ✔
3069
  this->initialize();
1 ✔
3070
}
1 !
3071

3072
void MOABMesh::initialize()
26 ✔
3073
{
3074

3075
  // Create the MOAB interface and load data from file
3076
  this->create_interface();
26 ✔
3077

3078
  // Initialise MOAB error code
3079
  moab::ErrorCode rval = moab::MB_SUCCESS;
26 ✔
3080

3081
  // Set the dimension
3082
  n_dimension_ = 3;
26 ✔
3083

3084
  // set member range of tetrahedral entities
3085
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
26 ✔
3086
  if (rval != moab::MB_SUCCESS) {
26 !
3087
    fatal_error("Failed to get all tetrahedral elements");
3088
  }
3089

3090
  if (!ehs_.all_of_type(moab::MBTET)) {
26 !
3091
    warning("Non-tetrahedral elements found in unstructured "
×
3092
            "mesh file: " +
3093
            filename_);
3094
  }
3095

3096
  // set member range of vertices
3097
  int vertex_dim = 0;
26 ✔
3098
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
26 ✔
3099
  if (rval != moab::MB_SUCCESS) {
26 !
3100
    fatal_error("Failed to get all vertex handles");
3101
  }
3102

3103
  // make an entity set for all tetrahedra
3104
  // this is used for convenience later in output
3105
  rval = mbi_->create_meshset(moab::MESHSET_SET, tetset_);
26 ✔
3106
  if (rval != moab::MB_SUCCESS) {
26 !
3107
    fatal_error("Failed to create an entity set for the tetrahedral elements");
3108
  }
3109

3110
  rval = mbi_->add_entities(tetset_, ehs_);
26 ✔
3111
  if (rval != moab::MB_SUCCESS) {
26 !
3112
    fatal_error("Failed to add tetrahedra to an entity set.");
3113
  }
3114

3115
  if (length_multiplier_ > 0.0) {
26 ✔
3116
    // get the connectivity of all tets
3117
    moab::Range adj;
1 ✔
3118
    rval = mbi_->get_adjacencies(ehs_, 0, true, adj, moab::Interface::UNION);
1 ✔
3119
    if (rval != moab::MB_SUCCESS) {
1 !
3120
      fatal_error("Failed to get adjacent vertices of tetrahedra.");
3121
    }
3122
    // scale all vertex coords by multiplier (done individually so not all
3123
    // coordinates are in memory twice at once)
3124
    for (auto vert : adj) {
2,333 ✔
3125
      // retrieve coords
3126
      std::array<double, 3> coord;
2,331 ✔
3127
      rval = mbi_->get_coords(&vert, 1, coord.data());
2,331 ✔
3128
      if (rval != moab::MB_SUCCESS) {
2,331 !
3129
        fatal_error("Could not get coordinates of vertex.");
3130
      }
3131
      // scale coords
3132
      for (auto& c : coord) {
9,324 ✔
3133
        c *= length_multiplier_;
6,993 ✔
3134
      }
3135
      // set new coords
3136
      rval = mbi_->set_coords(&vert, 1, coord.data());
2,331 ✔
3137
      if (rval != moab::MB_SUCCESS) {
2,331 !
3138
        fatal_error("Failed to set new vertex coordinates");
3139
      }
3140
    }
3141
  }
1 ✔
3142

3143
  // Determine bounds of mesh
3144
  this->determine_bounds();
26 ✔
3145
}
26 ✔
3146

3147
void MOABMesh::prepare_for_point_location()
22 ✔
3148
{
3149
  // if the KDTree has already been constructed, do nothing
3150
  if (kdtree_)
22 !
3151
    return;
3152

3153
  // build acceleration data structures
3154
  compute_barycentric_data(ehs_);
22 ✔
3155
  build_kdtree(ehs_);
22 ✔
3156
}
3157

3158
void MOABMesh::create_interface()
26 ✔
3159
{
3160
  // Do not create a MOAB instance if one is already in memory
3161
  if (mbi_)
26 ✔
3162
    return;
3163

3164
  // create MOAB instance
3165
  mbi_ = std::make_shared<moab::Core>();
25 !
3166

3167
  // load unstructured mesh file
3168
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
25 ✔
3169
  if (rval != moab::MB_SUCCESS) {
25 !
3170
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
3171
  }
3172
}
3173

3174
void MOABMesh::build_kdtree(const moab::Range& all_tets)
22 ✔
3175
{
3176
  moab::Range all_tris;
22 ✔
3177
  int adj_dim = 2;
22 ✔
3178
  write_message("Getting tet adjacencies...", 7);
22 ✔
3179
  moab::ErrorCode rval = mbi_->get_adjacencies(
22 ✔
3180
    all_tets, adj_dim, true, all_tris, moab::Interface::UNION);
3181
  if (rval != moab::MB_SUCCESS) {
22 !
3182
    fatal_error("Failed to get adjacent triangles for tets");
3183
  }
3184

3185
  if (!all_tris.all_of_type(moab::MBTRI)) {
22 !
3186
    warning("Non-triangle elements found in tet adjacencies in "
×
3187
            "unstructured mesh file: " +
3188
            filename_);
×
3189
  }
3190

3191
  // combine into one range
3192
  moab::Range all_tets_and_tris;
22 ✔
3193
  all_tets_and_tris.merge(all_tets);
22 ✔
3194
  all_tets_and_tris.merge(all_tris);
22 ✔
3195

3196
  // create a kd-tree instance
3197
  write_message(
22 ✔
3198
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
22 ✔
3199
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
22 ✔
3200

3201
  // Determine what options to use
3202
  std::ostringstream options_stream;
22 ✔
3203
  if (options_.empty()) {
22 ✔
3204
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
6 ✔
3205
  } else {
3206
    options_stream << options_;
16 ✔
3207
  }
3208
  moab::FileOptions file_opts(options_stream.str().c_str());
22 ✔
3209

3210
  // Build the k-d tree
3211
  rval = kdtree_->build_tree(all_tets_and_tris, &kdtree_root_, &file_opts);
22 ✔
3212
  if (rval != moab::MB_SUCCESS) {
22 !
3213
    fatal_error("Failed to construct KDTree for the "
3214
                "unstructured mesh file: " +
3215
                filename_);
×
3216
  }
3217
}
22 ✔
3218

3219
void MOABMesh::intersect_track(const moab::CartVect& start,
1,405,608 ✔
3220
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3221
{
3222
  hits.clear();
1,405,608 !
3223

3224
  moab::ErrorCode rval;
1,405,608 ✔
3225
  vector<moab::EntityHandle> tris;
1,405,608 ✔
3226
  // get all intersections with triangles in the tet mesh
3227
  // (distances are relative to the start point, not the previous
3228
  // intersection)
3229
  rval = kdtree_->ray_intersect_triangles(kdtree_root_, FP_COINCIDENT,
1,405,608 ✔
3230
    dir.array(), start.array(), tris, hits, 0, track_len);
3231
  if (rval != moab::MB_SUCCESS) {
1,405,608 !
3232
    fatal_error(
3233
      "Failed to compute intersections on unstructured mesh: " + filename_);
×
3234
  }
3235

3236
  // remove duplicate intersection distances
3237
  std::unique(hits.begin(), hits.end());
1,405,608 ✔
3238

3239
  // sorts by first component of std::pair by default
3240
  std::sort(hits.begin(), hits.end());
1,405,608 ✔
3241
}
1,405,608 ✔
3242

3243
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,405,608 ✔
3244
  vector<int>& bins, vector<double>& lengths) const
3245
{
3246
  moab::CartVect start(r0.x, r0.y, r0.z);
1,405,608 ✔
3247
  moab::CartVect end(r1.x, r1.y, r1.z);
1,405,608 ✔
3248
  moab::CartVect dir(u.x, u.y, u.z);
1,405,608 ✔
3249
  dir.normalize();
1,405,608 ✔
3250

3251
  double track_len = (end - start).length();
1,405,608 ✔
3252
  if (track_len == 0.0)
1,405,608 !
3253
    return;
661,478 ✔
3254

3255
  start -= TINY_BIT * dir;
1,405,608 ✔
3256
  end += TINY_BIT * dir;
1,405,608 ✔
3257

3258
  vector<double> hits;
1,405,608 ✔
3259
  intersect_track(start, dir, track_len, hits);
1,405,608 ✔
3260

3261
  bins.clear();
1,405,608 !
3262
  lengths.clear();
1,405,608 !
3263

3264
  // if there are no intersections the track may lie entirely
3265
  // within a single tet. If this is the case, apply entire
3266
  // score to that tet and return.
3267
  if (hits.size() == 0) {
1,405,608 ✔
3268
    Position midpoint = r0 + u * (track_len * 0.5);
661,478 ✔
3269
    int bin = this->get_bin(midpoint);
661,478 ✔
3270
    if (bin != -1) {
661,478 ✔
3271
      bins.push_back(bin);
211,968 ✔
3272
      lengths.push_back(1.0);
211,968 ✔
3273
    }
3274
    return;
661,478 ✔
3275
  }
3276

3277
  // for each segment in the set of tracks, try to look up a tet
3278
  // at the midpoint of the segment
3279
  Position current = r0;
3280
  double last_dist = 0.0;
3281
  for (const auto& hit : hits) {
5,457,131 ✔
3282
    // get the segment length
3283
    double segment_length = hit - last_dist;
4,713,001 ✔
3284
    last_dist = hit;
4,713,001 ✔
3285
    // find the midpoint of this segment
3286
    Position midpoint = current + u * (segment_length * 0.5);
4,713,001 ✔
3287
    // try to find a tet for this position
3288
    int bin = this->get_bin(midpoint);
4,713,001 ✔
3289

3290
    // determine the start point for this segment
3291
    current = r0 + u * hit;
4,713,001 ✔
3292

3293
    if (bin == -1) {
4,713,001 ✔
3294
      continue;
20,954 ✔
3295
    }
3296

3297
    bins.push_back(bin);
4,692,047 ✔
3298
    lengths.push_back(segment_length / track_len);
4,692,047 ✔
3299
  }
3300

3301
  // tally remaining portion of track after last hit if
3302
  // the last segment of the track is in the mesh but doesn't
3303
  // reach the other side of the tet
3304
  if (hits.back() < track_len) {
744,130 !
3305
    Position segment_start = r0 + u * hits.back();
744,130 ✔
3306
    double segment_length = track_len - hits.back();
744,130 ✔
3307
    Position midpoint = segment_start + u * (segment_length * 0.5);
744,130 ✔
3308
    int bin = this->get_bin(midpoint);
744,130 ✔
3309
    if (bin != -1) {
744,130 ✔
3310
      bins.push_back(bin);
688,365 ✔
3311
      lengths.push_back(segment_length / track_len);
688,365 ✔
3312
    }
3313
  }
3314
};
1,405,608 ✔
3315

3316
moab::EntityHandle MOABMesh::get_tet(const Position& r) const
7,215,010 ✔
3317
{
3318
  moab::CartVect pos(r.x, r.y, r.z);
7,215,010 ✔
3319
  // find the leaf of the kd-tree for this position
3320
  moab::AdaptiveKDTreeIter kdtree_iter;
7,215,010 ✔
3321
  moab::ErrorCode rval = kdtree_->point_search(pos.array(), kdtree_iter);
7,215,010 ✔
3322
  if (rval != moab::MB_SUCCESS) {
7,215,010 ✔
3323
    return 0;
3324
  }
3325

3326
  // retrieve the tet elements of this leaf
3327
  moab::EntityHandle leaf = kdtree_iter.handle();
6,218,763 ✔
3328
  moab::Range tets;
6,218,763 ✔
3329
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
6,218,763 ✔
3330
  if (rval != moab::MB_SUCCESS) {
6,218,763 !
3331
    warning("MOAB error finding tets.");
×
3332
  }
3333

3334
  // loop over the tets in this leaf, returning the containing tet if found
3335
  for (const auto& tet : tets) {
257,906,893 ✔
3336
    if (point_in_tet(pos, tet)) {
257,904,274 ✔
3337
      return tet;
6,216,144 ✔
3338
    }
3339
  }
3340

3341
  // if no tet is found, return an invalid handle
3342
  return 0;
2,619 ✔
3343
}
14,430,020 ✔
3344

3345
double MOABMesh::volume(int bin) const
179,880 ✔
3346
{
3347
  return tet_volume(get_ent_handle_from_bin(bin));
179,880 ✔
3348
}
3349

3350
std::string MOABMesh::library() const
35 ✔
3351
{
3352
  return mesh_lib_type;
35 ✔
3353
}
3354

3355
// Sample position within a tet for MOAB type tets
3356
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
200,410 ✔
3357
{
3358

3359
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410 ✔
3360

3361
  // Get vertex coordinates for MOAB tet
3362
  const moab::EntityHandle* conn1;
200,410 ✔
3363
  int conn1_size;
200,410 ✔
3364
  moab::ErrorCode rval = mbi_->get_connectivity(tet_ent, conn1, conn1_size);
200,410 ✔
3365
  if (rval != moab::MB_SUCCESS || conn1_size != 4) {
200,410 !
3366
    fatal_error(fmt::format(
3367
      "Failed to get tet connectivity or connectivity size ({}) is invalid.",
3368
      conn1_size));
3369
  }
3370
  moab::CartVect p[4];
200,410 ✔
3371
  rval = mbi_->get_coords(conn1, conn1_size, p[0].array());
200,410 ✔
3372
  if (rval != moab::MB_SUCCESS) {
200,410 !
3373
    fatal_error("Failed to get tet coords");
3374
  }
3375

3376
  std::array<Position, 4> tet_verts;
200,410 ✔
3377
  for (int i = 0; i < 4; i++) {
1,002,050 ✔
3378
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
801,640 ✔
3379
  }
3380
  // Samples position within tet using Barycentric stuff
3381
  return this->sample_tet(tet_verts, seed);
200,410 ✔
3382
}
3383

3384
double MOABMesh::tet_volume(moab::EntityHandle tet) const
179,880 ✔
3385
{
3386
  vector<moab::EntityHandle> conn;
179,880 ✔
3387
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
179,880 ✔
3388
  if (rval != moab::MB_SUCCESS) {
179,880 !
3389
    fatal_error("Failed to get tet connectivity");
3390
  }
3391

3392
  moab::CartVect p[4];
179,880 ✔
3393
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
179,880 ✔
3394
  if (rval != moab::MB_SUCCESS) {
179,880 !
3395
    fatal_error("Failed to get tet coords");
3396
  }
3397

3398
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
179,880 ✔
3399
}
179,880 ✔
3400

3401
int MOABMesh::get_bin(Position r) const
7,215,010 ✔
3402
{
3403
  moab::EntityHandle tet = get_tet(r);
7,215,010 ✔
3404
  if (tet == 0) {
7,215,010 ✔
3405
    return -1;
3406
  } else {
3407
    return get_bin_from_ent_handle(tet);
6,216,144 ✔
3408
  }
3409
}
3410

3411
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
22 ✔
3412
{
3413
  moab::ErrorCode rval;
22 ✔
3414

3415
  baryc_data_.clear();
22 !
3416
  baryc_data_.resize(tets.size());
22 ✔
3417

3418
  // compute the barycentric data for each tet element
3419
  // and store it as a 3x3 matrix
3420
  for (auto& tet : tets) {
251,758 ✔
3421
    vector<moab::EntityHandle> verts;
251,736 ✔
3422
    rval = mbi_->get_connectivity(&tet, 1, verts);
251,736 ✔
3423
    if (rval != moab::MB_SUCCESS) {
251,736 !
3424
      fatal_error("Failed to get connectivity of tet on umesh: " + filename_);
×
3425
    }
3426

3427
    moab::CartVect p[4];
251,736 ✔
3428
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
251,736 ✔
3429
    if (rval != moab::MB_SUCCESS) {
251,736 !
3430
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
×
3431
    }
3432

3433
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
251,736 ✔
3434

3435
    // invert now to avoid this cost later
3436
    a = a.transpose().inverse();
251,736 ✔
3437
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
251,736 ✔
3438
  }
251,736 ✔
3439
}
22 ✔
3440

3441
bool MOABMesh::point_in_tet(
257,904,274 ✔
3442
  const moab::CartVect& r, moab::EntityHandle tet) const
3443
{
3444

3445
  moab::ErrorCode rval;
257,904,274 ✔
3446

3447
  // get tet vertices
3448
  vector<moab::EntityHandle> verts;
257,904,274 ✔
3449
  rval = mbi_->get_connectivity(&tet, 1, verts);
257,904,274 ✔
3450
  if (rval != moab::MB_SUCCESS) {
257,904,274 !
3451
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3452
    return false;
3453
  }
3454

3455
  // first vertex is used as a reference point for the barycentric data -
3456
  // retrieve its coordinates
3457
  moab::CartVect p_zero;
257,904,274 ✔
3458
  rval = mbi_->get_coords(verts.data(), 1, p_zero.array());
257,904,274 ✔
3459
  if (rval != moab::MB_SUCCESS) {
257,904,274 !
3460
    warning("Failed to get coordinates of a vertex in "
×
3461
            "unstructured mesh: " +
3462
            filename_);
×
3463
    return false;
3464
  }
3465

3466
  // look up barycentric data
3467
  int idx = get_bin_from_ent_handle(tet);
257,904,274 ✔
3468
  const moab::Matrix3& a_inv = baryc_data_[idx];
257,904,274 ✔
3469

3470
  moab::CartVect bary_coords = a_inv * (r - p_zero);
257,904,274 ✔
3471

3472
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
159,735,131 ✔
3473
          bary_coords[2] >= 0.0 &&
316,040,001 ✔
3474
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,451,029 ✔
3475
}
257,904,274 ✔
3476

3477
int MOABMesh::get_bin_from_index(int idx) const
3478
{
3479
  if (idx >= n_bins()) {
×
3480
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3481
  }
3482
  return ehs_[idx] - ehs_[0];
3483
}
3484

3485
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3486
{
3487
  int bin = get_bin(r);
3488
  *in_mesh = bin != -1;
3489
  return bin;
3490
}
3491

3492
int MOABMesh::get_index_from_bin(int bin) const
3493
{
3494
  return bin;
3495
}
3496

3497
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3498
  Position plot_ll, Position plot_ur) const
3499
{
3500
  // TODO: Implement mesh lines
3501
  return {};
3502
}
3503

3504
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
863,520 ✔
3505
{
3506
  int idx = vert - verts_[0];
863,520 ✔
3507
  if (idx >= n_vertices()) {
863,520 !
3508
    fatal_error(
3509
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
×
3510
  }
3511
  return idx;
863,520 ✔
3512
}
3513

3514
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
264,372,154 ✔
3515
{
3516
  int bin = eh - ehs_[0];
264,372,154 ✔
3517
  if (bin >= n_bins()) {
264,372,154 !
3518
    fatal_error(fmt::format("Invalid bin: {}", bin));
3519
  }
3520
  return bin;
264,372,154 ✔
3521
}
3522

3523
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
596,170 ✔
3524
{
3525
  if (bin >= n_bins()) {
596,170 !
3526
    fatal_error(fmt::format("Invalid bin index: ", bin));
3527
  }
3528
  return ehs_[0] + bin;
596,170 ✔
3529
}
3530

3531
int MOABMesh::n_bins() const
265,184,283 ✔
3532
{
3533
  return ehs_.size();
265,184,283 ✔
3534
}
3535

3536
int MOABMesh::n_surface_bins() const
3537
{
3538
  // collect all triangles in the set of tets for this mesh
3539
  moab::Range tris;
×
3540
  moab::ErrorCode rval;
3541
  rval = mbi_->get_entities_by_type(0, moab::MBTRI, tris);
×
3542
  if (rval != moab::MB_SUCCESS) {
×
3543
    warning("Failed to get all triangles in the mesh instance");
×
3544
    return -1;
3545
  }
3546
  return 2 * tris.size();
×
3547
}
3548

3549
Position MOABMesh::centroid(int bin) const
3550
{
3551
  moab::ErrorCode rval;
3552

3553
  auto tet = this->get_ent_handle_from_bin(bin);
3554

3555
  // look up the tet connectivity
3556
  vector<moab::EntityHandle> conn;
×
3557
  rval = mbi_->get_connectivity(&tet, 1, conn);
×
3558
  if (rval != moab::MB_SUCCESS) {
×
3559
    warning("Failed to get connectivity of a mesh element.");
×
3560
    return {};
3561
  }
3562

3563
  // get the coordinates
3564
  vector<moab::CartVect> coords(conn.size());
×
3565
  rval = mbi_->get_coords(conn.data(), conn.size(), coords[0].array());
×
3566
  if (rval != moab::MB_SUCCESS) {
×
3567
    warning("Failed to get the coordinates of a mesh element.");
×
3568
    return {};
3569
  }
3570

3571
  // compute the centroid of the element vertices
3572
  moab::CartVect centroid(0.0, 0.0, 0.0);
3573
  for (const auto& coord : coords) {
×
3574
    centroid += coord;
3575
  }
3576
  centroid /= double(coords.size());
3577

3578
  return {centroid[0], centroid[1], centroid[2]};
3579
}
3580

3581
int MOABMesh::n_vertices() const
896,208 ✔
3582
{
3583
  return verts_.size();
896,208 ✔
3584
}
3585

3586
Position MOABMesh::vertex(int id) const
90,889 ✔
3587
{
3588

3589
  moab::ErrorCode rval;
90,889 ✔
3590

3591
  moab::EntityHandle vert = verts_[id];
90,889 ✔
3592

3593
  moab::CartVect coords;
90,889 ✔
3594
  rval = mbi_->get_coords(&vert, 1, coords.array());
90,889 ✔
3595
  if (rval != moab::MB_SUCCESS) {
90,889 !
3596
    fatal_error("Failed to get the coordinates of a vertex.");
3597
  }
3598

3599
  return {coords[0], coords[1], coords[2]};
90,889 ✔
3600
}
3601

3602
std::vector<int> MOABMesh::connectivity(int bin) const
215,880 ✔
3603
{
3604
  moab::ErrorCode rval;
215,880 ✔
3605

3606
  auto tet = get_ent_handle_from_bin(bin);
215,880 ✔
3607

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

3616
  std::vector<int> verts(4);
215,880 ✔
3617
  for (int i = 0; i < verts.size(); i++) {
1,079,400 ✔
3618
    verts[i] = get_vert_idx_from_handle(conn[i]);
863,520 ✔
3619
  }
3620

3621
  return verts;
215,880 ✔
3622
}
215,880 ✔
3623

3624
std::pair<moab::Tag, moab::Tag> MOABMesh::get_score_tags(
3625
  std::string score) const
3626
{
3627
  moab::ErrorCode rval;
3628
  // add a tag to the mesh
3629
  // all scores are treated as a single value
3630
  // with an uncertainty
3631
  moab::Tag value_tag;
3632

3633
  // create the value tag if not present and get handle
3634
  double default_val = 0.0;
3635
  auto val_string = score + "_mean";
3636
  rval = mbi_->tag_get_handle(val_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3637
    value_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3638
  if (rval != moab::MB_SUCCESS) {
×
3639
    auto msg =
3640
      fmt::format("Could not create or retrieve the value tag for the score {}"
3641
                  " on unstructured mesh {}",
3642
        score, id_);
×
3643
    fatal_error(msg);
3644
  }
3645

3646
  // create the std dev tag if not present and get handle
3647
  moab::Tag error_tag;
3648
  std::string err_string = score + "_std_dev";
×
3649
  rval = mbi_->tag_get_handle(err_string.c_str(), 1, moab::MB_TYPE_DOUBLE,
×
3650
    error_tag, moab::MB_TAG_DENSE | moab::MB_TAG_CREAT, &default_val);
3651
  if (rval != moab::MB_SUCCESS) {
×
3652
    auto msg =
3653
      fmt::format("Could not create or retrieve the error tag for the score {}"
3654
                  " on unstructured mesh {}",
3655
        score, id_);
×
3656
    fatal_error(msg);
3657
  }
3658

3659
  // return the populated tag handles
3660
  return {value_tag, error_tag};
3661
}
3662

3663
void MOABMesh::add_score(const std::string& score)
3664
{
3665
  auto score_tags = get_score_tags(score);
×
3666
  tag_names_.push_back(score);
3667
}
3668

3669
void MOABMesh::remove_scores()
3670
{
3671
  for (const auto& name : tag_names_) {
×
3672
    auto value_name = name + "_mean";
3673
    moab::Tag tag;
3674
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3675
    if (rval != moab::MB_SUCCESS)
×
3676
      return;
3677

3678
    rval = mbi_->tag_delete(tag);
×
3679
    if (rval != moab::MB_SUCCESS) {
×
3680
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3681
                             " on unstructured mesh {}",
3682
        name, id_);
×
3683
      fatal_error(msg);
3684
    }
3685

3686
    auto std_dev_name = name + "_std_dev";
×
3687
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3688
    if (rval != moab::MB_SUCCESS) {
×
3689
      auto msg =
3690
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3691
                    " on unstructured mesh {}",
3692
          name, id_);
×
3693
    }
3694

3695
    rval = mbi_->tag_delete(tag);
×
3696
    if (rval != moab::MB_SUCCESS) {
×
3697
      auto msg = fmt::format("Failed to delete mesh tag for the score {}"
3698
                             " on unstructured mesh {}",
3699
        name, id_);
×
3700
      fatal_error(msg);
3701
    }
3702
  }
3703
  tag_names_.clear();
3704
}
3705

3706
void MOABMesh::set_score_data(const std::string& score,
3707
  const vector<double>& values, const vector<double>& std_dev)
3708
{
3709
  auto score_tags = this->get_score_tags(score);
×
3710

3711
  moab::ErrorCode rval;
3712
  // set the score value
3713
  rval = mbi_->tag_set_data(score_tags.first, ehs_, values.data());
3714
  if (rval != moab::MB_SUCCESS) {
×
3715
    auto msg = fmt::format("Failed to set the tally value for score '{}' "
3716
                           "on unstructured mesh {}",
3717
      score, id_);
3718
    warning(msg);
×
3719
  }
3720

3721
  // set the error value
3722
  rval = mbi_->tag_set_data(score_tags.second, ehs_, std_dev.data());
3723
  if (rval != moab::MB_SUCCESS) {
×
3724
    auto msg = fmt::format("Failed to set the tally error for score '{}' "
3725
                           "on unstructured mesh {}",
3726
      score, id_);
3727
    warning(msg);
×
3728
  }
3729
}
3730

3731
void MOABMesh::write(const std::string& base_filename) const
3732
{
3733
  // add extension to the base name
3734
  auto filename = base_filename + ".vtk";
3735
  write_message(5, "Writing unstructured mesh {}...", filename);
×
3736
  filename = settings::path_output + filename;
×
3737

3738
  // write the tetrahedral elements of the mesh only
3739
  // to avoid clutter from zero-value data on other
3740
  // elements during visualization
3741
  moab::ErrorCode rval;
3742
  rval = mbi_->write_mesh(filename.c_str(), &tetset_, 1);
×
3743
  if (rval != moab::MB_SUCCESS) {
×
3744
    auto msg = fmt::format("Failed to write unstructured mesh {}", id_);
×
3745
    warning(msg);
×
3746
  }
3747
}
3748

3749
#endif
3750

3751
#ifdef OPENMC_LIBMESH_ENABLED
3752

3753
const std::string LibMesh::mesh_lib_type = "libmesh";
3754

3755
LibMesh::LibMesh(pugi::xml_node node) : UnstructuredMesh(node)
25 ✔
3756
{
3757
  // filename_ and length_multiplier_ will already be set by the
3758
  // UnstructuredMesh constructor
3759
  set_mesh_pointer_from_filename(filename_);
25 ✔
3760
  set_length_multiplier(length_multiplier_);
25 ✔
3761
  initialize();
25 ✔
3762
}
25 ✔
3763

3764
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
×
3765
{
3766
  // filename_ and length_multiplier_ will already be set by the
3767
  // UnstructuredMesh constructor
3768
  set_mesh_pointer_from_filename(filename_);
×
3769
  set_length_multiplier(length_multiplier_);
×
3770
  initialize();
×
3771
}
3772

3773
// create the mesh from a pointer to a libMesh Mesh
3774
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
×
3775
{
3776
  if (!input_mesh.is_replicated()) {
×
3777
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3778
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3779
  }
3780

3781
  m_ = &input_mesh;
3782
  set_length_multiplier(length_multiplier);
×
3783
  initialize();
×
3784
}
3785

3786
// create the mesh from an input file
3787
LibMesh::LibMesh(const std::string& filename, double length_multiplier,
2 ✔
3788
  const std::string& options)
2 ✔
3789
{
3790
  n_dimension_ = 3;
2 ✔
3791
  options_ = options;
2 ✔
3792
  set_mesh_pointer_from_filename(filename);
2 ✔
3793
  set_length_multiplier(length_multiplier);
2 ✔
3794
  initialize();
2 ✔
3795
}
2 ✔
3796

3797
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
27 ✔
3798
{
3799
  filename_ = filename;
27 ✔
3800
  unique_m_ =
27 ✔
3801
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
27 ✔
3802
  m_ = unique_m_.get();
27 ✔
3803
  m_->read(filename_);
27 ✔
3804
}
27 ✔
3805

3806
// build a libMesh equation system for storing values
3807
void LibMesh::build_eqn_sys()
17 ✔
3808
{
3809
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
17 ✔
3810
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
17 ✔
3811
  libMesh::ExplicitSystem& eq_sys =
17 ✔
3812
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
17 ✔
3813
}
17 ✔
3814

3815
// intialize from mesh file
3816
void LibMesh::initialize()
27 ✔
3817
{
3818
  if (!settings::libmesh_comm) {
27 !
3819
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3820
                "communicator.");
3821
  }
3822

3823
  // assuming that unstructured meshes used in OpenMC are 3D
3824
  n_dimension_ = 3;
27 ✔
3825

3826
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3827
  // Otherwise assume that it is prepared by its owning application
3828
  if (unique_m_) {
27 !
3829
    m_->prepare_for_use();
27 ✔
3830
  }
3831

3832
  // ensure that the loaded mesh is 3 dimensional
3833
  if (m_->mesh_dimension() != n_dimension_) {
27 !
3834
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3835
                            "mesh is not a 3D mesh.",
3836
      filename_));
3837
  }
3838

3839
  for (int i = 0; i < num_threads(); i++) {
73 ✔
3840
    pl_.emplace_back(m_->sub_point_locator());
46 ✔
3841
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
46 ✔
3842
    pl_.back()->enable_out_of_mesh_mode();
46 ✔
3843
  }
3844

3845
  // store first element in the mesh to use as an offset for bin indices
3846
  auto first_elem = *m_->elements_begin();
54 ✔
3847
  first_element_id_ = first_elem->id();
27 ✔
3848

3849
  // bounding box for the mesh for quick rejection checks
3850
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
27 ✔
3851
  libMesh::Point ll = bbox_.min();
27 ✔
3852
  libMesh::Point ur = bbox_.max();
27 ✔
3853
  if (length_multiplier_ > 0.0) {
27 ✔
3854
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
4 ✔
3855
      length_multiplier_ * ll(2)};
2 ✔
3856
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
2 ✔
3857
      length_multiplier_ * ur(2)};
2 ✔
3858
  } else {
3859
    lower_left_ = {ll(0), ll(1), ll(2)};
25 ✔
3860
    upper_right_ = {ur(0), ur(1), ur(2)};
25 ✔
3861
  }
3862
}
27 ✔
3863

3864
// Sample position within a tet for LibMesh type tets
3865
Position LibMesh::sample_element(int32_t bin, uint64_t* seed) const
400,820 ✔
3866
{
3867
  const auto& elem = get_element_from_bin(bin);
400,820 ✔
3868
  // Get tet vertex coordinates from LibMesh
3869
  std::array<Position, 4> tet_verts;
400,820 ✔
3870
  for (int i = 0; i < elem.n_nodes(); i++) {
2,004,100 ✔
3871
    const auto& node_ref = elem.node_ref(i);
1,603,280 ✔
3872
    tet_verts[i] = {node_ref(0), node_ref(1), node_ref(2)};
1,603,280 ✔
3873
  }
3874
  // Samples position within tet using Barycentric coordinates
3875
  Position sampled_position = this->sample_tet(tet_verts, seed);
400,820 ✔
3876
  if (length_multiplier_ > 0.0) {
400,820 !
3877
    return length_multiplier_ * sampled_position;
3878
  } else {
3879
    return sampled_position;
400,820 ✔
3880
  }
3881
}
3882

3883
Position LibMesh::centroid(int bin) const
3884
{
3885
  const auto& elem = this->get_element_from_bin(bin);
3886
  auto centroid = elem.vertex_average();
3887
  if (length_multiplier_ > 0.0) {
×
3888
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3889
  } else {
3890
    return {centroid(0), centroid(1), centroid(2)};
3891
  }
3892
}
3893

3894
int LibMesh::n_vertices() const
47,310 ✔
3895
{
3896
  return m_->n_nodes();
47,310 ✔
3897
}
3898

3899
Position LibMesh::vertex(int vertex_id) const
47,266 ✔
3900
{
3901
  const auto& node_ref = m_->node_ref(vertex_id);
47,266 ✔
3902
  if (length_multiplier_ > 0.0) {
47,266 ✔
3903
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
4,662 ✔
3904
  } else {
3905
    return {node_ref(0), node_ref(1), node_ref(2)};
42,604 ✔
3906
  }
3907
}
3908

3909
std::vector<int> LibMesh::connectivity(int elem_id) const
291,856 ✔
3910
{
3911
  std::vector<int> conn;
291,856 ✔
3912
  const auto* elem_ptr = m_->elem_ptr(elem_id);
291,856 ✔
3913
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
1,475,280 ✔
3914
    conn.push_back(elem_ptr->node_id(i));
1,183,424 ✔
3915
  }
3916
  return conn;
291,856 ✔
3917
}
3918

3919
std::string LibMesh::library() const
39 ✔
3920
{
3921
  return mesh_lib_type;
39 ✔
3922
}
3923

3924
int LibMesh::n_bins() const
1,823,785 ✔
3925
{
3926
  return m_->n_elem();
1,823,785 ✔
3927
}
3928

3929
int LibMesh::n_surface_bins() const
3930
{
3931
  int n_bins = 0;
3932
  for (int i = 0; i < this->n_bins(); i++) {
×
3933
    const libMesh::Elem& e = get_element_from_bin(i);
3934
    n_bins += e.n_faces();
3935
    // if this is a boundary element, it will only be visited once,
3936
    // the number of surface bins is incremented to
3937
    for (auto neighbor_ptr : e.neighbor_ptr_range()) {
×
3938
      // null neighbor pointer indicates a boundary face
3939
      if (!neighbor_ptr) {
×
3940
        n_bins++;
3941
      }
3942
    }
3943
  }
3944
  return n_bins;
3945
}
3946

3947
void LibMesh::add_score(const std::string& var_name)
17 ✔
3948
{
3949
  if (!equation_systems_) {
17 !
3950
    build_eqn_sys();
17 ✔
3951
  }
3952

3953
  // check if this is a new variable
3954
  std::string value_name = var_name + "_mean";
17 ✔
3955
  if (!variable_map_.count(value_name)) {
17 ✔
3956
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17 ✔
3957
    auto var_num =
17 ✔
3958
      eqn_sys.add_variable(value_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17 ✔
3959
    variable_map_[value_name] = var_num;
17 ✔
3960
  }
3961

3962
  std::string std_dev_name = var_name + "_std_dev";
17 ✔
3963
  // check if this is a new variable
3964
  if (!variable_map_.count(std_dev_name)) {
17 ✔
3965
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17 ✔
3966
    auto var_num =
17 ✔
3967
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
17 ✔
3968
    variable_map_[std_dev_name] = var_num;
17 ✔
3969
  }
3970
}
17 ✔
3971

3972
void LibMesh::remove_scores()
17 ✔
3973
{
3974
  if (equation_systems_) {
17 !
3975
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17 ✔
3976
    eqn_sys.clear();
17 ✔
3977
    variable_map_.clear();
17 ✔
3978
  }
3979
}
17 ✔
3980

3981
void LibMesh::set_score_data(const std::string& var_name,
17 ✔
3982
  const vector<double>& values, const vector<double>& std_dev)
3983
{
3984
  if (!equation_systems_) {
17 !
3985
    build_eqn_sys();
3986
  }
3987

3988
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17 ✔
3989

3990
  if (!eqn_sys.is_initialized()) {
17 !
3991
    equation_systems_->init();
17 ✔
3992
  }
3993

3994
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17 ✔
3995

3996
  // look up the value variable
3997
  std::string value_name = var_name + "_mean";
17 ✔
3998
  unsigned int value_num = variable_map_.at(value_name);
17 ✔
3999
  // look up the std dev variable
4000
  std::string std_dev_name = var_name + "_std_dev";
17 ✔
4001
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
17 ✔
4002

4003
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
199,763 ✔
4004
       it++) {
4005
    if (!(*it)->active()) {
99,856 !
4006
      continue;
4007
    }
4008

4009
    auto bin = get_bin_from_element(*it);
99,856 ✔
4010

4011
    // set value
4012
    vector<libMesh::dof_id_type> value_dof_indices;
99,856 ✔
4013
    dof_map.dof_indices(*it, value_dof_indices, value_num);
99,856 ✔
4014
    assert(value_dof_indices.size() == 1);
99,856 ✔
4015
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
99,856 ✔
4016

4017
    // set std dev
4018
    vector<libMesh::dof_id_type> std_dev_dof_indices;
99,856 ✔
4019
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
99,856 ✔
4020
    assert(std_dev_dof_indices.size() == 1);
99,856 ✔
4021
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
99,856 ✔
4022
  }
99,873 ✔
4023
}
17 ✔
4024

4025
void LibMesh::write(const std::string& filename) const
17 ✔
4026
{
4027
  // A serial libMesh communicator considers every OpenMC rank to be its
4028
  // processor 0. Restrict the non-collective write to the OpenMC master in
4029
  // that case. With a parallel communicator, all ranks must participate in
4030
  // libMesh's solution assembly.
4031
  if (settings::libmesh_comm->size() == 1 && !mpi::master) {
17 !
4032
    return;
4033
  }
4034

4035
  write_message(fmt::format(
17 ✔
4036
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17 ✔
4037
  libMesh::ExodusII_IO exo(*m_);
17 ✔
4038
  std::set<std::string> systems_out = {eq_system_name_};
34 !
4039
  exo.write_discontinuous_exodusII(
17 ✔
4040
    filename + ".e", *equation_systems_, &systems_out);
34 ✔
4041
}
17 ✔
4042

4043
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
4044
  vector<int>& bins, vector<double>& lengths) const
4045
{
4046
  // TODO: Implement triangle crossings here
4047
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
4048
}
4049

4050
int LibMesh::get_bin(Position r) const
2,377,206 ✔
4051
{
4052
  // look-up a tet using the point locator
4053
  libMesh::Point p(r.x, r.y, r.z);
2,377,206 !
4054

4055
  if (length_multiplier_ > 0.0) {
2,377,206 !
4056
    // Scale the point down
4057
    p /= length_multiplier_;
2,377,206 ✔
4058
  }
4059

4060
  // quick rejection check
4061
  if (!bbox_.contains_point(p)) {
2,377,206 ✔
4062
    return -1;
4063
  }
4064

4065
  const auto& point_locator = pl_.at(thread_num());
1,433,042 ✔
4066

4067
  const auto elem_ptr = (*point_locator)(p);
1,433,042 ✔
4068
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,433,042 ✔
4069
}
2,377,206 ✔
4070

4071
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,531,788 ✔
4072
{
4073
  int bin = elem->id() - first_element_id_;
1,531,788 ✔
4074
  if (bin >= n_bins() || bin < 0) {
1,531,788 !
4075
    fatal_error(fmt::format("Invalid bin: {}", bin));
4076
  }
4077
  return bin;
1,531,788 ✔
4078
}
4079

4080
std::pair<vector<double>, vector<double>> LibMesh::plot(
4081
  Position plot_ll, Position plot_ur) const
4082
{
4083
  return {};
4084
}
4085

4086
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
793,460 ✔
4087
{
4088
  return m_->elem_ref(bin);
793,460 ✔
4089
}
4090

4091
double LibMesh::volume(int bin) const
392,640 ✔
4092
{
4093
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
392,640 ✔
4094
         length_multiplier_ * length_multiplier_;
392,640 ✔
4095
}
4096

4097
AdaptiveLibMesh::AdaptiveLibMesh(libMesh::MeshBase& input_mesh,
4098
  double length_multiplier,
4099
  const std::set<libMesh::subdomain_id_type>& block_ids)
4100
  : LibMesh(input_mesh, length_multiplier), block_ids_(block_ids),
4101
    block_restrict_(!block_ids_.empty()),
×
4102
    num_active_(
×
4103
      block_restrict_
4104
        ? std::distance(m_->active_subdomain_set_elements_begin(block_ids_),
×
4105
            m_->active_subdomain_set_elements_end(block_ids_))
×
4106
        : m_->n_active_elem())
×
4107
{
4108
  // if the mesh is adaptive elements aren't guaranteed by libMesh to be
4109
  // contiguous in ID space, so we need to map from bin indices (defined over
4110
  // active elements) to global dof ids
4111
  bin_to_elem_map_.reserve(num_active_);
×
4112
  elem_to_bin_map_.resize(m_->n_elem(), -1);
×
4113
  auto begin = block_restrict_
4114
                 ? m_->active_subdomain_set_elements_begin(block_ids_)
×
4115
                 : m_->active_elements_begin();
×
4116
  auto end = block_restrict_ ? m_->active_subdomain_set_elements_end(block_ids_)
×
4117
                             : m_->active_elements_end();
×
4118
  for (const auto& elem : libMesh::as_range(begin, end)) {
×
4119
    bin_to_elem_map_.push_back(elem->id());
×
4120
    elem_to_bin_map_[elem->id()] = bin_to_elem_map_.size() - 1;
×
4121
  }
4122
}
4123

4124
int AdaptiveLibMesh::n_bins() const
4125
{
4126
  return num_active_;
4127
}
4128

4129
void AdaptiveLibMesh::add_score(const std::string& var_name)
4130
{
4131
  warning(fmt::format(
×
4132
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4133
    this->id_));
4134
}
4135

4136
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
4137
  const vector<double>& values, const vector<double>& std_dev)
4138
{
4139
  warning(fmt::format(
×
4140
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4141
    this->id_));
4142
}
4143

4144
void AdaptiveLibMesh::write(const std::string& filename) const
4145
{
4146
  warning(fmt::format(
×
4147
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
4148
    this->id_));
4149
}
4150

4151
int AdaptiveLibMesh::get_bin(Position r) const
4152
{
4153
  // look-up a tet using the point locator
4154
  libMesh::Point p(r.x, r.y, r.z);
×
4155

4156
  if (length_multiplier_ > 0.0) {
×
4157
    // Scale the point down
4158
    p /= length_multiplier_;
4159
  }
4160

4161
  // quick rejection check
4162
  if (!bbox_.contains_point(p)) {
×
4163
    return -1;
4164
  }
4165

4166
  const auto& point_locator = pl_.at(thread_num());
×
4167

4168
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4169
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4170
}
4171

4172
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4173
{
4174
  int bin = elem_to_bin_map_[elem->id()];
4175
  if (bin >= n_bins() || bin < 0) {
×
4176
    fatal_error(fmt::format("Invalid bin: {}", bin));
4177
  }
4178
  return bin;
4179
}
4180

4181
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4182
{
4183
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4184
}
4185

4186
#endif // OPENMC_LIBMESH_ENABLED
4187

4188
//==============================================================================
4189
// Non-member functions
4190
//==============================================================================
4191

4192
void read_meshes(pugi::xml_node root)
14,414 ✔
4193
{
4194
  std::unordered_set<int> mesh_ids;
14,414 ✔
4195

4196
  for (auto node : root.children("mesh")) {
17,853 ✔
4197
    // Check to make sure multiple meshes in the same file don't share IDs
4198
    int id = std::stoi(get_node_value(node, "id"));
6,878 ✔
4199
    if (contains(mesh_ids, id)) {
6,878 !
UNCOV
4200
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4201
                              "'{}' in the same input file",
4202
        id));
4203
    }
4204
    mesh_ids.insert(id);
3,439 ✔
4205

4206
    // If we've already read a mesh with the same ID in a *different* file,
4207
    // assume it is the same here
4208
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,439 !
UNCOV
4209
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
UNCOV
4210
      continue;
×
4211
    }
4212

4213
    std::string mesh_type;
3,439 ✔
4214
    if (check_for_node(node, "type")) {
3,439 ✔
4215
      mesh_type = get_node_value(node, "type", true, true);
972 ✔
4216
    } else {
4217
      mesh_type = "regular";
2,467 ✔
4218
    }
4219

4220
    // determine the mesh library to use
4221
    std::string mesh_lib;
3,439 ✔
4222
    if (check_for_node(node, "library")) {
3,439 ✔
4223
      mesh_lib = get_node_value(node, "library", true, true);
49 !
4224
    }
4225

4226
    Mesh::create(node, mesh_type, mesh_lib);
3,439 ✔
4227
  }
3,439 ✔
4228
}
14,414 ✔
4229

4230
void read_meshes(hid_t group)
48 ✔
4231
{
4232
  std::unordered_set<int> mesh_ids;
48 ✔
4233

4234
  std::vector<int> ids;
48 ✔
4235
  read_attribute(group, "ids", ids);
48 ✔
4236

4237
  for (auto id : ids) {
107 ✔
4238

4239
    // Check to make sure multiple meshes in the same file don't share IDs
4240
    if (contains(mesh_ids, id)) {
118 !
UNCOV
4241
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4242
                              "'{}' in the same HDF5 input file",
4243
        id));
4244
    }
4245
    mesh_ids.insert(id);
59 ✔
4246

4247
    // If we've already read a mesh with the same ID in a *different* file,
4248
    // assume it is the same here
4249
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
59 ✔
4250
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
33 ✔
4251
      continue;
33 ✔
4252
    }
4253

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

4257
    std::string mesh_type;
26 ✔
4258
    if (object_exists(mesh_group, "type")) {
26 !
4259
      read_dataset(mesh_group, "type", mesh_type);
26 ✔
4260
    } else {
UNCOV
4261
      mesh_type = "regular";
×
4262
    }
4263

4264
    // determine the mesh library to use
4265
    std::string mesh_lib;
26 ✔
4266
    if (object_exists(mesh_group, "library")) {
26 !
UNCOV
4267
      read_dataset(mesh_group, "library", mesh_lib);
×
4268
    }
4269

4270
    Mesh::create(mesh_group, mesh_type, mesh_lib);
26 ✔
4271
  }
26 ✔
4272
}
96 ✔
4273

4274
void meshes_to_hdf5(hid_t group)
7,987 ✔
4275
{
4276
  // Write number of meshes
4277
  hid_t meshes_group = create_group(group, "meshes");
7,987 ✔
4278
  int32_t n_meshes = model::meshes.size();
7,987 ✔
4279
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,987 ✔
4280

4281
  if (n_meshes > 0) {
7,987 ✔
4282
    // Write IDs of meshes
4283
    vector<int> ids;
2,447 ✔
4284
    for (const auto& m : model::meshes) {
5,638 ✔
4285
      m->to_hdf5(meshes_group);
3,191 ✔
4286
      ids.push_back(m->id_);
3,191 ✔
4287
    }
4288
    write_attribute(meshes_group, "ids", ids);
2,447 ✔
4289
  }
2,447 ✔
4290

4291
  close_group(meshes_group);
7,987 ✔
4292
}
7,987 ✔
4293

4294
void free_memory_mesh()
9,430 ✔
4295
{
4296
  model::meshes.clear();
9,430 ✔
4297
  model::mesh_map.clear();
9,430 ✔
4298
}
9,430 ✔
4299

4300
extern "C" int n_meshes()
374 ✔
4301
{
4302
  return model::meshes.size();
374 ✔
4303
}
4304

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