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

openmc-dev / openmc / 32734756650

24 Aug 2026 01:47PM UTC coverage: 81.299% (-0.1%) from 81.425%
32734756650

Pull #3675

github

web-flow
Merge d355de710 into 7ecd3a961
Pull Request #3675: Extend level scattering to support incident photons

18557 of 27030 branches covered (68.65%)

Branch coverage included in aggregate %.

55 of 77 new or added lines in 4 files covered. (71.43%)

738 existing lines in 26 files now uncovered.

60342 of 70018 relevant lines covered (86.18%)

49966364.8 hits per line

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

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

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

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

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

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

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

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

58
namespace openmc {
59

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

64
// Value used to indicate an empty slot in the hash table. We use -2 because
65
// the value -1 is used to indicate a void material.
66
constexpr int32_t EMPTY = -2;
67

68
namespace model {
69

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

73
} // namespace model
74

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

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

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

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

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

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

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

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

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

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

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

181
inline void atomic_max_double(double* ptr, double value)
19,233,576✔
182
{
183
  atomic_update_double(ptr, value, false);
6,411,192✔
184
}
6,411,192✔
185

186
inline void atomic_min_double(double* ptr, double value)
19,233,576✔
187
{
188
  atomic_update_double(ptr, value, true);
6,411,192✔
189
}
190

191
namespace detail {
192

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

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

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

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

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

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

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

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

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

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

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

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

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

320
} // namespace detail
321

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

485
  // Set flag for mesh being contained within model
486
  bool out_of_model = false;
209✔
487

488
#pragma omp parallel
114✔
489
  {
95✔
490
    // Preallocate vector for mesh indices and length fractions and particle
491
    vector<int> bins;
95✔
492
    vector<double> length_fractions;
95✔
493
    Particle p;
95✔
494

495
    SourceSite site;
95✔
496
    site.E = 1.0;
95✔
497
    site.particle = ParticleType::neutron();
95✔
498

499
    for (int axis = 0; axis < 3; ++axis) {
380✔
500
      // Set starting position and direction
501
      site.r = {0.0, 0.0, 0.0};
285✔
502
      site.r[axis] = bbox.min[axis];
285✔
503
      site.u = {0.0, 0.0, 0.0};
285✔
504
      site.u[axis] = 1.0;
285✔
505

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

519
      // Divide rays in first direction over MPI processes by computing starting
520
      // and ending indices
521
      int min_work = n1 / mpi::n_procs;
225✔
522
      int remainder = n1 % mpi::n_procs;
225✔
523
      int n1_local = (mpi::rank < remainder) ? min_work + 1 : min_work;
225!
524
      int i1_start = mpi::rank * min_work + std::min(mpi::rank, remainder);
225!
525
      int i1_end = i1_start + n1_local;
225✔
526

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

534
          p.from_source(&site);
3,062,845✔
535

536
          // Determine particle's location
537
          if (!exhaustive_find_cell(p)) {
3,062,845✔
538
            out_of_model = true;
39,930✔
539
            continue;
39,930✔
540
          }
541

542
          // Set birth cell attribute
543
          if (p.cell_born() == C_NONE)
3,022,915!
544
            p.cell_born() = p.lowest_coord().cell();
3,022,915✔
545

546
          // Initialize last cells from current cell
547
          for (int j = 0; j < p.n_coord(); ++j) {
6,045,830✔
548
            p.cell_last(j) = p.coord(j).cell();
3,022,915✔
549
          }
550
          p.n_coord_last() = p.n_coord();
3,022,915✔
551

552
          while (true) {
4,786,883✔
553
            // Ray trace from r_start to r_end
554
            Position r0 = p.r();
3,904,899✔
555
            double max_distance = bbox.max[axis] - r0[axis];
3,904,899✔
556

557
            // Find the distance to the nearest boundary
558
            BoundaryInfo boundary = distance_to_boundary(p);
3,904,899✔
559

560
            // Advance particle forward
561
            double distance = std::min(boundary.distance(), max_distance);
3,904,899✔
562
            p.move_distance(distance);
3,904,899✔
563

564
            // Determine what mesh elements were crossed by particle
565
            bins.clear();
3,904,899✔
566
            length_fractions.clear();
3,904,899✔
567
            this->bins_crossed(r0, p.r(), p.u(), bins, length_fractions);
3,904,899✔
568

569
            // Add volumes to any mesh elements that were crossed
570
            int i_material = p.material();
3,904,899✔
571
            if (i_material != C_NONE) {
3,904,899✔
572
              i_material = model::materials[i_material]->id();
1,236,597✔
573
            }
574
            double cumulative_frac = 0.0;
3,904,899✔
575
            for (int i_bin = 0; i_bin < bins.size(); i_bin++) {
8,028,448✔
576
              int mesh_index = bins[i_bin];
4,123,549✔
577
              double length = distance * length_fractions[i_bin];
4,123,549✔
578
              double volume = length * d1 * d2;
4,123,549✔
579

580
              if (compute_bboxes) {
4,123,549✔
581
                double axis_start = r0[axis] + distance * cumulative_frac;
2,917,464✔
582
                double axis_end = axis_start + length;
2,917,464✔
583
                cumulative_frac += length_fractions[i_bin];
2,917,464✔
584

585
                Position contrib_min = site.r;
2,917,464✔
586
                Position contrib_max = site.r;
2,917,464✔
587

588
                contrib_min[ax1] = site.r[ax1] - 0.5 * d1;
2,917,464✔
589
                contrib_max[ax1] = site.r[ax1] + 0.5 * d1;
2,917,464✔
590
                contrib_min[ax2] = site.r[ax2] - 0.5 * d2;
2,917,464✔
591
                contrib_max[ax2] = site.r[ax2] + 0.5 * d2;
2,917,464✔
592
                contrib_min[axis] = std::min(axis_start, axis_end);
2,917,464!
593
                contrib_max[axis] = std::max(axis_start, axis_end);
5,834,928!
594

595
                BoundingBox contrib_bbox {contrib_min, contrib_max};
2,917,464✔
596
                contrib_bbox &= bbox;
2,917,464✔
597

598
                result.add_volume(
2,917,464✔
599
                  mesh_index, i_material, volume, &contrib_bbox);
600
              } else {
601
                // Add volume to result
602
                result.add_volume(mesh_index, i_material, volume);
1,206,085✔
603
              }
604
            }
605

606
            if (distance == max_distance)
3,904,899✔
607
              break;
608

609
            // cross next geometric surface
610
            for (int j = 0; j < p.n_coord(); ++j) {
1,763,968✔
611
              p.cell_last(j) = p.coord(j).cell();
881,984✔
612
            }
613
            p.n_coord_last() = p.n_coord();
881,984✔
614

615
            // Set surface that particle is on and adjust coordinate levels
616
            p.surface() = boundary.surface();
881,984✔
617
            p.n_coord() = boundary.coord_level();
881,984✔
618

619
            if (boundary.lattice_translation()[0] != 0 ||
881,984!
620
                boundary.lattice_translation()[1] != 0 ||
881,984!
621
                boundary.lattice_translation()[2] != 0) {
881,984!
622
              // Particle crosses lattice boundary
623
              cross_lattice(p, boundary);
×
624
            } else {
625
              // Particle crosses surface
626
              const auto& surf {model::surfaces[p.surface_index()].get()};
881,984✔
627
              p.cross_surface(*surf);
881,984✔
628
            }
629
          }
881,984✔
630
        }
631
      }
632
    }
633
  }
95✔
634

635
  // Check for errors
636
  if (out_of_model) {
209✔
637
    throw std::runtime_error("Mesh not fully contained in geometry.");
11✔
638
  } else if (result.table_full()) {
198!
UNCOV
639
    throw std::runtime_error("Maximum number of materials for mesh material "
×
UNCOV
640
                             "volume calculation insufficient.");
×
641
  }
642

643
  // Compute time for raytracing
644
  double t_raytrace = timer.elapsed();
198✔
645

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

