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

openmc-dev / openmc / 27291478556

10 Jun 2026 04:47PM UTC coverage: 80.477% (-0.9%) from 81.356%
27291478556

Pull #3951

github

web-flow
Merge a9c9d6b5d into 02eb999af
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16680 of 24156 branches covered (69.05%)

Branch coverage included in aggregate %.

70 of 119 new or added lines in 10 files covered. (58.82%)

1139 existing lines in 52 files now uncovered.

57358 of 67843 relevant lines covered (84.55%)

17252148.68 hits per line

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

66.94
/src/mesh.cpp
1
#include "openmc/mesh.h"
2
#include <algorithm> // for copy, equal, min, min_element
3
#include <cassert>
4
#include <cstdint>        // for uint64_t
5
#include <cstring>        // for memcpy
6
#define _USE_MATH_DEFINES // to make M_PI declared in Intel and MSVC compilers
7
#include <cmath>          // for ceil
8
#include <cstddef>        // for size_t
9
#include <numeric>        // for accumulate
10
#include <string>
11

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

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

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

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

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

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

58
#include "hdf5.h"
59

60
namespace openmc {
61

62
//==============================================================================
63
// Global variables
64
//==============================================================================
65

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

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

76
namespace model {
77

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

81
} // namespace model
82

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

90
//==============================================================================
91
// Helper functions
92
//==============================================================================
93

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

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

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

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

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

142
// Helper function equivalent to std::bit_cast in C++20
143
template<typename To, typename From>
144
inline To bit_cast_value(const From& value)
6,995,376✔
145
{
146
  To out;
147
  std::memcpy(&out, &value, sizeof(To));
7,102✔
148
  return out;
149
}
150

151
inline void atomic_update_double(double* ptr, double value, bool is_min)
6,995,376✔
152
{
153
#if defined(__GNUC__) || defined(__clang__)
154
  using may_alias_uint64_t [[gnu::may_alias]] = uint64_t;
6,995,376✔
155
  auto* bits_ptr = reinterpret_cast<may_alias_uint64_t*>(ptr);
6,995,376✔
156
  uint64_t current_bits = __atomic_load_n(bits_ptr, __ATOMIC_SEQ_CST);
6,995,376✔
157
  double current = bit_cast_value<double>(current_bits);
6,995,376✔
158
  while (is_min ? (value < current) : (value > current)) {
6,995,376✔
159
    uint64_t desired_bits = bit_cast_value<uint64_t>(value);
7,102✔
160
    uint64_t expected_bits = current_bits;
7,102✔
161
    if (__atomic_compare_exchange_n(bits_ptr, &expected_bits, desired_bits,
7,102!
162
          false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
163
      return;
6,995,376✔
164
    }
UNCOV
165
    current_bits = expected_bits;
×
UNCOV
166
    current = bit_cast_value<double>(current_bits);
×
167
  }
168

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

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

189
inline void atomic_max_double(double* ptr, double value)
3,497,688✔
190
{
191
  atomic_update_double(ptr, value, false);
1,165,896✔
192
}
1,165,896✔
193

194
inline void atomic_min_double(double* ptr, double value)
3,497,688✔
195
{
196
  atomic_update_double(ptr, value, true);
1,165,896✔
197
}
198

199
namespace detail {
200

201
//==============================================================================
202
// MaterialVolumes implementation
203
//==============================================================================
204

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

214
  // Loop for linear probing
215
  for (int attempt = 0; attempt < table_size_; ++attempt) {
1,648,330!
216
    // Determine slot to check, making sure it is positive
217
    int slot = (index_material + attempt) % table_size_;
1,648,330✔
218
    if (slot < 0)
1,648,330✔
219
      slot += table_size_;
1,062,496✔
220
    int32_t* slot_ptr = &this->materials(index_elem, slot);
1,648,330✔
221

222
    // Non-atomic read of current material
223
    int32_t current_val = *slot_ptr;
1,648,330✔
224

225
    // Found the desired material; accumulate volume and bbox
226
    if (current_val == index_material) {
1,648,330✔
227
#pragma omp atomic
228
      this->volumes(index_elem, slot) += volume;
1,648,048✔
229
      if (bbox) {
1,648,048✔
230
        atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
1,165,866✔
231
        atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
1,165,866✔
232
        atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
1,165,866✔
233
        atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
1,165,866✔
234
        atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
1,165,866✔
235
        atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
1,165,866✔
236
      }
237
      return;
1,648,048✔
238
    }
239

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

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

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

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

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

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

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

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

328
} // namespace detail
329

330
//==============================================================================
331
// Mesh implementation
332
//==============================================================================
333

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

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

367
  return model::meshes.back();
514✔
368
}
369

370
Mesh::Mesh(pugi::xml_node node)
522✔
371
{
372
  // Read mesh id
373
  id_ = std::stoi(get_node_value(node, "id"));
1,044✔
374
  if (check_for_node(node, "name"))
522✔
375
    name_ = get_node_value(node, "name");
2✔
376
}
522✔
377

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

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

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

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

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

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

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

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

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

425
vector<double> Mesh::volumes() const
46✔
426
{
427
  vector<double> volumes(n_bins());
46✔
428
  for (int i = 0; i < n_bins(); i++) {
193,502✔
429
    volumes[i] = this->volume(i);
193,456✔
430
  }
431
  return volumes;
46✔
432
}
×
433

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

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

456
  Timer timer;
38✔
457
  timer.start();
38✔
458

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

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

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

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

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

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

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

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

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

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

516
      // Loop over rays on face of bounding box
517
#pragma omp for collapse(2)
518
      for (int i1 = i1_start; i1 < i1_end; ++i1) {
7,040✔
519
        for (int i2 = 0; i2 < n2; ++i2) {
1,232,088✔
520
          site.r[ax1] = min1 + (i1 + 0.5) * d1;
1,225,138✔
521
          site.r[ax2] = min2 + (i2 + 0.5) * d2;
1,225,138✔
522

523
          p.from_source(&site);
1,225,138✔
524

525
          // Determine particle's location
526
          if (!exhaustive_find_cell(p)) {
1,225,138✔
527
            out_of_model = true;
15,972✔
528
            continue;
15,972✔
529
          }
530

531
          // Set birth cell attribute
532
          if (p.cell_born() == C_NONE)
1,209,166!
533
            p.cell_born() = p.lowest_coord().cell();
1,209,166✔
534

535
          // Initialize last cells from current cell
536
          for (int j = 0; j < p.n_coord(); ++j) {
2,418,332✔
537
            p.cell_last(j) = p.coord(j).cell();
1,209,166✔
538
          }
539
          p.n_coord_last() = p.n_coord();
1,209,166✔
540

541
          while (true) {
1,912,574✔
542
            // Ray trace from r_start to r_end
543
            Position r0 = p.r();
1,560,870✔
544
            double max_distance = bbox.max[axis] - r0[axis];
1,560,870✔
545

546
            // Find the distance to the nearest boundary
547
            BoundaryInfo boundary = distance_to_boundary(p);
1,560,870✔
548

549
            // Advance particle forward
550
            double distance = std::min(boundary.distance(), max_distance);
1,560,870✔
551
            p.move_distance(distance);
1,560,870✔
552

553
            // Determine what mesh elements were crossed by particle
554
            bins.clear();
1,560,870✔
555
            length_fractions.clear();
1,560,870✔
556
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
1,560,870✔
557

558
            // Add volumes to any mesh elements that were crossed
559
            int i_material = p.material();
1,560,870✔
560
            if (i_material != C_NONE) {
1,560,870✔
561
              i_material = model::materials[i_material]->id();
494,094✔
562
            }
563
            double cumulative_frac = 0.0;
1,560,870✔
564
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
3,209,200✔
565
              int mesh_index = bins[i_bin];
1,648,330✔
566
              double length = distance * length_fractions[i_bin];
1,648,330✔
567
              double volume = length * d1 * d2;
1,648,330✔
568

569
              if (compute_bboxes) {
1,648,330✔
570
                double axis_start = r0[axis] + distance * cumulative_frac;
1,165,896✔
571
                double axis_end = axis_start + length;
1,165,896✔
572
                cumulative_frac += length_fractions[i_bin];
1,165,896✔
573

574
                Position contrib_min = site.r;
1,165,896✔
575
                Position contrib_max = site.r;
1,165,896✔
576

577
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
1,165,896✔
578
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
1,165,896✔
579
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
1,165,896✔
580
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
1,165,896✔
581
                contrib_min[axis] = std::min(axis_start, axis_end);
1,165,896!
582
                contrib_max[axis] = std::max(axis_start, axis_end);
2,331,792!
583

584
                BoundingBox contrib_bbox {contrib_min, contrib_max};
1,165,896✔
585
                contrib_bbox &= bbox;
1,165,896✔
586

587
                result.add_volume(
1,165,896✔
588
                  mesh_index, i_material, volume, &contrib_bbox);
589
              } else {
590
                // Add volume to result
591
                result.add_volume(mesh_index, i_material, volume);
482,434✔
592
              }
593
            }
594

595
            if (distance == max_distance)
1,560,870✔
596
              break;
597

598
            // cross next geometric surface
599
            for (int j = 0; j < p.n_coord(); ++j) {
703,408✔
600
              p.cell_last(j) = p.coord(j).cell();
351,704✔
601
            }
602
            p.n_coord_last() = p.n_coord();
351,704✔
603

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

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

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

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

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

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

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

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

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

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

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

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

739
  // Write mesh type
740
  write_dataset(mesh_group, "type", this->get_mesh_type());
562✔
741

742
  // Write mesh ID
743
  write_attribute(mesh_group, "id", id_);
562✔
744

745
  // Write mesh name
746
  write_dataset(mesh_group, "name", name_);
562✔
747

748
  // Write mesh data
749
  this->to_hdf5_inner(mesh_group);
562✔
750

751
  // Close group
752
  close_group(mesh_group);
562✔
753
}
562✔
754

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

759
std::string StructuredMesh::bin_label(int bin) const
934,960✔
760
{
761
  MeshIndex ijk = get_indices_from_bin(bin);
934,960✔
762

763
  if (n_dimension_ > 2) {
934,960✔
764
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
932,062✔
765
  } else if (n_dimension_ > 1) {
2,898✔
766
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
2,848✔
767
  } else {
768
    return fmt::format("Mesh Index ({})", ijk[0]);
50✔
769
  }
770
}
771

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

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

784
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
254,829!
785
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
254,829!
786

787
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
254,829!
788
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
254,829!
789

790
  return {x_min + (x_max - x_min) * prn(seed),
254,829✔
791
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
254,829✔
792
}
793

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

UNCOV
798
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
×
799
{
UNCOV
800
  n_dimension_ = 3;
×
801

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

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

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

UNCOV
826
  if (check_for_node(node, "options")) {
×
UNCOV
827
    options_ = get_node_value(node, "options");
×
828
  }
829

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

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

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

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

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

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

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

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

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

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

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

UNCOV
931
std::string UnstructuredMesh::get_mesh_type() const
×
932
{
UNCOV
933
  return mesh_type;
×
934
}
935

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

UNCOV
942
std::string UnstructuredMesh::bin_label(int bin) const
×
943
{
UNCOV
944
  return fmt::format("Mesh Index ({})", bin);
×
945
};
946

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

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

958
  // write vertex coordinates
UNCOV
959
  tensor::Tensor<double> vertices(
×
UNCOV
960
    {static_cast<size_t>(this->n_vertices()), static_cast<size_t>(3)});
×
UNCOV
961
  for (int i = 0; i < this->n_vertices(); i++) {
×
UNCOV
962
    auto v = this->vertex(i);
×
UNCOV
963
    vertices.slice(i) = {v.x, v.y, v.z};
×
964
  }
UNCOV
965
  write_dataset(mesh_group, "vertices", vertices);
×
966

UNCOV
967
  int num_elem_skipped = 0;
×
968

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

UNCOV
978
    volumes.emplace_back(this->volume(i));
×
979

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

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

UNCOV
1005
  write_dataset(mesh_group, "volumes", volumes);
×
UNCOV
1006
  write_dataset(mesh_group, "connectivity", connectivity);
×
UNCOV
1007
  write_dataset(mesh_group, "element_types", elem_types);
×
UNCOV
1008
}
×
1009

UNCOV
1010
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
×
1011
{
UNCOV
1012
  length_multiplier_ = length_multiplier;
×
UNCOV
1013
}
×
1014

UNCOV
1015
ElementType UnstructuredMesh::element_type(int bin) const
×
1016
{
UNCOV
1017
  auto conn = connectivity(bin);
×
1018

UNCOV
1019
  if (conn.size() == 4)
×
1020
    return ElementType::LINEAR_TET;
1021
  else if (conn.size() == 8)
×
1022
    return ElementType::LINEAR_HEX;
1023
  else
1024
    return ElementType::UNSUPPORTED;
×
UNCOV
1025
}
×
1026

1027
StructuredMesh::MeshIndex StructuredMesh::get_indices(
289,887,190✔
1028
  Position r, bool& in_mesh) const
1029
{
1030
  MeshIndex ijk;
289,887,190✔
1031
  in_mesh = true;
289,887,190✔
1032
  for (int i = 0; i < n_dimension_; ++i) {
1,142,021,556✔
1033
    ijk[i] = get_index_in_direction(r[i], i);
852,134,366✔
1034

1035
    if (ijk[i] < 1 || ijk[i] > shape_[i])
852,134,366✔
1036
      in_mesh = false;
18,712,970✔
1037
  }
1038
  return ijk;
289,887,190✔
1039
}
1040

1041
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
399,037,324✔
1042
{
1043
  switch (n_dimension_) {
399,037,324!
1044
  case 1:
160,110✔
1045
    return ijk[0] - 1;
160,110✔
1046
  case 2:
24,795,496✔
1047
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
24,795,496✔
1048
  case 3:
374,081,718✔
1049
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
374,081,718✔
1050
  default:
×
1051
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1052
  }
1053
}
1054

1055
StructuredMesh::MeshIndex StructuredMesh::get_indices_from_bin(int bin) const
1,399,851✔
1056
{
1057
  MeshIndex ijk;
1,399,851✔
1058
  if (n_dimension_ == 1) {
1,399,851✔
1059
    ijk[0] = bin + 1;
50✔
1060
  } else if (n_dimension_ == 2) {
1,399,801✔
1061
    ijk[0] = bin % shape_[0] + 1;
2,848✔
1062
    ijk[1] = bin / shape_[0] + 1;
2,848✔
1063
  } else if (n_dimension_ == 3) {
1,396,953!
1064
    ijk[0] = bin % shape_[0] + 1;
1,396,953✔
1065
    ijk[1] = (bin % (shape_[0] * shape_[1])) / shape_[0] + 1;
1,396,953✔
1066
    ijk[2] = bin / (shape_[0] * shape_[1]) + 1;
1,396,953✔
1067
  }
1068
  return ijk;
1,399,851✔
1069
}
1070

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

1079
  // Convert indices to bin
1080
  return get_bin_from_indices(ijk);
71,488,052✔
1081
}
1082

1083
int StructuredMesh::n_bins() const
196,120✔
1084
{
1085
  return std::accumulate(
392,240✔
1086
    shape_.begin(), shape_.begin() + n_dimension_, 1, std::multiplies<>());
196,120✔
1087
}
1088

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

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

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

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

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

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

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

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

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

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

1140
  return counts;
×
1141
}
×
1142

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

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

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

1166
  const int n = n_dimension_;
213,503,176✔
1167

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

1171
  // Position is r = r0 + u * traveled_distance, start at r0
1172
  double traveled_distance {0.0};
213,503,176✔
1173

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

1178
  // if track is very short, assume that it is completely inside one cell.
1179
  // Only the current cell will score and no surfaces
1180
  if (total_distance < 2 * TINY_BIT) {
213,503,176✔
1181
    if (in_mesh) {
65,758✔
1182
      tally.track(ijk, 1.0);
65,670✔
1183
    }
1184
    return;
65,758✔
1185
  }
1186

1187
  // Calculate initial distances to next surfaces in all three dimensions
1188
  std::array<MeshDistance, 3> distances;
426,874,836✔
1189
  for (int k = 0; k < n; ++k) {
836,579,710✔
1190
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
623,142,292✔
1191
  }
1192

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

1196
    if (in_mesh) {
358,433,348✔
1197

1198
      // find surface with minimal distance to current position
1199
      const auto k = std::min_element(distances.begin(), distances.end()) -
342,371,852✔
1200
                     distances.begin();
342,371,852✔
1201

1202
      // Tally track length delta since last step
1203
      tally.track(ijk,
342,371,852✔
1204
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
517,131,458✔
1205
          total_distance);
1206

1207
      // update position and leave, if we have reached end position
1208
      traveled_distance = distances[k].distance;
342,371,852✔
1209
      if (traveled_distance >= total_distance)
342,371,852✔
1210
        return;
1211

1212
      // If we have not reached r1, we have hit a surface. Tally outward
1213
      // current
1214
      tally.surface(ijk, k, distances[k].max_surface, false);
143,681,946✔
1215

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

1222
      // Check if we have left the interior of the mesh
1223
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
144,931,548✔
1224

1225
      // If we are still inside the mesh, tally inward current for the next
1226
      // cell
1227
      if (in_mesh)
5,377,618✔
1228
        tally.surface(ijk, k, !distances[k].max_surface, true);
144,738,436✔
1229

1230
    } else { // not inside mesh
1231

1232
      // For all directions outside the mesh, find the distance that we need
1233
      // to travel to reach the next surface. Use the largest distance, as
1234
      // only this will cross all outer surfaces.
1235
      int k_max {-1};
1236
      for (int k = 0; k < n; ++k) {
63,983,372✔
1237
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
47,921,876✔
1238
            (distances[k].distance > traveled_distance)) {
17,500,770✔
1239
          traveled_distance = distances[k].distance;
1240
          k_max = k;
1241
        }
1242
      }
1243
      // Assure some distance is traveled
1244
      if (k_max == -1) {
16,061,496✔
1245
        traveled_distance += TINY_BIT;
20✔
1246
      }
1247

1248
      // If r1 is not inside the mesh, exit here
1249
      if (traveled_distance >= total_distance)
16,061,496✔
1250
        return;
1251

1252
      // Calculate the new cell index and update all distances to next
1253
      // surfaces.
1254
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
1,313,984✔
1255
      for (int k = 0; k < n; ++k) {
5,218,020✔
1256
        distances[k] =
3,904,036✔
1257
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
3,904,036✔
1258
      }
1259

1260
      // If inside the mesh, Tally inward current
1261
      if (in_mesh && k_max >= 0)
1,313,984!
1262
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
139,614,136✔
1263
    }
1264
  }