660
      for (int i = 1; i < mpi::n_procs; ++i) {
×
661
        // Receive material indices and volumes from process i
662
        MPI_Recv(mats.data(), total, MPI_INT32_T, i, i, mpi::intracomm,
×
663
          MPI_STATUS_IGNORE);
664
        MPI_Recv(vols.data(), total, MPI_DOUBLE, i, i, mpi::intracomm,
×
665
          MPI_STATUS_IGNORE);
666
        if (compute_bboxes) {
×
667
          MPI_Recv(recv_bboxes.data(), total_bbox, MPI_DOUBLE, i, i,
×
668
            mpi::intracomm, MPI_STATUS_IGNORE);
669
        }
670

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

704
  // Report time for MPI communication
705
  double t_mpi = timer.elapsed() - t_raytrace;
72✔
706
#else
707
  double t_mpi = 0.0;
108✔
708
#endif
709

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

724
  // Get total time and normalization time
725
  timer.stop();
198✔
726
  double t_total = timer.elapsed();
198✔
727
  double t_norm = t_total - t_raytrace - t_mpi;
198✔
728

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

744
void Mesh::to_hdf5(hid_t group) const
3,379✔
745
{
746
  // Create group for mesh
747
  std::string group_name = fmt::format("mesh {}", id_);
3,379✔
748
  hid_t mesh_group = create_group(group, group_name.c_str());
3,379✔
749

750
  // Write mesh type
751
  write_dataset(mesh_group, "type", this->get_mesh_type());
3,379✔
752

753
  // Write mesh ID
754
  write_attribute(mesh_group, "id", id_);
3,379✔
755

756
  // Write mesh name
757
  write_dataset(mesh_group, "name", name_);
3,379✔
758

759
  // Write mesh data
760
  this->to_hdf5_inner(mesh_group);
3,379✔
761

762
  // Close group
763
  close_group(mesh_group);
3,379✔
764
}
3,379✔
765

766
//==============================================================================
767
// Structured Mesh implementation
768
//==============================================================================
769

770
std::string StructuredMesh::bin_label(int bin) const
5,315,732✔
771
{
772
  MeshIndex ijk = get_indices_from_bin(bin);
5,315,732✔
773

774
  if (n_dimension_ > 2) {
5,315,732✔
775
    return fmt::format("Mesh Index ({}, {}, {})", ijk[0], ijk[1], ijk[2]);
5,299,133✔
776
  } else if (n_dimension_ > 1) {
16,599✔
777
    return fmt::format("Mesh Index ({}, {})", ijk[0], ijk[1]);
16,236✔
778
  } else {
779
    return fmt::format("Mesh Index ({})", ijk[0]);
363✔
780
  }
781
}
782

783
tensor::Tensor<int> StructuredMesh::get_shape_tensor() const
2,949✔
784
{
785
  return tensor::Tensor<int>(shape_.data(), static_cast<size_t>(n_dimension_));
2,949✔
786
}
787

788
Position StructuredMesh::sample_element(
1,438,198✔
789
  const MeshIndex& ijk, uint64_t* seed) const
790
{
791
  // lookup the lower/upper bounds for the mesh element
792
  double x_min = negative_grid_boundary(ijk, 0);
1,438,198✔
793
  double x_max = positive_grid_boundary(ijk, 0);
1,438,198✔
794

795
  double y_min = (n_dimension_ >= 2) ? negative_grid_boundary(ijk, 1) : 0.0;
1,438,198!
796
  double y_max = (n_dimension_ >= 2) ? positive_grid_boundary(ijk, 1) : 0.0;
1,438,198!
797

798
  double z_min = (n_dimension_ == 3) ? negative_grid_boundary(ijk, 2) : 0.0;
1,438,198!
799
  double z_max = (n_dimension_ == 3) ? positive_grid_boundary(ijk, 2) : 0.0;
1,438,198!
800

801
  return {x_min + (x_max - x_min) * prn(seed),
1,438,198✔
802
    y_min + (y_max - y_min) * prn(seed), z_min + (z_max - z_min) * prn(seed)};
1,438,198✔
803
}
804

805
//==============================================================================
806
// Unstructured Mesh implementation
807
//==============================================================================
808

809
UnstructuredMesh::UnstructuredMesh(pugi::xml_node node) : Mesh(node)
49!
810
{
811
  n_dimension_ = 3;
49✔
812

813
  // check the mesh type
814
  if (check_for_node(node, "type")) {
49!
815
    auto temp = get_node_value(node, "type", true, true);
49!
816
    if (temp != mesh_type) {
49!
UNCOV
817
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
818
    }
819
  }
49✔
820

821
  // check if a length unit multiplier was specified
822
  if (check_for_node(node, "length_multiplier")) {
49!
823
    length_multiplier_ = std::stod(get_node_value(node, "length_multiplier"));
×
824
  }
825

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

837
  if (check_for_node(node, "options")) {
49!
838
    options_ = get_node_value(node, "options");
16!
839
  }
840

841
  // check if mesh tally data should be written with
842
  // statepoint files
843
  if (check_for_node(node, "output")) {
49!
UNCOV
844
    output_ = get_node_value_bool(node, "output");
×
845
  }
846
}
49✔
847

UNCOV
848
UnstructuredMesh::UnstructuredMesh(hid_t group) : Mesh(group)
×
849
{
850
  n_dimension_ = 3;
×
851

852
  // check the mesh type
UNCOV
853
  if (object_exists(group, "type")) {
×
854
    std::string temp;
×
UNCOV
855
    read_dataset(group, "type", temp);
×
856
    if (temp != mesh_type) {
×
UNCOV
857
      fatal_error(fmt::format("Invalid mesh type: {}", temp));
×
858
    }
859
  }
×
860

861
  // check if a length unit multiplier was specified
862
  if (object_exists(group, "length_multiplier")) {
×
863
    read_dataset(group, "length_multiplier", length_multiplier_);
×
864
  }
865

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

UNCOV
877
  if (attribute_exists(group, "options")) {
×
UNCOV
878
    read_attribute(group, "options", options_);
×
879
  }
880

881
  // check if mesh tally data should be written with
882
  // statepoint files
883
  if (attribute_exists(group, "output")) {
×
884
    read_attribute(group, "output", output_);
×
885
  }
UNCOV
886
}
×
887

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

910
Position UnstructuredMesh::sample_tet(
601,230✔
911
  std::array<Position, 4> coords, uint64_t* seed) const
912
{
913
  // Uniform distribution
914
  double s = prn(seed);
601,230✔
915
  double t = prn(seed);
601,230✔
916
  double u = prn(seed);
601,230✔
917

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

940
const std::string UnstructuredMesh::mesh_type = "unstructured";
941

942
std::string UnstructuredMesh::get_mesh_type() const
34✔
943
{
944
  return mesh_type;
34✔
945
}
946

UNCOV
947
void UnstructuredMesh::surface_bins_crossed(
×
948
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
949
{
UNCOV
950
  fatal_error("Unstructured mesh surface tallies are not implemented.");
×
951
}
952

953
std::string UnstructuredMesh::bin_label(int bin) const
207,736✔
954
{
955
  return fmt::format("Mesh Index ({})", bin);
207,736✔
956
};
957

958
void UnstructuredMesh::to_hdf5_inner(hid_t mesh_group) const
34✔
959
{
960
  write_dataset(mesh_group, "filename", filename_);
34!
961
  write_dataset(mesh_group, "library", this->library());
34!
962
  if (!options_.empty()) {
34✔
963
    write_attribute(mesh_group, "options", options_);
8✔
964
  }
965

966
  if (length_multiplier_ > 0.0)
34!
UNCOV
967
    write_dataset(mesh_group, "length_multiplier", length_multiplier_);
×
968

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

978
  int num_elem_skipped = 0;
34✔
979

980
  // write element types and connectivity
981
  vector<double> volumes;
34!
982
  tensor::Tensor<int> connectivity(
34✔
983
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(8)});
34!
984
  tensor::Tensor<int> elem_types(
34✔
985
    {static_cast<size_t>(this->n_bins()), static_cast<size_t>(1)});
34!
986
  for (int i = 0; i < this->n_bins(); i++) {
351,770!
987
    auto conn = this->connectivity(i);
351,736!
988

989
    volumes.emplace_back(this->volume(i));
351,736!
990

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

1008
  // warn users that some elements were skipped
1009
  if (num_elem_skipped > 0) {
34!
1010
    warning(fmt::format("The connectivity of {} elements "
×
1011
                        "on mesh {} were not written "
1012
                        "because they are not of type linear tet/hex.",
UNCOV
1013
      num_elem_skipped, this->id_));
×
1014
  }
1015

1016
  write_dataset(mesh_group, "volumes", volumes);
34!
1017
  write_dataset(mesh_group, "connectivity", connectivity);
34!
1018
  write_dataset(mesh_group, "element_types", elem_types);
34!
1019
}
102✔
1020

1021
void UnstructuredMesh::set_length_multiplier(double length_multiplier)
25✔
1022
{
1023
  length_multiplier_ = length_multiplier;
25✔
1024
}
25✔
1025

1026
ElementType UnstructuredMesh::element_type(int bin) const
120,000✔
1027
{
1028
  auto conn = connectivity(bin);
120,000✔
1029

1030
  if (conn.size() == 4)
120,000!
1031
    return ElementType::LINEAR_TET;
UNCOV
1032
  else if (conn.size() == 8)
×
1033
    return ElementType::LINEAR_HEX;
1034
  else
UNCOV
1035
    return ElementType::UNSUPPORTED;
×
1036
}
120,000✔
1037

1038
StructuredMesh::MeshIndex StructuredMesh::get_indices(
1,799,653,180✔
1039
  Position r, bool& in_mesh) const
1040
{
1041
  MeshIndex ijk;
1,799,653,180✔
1042
  in_mesh = true;
1,799,653,180✔
1043
  for (int i = 0; i < n_dimension_; ++i) {
2,147,483,647✔
1044
    ijk[i] = get_index_in_direction(r[i], i);
2,147,483,647✔
1045

1046
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1047
      in_mesh = false;
102,039,409✔
1048
  }
1049
  return ijk;
1,799,653,180✔
1050
}
1051

1052
int StructuredMesh::get_bin_from_indices(const MeshIndex& ijk) const
2,147,483,647✔
1053
{
1054
  switch (n_dimension_) {
2,147,483,647!
1055
  case 1:
824,582✔
1056
    return ijk[0] - 1;
824,582✔
1057
  case 2:
141,543,281✔
1058
    return (ijk[1] - 1) * shape_[0] + ijk[0] - 1;
141,543,281✔
1059
  case 3:
2,147,483,647✔
1060
    return ((ijk[2] - 1) * shape_[1] + (ijk[1] - 1)) * shape_[0] + ijk[0] - 1;
2,147,483,647✔
UNCOV
1061
  default:
×
UNCOV
1062
    throw std::runtime_error {"Invalid number of mesh dimensions"};
×
1063
  }
1064
}
1065

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

1082
int StructuredMesh::get_bin(Position r) const
604,156,747✔
1083
{
1084
  // Determine indices
1085
  bool in_mesh;
604,156,747✔
1086
  MeshIndex ijk = get_indices(r, in_mesh);
604,156,747✔
1087
  if (!in_mesh)
604,156,747✔
1088
    return -1;
1089

1090
  // Convert indices to bin
1091
  return get_bin_from_indices(ijk);
583,098,975✔
1092
}
1093

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

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

1118
tensor::Tensor<double> StructuredMesh::count_sites(
×
1119
  const SourceSite* bank, int64_t length, bool* outside) const
1120
{
1121
  // Determine shape of array for counts
UNCOV
1122
  std::size_t m = this->n_bins();
×
UNCOV
1123
  vector<std::size_t> shape = {m};
×
1124

1125
  // Create array of zeros
UNCOV
1126
  auto cnt = tensor::zeros<double>(shape);
×
1127
  bool outside_ = false;
1128

1129
  for (int64_t i = 0; i < length; i++) {
×
UNCOV
1130
    const auto& site = bank[i];
×
1131

1132
    // determine scoring bin for entropy mesh
UNCOV
1133
    int mesh_bin = get_bin(site.r);
×
1134

1135
    // if outside mesh, skip particle
1136
    if (mesh_bin < 0) {
×
UNCOV
1137
      outside_ = true;
×
UNCOV
1138
      continue;
×
1139
    }
1140

1141
    // Add to appropriate bin
1142
    cnt(mesh_bin) += site.wgt;
×
1143
  }
1144

1145
  // Create reduced count data
UNCOV
1146
  auto counts = tensor::zeros<double>(shape);
×
UNCOV
1147
  int total = cnt.size();
×
1148

1149
#ifdef OPENMC_MPI
1150
  // collect values from all processors
1151
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
×
1152

1153
  // Check if there were sites outside the mesh for any processor
1154
  if (outside) {
×
1155
    MPI_Reduce(&outside_, outside, 1, MPI_C_BOOL, MPI_LOR, 0, mpi::intracomm);
×
1156
  }
1157
#else
1158
  std::copy(cnt.data(), cnt.data() + total, counts.data());
1159
  if (outside)
×
1160
    *outside = outside_;
1161
#endif
1162

UNCOV
1163
  return counts;
×
UNCOV
1164
}
×
1165

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

1179
  // Compute the length of the entire track.
1180
  double total_distance = (r1 - r0).norm();
1,188,676,322✔
1181
  if (total_distance == 0.0 && settings::solver_type != SolverType::RANDOM_RAY)
1,188,676,322✔
1182
    return;
1183

1184
  // keep a copy of the original global position to pass to get_indices,
1185
  // which performs its own transformation to local coordinates
1186
  Position global_r = r0;
1,188,667,929✔
1187
  Position local_r = local_coords(r0);
1,188,667,929✔
1188

1189
  const int n = n_dimension_;
1,188,667,929✔
1190

1191
  // Flag if position is inside the mesh
1192
  bool in_mesh;
1193

1194
  // Position is r = r0 + u * traveled_distance, start at r0
1195
  double traveled_distance {0.0};
1,188,667,929✔
1196

1197
  // Calculate index of current cell. Offset the position a tiny bit in
1198
  // direction of flight
1199
  MeshIndex ijk = get_indices(global_r + TINY_BIT * u, in_mesh);
1,188,667,929✔
1200

1201
  // if track is very short, assume that it is completely inside one cell.
1202
  // Only the current cell will score and no surfaces
1203
  if (total_distance < 2 * TINY_BIT) {
1,188,667,929✔
1204
    if (in_mesh) {
675,816✔
1205
      tally.track(ijk, 1.0);
675,332✔
1206
    }
1207
    return;
675,816✔
1208
  }
1209

1210
  // Calculate initial distances to next surfaces in all three dimensions
1211
  std::array<MeshDistance, 3> distances;
2,147,483,647✔
1212
  for (int k = 0; k < n; ++k) {
2,147,483,647✔
1213
    distances[k] = distance_to_grid_boundary(ijk, k, local_r, u, 0.0);
2,147,483,647✔
1214
  }
1215

1216
  // Loop until r = r1 is eventually reached
1217
  while (true) {
1218

1219
    if (in_mesh) {
2,050,722,498✔
1220

1221
      // find surface with minimal distance to current position
1222
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,964,975,732✔
1223
                     distances.begin();
1,964,975,732✔
1224

1225
      // Tally track length delta since last step
1226
      tally.track(ijk,
1,964,975,732✔
1227
        (std::min(distances[k].distance, total_distance) - traveled_distance) /
2,147,483,647✔
1228
          total_distance);
1229

1230
      // update position and leave, if we have reached end position
1231
      traveled_distance = distances[k].distance;
1,964,975,732✔
1232
      if (traveled_distance >= total_distance)
1,964,975,732✔
1233
        return;
1234

1235
      // If we have not reached r1, we have hit a surface. Tally outward
1236
      // current
1237
      tally.surface(ijk, k, distances[k].max_surface, false);
855,901,881✔
1238

1239
      // Update cell and calculate distance to next surface in k-direction.
1240
      // The two other directions are still valid!
1241
      ijk[k] = distances[k].next_index;
855,901,881✔
1242
      distances[k] =
855,901,881✔
1243
        distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
855,901,881✔
1244

1245
      // Check if we have left the interior of the mesh
1246
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
862,744,193✔
1247

1248
      // If we are still inside the mesh, tally inward current for the next
1249
      // cell
1250
      if (in_mesh)
29,487,799✔
1251
        tally.surface(ijk, k, !distances[k].max_surface, true);
861,322,759✔
1252

1253
    } else { // not inside mesh
1254

1255
      // For all directions outside the mesh, find the distance that we need
1256
      // to travel to reach the next surface. Use the largest distance, as
1257
      // only this will cross all outer surfaces.
1258
      int k_max {-1};
1259
      for (int k = 0; k < n; ++k) {
341,582,188✔
1260
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
255,835,422✔
1261
            (distances[k].distance > traveled_distance)) {
93,676,948✔
1262
          traveled_distance = distances[k].distance;
1263
          k_max = k;
1264
        }
1265
      }
1266
      // Assure some distance is traveled
1267
      if (k_max == -1) {
85,746,766!
UNCOV
1268
        traveled_distance += TINY_BIT;
×
1269
      }
1270

1271
      // If r1 is not inside the mesh, exit here
1272
      if (traveled_distance >= total_distance)
85,746,766✔
1273
        return;
1274

1275
      // Calculate the new cell index and update all distances to next
1276
      // surfaces.
1277
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,828,504✔
1278
      for (int k = 0; k < n; ++k) {
27,108,151✔
1279
        distances[k] =
20,279,647✔
1280
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
20,279,647✔
1281
      }
1282

1283
      // If inside the mesh, Tally inward current
1284
      if (in_mesh && k_max >= 0)
6,828,504!
1285
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
833,218,507✔
1286
    }
1287
  }
1288
}
1289

1290
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,076,565,939✔
1291
  vector<int>& bins, vector<double>& lengths) const
1292
{
1293

1294
  // Helper tally class.
1295
  // stores a pointer to the mesh class and references to bins and lengths
1296
  // parameters. Performs the actual tally through the track method.
1297
  struct TrackAggregator {
1,076,565,939✔
1298
    TrackAggregator(
1,076,565,939✔
1299
      const StructuredMesh* _mesh, vector<int>& _bins, vector<double>& _lengths)
1300
      : mesh(_mesh), bins(_bins), lengths(_lengths)
1,076,565,939✔
1301
    {}
1302
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const {}
1303
    void track(const MeshIndex& ijk, double l) const
1,825,704,807✔
1304
    {
1305
      bins.push_back(mesh->get_bin_from_indices(ijk));
1,825,704,807✔
1306
      lengths.push_back(l);
1,825,704,807✔
1307
    }
1,825,704,807✔
1308

1309
    const StructuredMesh* mesh;
1310
    vector<int>& bins;
1311
    vector<double>& lengths;
1312
  };
1313

1314
  // Perform the mesh raytrace with the helper class.
1315
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,076,565,939✔
1316
}
1,076,565,939✔
1317

1318
void StructuredMesh::surface_bins_crossed(
112,110,383✔
1319
  Position r0, Position r1, const Direction& u, vector<int>& bins) const