1265
}
1266

1267
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
201,128,156✔
1268
  vector<int>& bins, vector<double>& lengths) const
1269
{
1270

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

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

1291
  // Perform the mesh raytrace with the helper class.
1292
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
201,128,156✔
1293
}
201,128,156✔
1294

1295
void StructuredMesh::surface_bins_crossed(
20,386,830✔
1296
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1297
{
1298

1299
  // Helper tally class.
1300
  // stores a pointer to the mesh class and a reference to the bins parameter.
1301
  // Performs the actual tally through the surface method.
1302
  struct SurfaceAggregator {
20,386,830✔
1303
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
20,386,830✔
1304
      : mesh(_mesh), bins(_bins)
20,386,830✔
1305
    {}
1306
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
10,574,398✔
1307
    {
1308
      int i_bin =
10,574,398✔
1309
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
10,574,398✔
1310
      if (max)
10,574,398✔
1311
        i_bin += 2;
5,282,080✔
1312
      if (inward)
10,574,398✔
1313
        i_bin += 1;
5,196,780✔
1314
      bins.push_back(i_bin);
10,574,398✔
1315
    }
10,574,398✔
1316
    void track(const MeshIndex& idx, double l) const {}
1317

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

1322
  // Perform the mesh raytrace with the helper class.
1323
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
20,386,830✔
1324
}
20,386,830✔
1325

1326
//==============================================================================
1327
// RegularMesh implementation
1328
//==============================================================================
1329

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

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

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

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

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

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

1365
  } else if (upper_right_.size() > 0) {
366!
1366

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

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

1382
    // Set width
1383
    width_ = (upper_right_ - lower_left_) / shape;
1,098✔
1384
  }
1385

1386
  // Set material volumes
1387
  volume_frac_ = 1.0 / shape.prod();
372✔
1388

1389
  element_volume_ = 1.0;
372✔
1390
  for (int i = 0; i < n_dimension_; i++) {
1,414✔
1391
    element_volume_ *= width_[i];
1,042✔
1392
  }
1393
  return 0;
1394
}
372✔
1395

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

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

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

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