1320
{
1321

1322
  // Helper tally class.
1323
  // stores a pointer to the mesh class and a reference to the bins parameter.
1324
  // Performs the actual tally through the surface method.
1325
  struct SurfaceAggregator {
112,110,383✔
1326
    SurfaceAggregator(const StructuredMesh* _mesh, vector<int>& _bins)
112,110,383✔
1327
      : mesh(_mesh), bins(_bins)
112,110,383✔
1328
    {}
1329
    void surface(const MeshIndex& ijk, int k, bool max, bool inward) const
57,982,243✔
1330
    {
1331
      int i_bin =
57,982,243✔
1332
        4 * mesh->n_dimension_ * mesh->get_bin_from_indices(ijk) + 4 * k;
57,982,243✔
1333
      if (max)
57,982,243✔
1334
        i_bin += 2;
28,961,559✔
1335
      if (inward)
57,982,243✔
1336
        i_bin += 1;
28,494,444✔
1337
      bins.push_back(i_bin);
57,982,243✔
1338
    }
57,982,243✔
1339
    void track(const MeshIndex& idx, double l) const {}
1340

1341
    const StructuredMesh* mesh;
1342
    vector<int>& bins;
1343
  };
1344

1345
  // Perform the mesh raytrace with the helper class.
1346
  raytrace_mesh(r0, r1, u, SurfaceAggregator(this, bins));
112,110,383✔
1347
}
112,110,383✔
1348

1349
//==============================================================================
1350
// RegularMesh implementation
1351
//==============================================================================
1352

1353
int RegularMesh::set_grid()
2,581✔
1354
{
1355
  tensor::Tensor<int> shape(shape_.data(), static_cast<size_t>(n_dimension_));
2,581✔
1356

1357
  // Check that dimensions are all greater than zero
1358
  if ((shape <= 0).any()) {
7,743!
UNCOV
1359
    set_errmsg("All entries for a regular mesh dimensions "
×
1360
               "must be positive.");
1361
    return OPENMC_E_INVALID_ARGUMENT;
1362
  }
1363

1364
  // Make sure lower_left and dimension match
1365
  if (lower_left_.size() != n_dimension_) {
2,581!
UNCOV
1366
    set_errmsg("Number of entries in lower_left must be the same "
×
1367
               "as the regular mesh dimensions.");
1368
    return OPENMC_E_INVALID_ARGUMENT;
1369
  }
1370
  if (width_.size() > 0) {
2,581✔
1371

1372
    // Check to ensure width has same dimensions
1373
    if (width_.size() != n_dimension_) {
46!
1374
      set_errmsg("Number of entries on width must be the same as "
×
1375
                 "the regular mesh dimensions.");
1376
      return OPENMC_E_INVALID_ARGUMENT;
1377
    }
1378

1379
    // Check for negative widths
1380
    if ((width_ < 0.0).any()) {
138!
UNCOV
1381
      set_errmsg("Cannot have a negative width on a regular mesh.");
×
1382
      return OPENMC_E_INVALID_ARGUMENT;
1383
    }
1384

1385
    // Set width and upper right coordinate
1386
    upper_right_ = lower_left_ + shape * width_;
138✔
1387

1388
  } else if (upper_right_.size() > 0) {
2,535!
1389

1390
    // Check to ensure upper_right_ has same dimensions
1391
    if (upper_right_.size() != n_dimension_) {
2,535!
UNCOV
1392
      set_errmsg("Number of entries on upper_right must be the "
×
1393
                 "same as the regular mesh dimensions.");
1394
      return OPENMC_E_INVALID_ARGUMENT;
1395
    }
1396

1397
    // Check that upper-right is above lower-left
1398
    if ((upper_right_ < lower_left_).any()) {
7,605!
UNCOV
1399
      set_errmsg(
×
1400
        "The upper_right coordinates of a regular mesh must be greater than "
1401
        "the lower_left coordinates.");
1402
      return OPENMC_E_INVALID_ARGUMENT;
1403
    }
1404

1405
    // Set width
1406
    width_ = (upper_right_ - lower_left_) / shape;
7,605✔
1407
  }
1408

1409
  // Set material volumes
1410
  volume_frac_ = 1.0 / shape.prod();
2,581✔
1411

1412
  element_volume_ = 1.0;
2,581✔
1413
  for (int i = 0; i < n_dimension_; i++) {
9,729✔
1414
    element_volume_ *= width_[i];
7,148✔
1415
  }
1416
  return 0;
1417
}
2,581✔
1418

1419
RegularMesh::RegularMesh(pugi::xml_node node) : StructuredMesh {node}
2,544✔
1420
{
1421
  // Determine number of dimensions for mesh
1422
  if (!check_for_node(node, "dimension")) {
2,544!
UNCOV
1423
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1424
  }
1425

1426
  tensor::Tensor<int> shape = get_node_tensor<int>(node, "dimension");
2,544✔
1427
  int n = n_dimension_ = shape.size();
2,544!
1428
  if (n != 1 && n != 2 && n != 3) {
2,544!
1429
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1430
  }
1431
  std::copy(shape.begin(), shape.end(), shape_.begin());
2,544✔
1432

1433
  // Check for lower-left coordinates
1434
  if (check_for_node(node, "lower_left")) {
2,544!
1435
    // Read mesh lower-left corner location
1436
    lower_left_ = get_node_tensor<double>(node, "lower_left");
2,544✔
1437
  } else {
UNCOV
1438
    fatal_error("Must specify <lower_left> on a mesh.");
×
1439
  }
1440

1441
  if (check_for_node(node, "width")) {
2,544✔
1442
    // Make sure one of upper-right or width were specified
1443
    if (check_for_node(node, "upper_right")) {
46!
1444
      fatal_error("Cannot specify both <upper_right> and <width> on a mesh.");
×
1445
    }
1446

1447
    width_ = get_node_tensor<double>(node, "width");
92✔
1448

1449
  } else if (check_for_node(node, "upper_right")) {
2,498!
1450

1451
    upper_right_ = get_node_tensor<double>(node, "upper_right");
4,996✔
1452

1453
  } else {
UNCOV
1454
    fatal_error("Must specify either <upper_right> or <width> on a mesh.");
×
1455
  }
1456

1457
  if (int err = set_grid()) {
2,544!
UNCOV
1458
    fatal_error(get_errmsg());
×
1459
  }
1460
}
2,544✔
1461

1462
RegularMesh::RegularMesh(hid_t group) : StructuredMesh {group}
37✔
1463
{
1464
  // Determine number of dimensions for mesh
1465
  if (!object_exists(group, "dimension")) {
37!
UNCOV
1466
    fatal_error("Must specify <dimension> on a regular mesh.");
×
1467
  }
1468

1469
  tensor::Tensor<int> shape;
37✔
1470
  read_dataset(group, "dimension", shape);
37✔
1471
  int n = n_dimension_ = shape.size();
37!
1472
  if (n != 1 && n != 2 && n != 3) {
37!
UNCOV
1473
    fatal_error("Mesh must be one, two, or three dimensions.");
×
1474
  }
1475
  std::copy(shape.begin(), shape.end(), shape_.begin());
37✔
1476

1477
  // Check for lower-left coordinates
1478
  if (object_exists(group, "lower_left")) {
37!
1479
    // Read mesh lower-left corner location
1480
    read_dataset(group, "lower_left", lower_left_);
37✔
1481
  } else {
UNCOV
1482
    fatal_error("Must specify lower_left dataset on a mesh.");
×
1483
  }
1484

1485
  if (object_exists(group, "upper_right")) {
37!
1486

1487
    read_dataset(group, "upper_right", upper_right_);
37✔
1488

1489
  } else {
UNCOV
1490
    fatal_error("Must specify either upper_right dataset on a mesh.");
×
1491
  }
1492

1493
  if (int err = set_grid()) {
37!
UNCOV
1494
    fatal_error(get_errmsg());
×
1495
  }
1496
}
37✔
1497

1498
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1499
{
1500
  if (r <= lower_left_[i])
2,147,483,647✔
1501
    return r == lower_left_[i] ? 1 : 0;
13,716,941✔
1502
  if (r >= upper_right_[i])
2,147,483,647✔
1503
    return r == upper_right_[i] ? shape_[i] : shape_[i] + 1;
11,319,685✔
1504

1505
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1506
}
1507

1508
const std::string RegularMesh::mesh_type = "regular";
1509

1510
std::string RegularMesh::get_mesh_type() const
3,664✔
1511
{
1512
  return mesh_type;
3,664✔
1513
}
1514

1515
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,926,205,715✔
1516
{
1517
  return lower_left_[i] + ijk[i] * width_[i];
1,926,205,715✔
1518
}
1519

1520
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,856,483,437✔
1521
{
1522
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,856,483,437✔
1523
}
1524

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

1534
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1535
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1536
    d.next_index++;
1,921,891,121✔
1537
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,921,891,121✔
1538
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,873,618,015✔
1539
    d.next_index--;
1,852,168,843✔
1540
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,852,168,843✔
1541
  }
1542

1543
  return d;
2,147,483,647✔
1544
}
1545

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

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

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

1584
  return {axis_lines[0], axis_lines[1]};
44✔
1585
}
1586

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

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

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

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

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

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

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

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

1626
#ifdef OPENMC_MPI
1627
  // collect values from all processors
1628
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
2,892✔
1629

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

1640
  return counts;
7,820✔
1641
}
7,820✔
1642

1643
double RegularMesh::volume(const MeshIndex& ijk) const
1,244,598✔
1644
{
1645
  return element_volume_;
1,244,598✔
1646
}
1647

1648
//==============================================================================
1649
// RectilinearMesh implementation
1650
//==============================================================================
1651