1424
    width_ = get_node_tensor<double>(node, "width");
12✔
1425

1426
  } else if (check_for_node(node, "upper_right")) {
364!
1427

1428
    upper_right_ = get_node_tensor<double>(node, "upper_right");
728✔
1429

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

1434
  if (int err = set_grid()) {
370!
1435
    fatal_error(openmc_err_msg);
×
1436
  }
1437
}
370✔
1438

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

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

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

1462
  if (object_exists(group, "upper_right")) {
2!
1463

1464
    read_dataset(group, "upper_right", upper_right_);
2✔
1465

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

1470
  if (int err = set_grid()) {
2!
1471
    fatal_error(openmc_err_msg);
×
1472
  }
1473
}
2✔
1474

1475
int RegularMesh::get_index_in_direction(double r, int i) const
775,210,448✔
1476
{
1477
  return std::ceil((r - lower_left_[i]) / width_[i]);
775,210,448✔
1478
}
1479

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

1482
std::string RegularMesh::get_mesh_type() const
628✔
1483
{
1484
  return mesh_type;
628✔
1485
}
1486

1487
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
340,624,313✔
1488
{
1489
  return lower_left_[i] + ijk[i] * width_[i];
340,624,313✔
1490
}
1491

1492
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
328,068,881✔
1493
{
1494
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
328,068,881✔
1495
}
1496

1497
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
674,044,882✔
1498
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1499
  double l) const
1500
{
1501
  MeshDistance d;
674,044,882✔
1502
  d.next_index = ijk[i];
674,044,882✔
1503
  if (std::abs(u[i]) < FP_PRECISION)
674,044,882✔
1504
    return d;
2,772,960✔
1505

1506
  d.max_surface = (u[i] > 0);
671,271,922✔
1507
  if (d.max_surface && (ijk[i] <= shape_[i])) {
671,271,922✔
1508
    d.next_index++;
339,859,826✔
1509
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
339,859,826✔
1510
  } else if (!d.max_surface && (ijk[i] >= 1)) {
331,412,096✔
1511
    d.next_index--;
327,304,394✔
1512
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
327,304,394✔
1513
  }
1514

1515
  return d;
671,271,922✔
1516
}
1517

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

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

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

1556
  return {axis_lines[0], axis_lines[1]};
8✔
1557
}
1558

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

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

1574
  // Create array of zeros
1575
  auto cnt = tensor::zeros<double>(shape);
1,408✔
1576
  bool outside_ = false;
1577

1578
  for (int64_t i = 0; i < length; i++) {
1,395,490✔
1579
    const auto& site = bank[i];
1,394,082✔
1580

1581
    // determine scoring bin for entropy mesh
1582
    int mesh_bin = get_bin(site.r);
1,394,082✔
1583

1584
    // if outside mesh, skip particle
1585
    if (mesh_bin < 0) {
1,394,082!
1586
      outside_ = true;
×
1587
      continue;
×
1588
    }
1589

1590
    // Add to appropriate bin
1591
    cnt(mesh_bin) += site.wgt;
1,394,082✔
1592
  }
1593

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

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

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

1613
  return counts;
1,408✔
1614
}
1,408✔
1615

1616
double RegularMesh::volume(const MeshIndex& ijk) const
193,684✔
1617
{
1618
  return element_volume_;
193,684✔
1619
}
1620

1621
//==============================================================================
1622
// RectilinearMesh implementation
1623
//==============================================================================
1624

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

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

1633
  if (int err = set_grid()) {
18!
1634
    fatal_error(openmc_err_msg);
×
1635
  }
1636
}
18✔
1637

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

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

1646
  if (int err = set_grid()) {
2!
1647
    fatal_error(openmc_err_msg);
×
1648
  }
1649
}
2✔
1650

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

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

1658
double RectilinearMesh::positive_grid_boundary(
4,819,266✔
1659
  const MeshIndex& ijk, int i) const
1660
{
1661
  return grid_[i][ijk[i]];
4,819,266✔
1662
}
1663

1664
double RectilinearMesh::negative_grid_boundary(
4,679,892✔
1665
  const MeshIndex& ijk, int i) const
1666
{
1667
  return grid_[i][ijk[i] - 1];
4,679,892✔
1668
}
1669

1670
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
9,745,834✔
1671
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1672
  double l) const
1673
{
1674
  MeshDistance d;
9,745,834✔
1675
  d.next_index = ijk[i];
9,745,834✔
1676
  if (std::abs(u[i]) < FP_PRECISION)
9,745,834✔
1677
    return d;
103,968✔
1678

1679
  d.max_surface = (u[i] > 0);
9,641,866✔
1680
  if (d.max_surface && (ijk[i] <= shape_[i])) {
9,641,866✔
1681
    d.next_index++;
4,819,266✔
1682
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
4,819,266✔
1683
  } else if (!d.max_surface && (ijk[i] > 0)) {
4,822,600✔
1684
    d.next_index--;
4,679,892✔
1685
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
4,679,892✔
1686
  }
1687
  return d;
9,641,866✔
1688
}
1689

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

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

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

1713
  return 0;
28✔
1714
}
1715

1716
int RectilinearMesh::get_index_in_direction(double r, int i) const
13,474,344✔
1717
{
1718
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
13,474,344✔
1719
}
1720

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

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

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

1748
  return {axis_lines[0], axis_lines[1]};
4✔
1749
}
1750

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

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

1762
  for (int i = 0; i < n_dimension_; i++) {
96✔
1763
    vol *= grid_[i][ijk[i]] - grid_[i][ijk[i] - 1];
72✔
1764
  }
1765
  return vol;
24✔
1766
}
1767

1768
//==============================================================================
1769
// CylindricalMesh implementation
1770
//==============================================================================
1771

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

1781
  if (int err = set_grid()) {
72!
1782
    fatal_error(openmc_err_msg);
×
1783
  }
1784
}
72✔
1785

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

1794
  if (int err = set_grid()) {
2!
1795
    fatal_error(openmc_err_msg);
×
1796
  }
1797
}
2✔
1798

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

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

1806
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
8,678,562✔
1807
  Position r, bool& in_mesh) const
1808
{
1809
  r = local_coords(r);
8,678,562✔
1810

1811
  Position mapped_r;
8,678,562✔
1812
  mapped_r[0] = std::hypot(r.x, r.y);
8,678,562✔
1813
  mapped_r[2] = r[2];
8,678,562✔
1814

1815
  if (mapped_r[0] < FP_PRECISION) {
8,678,562!
1816
    mapped_r[1] = 0.0;
1817
  } else {
1818
    mapped_r[1] = std::atan2(r.y, r.x);
8,678,562✔
1819
    if (mapped_r[1] < 0)
8,678,562✔
1820
      mapped_r[1] += 2 * M_PI;
4,340,884✔
1821
  }
1822

1823
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
8,678,562✔
1824

1825
  idx[1] = sanitize_phi(idx[1]);
8,678,562✔
1826

1827
  return idx;
8,678,562✔
1828
}
1829

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

1836
  double phi_min = this->phi(ijk[1] - 1);
16,020✔
1837
  double phi_max = this->phi(ijk[1]);
16,020✔
1838

1839
  double z_min = this->z(ijk[2] - 1);
16,020✔
1840
  double z_max = this->z(ijk[2]);
16,020✔
1841

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

1848
  double x = r * std::cos(phi);
16,020✔
1849
  double y = r * std::sin(phi);
16,020✔
1850

1851
  return origin_ + Position(x, y, z);
16,020✔
1852
}
1853

1854
double CylindricalMesh::find_r_crossing(
25,924,668✔
1855
  const Position& r, const Direction& u, double l, int shell) const
1856
{
1857

1858
  if ((shell < 0) || (shell > shape_[0]))
25,924,668!
1859
    return INFTY;
1860

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

1865
  const double r0 = grid_[0][shell];
22,667,610✔
1866
  if (r0 == 0.0)
22,667,610✔
1867
    return INFTY;
1868

1869
  const double denominator = u.x * u.x + u.y * u.y;
21,370,142✔
1870

1871
  // Direction of flight is in z-direction. Will never intersect r.
1872
  if (std::abs(denominator) < FP_PRECISION)
21,370,142✔
1873
    return INFTY;
1874

1875
  // inverse of dominator to help the compiler to speed things up
1876
  const double inv_denominator = 1.0 / denominator;
21,359,422✔
1877

1878
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
21,359,422✔
1879
  double R = std::sqrt(r.x * r.x + r.y * r.y);
21,359,422✔
1880
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
21,359,422✔
1881

1882
  if (D < 0.0)
21,359,422✔
1883
    return INFTY;
1884

1885
  D = std::sqrt(D);
19,589,218✔
1886

1887
  // Particle is already on the shell surface; avoid spurious crossing
1888
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
19,589,218✔
1889
    return INFTY;
1890

1891
  // Check -p - D first because it is always smaller as -p + D
1892
  if (-p - D > l)
18,383,150✔
1893
    return -p - D;
1894
  if (-p + D > l)
14,709,044✔
1895
    return -p + D;
9,104,954✔
1896

1897
  return INFTY;
1898
}
1899

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

1907
  shell = sanitize_phi(shell);
7,994,676✔
1908

1909
  const double p0 = grid_[1][shell];
7,994,676✔
1910

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

1916
  const double c0 = std::cos(p0);
7,994,676✔
1917
  const double s0 = std::sin(p0);
7,994,676✔
1918

1919
  const double denominator = (u.x * s0 - u.y * c0);
7,994,676✔
1920

1921
  // Check if direction of flight is not parallel to phi surface
1922
  if (std::abs(denominator) > FP_PRECISION) {
7,994,676✔
1923
    const double s = -(r.x * s0 - r.y * c0) / denominator;
7,947,268✔
1924
    // Check if solution is in positive direction of flight and crosses the
1925
    // correct phi surface (not -phi)
1926
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
7,947,268✔
1927
      return s;
3,676,338✔
1928
  }
1929

1930
  return INFTY;
1931
}
1932

1933
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
6,671,954✔
1934
  const Position& r, const Direction& u, double l, int shell) const
1935
{
1936
  MeshDistance d;
6,671,954✔
1937
  d.next_index = shell;
6,671,954✔
1938

1939
  // Direction of flight is within xy-plane. Will never intersect z.
1940
  if (std::abs(u.z) < FP_PRECISION)
6,671,954✔
1941
    return d;
203,312✔
1942

1943
  d.max_surface = (u.z > 0.0);
6,468,642✔
1944
  if (d.max_surface && (shell <= shape_[2])) {
6,468,642✔
1945
    d.next_index += 1;
3,068,344✔
1946
    d.distance = (grid_[2][shell] - r.z) / u.z;
3,068,344✔
1947
  } else if (!d.max_surface && (shell > 0)) {
3,400,298✔
1948
    d.next_index -= 1;
3,062,950✔
1949
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
3,062,950✔
1950
  }
1951
  return d;
6,468,642✔
1952
}
1953

1954
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
26,403,052✔
1955
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1956
  double l) const
1957
{
1958
  if (i == 0) {
26,403,052✔
1959

1960
    return std::min(
25,924,668✔
1961
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
12,962,334✔
1962
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
25,924,668✔
1963

1964
  } else if (i == 1) {
13,440,718✔
1965

1966
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
6,768,764✔
1967
                      find_phi_crossing(r0, u, l, ijk[i])),
6,768,764✔
1968
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
6,768,764✔
1969
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
13,537,528✔
1970

1971
  } else {
1972
    return find_z_crossing(r0, u, l, ijk[i]);
6,671,954✔
1973
  }
1974
}
1975

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

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

2009
    return OPENMC_E_INVALID_ARGUMENT;
×
2010
  }
2011

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

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

2019
  return 0;
78✔
2020
}
2021

2022
int CylindricalMesh::get_index_in_direction(double r, int i) const
26,035,686✔
2023
{
2024
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
26,035,686✔
2025
}
2026

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

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

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

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

2050
  double phi_i = grid_[1][ijk[1] - 1];
144✔
2051
  double phi_o = grid_[1][ijk[1]];
144✔
2052

2053
  double z_i = grid_[2][ijk[2] - 1];
144✔
2054
  double z_o = grid_[2][ijk[2]];
144✔
2055

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

2059
//==============================================================================
2060
// SphericalMesh implementation
2061
//==============================================================================
2062

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

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

2073
  if (int err = set_grid()) {
62!
2074
    fatal_error(openmc_err_msg);
×
2075
  }
2076
}
62✔
2077

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

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

2087
  if (int err = set_grid()) {
2!
2088
    fatal_error(openmc_err_msg);
×
2089
  }
2090
}
2✔
2091

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

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

2099
StructuredMesh::MeshIndex SphericalMesh::get_indices(
12,471,296✔
2100
  Position r, bool& in_mesh) const
2101
{
2102
  r = local_coords(r);
12,471,296✔
2103

2104
  Position mapped_r;
12,471,296✔
2105
  mapped_r[0] = r.norm();
12,471,296✔
2106

2107
  if (mapped_r[0] < FP_PRECISION) {
12,471,296!
2108
    mapped_r[1] = 0.0;
2109
    mapped_r[2] = 0.0;
2110
  } else {
2111
    mapped_r[1] = std::acos(r.z / mapped_r.x);
12,471,296✔
2112
    mapped_r[2] = std::atan2(r.y, r.x);
12,471,296✔
2113
    if (mapped_r[2] < 0)
12,471,296✔
2114
      mapped_r[2] += 2 * M_PI;
6,230,670✔
2115
  }
2116

2117
  MeshIndex idx = StructuredMesh::get_indices(mapped_r, in_mesh);
12,471,296✔
2118

2119
  idx[1] = sanitize_theta(idx[1]);
12,471,296✔
2120
  idx[2] = sanitize_phi(idx[2]);
12,471,296✔
2121

2122
  return idx;
12,471,296✔
2123
}
2124

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

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

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

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

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

2150
  return origin_ + Position(x, y, z);
20✔
2151
}
2152

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

2159
  // solve |r+s*u| = r0
2160
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2161
  const double r0 = grid_[0][shell];
73,517,510✔
2162
  if (r0 == 0.0)
73,517,510✔
2163
    return INFTY;
2164
  const double p = r.dot(u);
72,121,416✔
2165
  double R = r.norm();
72,121,416✔
2166
  double D = p * p - (R - r0) * (R + r0);
72,121,416✔
2167

2168
  // Particle is already on the shell surface; avoid spurious crossing
2169
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
72,121,416✔
2170
    return INFTY;
2171

2172
  if (D >= 0.0) {
70,174,388✔
2173
    D = std::sqrt(D);
65,105,852✔
2174
    // Check -p - D first because it is always smaller as -p + D
2175
    if (-p - D > l)
65,105,852✔
2176
      return -p - D;
2177
    if (-p + D > l)
53,413,204✔
2178
      return -p + D;
32,224,524✔
2179
  }
2180

2181
  return INFTY;
2182
}
2183

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

2191
  shell = sanitize_theta(shell);
6,974,280✔
2192

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

2200
  const double cos_t = std::cos(grid_[1][shell]);
6,974,280✔
2201
  const bool sgn = std::signbit(cos_t);
6,974,280✔
2202
  const double cos_t_2 = cos_t * cos_t;
6,974,280✔
2203

2204
  const double a = cos_t_2 - u.z * u.z;
6,974,280✔
2205
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
6,974,280✔
2206
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
6,974,280✔
2207

2208
  // if factor of s^2 is zero, direction of flight is parallel to theta
2209
  // surface
2210
  if (std::abs(a) < FP_PRECISION) {
6,974,280✔
2211
    // if b vanishes, direction of flight is within theta surface and crossing
2212
    // is not possible
2213
    if (std::abs(b) < FP_PRECISION)
87,736!
2214
      return INFTY;
2215

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

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

2226
  const double p = b / a;
6,886,544✔
2227
  double D = p * p - c / a;
6,886,544✔
2228

2229
  if (D < 0.0)
6,886,544✔
2230
    return INFTY;
2231

2232
  D = std::sqrt(D);
4,894,728✔
2233

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

2240
  s = -p + D;
3,934,254✔
2241
  // Check if solution is in positive direction of flight and has correct sign
2242
  if ((s > l) && (std::signbit(r.z + s * u.z) == sgn))
3,934,254✔
2243
    return s;
1,847,872✔
2244

2245
  return INFTY;
2246
}
2247

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

2255
  shell = sanitize_phi(shell);
7,263,276✔
2256