1652
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
144✔
1653
{
1654
  n_dimension_ = 3;
144✔
1655

1656
  grid_[0] = get_node_array<double>(node, "x_grid");
144✔
1657
  grid_[1] = get_node_array<double>(node, "y_grid");
144✔
1658
  grid_[2] = get_node_array<double>(node, "z_grid");
144✔
1659

1660
  if (int err = set_grid()) {
144!
UNCOV
1661
    fatal_error(get_errmsg());
×
1662
  }
1663
}
144✔
1664

1665
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1666
{
1667
  n_dimension_ = 3;
11✔
1668

1669
  read_dataset(group, "x_grid", grid_[0]);
11✔
1670
  read_dataset(group, "y_grid", grid_[1]);
11✔
1671
  read_dataset(group, "z_grid", grid_[2]);
11✔
1672

1673
  if (int err = set_grid()) {
11!
UNCOV
1674
    fatal_error(get_errmsg());
×
1675
  }
1676
}
11✔
1677

1678
const std::string RectilinearMesh::mesh_type = "rectilinear";
1679

1680
std::string RectilinearMesh::get_mesh_type() const
286✔
1681
{
1682
  return mesh_type;
286✔
1683
}
1684

1685
double RectilinearMesh::positive_grid_boundary(
26,221,162✔
1686
  const MeshIndex& ijk, int i) const
1687
{
1688
  return grid_[i][ijk[i]];
26,221,162✔
1689
}
1690

1691
double RectilinearMesh::negative_grid_boundary(
25,464,714✔
1692
  const MeshIndex& ijk, int i) const
1693
{
1694
  return grid_[i][ijk[i] - 1];
25,464,714✔
1695
}
1696

1697
StructuredMesh::MeshDistance RectilinearMesh::distance_to_grid_boundary(
52,977,749✔
1698
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1699
  double l) const
1700
{
1701
  MeshDistance d;
52,977,749✔
1702
  d.next_index = ijk[i];
52,977,749✔
1703
  if (std::abs(u[i]) < FP_PRECISION)
52,977,749✔
1704
    return d;
571,824✔
1705

1706
  d.max_surface = (u[i] > 0);
52,405,925✔
1707
  if (d.max_surface && (ijk[i] <= shape_[i])) {
52,405,925✔
1708
    d.next_index++;
26,221,162✔
1709
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
26,221,162✔
1710
  } else if (!d.max_surface && (ijk[i] > 0)) {
26,184,763✔
1711
    d.next_index--;
25,464,714✔
1712
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
25,464,714✔
1713
  }
1714
  return d;
52,405,925✔
1715
}
1716

1717
int RectilinearMesh::set_grid()
199✔
1718
{
1719
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
199✔
1720
    static_cast<int>(grid_[1].size()) - 1,
199✔
1721
    static_cast<int>(grid_[2].size()) - 1};
199✔
1722

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

1737
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
199✔
1738
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
199✔
1739

1740
  return 0;
199✔
1741
}
1742

1743
int RectilinearMesh::get_index_in_direction(double r, int i) const
73,540,885✔
1744
{
1745
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
73,540,885✔
1746
}
1747

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

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

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

1775
  return {axis_lines[0], axis_lines[1]};
22✔
1776
}
1777

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

1785
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1786
{
1787
  double vol {1.0};
132✔
1788

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

1795
//==============================================================================
1796
// CylindricalMesh implementation
1797
//==============================================================================
1798

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

1808
  if (int err = set_grid()) {
411!
UNCOV
1809
    fatal_error(get_errmsg());
×
1810
  }
1811
}
411✔
1812

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

1821
  if (int err = set_grid()) {
11!
UNCOV
1822
    fatal_error(get_errmsg());
×
1823
  }
1824
}
11✔
1825

1826
const std::string CylindricalMesh::mesh_type = "cylindrical";
1827

1828
std::string CylindricalMesh::get_mesh_type() const
495✔
1829
{
1830
  return mesh_type;
495✔
1831
}
1832

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

1838
StructuredMesh::MeshIndex CylindricalMesh::get_indices(
47,667,686✔
1839
  Position r, bool& in_mesh) const
1840
{
1841
  r = local_coords(r);
47,667,686✔
1842

1843
  Position mapped_r;
47,667,686✔
1844
  mapped_r[0] = std::hypot(r.x, r.y);
47,667,686✔
1845
  mapped_r[2] = r[2];
47,667,686✔
1846

1847
  if (mapped_r[0] < FP_PRECISION) {
47,667,686!
1848
    mapped_r[1] = 0.0;
1849
  } else {
1850
    mapped_r[1] = std::atan2(r.y, r.x);
47,667,686✔
1851
    if (mapped_r[1] < 0)
47,667,686✔
1852
      mapped_r[1] += 2 * PI;
23,854,556✔
1853
  }
1854

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

1857
  idx[1] = sanitize_phi(idx[1]);
47,667,686✔
1858

1859
  return idx;
47,667,686✔
1860
}
1861

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

1868
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1869
  double phi_max = this->phi(ijk[1]);
88,110✔
1870

1871
  double z_min = this->z(ijk[2] - 1);
88,110✔
1872
  double z_max = this->z(ijk[2]);
88,110✔
1873

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

1880
  double x = r * std::cos(phi);
88,110✔
1881
  double y = r * std::sin(phi);
88,110✔
1882

1883
  return origin_ + Position(x, y, z);
88,110✔
1884
}
1885

1886
double CylindricalMesh::find_r_crossing(
142,409,758✔
1887
  const Position& r, const Direction& u, double l, int shell) const
1888
{
1889

1890
  if ((shell < 0) || (shell > shape_[0]))
142,409,758!
1891
    return INFTY;
1892

1893
  // solve r.x^2 + r.y^2 == r0^2
1894
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1895
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1896

1897
  const double r0 = grid_[0][shell];
124,548,506✔
1898
  if (r0 == 0.0)
124,548,506✔
1899
    return INFTY;
1900

1901
  const double denominator = u.x * u.x + u.y * u.y;
117,412,883✔
1902

1903
  // Direction of flight is in z-direction. Will never intersect r.
1904
  if (std::abs(denominator) < FP_PRECISION)
117,412,883✔
1905
    return INFTY;
1906

1907
  // inverse of dominator to help the compiler to speed things up
1908
  const double inv_denominator = 1.0 / denominator;
117,353,923✔
1909

1910
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,353,923✔
1911
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,353,923✔
1912
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,353,923✔
1913

1914
  if (D < 0.0)
117,353,923✔
1915
    return INFTY;
1916

1917
  D = std::sqrt(D);
107,643,321✔
1918

1919
  // Particle is already on the shell surface; avoid spurious crossing
1920
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,643,321✔
1921
    return INFTY;
1922

1923
  // Check -p - D first because it is always smaller as -p + D
1924
  if (-p - D > l)
101,009,947✔
1925
    return -p - D;
1926
  if (-p + D > l)
80,819,733✔
1927
    return -p + D;
50,041,856✔
1928

1929
  return INFTY;
1930
}
1931

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

1939
  shell = sanitize_phi(shell);
43,811,262✔
1940

1941
  const double p0 = grid_[1][shell];
43,811,262✔
1942

1943
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1944
  // => x(s) * cos(p0) = y(s) * sin(p0)
1945
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1946
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1947

1948
  const double c0 = std::cos(p0);
43,811,262✔
1949
  const double s0 = std::sin(p0);
43,811,262✔
1950

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

1953
  // Check if direction of flight is not parallel to phi surface
1954
  if (std::abs(denominator) > FP_PRECISION) {
43,811,262✔
1955
    const double s = -(r.x * s0 - r.y * c0) / denominator;
43,550,518✔
1956
    // Check if solution is in positive direction of flight and crosses the
1957
    // correct phi surface (not -phi)
1958
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
43,550,518✔
1959
      return s;
20,148,227✔
1960
  }
1961

1962
  return INFTY;
1963
}
1964

1965
StructuredMesh::MeshDistance CylindricalMesh::find_z_crossing(
36,620,210✔
1966
  const Position& r, const Direction& u, double l, int shell) const
1967
{
1968
  MeshDistance d;
36,620,210✔
1969
  d.next_index = shell;
36,620,210✔
1970

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

1975
  d.max_surface = (u.z > 0.0);
35,501,994✔
1976
  if (d.max_surface && (shell <= shape_[2])) {
35,501,994✔
1977
    d.next_index += 1;
16,844,971✔
1978
    d.distance = (grid_[2][shell] - r.z) / u.z;
16,844,971✔
1979
  } else if (!d.max_surface && (shell > 0)) {
18,657,023✔
1980
    d.next_index -= 1;
16,811,223✔
1981
    d.distance = (grid_[2][shell - 1] - r.z) / u.z;
16,811,223✔
1982
  }
1983
  return d;
35,501,994✔
1984
}
1985

1986
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
144,973,574✔
1987
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1988
  double l) const
1989
{
1990
  if (i == 0) {
144,973,574✔
1991

1992
    return std::min(
142,409,758✔
1993
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,204,879✔
1994
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,409,758✔
1995

1996
  } else if (i == 1) {
73,768,695✔
1997

1998
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
37,148,485✔
1999
                      find_phi_crossing(r0, u, l, ijk[i])),
37,148,485✔
2000
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
37,148,485✔
2001
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
74,296,970✔
2002

2003
  } else {
2004
    return find_z_crossing(r0, u, l, ijk[i]);
36,620,210✔
2005
  }
2006
}
2007

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

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