2257
  const double p0 = grid_[2][shell];
7,263,276✔
2258

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

2264
  const double c0 = std::cos(p0);
7,263,276✔
2265
  const double s0 = std::sin(p0);
7,263,276✔
2266

2267
  const double denominator = (u.x * s0 - u.y * c0);
7,263,276✔
2268

2269
  // Check if direction of flight is not parallel to phi surface
2270
  if (std::abs(denominator) > FP_PRECISION) {
7,263,276✔
2271
    const double s = -(r.x * s0 - r.y * c0) / denominator;
7,220,732✔
2272
    // Check if solution is in positive direction of flight and crosses the
2273
    // correct phi surface (not -phi)
2274
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
7,220,732✔
2275
      return s;
3,196,264✔
2276
  }
2277

2278
  return INFTY;
2279
}
2280

2281
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
60,534,506✔
2282
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2283
  double l) const
2284
{
2285

2286
  if (i == 0) {
60,534,506✔
2287
    return std::min(
80,721,344✔
2288
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
40,360,672✔
2289
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
80,721,344✔
2290

2291
  } else if (i == 1) {
20,173,834✔
2292
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
10,014,668✔
2293
                      find_theta_crossing(r0, u, l, ijk[i])),
10,014,668✔
2294
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
10,014,668✔
2295
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
20,029,336✔
2296

2297
  } else {
2298
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
10,159,166✔
2299
                      find_phi_crossing(r0, u, l, ijk[i])),
10,159,166✔
2300
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
10,159,166✔
2301
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
20,318,332✔
2302
  }
2303
}
2304

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

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

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

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

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

2348
  return 0;
68✔
2349
}
2350

2351
int SphericalMesh::get_index_in_direction(double r, int i) const
37,413,888✔
2352
{
2353
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
37,413,888✔
2354
}
2355

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

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

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

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

2379
  double theta_i = grid_[1][ijk[1] - 1];
170✔
2380
  double theta_o = grid_[1][ijk[1]];
170✔
2381

2382
  double phi_i = grid_[2][ijk[2] - 1];
170✔
2383
  double phi_o = grid_[2][ijk[2]];
170✔
2384

2385
  return (1.0 / 3.0) * (r_o * r_o * r_o - r_i * r_i * r_i) *
340✔
2386
         (std::cos(theta_i) - std::cos(theta_o)) * (phi_o - phi_i);
170✔
2387
}
2388

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

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

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

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

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

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

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

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

2435
  return 0;
272✔
2436
}
2437

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

2446
  for (int i = 0; i < n; ++i) {
92✔
2447
    if (RegularMesh::mesh_type == type) {
46✔
2448
      model::meshes.push_back(make_unique<RegularMesh>());
30✔
2449
    } else if (RectilinearMesh::mesh_type == type) {
16✔
2450
      model::meshes.push_back(make_unique<RectilinearMesh>());
8✔
2451
    } else if (CylindricalMesh::mesh_type == type) {
8✔
2452
      model::meshes.push_back(make_unique<CylindricalMesh>());
4✔
2453
    } else if (SphericalMesh::mesh_type == type) {
4!
2454
      model::meshes.push_back(make_unique<SphericalMesh>());
4✔
2455
    } else {
2456
      throw std::runtime_error {"Unknown mesh type: " + std::string(type)};
×
2457
    }
2458
  }
2459
  if (index_end)
46!
2460
    *index_end = model::meshes.size() - 1;
×
2461

2462
  return 0;
46✔
2463
}
46✔
2464

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

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

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

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

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

2498
  return 0;
2499
}
×
2500

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

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

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

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

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

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

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

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

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

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

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

2590
  return 0;
2591
}
2592

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

2600
  int pixel_width = pixels[0];
8✔
2601
  int pixel_height = pixels[1];
8✔
2602

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

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

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

2633
#pragma omp parallel
2634
  {
8✔
2635
    Position r = xyz;
8✔
2636

2637
#pragma omp for
2638
    for (int y = 0; y < pixel_height; y++) {
168✔
2639
      r[out_i] = xyz[out_i] - out_pixel * y;
160✔
2640
      for (int x = 0; x < pixel_width; x++) {
3,360✔
2641
        r[in_i] = xyz[in_i] + in_pixel * x;
3,200✔
2642
        data[pixel_width * y + x] = mesh->get_bin(r);
3,200✔
2643
      }
2644
    }
2645
  }
2646

2647
  return 0;
8✔
2648
}
2649

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

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

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

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

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

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

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

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

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

2727
  // Set material volumes
2728

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

2737
  return 0;
2738
}
40✔
2739

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

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

2751
  m->n_dimension_ = 3;
16✔
2752

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

2757
  for (int i = 0; i < nx; i++) {
104✔
2758
    m->grid_[0].push_back(grid_x[i]);
88✔
2759
  }
2760
  for (int i = 0; i < ny; i++) {
62✔
2761
    m->grid_[1].push_back(grid_y[i]);
46✔
2762
  }
2763
  for (int i = 0; i < nz; i++) {
58✔
2764
    m->grid_[2].push_back(grid_z[i]);
42✔
2765
  }
2766

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

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

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

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

2792
  return 0;
70✔
2793
}
2794

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

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

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

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

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

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

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

NEW
2848
extern "C" int openmc_unstructured_mesh_export_hdf5(
×
2849
  int32_t index, hid_t mesh_group)
2850
{
NEW
2851
  if (!mpi::master)
×
2852
    return 0;
2853

NEW
2854
  if (H5Iis_valid(mesh_group) <= 0)
×
NEW
2855
    fatal_error("Not a valid group");
×
NEW
2856
  if (H5Iget_type(mesh_group) != H5I_GROUP)
×
NEW
2857
    fatal_error("Not a valid group");
×
2858

NEW
2859
  if (int err = check_mesh_type<UnstructuredMesh>(index))
×
2860
    return err;
NEW
2861
  UnstructuredMesh* m =
×
NEW
2862
    dynamic_cast<UnstructuredMesh*>(model::meshes[index].get());
×
2863

NEW
2864
  m->to_hdf5_inner(mesh_group);
×
NEW
2865
  return 0;
×
2866
}
2867

2868
#ifdef OPENMC_DAGMC_ENABLED
2869

2870
const std::string MOABMesh::mesh_lib_type = "moab";
2871

2872
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
2873
{
2874
  initialize();
2875
}
2876

2877
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
2878
{
2879
  initialize();
2880
}
2881

2882
MOABMesh::MOABMesh(const std::string& filename, double length_multiplier)
2883
  : UnstructuredMesh()
2884
{
2885
  n_dimension_ = 3;
2886
  filename_ = filename;
2887
  set_length_multiplier(length_multiplier);
2888
  initialize();
2889
}
2890

2891
MOABMesh::MOABMesh(std::shared_ptr<moab::Interface> external_mbi)
2892
{
2893
  mbi_ = external_mbi;
2894
  filename_ = "unknown (external file)";
2895
  this->initialize();
2896
}
2897

2898
void MOABMesh::initialize()
2899
{
2900

2901
  // Create the MOAB interface and load data from file
2902
  this->create_interface();
2903

2904
  // Initialise MOAB error code
2905
  moab::ErrorCode rval = moab::MB_SUCCESS;
2906

2907
  // Set the dimension
2908
  n_dimension_ = 3;
2909

2910
  // set member range of tetrahedral entities
2911
  rval = mbi_->get_entities_by_dimension(0, n_dimension_, ehs_);
2912
  if (rval != moab::MB_SUCCESS) {
2913
    fatal_error("Failed to get all tetrahedral elements");
2914
  }
2915

2916
  if (!ehs_.all_of_type(moab::MBTET)) {
2917
    warning("Non-tetrahedral elements found in unstructured "
2918
            "mesh file: " +
2919
            filename_);
2920
  }
2921

2922
  // set member range of vertices
2923
  int vertex_dim = 0;
2924
  rval = mbi_->get_entities_by_dimension(0, vertex_dim, verts_);
2925
  if (rval != moab::MB_SUCCESS) {
2926
    fatal_error("Failed to get all vertex handles");
2927
  }
2928

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

2936
  rval = mbi_->add_entities(tetset_, ehs_);
2937
  if (rval != moab::MB_SUCCESS) {
2938
    fatal_error("Failed to add tetrahedra to an entity set.");
2939
  }
2940

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

2969
  // Determine bounds of mesh
2970
  this->determine_bounds();
2971
}
2972

2973
void MOABMesh::prepare_for_point_location()
2974
{
2975
  // if the KDTree has already been constructed, do nothing
2976
  if (kdtree_)
2977
    return;
2978

2979
  // build acceleration data structures
2980
  compute_barycentric_data(ehs_);
2981
  build_kdtree(ehs_);
2982
}
2983

2984
void MOABMesh::create_interface()
2985
{
2986
  // Do not create a MOAB instance if one is already in memory
2987
  if (mbi_)
2988
    return;
2989

2990
  // create MOAB instance
2991
  mbi_ = std::make_shared<moab::Core>();
2992

2993
  // load unstructured mesh file
2994
  moab::ErrorCode rval = mbi_->load_file(filename_.c_str());
2995
  if (rval != moab::MB_SUCCESS) {
2996
    fatal_error("Failed to load the unstructured mesh file: " + filename_);
2997
  }
2998
}
2999

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

3011
  if (!all_tris.all_of_type(moab::MBTRI)) {
3012
    warning("Non-triangle elements found in tet adjacencies in "
3013
            "unstructured mesh file: " +
3014
            filename_);
3015
  }
3016

3017
  // combine into one range
3018
  moab::Range all_tets_and_tris;
3019
  all_tets_and_tris.merge(all_tets);
3020
  all_tets_and_tris.merge(all_tris);
3021

3022
  // create a kd-tree instance
3023
  write_message(
3024
    7, "Building adaptive k-d tree for tet mesh with ID {}...", id_);
3025
  kdtree_ = make_unique<moab::AdaptiveKDTree>(mbi_.get());
3026

3027
  // Determine what options to use
3028
  std::ostringstream options_stream;
3029
  if (options_.empty()) {
3030
    options_stream << "MAX_DEPTH=20;PLANE_SET=2;";
3031
  } else {
3032
    options_stream << options_;
3033
  }
3034
  moab::FileOptions file_opts(options_stream.str().c_str());
3035

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

3045
void MOABMesh::intersect_track(const moab::CartVect& start,
3046
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3047
{
3048
  hits.clear();
3049

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

3062
  // remove duplicate intersection distances
3063
  std::unique(hits.begin(), hits.end());
3064

3065
  // sorts by first component of std::pair by default
3066
  std::sort(hits.begin(), hits.end());
3067
}
3068

3069
void MOABMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3070
  vector<int>& bins, vector<double>& lengths) const
3071
{
3072
  moab::CartVect start(r0.x, r0.y, r0.z);
3073
  moab::CartVect end(r1.x, r1.y, r1.z);
3074
  moab::CartVect dir(u.x, u.y, u.z);
3075
  dir.normalize();
3076

3077
  double track_len = (end - start).length();
3078
  if (track_len == 0.0)
3079
    return;
3080

3081
  start -= TINY_BIT * dir;
3082
  end += TINY_BIT * dir;
3083

3084
  vector<double> hits;
3085
  intersect_track(start, dir, track_len, hits);
3086

3087
  bins.clear();
3088
  lengths.clear();
3089

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

3103
  // for each segment in the set of tracks, try to look up a tet
3104
  // at the midpoint of the segment
3105
  Position current = r0;
3106
  double last_dist = 0.0;
3107
  for (const auto& hit : hits) {
3108
    // get the segment length
3109
    double segment_length = hit - last_dist;
3110
    last_dist = hit;
3111
    // find the midpoint of this segment
3112
    Position midpoint = current + u * (segment_length * 0.5);
3113
    // try to find a tet for this position
3114
    int bin = this->get_bin(midpoint);
3115

3116
    // determine the start point for this segment
3117
    current = r0 + u * hit;
3118

3119
    if (bin == -1) {
3120
      continue;
3121
    }
3122

3123
    bins.push_back(bin);
3124
    lengths.push_back(segment_length / track_len);
3125
  }
3126

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

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

3152
  // retrieve the tet elements of this leaf
3153
  moab::EntityHandle leaf = kdtree_iter.handle();
3154
  moab::Range tets;
3155
  rval = mbi_->get_entities_by_dimension(leaf, 3, tets, false);
3156
  if (rval != moab::MB_SUCCESS) {
3157
    warning("MOAB error finding tets.");
3158
  }
3159

3160
  // loop over the tets in this leaf, returning the containing tet if found
3161
  for (const auto& tet : tets) {
3162
    if (point_in_tet(pos, tet)) {
3163
      return tet;
3164
    }
3165
  }
3166

3167
  // if no tet is found, return an invalid handle
3168
  return 0;
3169
}
3170

3171
double MOABMesh::volume(int bin) const
3172
{
3173
  return tet_volume(get_ent_handle_from_bin(bin));
3174
}
3175

3176
std::string MOABMesh::library() const
3177
{
3178
  return mesh_lib_type;
3179
}
3180

3181
// Sample position within a tet for MOAB type tets
3182
Position MOABMesh::sample_element(int32_t bin, uint64_t* seed) const
3183
{
3184

3185
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
3186

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

3202
  std::array<Position, 4> tet_verts;
3203
  for (int i = 0; i < 4; i++) {
3204
    tet_verts[i] = {p[i][0], p[i][1], p[i][2]};
3205
  }
3206
  // Samples position within tet using Barycentric stuff
3207
  return this->sample_tet(tet_verts, seed);
3208
}
3209

3210
double MOABMesh::tet_volume(moab::EntityHandle tet) const
3211
{
3212
  vector<moab::EntityHandle> conn;
3213
  moab::ErrorCode rval = mbi_->get_connectivity(&tet, 1, conn);
3214
  if (rval != moab::MB_SUCCESS) {
3215
    fatal_error("Failed to get tet connectivity");
3216
  }
3217

3218
  moab::CartVect p[4];
3219
  rval = mbi_->get_coords(conn.data(), conn.size(), p[0].array());
3220
  if (rval != moab::MB_SUCCESS) {
3221
    fatal_error("Failed to get tet coords");
3222
  }
3223

3224
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
3225
}
3226

3227
int MOABMesh::get_bin(Position r) const
3228
{
3229
  moab::EntityHandle tet = get_tet(r);
3230
  if (tet == 0) {
3231
    return -1;
3232
  } else {
3233
    return get_bin_from_ent_handle(tet);
3234
  }
3235
}
3236

3237
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
3238
{
3239
  moab::ErrorCode rval;
3240

3241
  baryc_data_.clear();
3242
  baryc_data_.resize(tets.size());
3243

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

3253
    moab::CartVect p[4];
3254
    rval = mbi_->get_coords(verts.data(), verts.size(), p[0].array());
3255
    if (rval != moab::MB_SUCCESS) {
3256
      fatal_error("Failed to get coordinates of a tet in umesh: " + filename_);
3257
    }
3258

3259
    moab::Matrix3 a(p[1] - p[0], p[2] - p[0], p[3] - p[0], true);
3260

3261
    // invert now to avoid this cost later
3262
    a = a.transpose().inverse();
3263
    baryc_data_.at(get_bin_from_ent_handle(tet)) = a;
3264
  }
3265
}
3266

3267
bool MOABMesh::point_in_tet(
3268
  const moab::CartVect& r, moab::EntityHandle tet) const
3269
{
3270

3271
  moab::ErrorCode rval;
3272

3273
  // get tet vertices
3274
  vector<moab::EntityHandle> verts;
3275
  rval = mbi_->get_connectivity(&tet, 1, verts);
3276
  if (rval != moab::MB_SUCCESS) {
3277
    warning("Failed to get vertices of tet in umesh: " + filename_);
3278
    return false;
3279
  }
3280

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

3292
  // look up barycentric data
3293
  int idx = get_bin_from_ent_handle(tet);
3294
  const moab::Matrix3& a_inv = baryc_data_[idx];
3295

3296
  moab::CartVect bary_coords = a_inv * (r - p_zero);
3297

3298
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
3299
          bary_coords[2] >= 0.0 &&
3300
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
3301
}
3302

3303
int MOABMesh::get_bin_from_index(int idx) const
3304
{
3305
  if (idx >= n_bins()) {
3306
    fatal_error(fmt::format("Invalid bin index: {}", idx));
3307
  }
3308
  return ehs_[idx] - ehs_[0];
3309
}
3310

3311
int MOABMesh::get_index(const Position& r, bool* in_mesh) const
3312
{
3313
  int bin = get_bin(r);
3314
  *in_mesh = bin != -1;
3315
  return bin;
3316
}
3317

3318
int MOABMesh::get_index_from_bin(int bin) const
3319
{
3320
  return bin;
3321
}
3322

3323
std::pair<vector<double>, vector<double>> MOABMesh::plot(
3324
  Position plot_ll, Position plot_ur) const
3325
{
3326
  // TODO: Implement mesh lines
3327
  return {};
3328
}
3329

3330
int MOABMesh::get_vert_idx_from_handle(moab::EntityHandle vert) const
3331
{
3332
  int idx = vert - verts_[0];
3333
  if (idx >= n_vertices()) {
3334
    fatal_error(
3335
      fmt::format("Invalid vertex idx {} (# vertices {})", idx, n_vertices()));
3336
  }
3337
  return idx;
3338
}
3339

3340
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
3341
{
3342
  int bin = eh - ehs_[0];
3343
  if (bin >= n_bins()) {
3344
    fatal_error(fmt::format("Invalid bin: {}", bin));
3345
  }
3346
  return bin;
3347
}
3348

3349
moab::EntityHandle MOABMesh::get_ent_handle_from_bin(int bin) const
3350
{
3351
  if (bin >= n_bins()) {
3352
    fatal_error(fmt::format("Invalid bin index: ", bin));
3353
  }
3354
  return ehs_[0] + bin;
3355
}
3356

3357
int MOABMesh::n_bins() const
3358
{
3359
  return ehs_.size();
3360
}
3361

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

3375
Position MOABMesh::centroid(int bin) const
3376
{
3377
  moab::ErrorCode rval;
3378

3379
  auto tet = this->get_ent_handle_from_bin(bin);
3380

3381
  // look up the tet connectivity
3382
  vector<moab::EntityHandle> conn;
3383
  rval = mbi_->get_connectivity(&tet, 1, conn);
3384
  if (rval != moab::MB_SUCCESS) {
3385
    warning("Failed to get connectivity of a mesh element.");
3386
    return {};
3387
  }
3388

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

3397
  // compute the centroid of the element vertices
3398
  moab::CartVect centroid(0.0, 0.0, 0.0);
3399
  for (const auto& coord : coords) {
3400
    centroid += coord;
3401
  }
3402
  centroid /= double(coords.size());
3403

3404
  return {centroid[0], centroid[1], centroid[2]};
3405
}
3406