2041
    return OPENMC_E_INVALID_ARGUMENT;
×
2042
  }
2043

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

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

2051
  return 0;
444✔
2052
}
2053

2054
int CylindricalMesh::get_index_in_direction(double r, int i) const
143,003,058✔
2055
{
2056
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
143,003,058✔
2057
}
2058

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

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

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

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

2082
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2083
  double phi_o = grid_[1][ijk[1]];
792✔
2084

2085
  double z_i = grid_[2][ijk[2] - 1];
792✔
2086
  double z_o = grid_[2][ijk[2]];
792✔
2087

2088
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2089
}
2090

2091
//==============================================================================
2092
// SphericalMesh implementation
2093
//==============================================================================
2094

2095
SphericalMesh::SphericalMesh(pugi::xml_node node)
356✔
2096
  : PeriodicStructuredMesh {node}
356✔
2097
{
2098
  n_dimension_ = 3;
356✔
2099

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

2105
  if (int err = set_grid()) {
356!
UNCOV
2106
    fatal_error(get_errmsg());
×
2107
  }
2108
}
356✔
2109

2110
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2111
{
2112
  n_dimension_ = 3;
11✔
2113

2114
  read_dataset(group, "r_grid", grid_[0]);
11✔
2115
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2116
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2117
  read_dataset(group, "origin", origin_);
11✔
2118

2119
  if (int err = set_grid()) {
11!
UNCOV
2120
    fatal_error(get_errmsg());
×
2121
  }
2122
}
11✔
2123

2124
const std::string SphericalMesh::mesh_type = "spherical";
2125

2126
std::string SphericalMesh::get_mesh_type() const
396✔
2127
{
2128
  return mesh_type;
396✔
2129
}
2130

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

2136
StructuredMesh::MeshIndex SphericalMesh::get_indices(
68,528,196✔
2137
  Position r, bool& in_mesh) const
2138
{
2139
  r = local_coords(r);
68,528,196✔
2140

2141
  Position mapped_r;
68,528,196✔
2142
  mapped_r[0] = r.norm();
68,528,196✔
2143

2144
  if (mapped_r[0] < FP_PRECISION) {
68,528,196!
2145
    mapped_r[1] = 0.0;
2146
    mapped_r[2] = 0.0;
2147
  } else {
2148
    mapped_r[1] = std::acos(r.z / mapped_r.x);
68,528,196✔
2149
    mapped_r[2] = std::atan2(r.y, r.x);
68,528,196✔
2150
    if (mapped_r[2] < 0)
68,528,196✔
2151
      mapped_r[2] += 2 * PI;
34,249,050✔
2152
  }
2153

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

2156
  idx[1] = sanitize_theta(idx[1]);
68,528,196✔
2157
  idx[2] = sanitize_phi(idx[2]);
68,528,196✔
2158

2159
  return idx;
68,528,196✔
2160
}
2161

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

2168
  double theta_min = this->theta(ijk[1] - 1);
110✔
2169
  double theta_max = this->theta(ijk[1]);
110✔
2170

2171
  double phi_min = this->phi(ijk[2] - 1);
110✔
2172
  double phi_max = this->phi(ijk[2]);
110✔
2173

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

2183
  double x = r * std::cos(phi) * sin_theta;
110✔
2184
  double y = r * std::sin(phi) * sin_theta;
110✔
2185
  double z = r * cos_theta;
110✔
2186

2187
  return origin_ + Position(x, y, z);
110✔
2188
}
2189

2190
double SphericalMesh::find_r_crossing(
443,813,480✔
2191
  const Position& r, const Direction& u, double l, int shell) const
2192
{
2193
  if ((shell < 0) || (shell > shape_[0]))
443,813,480✔
2194
    return INFTY;
2195

2196
  // solve |r+s*u| = r0
2197
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2198
  const double r0 = grid_[0][shell];
404,251,606✔
2199
  if (r0 == 0.0)
404,251,606✔
2200
    return INFTY;
2201
  const double p = r.dot(u);
396,572,946✔
2202
  double R = r.norm();
396,572,946✔
2203
  double D = p * p - (R - r0) * (R + r0);
396,572,946✔
2204

2205
  // Particle is already on the shell surface; avoid spurious crossing
2206
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,572,946✔
2207
    return INFTY;
2208

2209
  if (D >= 0.0) {
385,864,292✔
2210
    D = std::sqrt(D);
358,027,065✔
2211
    // Check -p - D first because it is always smaller as -p + D
2212
    if (-p - D > l)
358,027,065✔
2213
      return -p - D;
2214
    if (-p + D > l)
293,729,117✔
2215
      return -p + D;
177,217,139✔
2216
  }
2217

2218
  return INFTY;
2219
}
2220

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

2228
  shell = sanitize_theta(shell);
38,223,152✔
2229

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

2237
  const double cos_t = std::cos(grid_[1][shell]);
38,223,152✔
2238
  const bool sgn = std::signbit(cos_t);
38,223,152✔
2239
  const double cos_t_2 = cos_t * cos_t;
38,223,152✔
2240

2241
  const double a = cos_t_2 - u.z * u.z;
38,223,152✔
2242
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,223,152✔
2243
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,223,152✔
2244

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

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

2259
    // no crossing is possible
2260
    return INFTY;
2261
  }
2262

2263
  const double p = b / a;
37,740,604✔
2264
  double D = p * p - c / a;
37,740,604✔
2265

2266
  if (D < 0.0)
37,740,604✔
2267
    return INFTY;
2268

2269
  D = std::sqrt(D);
26,823,456✔
2270

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

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

2282
  return INFTY;
2283
}
2284

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

2292
  shell = sanitize_phi(shell);
39,797,076✔
2293

2294
  const double p0 = grid_[2][shell];
39,797,076✔
2295

2296
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2297
  // => x(s) * cos(p0) = y(s) * sin(p0)
2298
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2299
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2300

2301
  const double c0 = std::cos(p0);
39,797,076✔
2302
  const double s0 = std::sin(p0);
39,797,076✔
2303

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

2306
  // Check if direction of flight is not parallel to phi surface
2307
  if (std::abs(denominator) > FP_PRECISION) {
39,797,076✔
2308
    const double s = -(r.x * s0 - r.y * c0) / denominator;
39,563,084✔
2309
    // Check if solution is in positive direction of flight and crosses the
2310
    // correct phi surface (not -phi)
2311
    if ((s > l) && ((c0 * (r.x + s * u.x) + s0 * (r.y + s * u.y)) > 0.0))
39,563,084✔
2312
      return s;
17,512,440✔
2313
  }
2314

2315
  return INFTY;
2316
}
2317

2318
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,719,684✔
2319
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2320
  double l) const
2321
{
2322

2323
  if (i == 0) {
332,719,684✔
2324
    return std::min(
443,813,480✔
2325
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,906,740✔
2326
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,813,480✔
2327

2328
  } else if (i == 1) {
110,812,944✔
2329
    return std::min(MeshDistance(sanitize_theta(ijk[i] + 1), true,
55,012,991✔
2330
                      find_theta_crossing(r0, u, l, ijk[i])),
55,012,991✔
2331
      MeshDistance(sanitize_theta(ijk[i] - 1), false,
55,012,991✔
2332
        find_theta_crossing(r0, u, l, ijk[i] - 1)));
110,025,982✔
2333

2334
  } else {
2335
    return std::min(MeshDistance(sanitize_phi(ijk[i] + 1), true,
55,799,953✔
2336
                      find_phi_crossing(r0, u, l, ijk[i])),
55,799,953✔
2337
      MeshDistance(sanitize_phi(ijk[i] - 1), false,
55,799,953✔
2338
        find_phi_crossing(r0, u, l, ijk[i] - 1)));
111,599,906✔
2339
  }
2340
}
2341

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

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

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

2378
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
389!
2379
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
389✔
2380

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

2385
  return 0;
389✔
2386
}
2387

2388
int SphericalMesh::get_index_in_direction(double r, int i) const
205,584,588✔
2389
{
2390
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
205,584,588✔
2391
}
2392

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

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

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

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

2416
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2417
  double theta_o = grid_[1][ijk[1]];
935✔
2418

2419
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2420
  double phi_o = grid_[2][ijk[2]];
935✔
2421

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

2426
//==============================================================================
2427
// Helper functions for the C API
2428
//==============================================================================
2429

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

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

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

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

2460
//==============================================================================
2461
// C API functions
2462
//==============================================================================
2463

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

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

2472
  return 0;
1,496✔
2473
}
2474

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

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

2499
  return 0;
253✔
2500
}
253✔
2501

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

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

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

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

2531
  // auto-assign new ID
2532
  model::meshes.back()->set_id(-1);
×
2533
  *id = model::meshes.back()->id_;
2534

2535
  return 0;
UNCOV
2536
}
×
2537

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

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

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

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

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

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

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

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

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

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

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

2627
  return 0;
2628
}
2629

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

2637
  int pixel_width = pixels[0];
44✔
2638
  int pixel_height = pixels[1];
44✔
2639

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

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

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

2670
#pragma omp parallel
24✔
2671
  {
20✔
2672
    Position r = xyz;
20✔
2673

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

2684
  return 0;
44✔
2685
}
2686

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

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

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

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

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

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

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

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

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

2764
  // Set material volumes