3407
int MOABMesh::n_vertices() const
3408
{
3409
  return verts_.size();
3410
}
3411

3412
Position MOABMesh::vertex(int id) const
3413
{
3414

3415
  moab::ErrorCode rval;
3416

3417
  moab::EntityHandle vert = verts_[id];
3418

3419
  moab::CartVect coords;
3420
  rval = mbi_->get_coords(&vert, 1, coords.array());
3421
  if (rval != moab::MB_SUCCESS) {
3422
    fatal_error("Failed to get the coordinates of a vertex.");
3423
  }
3424

3425
  return {coords[0], coords[1], coords[2]};
3426
}
3427

3428
std::vector<int> MOABMesh::connectivity(int bin) const
3429
{
3430
  moab::ErrorCode rval;
3431

3432
  auto tet = get_ent_handle_from_bin(bin);
3433

3434
  // look up the tet connectivity
3435
  vector<moab::EntityHandle> conn;
3436
  rval = mbi_->get_connectivity(&tet, 1, conn);
3437
  if (rval != moab::MB_SUCCESS) {
3438
    fatal_error("Failed to get connectivity of a mesh element.");
3439
    return {};
3440
  }
3441

3442
  std::vector<int> verts(4);
3443
  for (int i = 0; i < verts.size(); i++) {
3444
    verts[i] = get_vert_idx_from_handle(conn[i]);
3445
  }
3446

3447
  return verts;
3448
}
3449

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

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

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

3485
  // return the populated tag handles
3486
  return {value_tag, error_tag};
3487
}
3488

3489
void MOABMesh::add_score(const std::string& score)
3490
{
3491
  auto score_tags = get_score_tags(score);
3492
  tag_names_.push_back(score);
3493
}
3494