2765

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

2774
  return 0;
2775
}
220✔
2776

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

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

2788
  m->n_dimension_ = 3;
88✔
2789

2790
  m->grid_[0].reserve(nx);
88✔
2791
  m->grid_[1].reserve(ny);
88✔
2792
  m->grid_[2].reserve(nz);
88✔
2793

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

2804
  int err = m->set_grid();
88✔
2805
  return err;
88✔
2806
}
2807

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

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

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

2829
  return 0;
385✔
2830
}
2831

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

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

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

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

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

2871
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2872
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2873
  ;
121✔
2874
}
2875

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

2885
#ifdef OPENMC_DAGMC_ENABLED
2886

2887
const std::string MOABMesh::mesh_lib_type = "moab";
2888

2889
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2890
{
2891
  initialize();
24✔
2892
}
24!
2893

2894
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2895
{
2896
  initialize();
×
2897
}
×
2898

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

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

2915
void MOABMesh::initialize()
25✔
2916
{
2917

2918
  // Create the MOAB interface and load data from file
2919
  this->create_interface();
25✔
2920

2921
  // Initialise MOAB error code
2922
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2923

2924
  // Set the dimension
2925
  n_dimension_ = 3;
25✔
2926

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

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

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

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

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

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

2986
  // Determine bounds of mesh
2987
  this->determine_bounds();
25✔
2988
}
25✔
2989

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

2996
  // build acceleration data structures
2997
  compute_barycentric_data(ehs_);
21✔
2998
  build_kdtree(ehs_);
21✔
2999
}
3000

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

3007
  // create MOAB instance
3008
  mbi_ = std::make_shared<moab::Core>();
24!
3009

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

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

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

3034
  // combine into one range
3035
  moab::Range all_tets_and_tris;
21✔
3036
  all_tets_and_tris.merge(all_tets);
21✔
3037
  all_tets_and_tris.merge(all_tris);
21✔
3038

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

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

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

3062
void MOABMesh::intersect_track(const moab::CartVect& start,
1,405,608✔
3063
  const moab::CartVect& dir, double track_len, vector<double>& hits) const
3064
{
3065
  hits.clear();
1,405,608!
3066

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

3079
  // remove duplicate intersection distances
3080
  std::unique(hits.begin(), hits.end());
1,405,608✔
3081

3082
  // sorts by first component of std::pair by default
3083
  std::sort(hits.begin(), hits.end());
1,405,608✔
3084
}
1,405,608✔
3085

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

3094
  double track_len = (end - start).length();
1,405,608✔
3095
  if (track_len == 0.0)
1,405,608!
3096
    return;
661,478✔
3097

3098
  start -= TINY_BIT * dir;
1,405,608✔
3099
  end += TINY_BIT * dir;
1,405,608✔
3100

3101
  vector<double> hits;
1,405,608✔
3102
  intersect_track(start, dir, track_len, hits);
1,405,608✔
3103

3104
  bins.clear();
1,405,608!
3105
  lengths.clear();
1,405,608!
3106

3107
  // if there are no intersections the track may lie entirely
3108
  // within a single tet. If this is the case, apply entire
3109
  // score to that tet and return.
3110
  if (hits.size() == 0) {
1,405,608✔
3111
    Position midpoint = r0 + u * (track_len * 0.5);
661,478✔
3112
    int bin = this->get_bin(midpoint);
661,478✔
3113
    if (bin != -1) {
661,478✔
3114
      bins.push_back(bin);
211,968✔
3115
      lengths.push_back(1.0);
211,968✔
3116
    }
3117
    return;
661,478✔
3118
  }
3119

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

3133
    // determine the start point for this segment
3134
    current = r0 + u * hit;
4,713,001✔
3135

3136
    if (bin == -1) {
4,713,001✔
3137
      continue;
20,954✔
3138
    }
3139

3140
    bins.push_back(bin);
4,692,047✔
3141
    lengths.push_back(segment_length / track_len);
4,692,047✔
3142
  }
3143

3144
  // tally remaining portion of track after last hit if
3145
  // the last segment of the track is in the mesh but doesn't
3146
  // reach the other side of the tet
3147
  if (hits.back() < track_len) {
744,130!
3148
    Position segment_start = r0 + u * hits.back();
744,130✔
3149
    double segment_length = track_len - hits.back();
744,130✔
3150
    Position midpoint = segment_start + u * (segment_length * 0.5);
744,130✔
3151
    int bin = this->get_bin(midpoint);
744,130✔
3152
    if (bin != -1) {
744,130✔
3153
      bins.push_back(bin);
688,365✔
3154
      lengths.push_back(segment_length / track_len);
688,365✔
3155
    }
3156
  }
3157
};
1,405,608✔
3158

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

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

3177
  // loop over the tets in this leaf, returning the containing tet if found
3178
  for (const auto& tet : tets) {
257,906,893✔
3179
    if (point_in_tet(pos, tet)) {
257,904,274✔
3180
      return tet;
6,216,144✔
3181
    }
3182
  }
3183

3184
  // if no tet is found, return an invalid handle
3185
  return 0;
2,619✔
3186
}
14,430,020✔
3187

3188
double MOABMesh::volume(int bin) const
167,880✔
3189
{
3190
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3191
}
3192

3193
std::string MOABMesh::library() const
34✔
3194
{
3195
  return mesh_lib_type;
34✔
3196
}
3197

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

3202
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3203

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

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

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

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

3241
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3242
}
167,880✔
3243

3244
int MOABMesh::get_bin(Position r) const
7,215,010✔
3245
{
3246
  moab::EntityHandle tet = get_tet(r);
7,215,010✔
3247
  if (tet == 0) {
7,215,010✔
3248
    return -1;
3249
  } else {
3250
    return get_bin_from_ent_handle(tet);
6,216,144✔
3251
  }
3252
}
3253

3254
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3255
{
3256
  moab::ErrorCode rval;
21✔
3257

3258
  baryc_data_.clear();
21!
3259
  baryc_data_.resize(tets.size());
21✔
3260

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

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

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

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

3284
bool MOABMesh::point_in_tet(
257,904,274✔
3285
  const moab::CartVect& r, moab::EntityHandle tet) const
3286
{
3287

3288
  moab::ErrorCode rval;
257,904,274✔
3289

3290
  // get tet vertices
3291
  vector<moab::EntityHandle> verts;
257,904,274✔
3292
  rval = mbi_->get_connectivity(&tet, 1, verts);
257,904,274✔
3293
  if (rval != moab::MB_SUCCESS) {
257,904,274!
3294
    warning("Failed to get vertices of tet in umesh: " + filename_);
×
3295
    return false;
3296
  }
3297

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

3309
  // look up barycentric data
3310
  int idx = get_bin_from_ent_handle(tet);
257,904,274✔
3311
  const moab::Matrix3& a_inv = baryc_data_[idx];
257,904,274✔
3312

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

3315
  return (bary_coords[0] >= 0.0 && bary_coords[1] >= 0.0 &&
159,735,131✔
3316
          bary_coords[2] >= 0.0 &&
316,040,001✔
3317
          bary_coords[0] + bary_coords[1] + bary_coords[2] <= 1.0);
21,451,029✔
3318
}
257,904,274✔
3319

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

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

3335
int MOABMesh::get_index_from_bin(int bin) const
3336
{
3337
  return bin;
3338
}
3339

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

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

3357
int MOABMesh::get_bin_from_ent_handle(moab::EntityHandle eh) const
264,360,154✔
3358
{
3359
  int bin = eh - ehs_[0];
264,360,154✔
3360
  if (bin >= n_bins()) {
264,360,154!
3361
    fatal_error(fmt::format("Invalid bin: {}", bin));
3362
  }
3363
  return bin;
264,360,154✔
3364
}
3365

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

3374
int MOABMesh::n_bins() const
265,136,277✔
3375
{
3376
  return ehs_.size();
265,136,277✔
3377
}
3378

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

3392
Position MOABMesh::centroid(int bin) const
3393
{
3394
  moab::ErrorCode rval;
3395

3396
  auto tet = this->get_ent_handle_from_bin(bin);
3397

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

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

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

3421
  return {centroid[0], centroid[1], centroid[2]};
3422
}
3423

3424
int MOABMesh::n_vertices() const
845,874✔
3425
{
3426
  return verts_.size();
845,874✔
3427
}
3428

3429
Position MOABMesh::vertex(int id) const
86,227✔
3430
{
3431

3432
  moab::ErrorCode rval;
86,227✔
3433

3434
  moab::EntityHandle vert = verts_[id];
86,227✔
3435

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

3442
  return {coords[0], coords[1], coords[2]};
86,227✔
3443
}
3444

3445
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3446
{
3447
  moab::ErrorCode rval;
203,880✔
3448

3449
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3450

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

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

3464
  return verts;
203,880✔
3465
}
203,880✔
3466

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

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

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

3502
  // return the populated tag handles
3503
  return {value_tag, error_tag};
3504
}
3505

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

3512
void MOABMesh::remove_scores()
3513
{
3514
  for (const auto& name : tag_names_) {
×
3515
    auto value_name = name + "_mean";
3516
    moab::Tag tag;
3517
    moab::ErrorCode rval = mbi_->tag_get_handle(value_name.c_str(), tag);
×
3518
    if (rval != moab::MB_SUCCESS)
×
3519
      return;
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
    auto std_dev_name = name + "_std_dev";
×
3530
    rval = mbi_->tag_get_handle(std_dev_name.c_str(), tag);
×
3531
    if (rval != moab::MB_SUCCESS) {
×
3532
      auto msg =
3533
        fmt::format("Std. Dev. mesh tag does not exist for the score {}"
3534
                    " on unstructured mesh {}",
3535
          name, id_);
×
3536
    }
3537

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

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

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

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

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

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

3592
#endif
3593

3594
#ifdef OPENMC_LIBMESH_ENABLED
3595

3596
const std::string LibMesh::mesh_lib_type = "libmesh";
3597

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

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

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

3624
  m_ = &input_mesh;
3625
  set_length_multiplier(length_multiplier);
×
3626
  initialize();
×
3627
}
3628

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

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

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

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

3664
  // assuming that unstructured meshes used in OpenMC are 3D
3665
  n_dimension_ = 3;
25✔
3666

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

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

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

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

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

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

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

3735
int LibMesh::n_vertices() const
42,644✔
3736
{
3737
  return m_->n_nodes();
42,644✔
3738
}
3739

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

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

3760
std::string LibMesh::library() const
37✔
3761
{
3762
  return mesh_lib_type;
37✔
3763
}
3764

3765
int LibMesh::n_bins() const
1,799,773✔
3766
{
3767
  return m_->n_elem();
1,799,773✔
3768
}
3769

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

3788
void LibMesh::add_score(const std::string& var_name)
17✔
3789
{
3790
  if (!equation_systems_) {
17!
3791
    build_eqn_sys();
17✔
3792
  }
3793

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

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

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

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

3829
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3830

3831
  if (!eqn_sys.is_initialized()) {
17!
3832
    equation_systems_->init();
17✔
3833
  }
3834

3835
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3836

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

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

3850
    auto bin = get_bin_from_element(*it);
99,856✔
3851

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

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

3866
void LibMesh::write(const std::string& filename) const
17✔
3867
{
3868
  // A serial libMesh communicator considers every OpenMC rank to be its
3869
  // processor 0. Restrict the non-collective write to the OpenMC master in
3870
  // that case. With a parallel communicator, all ranks must participate in
3871
  // libMesh's solution assembly.
3872
  if (settings::libmesh_comm->size() == 1 && !mpi::master) {
17!
3873
    return;
3874
  }
3875

3876
  write_message(fmt::format(
17✔
3877
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3878
  libMesh::ExodusII_IO exo(*m_);
17✔
3879
  std::set<std::string> systems_out = {eq_system_name_};
34!
3880
  exo.write_discontinuous_exodusII(
17✔
3881
    filename + ".e", *equation_systems_, &systems_out);
34✔
3882
}
17✔
3883

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

3891
int LibMesh::get_bin(Position r) const
2,377,206✔
3892
{
3893
  // look-up a tet using the point locator
3894
  libMesh::Point p(r.x, r.y, r.z);
2,377,206!
3895

3896
  if (length_multiplier_ > 0.0) {
2,377,206!
3897
    // Scale the point down
3898
    p /= length_multiplier_;
2,377,206✔
3899
  }
3900

3901
  // quick rejection check
3902
  if (!bbox_.contains_point(p)) {
2,377,206✔
3903
    return -1;
3904
  }
3905

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

3908
  const auto elem_ptr = (*point_locator)(p);
1,433,042✔
3909
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,433,042✔
3910
}
2,377,206✔
3911

3912
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,531,788✔
3913
{
3914
  int bin = elem->id() - first_element_id_;
1,531,788✔
3915
  if (bin >= n_bins() || bin < 0) {
1,531,788!
3916
    fatal_error(fmt::format("Invalid bin: {}", bin));
3917
  }
3918
  return bin;
1,531,788✔
3919
}
3920

3921
std::pair<vector<double>, vector<double>> LibMesh::plot(
3922
  Position plot_ll, Position plot_ur) const
3923
{
3924
  return {};
3925
}
3926

3927
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3928
{
3929
  return m_->elem_ref(bin);
769,460✔
3930
}
3931

3932
double LibMesh::volume(int bin) const
368,640✔
3933
{
3934
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3935
         length_multiplier_ * length_multiplier_;
368,640✔
3936
}
3937

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

3965
int AdaptiveLibMesh::n_bins() const
3966
{
3967
  return num_active_;
3968
}
3969

3970
void AdaptiveLibMesh::add_score(const std::string& var_name)
3971
{
3972
  warning(fmt::format(
×
3973
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3974
    this->id_));
3975
}
3976

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

3985
void AdaptiveLibMesh::write(const std::string& filename) const
3986
{
3987
  warning(fmt::format(
×
3988
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3989
    this->id_));
3990
}
3991

3992
int AdaptiveLibMesh::get_bin(Position r) const
3993
{
3994
  // look-up a tet using the point locator
3995
  libMesh::Point p(r.x, r.y, r.z);
×
3996

3997
  if (length_multiplier_ > 0.0) {
×
3998
    // Scale the point down
3999
    p /= length_multiplier_;
4000
  }
4001

4002
  // quick rejection check
4003
  if (!bbox_.contains_point(p)) {
×
4004
    return -1;
4005
  }
4006

4007
  const auto& point_locator = pl_.at(thread_num());
×
4008

4009
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4010
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4011
}
4012

4013
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4014
{
4015
  int bin = elem_to_bin_map_[elem->id()];
4016
  if (bin >= n_bins() || bin < 0) {
×
4017
    fatal_error(fmt::format("Invalid bin: {}", bin));
4018
  }
4019
  return bin;
4020
}
4021

4022
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4023
{
4024
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4025
}
4026

4027
#endif // OPENMC_LIBMESH_ENABLED
4028

4029
//==============================================================================
4030
// Non-member functions
4031
//==============================================================================
4032

4033
void read_meshes(pugi::xml_node root)
14,148✔
4034
{
4035
  std::unordered_set<int> mesh_ids;
14,148✔
4036

4037
  for (auto node : root.children("mesh")) {
17,575✔
4038
    // Check to make sure multiple meshes in the same file don't share IDs
4039
    int id = std::stoi(get_node_value(node, "id"));
6,854✔
4040
    if (contains(mesh_ids, id)) {
6,854!
UNCOV
4041
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4042
                              "'{}' in the same input file",
4043
        id));
4044
    }
4045
    mesh_ids.insert(id);
3,427✔
4046

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

4054
    std::string mesh_type;
3,427✔
4055
    if (check_for_node(node, "type")) {
3,427✔
4056
      mesh_type = get_node_value(node, "type", true, true);
983✔
4057
    } else {
4058
      mesh_type = "regular";
2,444✔
4059
    }
4060

4061
    // determine the mesh library to use
4062
    std::string mesh_lib;
3,427✔
4063
    if (check_for_node(node, "library")) {
3,427✔
4064
      mesh_lib = get_node_value(node, "library", true, true);
49!
4065
    }
4066

4067
    Mesh::create(node, mesh_type, mesh_lib);
3,427✔
4068
  }
3,427✔
4069
}
14,148✔
4070

4071
void read_meshes(hid_t group)
48✔
4072
{
4073
  std::unordered_set<int> mesh_ids;
48✔
4074

4075
  std::vector<int> ids;
48✔
4076
  read_attribute(group, "ids", ids);
48✔
4077

4078
  for (auto id : ids) {
107✔
4079

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

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

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

4098
    std::string mesh_type;
26✔
4099
    if (object_exists(mesh_group, "type")) {
26!
4100
      read_dataset(mesh_group, "type", mesh_type);
26✔
4101
    } else {
UNCOV
4102
      mesh_type = "regular";
×
4103
    }
4104

4105
    // determine the mesh library to use
4106
    std::string mesh_lib;
26✔
4107
    if (object_exists(mesh_group, "library")) {
26!
4108
      read_dataset(mesh_group, "library", mesh_lib);
×
4109
    }
4110

4111
    Mesh::create(mesh_group, mesh_type, mesh_lib);
26✔
4112
  }
26✔
4113
}
96✔
4114

4115
void meshes_to_hdf5(hid_t group)
7,954✔
4116
{
4117
  // Write number of meshes
4118
  hid_t meshes_group = create_group(group, "meshes");
7,954✔
4119
  int32_t n_meshes = model::meshes.size();
7,954✔
4120
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,954✔
4121

4122
  if (n_meshes > 0) {
7,954✔
4123
    // Write IDs of meshes
4124
    vector<int> ids;
2,447✔
4125
    for (const auto& m : model::meshes) {
5,638✔
4126
      m->to_hdf5(meshes_group);
3,191✔
4127
      ids.push_back(m->id_);
3,191✔
4128
    }
4129
    write_attribute(meshes_group, "ids", ids);
2,447✔
4130
  }
2,447✔
4131

4132
  close_group(meshes_group);
7,954✔
4133
}
7,954✔
4134

4135
void free_memory_mesh()
9,224✔
4136
{
4137
  model::meshes.clear();
9,224✔
4138
  model::mesh_map.clear();
9,224✔
4139
}
9,224✔
4140

4141
extern "C" int n_meshes()
308✔
4142
{
4143
  return model::meshes.size();
308✔
4144
}
4145

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

© 2026 Coveralls, Inc