3495
void MOABMesh::remove_scores()
3496
{
3497
  for (const auto& name : tag_names_) {
3498
    auto value_name = name + "_mean";
3499
    moab::Tag tag;
3500
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
3501
    if (rval != moab::MB_SUCCESS)
3502
      return;
3503

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

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

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

3532
void MOABMesh::set_score_data(const std::string& score,
3533
  const vector<double>& values, const vector<double>& std_dev)
3534
{
3535
  auto score_tags = this->get_score_tags(score);
3536

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

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

3557
void MOABMesh::write(const std::string& base_filename) const
3558
{
3559
  // add extension to the base name
3560
  auto filename = base_filename + ".vtk";
3561
  write_message(5, "Writing unstructured mesh {}...", filename);
3562
  filename = settings::path_output + filename;
3563

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

3575
#endif
3576

3577
#ifdef OPENMC_LIBMESH_ENABLED
3578

3579
const std::string LibMesh::mesh_lib_type = "libmesh";
3580

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

3590
LibMesh::LibMesh(hid_t group) : UnstructuredMesh(group)
3591
{
3592
  // filename_ and length_multiplier_ will already be set by the
3593
  // UnstructuredMesh constructor
3594
  set_mesh_pointer_from_filename(filename_);
3595
  set_length_multiplier(length_multiplier_);
3596
  initialize();
3597
}
3598

3599
// create the mesh from a pointer to a libMesh Mesh
3600
LibMesh::LibMesh(libMesh::MeshBase& input_mesh, double length_multiplier)
3601
{
3602
  if (!input_mesh.is_replicated()) {
3603
    fatal_error("At present LibMesh tallies require a replicated mesh. Please "
3604
                "ensure 'input_mesh' is a libMesh::ReplicatedMesh.");
3605
  }
3606

3607
  m_ = &input_mesh;
3608
  set_length_multiplier(length_multiplier);
3609
  initialize();
3610
}
3611

3612
// create the mesh from an input file
3613
LibMesh::LibMesh(const std::string& filename, double length_multiplier)
3614
{
3615
  n_dimension_ = 3;
3616
  set_mesh_pointer_from_filename(filename);
3617
  set_length_multiplier(length_multiplier);
3618
  initialize();
3619
}
3620

3621
void LibMesh::set_mesh_pointer_from_filename(const std::string& filename)
3622
{
3623
  filename_ = filename;
3624
  unique_m_ =
3625
    make_unique<libMesh::ReplicatedMesh>(*settings::libmesh_comm, n_dimension_);
3626
  m_ = unique_m_.get();
3627
  m_->read(filename_);
3628
}
3629

3630
// build a libMesh equation system for storing values
3631
void LibMesh::build_eqn_sys()
3632
{
3633
  eq_system_name_ = fmt::format("mesh_{}_system", id_);
3634
  equation_systems_ = make_unique<libMesh::EquationSystems>(*m_);
3635
  libMesh::ExplicitSystem& eq_sys =
3636
    equation_systems_->add_system<libMesh::ExplicitSystem>(eq_system_name_);
3637
}
3638

3639
// intialize from mesh file
3640
void LibMesh::initialize()
3641
{
3642
  if (!settings::libmesh_comm) {
3643
    fatal_error("Attempting to use an unstructured mesh without a libMesh "
3644
                "communicator.");
3645
  }
3646

3647
  // assuming that unstructured meshes used in OpenMC are 3D
3648
  n_dimension_ = 3;
3649

3650
  // if OpenMC is managing the libMesh::MeshBase instance, prepare the mesh.
3651
  // Otherwise assume that it is prepared by its owning application
3652
  if (unique_m_) {
3653
    m_->prepare_for_use();
3654
  }
3655

3656
  // ensure that the loaded mesh is 3 dimensional
3657
  if (m_->mesh_dimension() != n_dimension_) {
3658
    fatal_error(fmt::format("Mesh file {} specified for use in an unstructured "
3659
                            "mesh is not a 3D mesh.",
3660
      filename_));
3661
  }
3662

3663
  for (int i = 0; i < num_threads(); i++) {
3664
    pl_.emplace_back(m_->sub_point_locator());
3665
    pl_.back()->set_contains_point_tol(FP_COINCIDENT);
3666
    pl_.back()->enable_out_of_mesh_mode();
3667
  }
3668

3669
  // store first element in the mesh to use as an offset for bin indices
3670
  auto first_elem = *m_->elements_begin();
3671
  first_element_id_ = first_elem->id();
3672

3673
  // bounding box for the mesh for quick rejection checks
3674
  bbox_ = libMesh::MeshTools::create_bounding_box(*m_);
3675
  libMesh::Point ll = bbox_.min();
3676
  libMesh::Point ur = bbox_.max();
3677
  if (length_multiplier_ > 0.0) {
3678
    lower_left_ = {length_multiplier_ * ll(0), length_multiplier_ * ll(1),
3679
      length_multiplier_ * ll(2)};
3680
    upper_right_ = {length_multiplier_ * ur(0), length_multiplier_ * ur(1),
3681
      length_multiplier_ * ur(2)};
3682
  } else {
3683
    lower_left_ = {ll(0), ll(1), ll(2)};
3684
    upper_right_ = {ur(0), ur(1), ur(2)};
3685
  }
3686
}
3687

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

3707
Position LibMesh::centroid(int bin) const
3708
{
3709
  const auto& elem = this->get_element_from_bin(bin);
3710
  auto centroid = elem.vertex_average();
3711
  if (length_multiplier_ > 0.0) {
3712
    return length_multiplier_ * Position(centroid(0), centroid(1), centroid(2));
3713
  } else {
3714
    return {centroid(0), centroid(1), centroid(2)};
3715
  }
3716
}
3717

3718
int LibMesh::n_vertices() const
3719
{
3720
  return m_->n_nodes();
3721
}
3722

3723
Position LibMesh::vertex(int vertex_id) const
3724
{
3725
  const auto& node_ref = m_->node_ref(vertex_id);
3726
  if (length_multiplier_ > 0.0) {
3727
    return length_multiplier_ * Position(node_ref(0), node_ref(1), node_ref(2));
3728
  } else {
3729
    return {node_ref(0), node_ref(1), node_ref(2)};
3730
  }
3731
}
3732

3733
std::vector<int> LibMesh::connectivity(int elem_id) const
3734
{
3735
  std::vector<int> conn;
3736
  const auto* elem_ptr = m_->elem_ptr(elem_id);
3737
  for (int i = 0; i < elem_ptr->n_nodes(); i++) {
3738
    conn.push_back(elem_ptr->node_id(i));
3739
  }
3740
  return conn;
3741
}
3742

3743
std::string LibMesh::library() const
3744
{
3745
  return mesh_lib_type;
3746
}
3747

3748
int LibMesh::n_bins() const
3749
{
3750
  return m_->n_elem();
3751
}
3752

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

3771
void LibMesh::add_score(const std::string& var_name)
3772
{
3773
  if (!equation_systems_) {
3774
    build_eqn_sys();
3775
  }
3776

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

3786
  std::string std_dev_name = var_name + "_std_dev";
3787
  // check if this is a new variable
3788
  if (!variable_map_.count(std_dev_name)) {
3789
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3790
    auto var_num =
3791
      eqn_sys.add_variable(std_dev_name, libMesh::CONSTANT, libMesh::MONOMIAL);
3792
    variable_map_[std_dev_name] = var_num;
3793
  }
3794
}
3795

3796
void LibMesh::remove_scores()
3797
{
3798
  if (equation_systems_) {
3799
    auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3800
    eqn_sys.clear();
3801
    variable_map_.clear();
3802
  }
3803
}
3804

3805
void LibMesh::set_score_data(const std::string& var_name,
3806
  const vector<double>& values, const vector<double>& std_dev)
3807
{
3808
  if (!equation_systems_) {
3809
    build_eqn_sys();
3810
  }
3811

3812
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
3813

3814
  if (!eqn_sys.is_initialized()) {
3815
    equation_systems_->init();
3816
  }
3817

3818
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
3819

3820
  // look up the value variable
3821
  std::string value_name = var_name + "_mean";
3822
  unsigned int value_num = variable_map_.at(value_name);
3823
  // look up the std dev variable
3824
  std::string std_dev_name = var_name + "_std_dev";
3825
  unsigned int std_dev_num = variable_map_.at(std_dev_name);
3826

3827
  for (auto it = m_->local_elements_begin(); it != m_->local_elements_end();
3828
       it++) {
3829
    if (!(*it)->active()) {
3830
      continue;
3831
    }
3832

3833
    auto bin = get_bin_from_element(*it);
3834

3835
    // set value
3836
    vector<libMesh::dof_id_type> value_dof_indices;
3837
    dof_map.dof_indices(*it, value_dof_indices, value_num);
3838
    assert(value_dof_indices.size() == 1);
3839
    eqn_sys.solution->set(value_dof_indices[0], values.at(bin));
3840

3841
    // set std dev
3842
    vector<libMesh::dof_id_type> std_dev_dof_indices;
3843
    dof_map.dof_indices(*it, std_dev_dof_indices, std_dev_num);
3844
    assert(std_dev_dof_indices.size() == 1);
3845
    eqn_sys.solution->set(std_dev_dof_indices[0], std_dev.at(bin));
3846
  }
3847
}
3848

3849
void LibMesh::write(const std::string& filename) const
3850
{
3851
  write_message(fmt::format(
3852
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
3853
  libMesh::ExodusII_IO exo(*m_);
3854
  std::set<std::string> systems_out = {eq_system_name_};
3855
  exo.write_discontinuous_exodusII(
3856
    filename + ".e", *equation_systems_, &systems_out);
3857
}
3858

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

3866
int LibMesh::get_bin(Position r) const
3867
{
3868
  // look-up a tet using the point locator
3869
  libMesh::Point p(r.x, r.y, r.z);
3870

3871
  if (length_multiplier_ > 0.0) {
3872
    // Scale the point down
3873
    p /= length_multiplier_;
3874
  }
3875

3876
  // quick rejection check
3877
  if (!bbox_.contains_point(p)) {
3878
    return -1;
3879
  }
3880

3881
  const auto& point_locator = pl_.at(thread_num());
3882

3883
  const auto elem_ptr = (*point_locator)(p);
3884
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3885
}
3886

3887
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3888
{
3889
  int bin = elem->id() - first_element_id_;
3890
  if (bin >= n_bins() || bin < 0) {
3891
    fatal_error(fmt::format("Invalid bin: {}", bin));
3892
  }
3893
  return bin;
3894
}
3895

3896
std::pair<vector<double>, vector<double>> LibMesh::plot(
3897
  Position plot_ll, Position plot_ur) const
3898
{
3899
  return {};
3900
}
3901

3902
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
3903
{
3904
  return m_->elem_ref(bin);
3905
}
3906

3907
double LibMesh::volume(int bin) const
3908
{
3909
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
3910
         length_multiplier_ * length_multiplier_;
3911
}
3912

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

3940
int AdaptiveLibMesh::n_bins() const
3941
{
3942
  return num_active_;
3943
}
3944

3945
void AdaptiveLibMesh::add_score(const std::string& var_name)
3946
{
3947
  warning(fmt::format(
3948
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3949
    this->id_));
3950
}
3951

3952
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3953
  const vector<double>& values, const vector<double>& std_dev)
3954
{
3955
  warning(fmt::format(
3956
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3957
    this->id_));
3958
}
3959

3960
void AdaptiveLibMesh::write(const std::string& filename) const
3961
{
3962
  warning(fmt::format(
3963
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3964
    this->id_));
3965
}
3966

3967
int AdaptiveLibMesh::get_bin(Position r) const
3968
{
3969
  // look-up a tet using the point locator
3970
  libMesh::Point p(r.x, r.y, r.z);
3971

3972
  if (length_multiplier_ > 0.0) {
3973
    // Scale the point down
3974
    p /= length_multiplier_;
3975
  }
3976

3977
  // quick rejection check
3978
  if (!bbox_.contains_point(p)) {
3979
    return -1;
3980
  }
3981

3982
  const auto& point_locator = pl_.at(thread_num());
3983

3984
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
3985
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
3986
}
3987

3988
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
3989
{
3990
  int bin = elem_to_bin_map_[elem->id()];
3991
  if (bin >= n_bins() || bin < 0) {
3992
    fatal_error(fmt::format("Invalid bin: {}", bin));
3993
  }
3994
  return bin;
3995
}
3996

3997
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
3998
{
3999
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4000
}
4001

4002
#endif // OPENMC_LIBMESH_ENABLED
4003

4004
//==============================================================================
4005
// Non-member functions
4006
//==============================================================================
4007

4008
void read_meshes(pugi::xml_node root)
2,176✔
4009
{
4010
  std::unordered_set<int> mesh_ids;
2,176✔
4011

4012
  for (auto node : root.children("mesh")) {
2,690✔
4013
    // Check to make sure multiple meshes in the same file don't share IDs
4014
    int id = std::stoi(get_node_value(node, "id"));
1,028✔
4015
    if (contains(mesh_ids, id)) {
1,028!
4016
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4017
                              "'{}' in the same input file",
4018
        id));
4019
    }
4020
    mesh_ids.insert(id);
514✔
4021

4022
    // If we've already read a mesh with the same ID in a *different* file,
4023
    // assume it is the same here
4024
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
514!
4025
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
4026
      continue;
×
4027
    }
4028

4029
    std::string mesh_type;
514✔
4030
    if (check_for_node(node, "type")) {
514✔
4031
      mesh_type = get_node_value(node, "type", true, true);
156✔
4032
    } else {
4033
      mesh_type = "regular";
358✔
4034
    }
4035

4036
    // determine the mesh library to use
4037
    std::string mesh_lib;
514✔
4038
    if (check_for_node(node, "library")) {
514!
UNCOV
4039
      mesh_lib = get_node_value(node, "library", true, true);
×
4040
    }
4041

4042
    Mesh::create(node, mesh_type, mesh_lib);
514✔
4043
  }
514✔
4044
}
2,176✔
4045

4046
void read_meshes(hid_t group)
4✔
4047
{
4048
  std::unordered_set<int> mesh_ids;
4✔
4049

4050
  std::vector<int> ids;
4✔
4051
  read_attribute(group, "ids", ids);
4✔
4052

4053
  for (auto id : ids) {
10✔
4054

4055
    // Check to make sure multiple meshes in the same file don't share IDs
4056
    if (contains(mesh_ids, id)) {
12!
4057
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4058
                              "'{}' in the same HDF5 input file",
4059
        id));
4060
    }
4061
    mesh_ids.insert(id);
6✔
4062

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

4070
    std::string name = fmt::format("mesh {}", id);
×
4071
    hid_t mesh_group = open_group(group, name.c_str());
×
4072

4073
    std::string mesh_type;
×
4074
    if (object_exists(mesh_group, "type")) {
×
4075
      read_dataset(mesh_group, "type", mesh_type);
×
4076
    } else {
4077
      mesh_type = "regular";
×
4078
    }
4079

4080
    // determine the mesh library to use
4081
    std::string mesh_lib;
×
4082
    if (object_exists(mesh_group, "library")) {
×
4083
      read_dataset(mesh_group, "library", mesh_lib);
×
4084
    }
4085

4086
    Mesh::create(mesh_group, mesh_type, mesh_lib);
×
4087
  }
×
4088
}
8✔
4089

4090
void meshes_to_hdf5(hid_t group)
1,388✔
4091
{
4092
  // Write number of meshes
4093
  hid_t meshes_group = create_group(group, "meshes");
1,388✔
4094
  int32_t n_meshes = model::meshes.size();
1,388✔
4095
  write_attribute(meshes_group, "n_meshes", n_meshes);
1,388✔
4096

4097
  if (n_meshes > 0) {
1,388✔
4098
    // Write IDs of meshes
4099
    vector<int> ids;
412✔
4100
    for (const auto& m : model::meshes) {
938✔
4101
      m->to_hdf5(meshes_group);
526✔
4102
      ids.push_back(m->id_);
526✔
4103
    }
4104
    write_attribute(meshes_group, "ids", ids);
412✔
4105
  }
412✔
4106

4107
  close_group(meshes_group);
1,388✔
4108
}
1,388✔
4109

4110
void free_memory_mesh()
1,416✔
4111
{
4112
  model::meshes.clear();
1,416✔
4113
  model::mesh_map.clear();
1,416✔
4114
}
1,416✔
4115

4116
extern "C" int n_meshes()
56✔
4117
{
4118
  return model::meshes.size();
56✔
4119
}
4120

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

© 2026 Coveralls, Inc