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

openmc-dev / openmc / 30591920874

30 Jul 2026 11:53PM UTC coverage: 81.46% (+0.008%) from 81.452%
30591920874

Pull #4037

github

web-flow
Merge 291940efd into ed5b7a299
Pull Request #4037: Fix MPI tally reductions for counts larger than `INT_MAX`

18409 of 26635 branches covered (69.12%)

Branch coverage included in aggregate %.

9 of 9 new or added lines in 5 files covered. (100.0%)

89 existing lines in 2 files now uncovered.

60057 of 69689 relevant lines covered (86.18%)

49197110.36 hits per line

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

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

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

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

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

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

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

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

58
namespace openmc {
59

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

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

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

74
namespace model {
75

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

79
} // namespace model
80

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

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

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

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

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

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

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

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

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

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

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

187
inline void atomic_max_double(double* ptr, double value)
19,280,448✔
188
{
189
  atomic_update_double(ptr, value, false);
6,426,816✔
190
}
6,426,816✔
191

192
inline void atomic_min_double(double* ptr, double value)
19,280,448✔
193
{
194
  atomic_update_double(ptr, value, true);
6,426,816✔
195
}
196

197
namespace detail {
198

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

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

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

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

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

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

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

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

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

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

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

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

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

326
} // namespace detail
327

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

586
              if (compute_bboxes) {
4,118,533✔
587
                double axis_start = r0[axis] + distance * cumulative_frac;
2,912,448✔
588
                double axis_end = axis_start + length;
2,912,448✔
589
                cumulative_frac += length_fractions[i_bin];
2,912,448✔
590

591
                Position contrib_min = site.r;
2,912,448✔
592
                Position contrib_max = site.r;
2,912,448✔
593

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

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

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

612
            if (distance == max_distance)
3,899,883✔
613
              break;
614

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

984
  int num_elem_skipped = 0;
34✔
985

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

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

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

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

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

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

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

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

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

1052
    if (ijk[i] < 1 || ijk[i] > shape_[i])
2,147,483,647✔
1053
      in_mesh = false;
102,389,931✔
1054
  }
1055
  return ijk;
1,790,921,047✔
1056
}
1057

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

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

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

1096
  // Convert indices to bin
1097
  return get_bin_from_indices(ijk);
555,347,882✔
1098
}
1099

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

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

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

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

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

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

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

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

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

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

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

1169
  return counts;
×
1170
}
×
1171

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

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

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

1195
  const int n = n_dimension_;
1,207,715,830✔
1196

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

1200
  // Position is r = r0 + u * traveled_distance, start at r0
1201
  double traveled_distance {0.0};
1,207,715,830✔
1202

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

1207
  // if track is very short, assume that it is completely inside one cell.
1208
  // Only the current cell will score and no surfaces
1209
  if (total_distance < 2 * TINY_BIT) {
1,207,715,830✔
1210
    if (in_mesh) {
675,882✔
1211
      tally.track(ijk, 1.0);
675,398✔
1212
    }
1213
    return;
675,882✔
1214
  }
1215

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

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

1225
    if (in_mesh) {
2,067,929,776✔
1226

1227
      // find surface with minimal distance to current position
1228
      const auto k = std::min_element(distances.begin(), distances.end()) -
1,981,802,133✔
1229
                     distances.begin();
1,981,802,133✔
1230

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

1236
      // update position and leave, if we have reached end position
1237
      traveled_distance = distances[k].distance;
1,981,802,133✔
1238
      if (traveled_distance >= total_distance)
1,981,802,133✔
1239
        return;
1240

1241
      // If we have not reached r1, we have hit a surface. Tally outward
1242
      // current
1243
      tally.surface(ijk, k, distances[k].max_surface, false);
854,052,213✔
1244

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

1251
      // Check if we have left the interior of the mesh
1252
      in_mesh = ((ijk[k] >= 1) && (ijk[k] <= shape_[k]));
860,906,698✔
1253

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

1259
    } else { // not inside mesh
1260

1261
      // For all directions outside the mesh, find the distance that we need
1262
      // to travel to reach the next surface. Use the largest distance, as
1263
      // only this will cross all outer surfaces.
1264
      int k_max {-1};
1265
      for (int k = 0; k < n; ++k) {
343,042,149✔
1266
        if ((ijk[k] < 1 || ijk[k] > shape_[k]) &&
256,914,506✔
1267
            (distances[k].distance > traveled_distance)) {
94,098,532✔
1268
          traveled_distance = distances[k].distance;
1269
          k_max = k;
1270
        }
1271
      }
1272
      // Assure some distance is traveled
1273
      if (k_max == -1) {
86,127,643!
UNCOV
1274
        traveled_distance += TINY_BIT;
×
1275
      }
1276

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

1281
      // Calculate the new cell index and update all distances to next
1282
      // surfaces.
1283
      ijk = get_indices(global_r + (traveled_distance + TINY_BIT) * u, in_mesh);
6,837,615✔
1284
      for (int k = 0; k < n; ++k) {
27,142,461✔
1285
        distances[k] =
20,304,846✔
1286
          distance_to_grid_boundary(ijk, k, local_r, u, traveled_distance);
20,304,846✔
1287
      }
1288

1289
      // If inside the mesh, Tally inward current
1290
      if (in_mesh && k_max >= 0)
6,837,615!
1291
        tally.surface(ijk, k_max, !distances[k_max].max_surface, true);
831,289,994✔
1292
    }
1293
  }
1294
}
1295

1296
void StructuredMesh::bins_crossed(Position r0, Position r1, const Direction& u,
1,149,934,711✔
1297
  vector<int>& bins, vector<double>& lengths) const
1298
{
1299

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

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

1320
  // Perform the mesh raytrace with the helper class.
1321
  raytrace_mesh(r0, r1, u, TrackAggregator(this, bins, lengths));
1,149,934,711✔
1322
}
1,149,934,711✔
1323

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

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

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

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

1355
//==============================================================================
1356
// RegularMesh implementation
1357
//==============================================================================
1358

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

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

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

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

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

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

1394
  } else if (upper_right_.size() > 0) {
2,524!
1395

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

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

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

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

1418
  element_volume_ = 1.0;
2,570✔
1419
  for (int i = 0; i < n_dimension_; i++) {
9,685✔
1420
    element_volume_ *= width_[i];
7,115✔
1421
  }
1422
  return 0;
1423
}
2,570✔
1424

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

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

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

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

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

1455
  } else if (check_for_node(node, "upper_right")) {
2,487!
1456

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

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

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

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

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

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

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

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

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

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

1504
int RegularMesh::get_index_in_direction(double r, int i) const
2,147,483,647✔
1505
{
1506
  if (r <= lower_left_[i])
2,147,483,647✔
1507
    return r == lower_left_[i] ? 1 : 0;
13,754,744✔
1508
  if (r >= upper_right_[i])
2,147,483,647✔
1509
    return r == upper_right_[i] ? shape_[i] : shape_[i] + 1;
11,403,923✔
1510

1511
  return std::ceil((r - lower_left_[i]) / width_[i]);
2,147,483,647✔
1512
}
1513

1514
const std::string RegularMesh::mesh_type = "regular";
1515

1516
std::string RegularMesh::get_mesh_type() const
3,653✔
1517
{
1518
  return mesh_type;
3,653✔
1519
}
1520

1521
double RegularMesh::positive_grid_boundary(const MeshIndex& ijk, int i) const
1,953,050,922✔
1522
{
1523
  return lower_left_[i] + ijk[i] * width_[i];
1,953,050,922✔
1524
}
1525

1526
double RegularMesh::negative_grid_boundary(const MeshIndex& ijk, int i) const
1,883,454,995✔
1527
{
1528
  return lower_left_[i] + (ijk[i] - 1) * width_[i];
1,883,454,995✔
1529
}
1530

1531
StructuredMesh::MeshDistance RegularMesh::distance_to_grid_boundary(
2,147,483,647✔
1532
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1533
  double l) const
1534
{
1535
  MeshDistance d;
2,147,483,647✔
1536
  d.next_index = ijk[i];
2,147,483,647✔
1537
  if (std::abs(u[i]) < FP_PRECISION)
2,147,483,647✔
1538
    return d;
15,280,144✔
1539

1540
  d.max_surface = (u[i] > 0);
2,147,483,647✔
1541
  if (d.max_surface && (ijk[i] <= shape_[i])) {
2,147,483,647✔
1542
    d.next_index++;
1,948,736,328✔
1543
    d.distance = (positive_grid_boundary(ijk, i) - r0[i]) / u[i];
1,948,736,328✔
1544
  } else if (!d.max_surface && (ijk[i] >= 1)) {
1,900,708,993✔
1545
    d.next_index--;
1,879,140,401✔
1546
    d.distance = (negative_grid_boundary(ijk, i) - r0[i]) / u[i];
1,879,140,401✔
1547
  }
1548

1549
  return d;
2,147,483,647✔
1550
}
1551

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

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

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

1590
  return {axis_lines[0], axis_lines[1]};
44✔
1591
}
1592

1593
void RegularMesh::to_hdf5_inner(hid_t mesh_group) const
2,498✔
1594
{
1595
  write_dataset(mesh_group, "dimension", get_shape_tensor());
2,498✔
1596
  write_dataset(mesh_group, "lower_left", lower_left_);
2,498✔
1597
  write_dataset(mesh_group, "upper_right", upper_right_);
2,498✔
1598
  write_dataset(mesh_group, "width", width_);
2,498✔
1599
}
2,498✔
1600

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

1608
  // Create array of zeros
1609
  auto cnt = tensor::zeros<double>(shape);
7,820✔
1610
  bool outside_ = false;
2,892✔
1611

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

1615
    // determine scoring bin for entropy mesh
1616
    int mesh_bin = get_bin(site.r);
7,667,451✔
1617

1618
    // if outside mesh, skip particle
1619
    if (mesh_bin < 0) {
7,667,451!
UNCOV
1620
      outside_ = true;
×
UNCOV
1621
      continue;
×
1622
    }
1623

1624
    // Add to appropriate bin
1625
    cnt(mesh_bin) += site.wgt;
7,667,451✔
1626
  }
1627

1628
  // Create reduced count data
1629
  auto counts = tensor::zeros<double>(shape);
7,820✔
1630
  int total = cnt.size();
7,820✔
1631

1632
#ifdef OPENMC_MPI
1633
  // collect values from all processors
1634
  mpi::reduce(cnt.data(), counts.data(), total, MPI_SUM, 0, mpi::intracomm);
2,892✔
1635

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

1646
  return counts;
7,820✔
1647
}
7,820✔
1648

1649
double RegularMesh::volume(const MeshIndex& ijk) const
1,244,598✔
1650
{
1651
  return element_volume_;
1,244,598✔
1652
}
1653

1654
//==============================================================================
1655
// RectilinearMesh implementation
1656
//==============================================================================
1657

1658
RectilinearMesh::RectilinearMesh(pugi::xml_node node) : StructuredMesh {node}
144✔
1659
{
1660
  n_dimension_ = 3;
144✔
1661

1662
  grid_[0] = get_node_array<double>(node, "x_grid");
144✔
1663
  grid_[1] = get_node_array<double>(node, "y_grid");
144✔
1664
  grid_[2] = get_node_array<double>(node, "z_grid");
144✔
1665

1666
  if (int err = set_grid()) {
144!
UNCOV
1667
    fatal_error(openmc_err_msg);
×
1668
  }
1669
}
144✔
1670

1671
RectilinearMesh::RectilinearMesh(hid_t group) : StructuredMesh {group}
11✔
1672
{
1673
  n_dimension_ = 3;
11✔
1674

1675
  read_dataset(group, "x_grid", grid_[0]);
11✔
1676
  read_dataset(group, "y_grid", grid_[1]);
11✔
1677
  read_dataset(group, "z_grid", grid_[2]);
11✔
1678

1679
  if (int err = set_grid()) {
11!
UNCOV
1680
    fatal_error(openmc_err_msg);
×
1681
  }
1682
}
11✔
1683

1684
const std::string RectilinearMesh::mesh_type = "rectilinear";
1685

1686
std::string RectilinearMesh::get_mesh_type() const
286✔
1687
{
1688
  return mesh_type;
286✔
1689
}
1690

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

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

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

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

1723
int RectilinearMesh::set_grid()
199✔
1724
{
1725
  shape_ = {static_cast<int>(grid_[0].size()) - 1,
199✔
1726
    static_cast<int>(grid_[1].size()) - 1,
199✔
1727
    static_cast<int>(grid_[2].size()) - 1};
199✔
1728

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

1743
  lower_left_ = {grid_[0].front(), grid_[1].front(), grid_[2].front()};
199✔
1744
  upper_right_ = {grid_[0].back(), grid_[1].back(), grid_[2].back()};
199✔
1745

1746
  return 0;
199✔
1747
}
1748

1749
int RectilinearMesh::get_index_in_direction(double r, int i) const
74,109,013✔
1750
{
1751
  return lower_bound_index(grid_[i].begin(), grid_[i].end(), r) + 1;
74,109,013✔
1752
}
1753

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

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

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

1781
  return {axis_lines[0], axis_lines[1]};
22✔
1782
}
1783

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

1791
double RectilinearMesh::volume(const MeshIndex& ijk) const
132✔
1792
{
1793
  double vol {1.0};
132✔
1794

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

1801
//==============================================================================
1802
// CylindricalMesh implementation
1803
//==============================================================================
1804

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

1814
  if (int err = set_grid()) {
411!
UNCOV
1815
    fatal_error(openmc_err_msg);
×
1816
  }
1817
}
411✔
1818

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

1827
  if (int err = set_grid()) {
11!
UNCOV
1828
    fatal_error(openmc_err_msg);
×
1829
  }
1830
}
11✔
1831

1832
const std::string CylindricalMesh::mesh_type = "cylindrical";
1833

1834
std::string CylindricalMesh::get_mesh_type() const
495✔
1835
{
1836
  return mesh_type;
495✔
1837
}
1838

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

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

1849
  Position mapped_r;
47,732,102✔
1850
  mapped_r[0] = std::hypot(r.x, r.y);
47,732,102✔
1851
  mapped_r[2] = r[2];
47,732,102✔
1852

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

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

1863
  idx[1] = sanitize_phi(idx[1]);
47,732,102✔
1864

1865
  return idx;
47,732,102✔
1866
}
1867

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

1874
  double phi_min = this->phi(ijk[1] - 1);
88,110✔
1875
  double phi_max = this->phi(ijk[1]);
88,110✔
1876

1877
  double z_min = this->z(ijk[2] - 1);
88,110✔
1878
  double z_max = this->z(ijk[2]);
88,110✔
1879

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

1886
  double x = r * std::cos(phi);
88,110✔
1887
  double y = r * std::sin(phi);
88,110✔
1888

1889
  return origin_ + Position(x, y, z);
88,110✔
1890
}
1891

1892
double CylindricalMesh::find_r_crossing(
142,588,530✔
1893
  const Position& r, const Direction& u, double l, int shell) const
1894
{
1895

1896
  if ((shell < 0) || (shell > shape_[0]))
142,588,530!
1897
    return INFTY;
1898

1899
  // solve r.x^2 + r.y^2 == r0^2
1900
  // x^2 + 2*s*u*x + s^2*u^2 + s^2*v^2+2*s*v*y + y^2 -r0^2 = 0
1901
  // s^2 * (u^2 + v^2) + 2*s*(u*x+v*y) + x^2+y^2-r0^2 = 0
1902

1903
  const double r0 = grid_[0][shell];
124,674,555✔
1904
  if (r0 == 0.0)
124,674,555✔
1905
    return INFTY;
1906

1907
  const double denominator = u.x * u.x + u.y * u.y;
117,538,470✔
1908

1909
  // Direction of flight is in z-direction. Will never intersect r.
1910
  if (std::abs(denominator) < FP_PRECISION)
117,538,470✔
1911
    return INFTY;
1912

1913
  // inverse of dominator to help the compiler to speed things up
1914
  const double inv_denominator = 1.0 / denominator;
117,479,510✔
1915

1916
  const double p = (u.x * r.x + u.y * r.y) * inv_denominator;
117,479,510✔
1917
  double R = std::sqrt(r.x * r.x + r.y * r.y);
117,479,510✔
1918
  double D = p * p - (R - r0) * (R + r0) * inv_denominator;
117,479,510✔
1919

1920
  if (D < 0.0)
117,479,510✔
1921
    return INFTY;
1922

1923
  D = std::sqrt(D);
107,743,388✔
1924

1925
  // Particle is already on the shell surface; avoid spurious crossing
1926
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
107,743,388✔
1927
    return INFTY;
1928

1929
  // Check -p - D first because it is always smaller as -p + D
1930
  if (-p - D > l)
101,110,014✔
1931
    return -p - D;
1932
  if (-p + D > l)
80,902,409✔
1933
    return -p + D;
50,078,519✔
1934

1935
  return INFTY;
1936
}
1937

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

1945
  shell = sanitize_phi(shell);
43,970,718✔
1946

1947
  const double p0 = grid_[1][shell];
43,970,718✔
1948

1949
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
1950
  // => x(s) * cos(p0) = y(s) * sin(p0)
1951
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
1952
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
1953

1954
  const double c0 = std::cos(p0);
43,970,718✔
1955
  const double s0 = std::sin(p0);
43,970,718✔
1956

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

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

1968
  return INFTY;
1969
}
1970

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

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

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

1992
StructuredMesh::MeshDistance CylindricalMesh::distance_to_grid_boundary(
145,218,236✔
1993
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
1994
  double l) const
1995
{
1996
  if (i == 0) {
145,218,236✔
1997

1998
    return std::min(
142,588,530✔
1999
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
71,294,265✔
2000
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
142,588,530✔
2001

2002
  } else if (i == 1) {
73,923,971✔
2003

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

2009
  } else {
2010
    return find_z_crossing(r0, u, l, ijk[i]);
36,695,758✔
2011
  }
2012
}
2013

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

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

UNCOV
2047
    return OPENMC_E_INVALID_ARGUMENT;
×
2048
  }
2049

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

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

2057
  return 0;
444✔
2058
}
2059

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

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

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

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

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

2088
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2089
  double phi_o = grid_[1][ijk[1]];
792✔
2090

2091
  double z_i = grid_[2][ijk[2] - 1];
792✔
2092
  double z_o = grid_[2][ijk[2]];
792✔
2093

2094
  return 0.5 * (r_o * r_o - r_i * r_i) * (phi_o - phi_i) * (z_o - z_i);
792✔
2095
}
2096

2097
//==============================================================================
2098
// SphericalMesh implementation
2099
//==============================================================================
2100

2101
SphericalMesh::SphericalMesh(pugi::xml_node node)
356✔
2102
  : PeriodicStructuredMesh {node}
356✔
2103
{
2104
  n_dimension_ = 3;
356✔
2105

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

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

2116
SphericalMesh::SphericalMesh(hid_t group) : PeriodicStructuredMesh {group}
11✔
2117
{
2118
  n_dimension_ = 3;
11✔
2119

2120
  read_dataset(group, "r_grid", grid_[0]);
11✔
2121
  read_dataset(group, "theta_grid", grid_[1]);
11✔
2122
  read_dataset(group, "phi_grid", grid_[2]);
11✔
2123
  read_dataset(group, "origin", origin_);
11✔
2124

2125
  if (int err = set_grid()) {
11!
UNCOV
2126
    fatal_error(openmc_err_msg);
×
2127
  }
2128
}
11✔
2129

2130
const std::string SphericalMesh::mesh_type = "spherical";
2131

2132
std::string SphericalMesh::get_mesh_type() const
396✔
2133
{
2134
  return mesh_type;
396✔
2135
}
2136

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

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

2147
  Position mapped_r;
68,592,139✔
2148
  mapped_r[0] = r.norm();
68,592,139✔
2149

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

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

2162
  idx[1] = sanitize_theta(idx[1]);
68,592,139✔
2163
  idx[2] = sanitize_phi(idx[2]);
68,592,139✔
2164

2165
  return idx;
68,592,139✔
2166
}
2167

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

2174
  double theta_min = this->theta(ijk[1] - 1);
110✔
2175
  double theta_max = this->theta(ijk[1]);
110✔
2176

2177
  double phi_min = this->phi(ijk[2] - 1);
110✔
2178
  double phi_max = this->phi(ijk[2]);
110✔
2179

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

2189
  double x = r * std::cos(phi) * sin_theta;
110✔
2190
  double y = r * std::sin(phi) * sin_theta;
110✔
2191
  double z = r * cos_theta;
110✔
2192

2193
  return origin_ + Position(x, y, z);
110✔
2194
}
2195

2196
double SphericalMesh::find_r_crossing(
443,981,934✔
2197
  const Position& r, const Direction& u, double l, int shell) const
2198
{
2199
  if ((shell < 0) || (shell > shape_[0]))
443,981,934✔
2200
    return INFTY;
2201

2202
  // solve |r+s*u| = r0
2203
  // |r+s*u| = |r| + 2*s*r*u + s^2 (|u|==1 !)
2204
  const double r0 = grid_[0][shell];
404,360,836✔
2205
  if (r0 == 0.0)
404,360,836✔
2206
    return INFTY;
2207
  const double p = r.dot(u);
396,682,308✔
2208
  double R = r.norm();
396,682,308✔
2209
  double D = p * p - (R - r0) * (R + r0);
396,682,308✔
2210

2211
  // Particle is already on the shell surface; avoid spurious crossing
2212
  if (std::abs(R - r0) <= RADIAL_MESH_TOL * (1.0 + std::abs(r0)))
396,682,308✔
2213
    return INFTY;
2214

2215
  if (D >= 0.0) {
385,973,654✔
2216
    D = std::sqrt(D);
358,096,706✔
2217
    // Check -p - D first because it is always smaller as -p + D
2218
    if (-p - D > l)
358,096,706✔
2219
      return -p - D;
2220
    if (-p + D > l)
293,783,006✔
2221
      return -p + D;
177,242,142✔
2222
  }
2223

2224
  return INFTY;
2225
}
2226

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

2234
  shell = sanitize_theta(shell);
38,358,540✔
2235

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

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

2247
  const double a = cos_t_2 - u.z * u.z;
38,358,540✔
2248
  const double b = r.dot(u) * cos_t_2 - r.z * u.z;
38,358,540✔
2249
  const double c = r.dot(r) * cos_t_2 - r.z * r.z;
38,358,540✔
2250

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

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

2265
    // no crossing is possible
2266
    return INFTY;
2267
  }
2268

2269
  const double p = b / a;
37,875,992✔
2270
  double D = p * p - c / a;
37,875,992✔
2271

2272
  if (D < 0.0)
37,875,992✔
2273
    return INFTY;
2274

2275
  D = std::sqrt(D);
26,921,004✔
2276

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

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

2288
  return INFTY;
2289
}
2290

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

2298
  shell = sanitize_phi(shell);
39,948,018✔
2299

2300
  const double p0 = grid_[2][shell];
39,948,018✔
2301

2302
  // solve y(s)/x(s) = tan(p0) = sin(p0)/cos(p0)
2303
  // => x(s) * cos(p0) = y(s) * sin(p0)
2304
  // => (y + s * v) * cos(p0) = (x + s * u) * sin(p0)
2305
  // = s * (v * cos(p0) - u * sin(p0)) = - (y * cos(p0) - x * sin(p0))
2306

2307
  const double c0 = std::cos(p0);
39,948,018✔
2308
  const double s0 = std::sin(p0);
39,948,018✔
2309

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

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

2321
  return INFTY;
2322
}
2323

2324
StructuredMesh::MeshDistance SphericalMesh::distance_to_grid_boundary(
332,947,076✔
2325
  const MeshIndex& ijk, int i, const Position& r0, const Direction& u,
2326
  double l) const
2327
{
2328

2329
  if (i == 0) {
332,947,076✔
2330
    return std::min(
443,981,934✔
2331
      MeshDistance(ijk[i] + 1, true, find_r_crossing(r0, u, l, ijk[i])),
221,990,967✔
2332
      MeshDistance(ijk[i] - 1, false, find_r_crossing(r0, u, l, ijk[i] - 1)));
443,981,934✔
2333

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

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

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

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

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

2384
  full_theta_ = (grid_[1].front() == 0.0) && (grid_[1].back() == PI);
389!
2385
  full_phi_ = (grid_[2].front() == 0.0) && (grid_[2].back() == 2 * PI);
389✔
2386

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

2391
  return 0;
389✔
2392
}
2393

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

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

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

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

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

2422
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2423
  double theta_o = grid_[1][ijk[1]];
935✔
2424

2425
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2426
  double phi_o = grid_[2][ijk[2]];
935✔
2427

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

2432
//==============================================================================
2433
// Helper functions for the C API
2434
//==============================================================================
2435

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

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

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

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

2466
//==============================================================================
2467
// C API functions
2468
//==============================================================================
2469

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

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

2478
  return 0;
1,496✔
2479
}
2480

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

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

2505
  return 0;
253✔
2506
}
253✔
2507

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

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

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

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

2537
  // auto-assign new ID
2538
  model::meshes.back()->set_id(-1);
×
2539
  *id = model::meshes.back()->id_;
2540

2541
  return 0;
UNCOV
2542
}
×
2543

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

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

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

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

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

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

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

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

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

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

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

2633
  return 0;
2634
}
2635

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

2643
  int pixel_width = pixels[0];
44✔
2644
  int pixel_height = pixels[1];
44✔
2645

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

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

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

2676
#pragma omp parallel
24✔
2677
  {
20✔
2678
    Position r = xyz;
20✔
2679

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

2690
  return 0;
44✔
2691
}
2692

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

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

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

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

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

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

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

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

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

2770
  // Set material volumes
2771

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

2780
  return 0;
2781
}
220✔
2782

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

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

2794
  m->n_dimension_ = 3;
88✔
2795

2796
  m->grid_[0].reserve(nx);
88✔
2797
  m->grid_[1].reserve(ny);
88✔
2798
  m->grid_[2].reserve(nz);
88✔
2799

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

2810
  int err = m->set_grid();
88✔
2811
  return err;
88✔
2812
}
2813

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

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

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

2835
  return 0;
385✔
2836
}
2837

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

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

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

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

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

2877
  return openmc_structured_mesh_get_grid_impl<SphericalMesh>(
121✔
2878
    index, grid_x, nx, grid_y, ny, grid_z, nz);
121✔
2879
  ;
121✔
2880
}
2881

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

2891
#ifdef OPENMC_DAGMC_ENABLED
2892

2893
const std::string MOABMesh::mesh_lib_type = "moab";
2894

2895
MOABMesh::MOABMesh(pugi::xml_node node) : UnstructuredMesh(node)
24✔
2896
{
2897
  initialize();
24✔
2898
}
24!
2899

2900
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2901
{
2902
  initialize();
×
2903
}
×
2904

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

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

2921
void MOABMesh::initialize()
25✔
2922
{
2923

2924
  // Create the MOAB interface and load data from file
2925
  this->create_interface();
25✔
2926

2927
  // Initialise MOAB error code
2928
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2929

2930
  // Set the dimension
2931
  n_dimension_ = 3;
25✔
2932

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

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

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

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

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

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

2992
  // Determine bounds of mesh
2993
  this->determine_bounds();
25✔
2994
}
25✔
2995

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

3002
  // build acceleration data structures
3003
  compute_barycentric_data(ehs_);
21✔
3004
  build_kdtree(ehs_);
21✔
3005
}
3006

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

3013
  // create MOAB instance
3014
  mbi_ = std::make_shared<moab::Core>();
24!
3015

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

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

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

3040
  // combine into one range
3041
  moab::Range all_tets_and_tris;
21✔
3042
  all_tets_and_tris.merge(all_tets);
21✔
3043
  all_tets_and_tris.merge(all_tris);
21✔
3044

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

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

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

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

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

3085
  // remove duplicate intersection distances
3086
  std::unique(hits.begin(), hits.end());
1,543,584✔
3087

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

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

3100
  double track_len = (end - start).length();
1,543,584✔
3101
  if (track_len == 0.0)
1,543,584!
3102
    return;
721,692✔
3103

3104
  start -= TINY_BIT * dir;
1,543,584✔
3105
  end += TINY_BIT * dir;
1,543,584✔
3106

3107
  vector<double> hits;
1,543,584✔
3108
  intersect_track(start, dir, track_len, hits);
1,543,584✔
3109

3110
  bins.clear();
1,543,584!
3111
  lengths.clear();
1,543,584!
3112

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

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

3139
    // determine the start point for this segment
3140
    current = r0 + u * hit;
4,694,269✔
3141

3142
    if (bin == -1) {
4,694,269✔
3143
      continue;
20,522✔
3144
    }
3145

3146
    bins.push_back(bin);
4,673,747✔
3147
    lengths.push_back(segment_length / track_len);
4,673,747✔
3148
  }
3149

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

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

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

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

3190
  // if no tet is found, return an invalid handle
3191
  return 0;
2,847✔
3192
}
14,634,464✔
3193

3194
double MOABMesh::volume(int bin) const
167,880✔
3195
{
3196
  return tet_volume(get_ent_handle_from_bin(bin));
167,880✔
3197
}
3198

3199
std::string MOABMesh::library() const
34✔
3200
{
3201
  return mesh_lib_type;
34✔
3202
}
3203

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

3208
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3209

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

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

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

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

3247
  return 1.0 / 6.0 * (((p[1] - p[0]) * (p[2] - p[0])) % (p[3] - p[0]));
167,880✔
3248
}
167,880✔
3249

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

3260
void MOABMesh::compute_barycentric_data(const moab::Range& tets)
21✔
3261
{
3262
  moab::ErrorCode rval;
21✔
3263

3264
  baryc_data_.clear();
21!
3265
  baryc_data_.resize(tets.size());
21✔
3266

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

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

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

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

3290
bool MOABMesh::point_in_tet(
260,208,426✔
3291
  const moab::CartVect& r, moab::EntityHandle tet) const
3292
{
3293

3294
  moab::ErrorCode rval;
260,208,426✔
3295

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

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

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

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

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

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

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

3341
int MOABMesh::get_index_from_bin(int bin) const
3342
{
3343
  return bin;
3344
}
3345

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

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

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

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

3380
int MOABMesh::n_bins() const
267,526,773✔
3381
{
3382
  return ehs_.size();
267,526,773✔
3383
}
3384

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

3398
Position MOABMesh::centroid(int bin) const
3399
{
3400
  moab::ErrorCode rval;
3401

3402
  auto tet = this->get_ent_handle_from_bin(bin);
3403

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

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

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

3427
  return {centroid[0], centroid[1], centroid[2]};
3428
}
3429

3430
int MOABMesh::n_vertices() const
845,874✔
3431
{
3432
  return verts_.size();
845,874✔
3433
}
3434

3435
Position MOABMesh::vertex(int id) const
86,227✔
3436
{
3437

3438
  moab::ErrorCode rval;
86,227✔
3439

3440
  moab::EntityHandle vert = verts_[id];
86,227✔
3441

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

3448
  return {coords[0], coords[1], coords[2]};
86,227✔
3449
}
3450

3451
std::vector<int> MOABMesh::connectivity(int bin) const
203,880✔
3452
{
3453
  moab::ErrorCode rval;
203,880✔
3454

3455
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3456

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

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

3470
  return verts;
203,880✔
3471
}
203,880✔
3472

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

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

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

3508
  // return the populated tag handles
3509
  return {value_tag, error_tag};
3510
}
3511

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

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

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

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

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

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

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

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

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

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

3598
#endif
3599

3600
#ifdef OPENMC_LIBMESH_ENABLED
3601

3602
const std::string LibMesh::mesh_lib_type = "libmesh";
3603

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

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

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

3630
  m_ = &input_mesh;
3631
  set_length_multiplier(length_multiplier);
×
3632
  initialize();
×
3633
}
3634

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

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

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

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

3670
  // assuming that unstructured meshes used in OpenMC are 3D
3671
  n_dimension_ = 3;
25✔
3672

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

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

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

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

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

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

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

3741
int LibMesh::n_vertices() const
42,644✔
3742
{
3743
  return m_->n_nodes();
42,644✔
3744
}
3745

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

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

3766
std::string LibMesh::library() const
37✔
3767
{
3768
  return mesh_lib_type;
37✔
3769
}
3770

3771
int LibMesh::n_bins() const
1,788,419✔
3772
{
3773
  return m_->n_elem();
1,788,419✔
3774
}
3775

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

3794
void LibMesh::add_score(const std::string& var_name)
17✔
3795
{
3796
  if (!equation_systems_) {
17!
3797
    build_eqn_sys();
17✔
3798
  }
3799

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

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

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

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

3835
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3836

3837
  if (!eqn_sys.is_initialized()) {
17!
3838
    equation_systems_->init();
17✔
3839
  }
3840

3841
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3842

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

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

3856
    auto bin = get_bin_from_element(*it);
99,856✔
3857

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

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

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

3882
  write_message(fmt::format(
17✔
3883
    "Writing file: {}.e for unstructured mesh {}", filename, this->id_));
17✔
3884
  libMesh::ExodusII_IO exo(*m_);
17✔
3885
  std::set<std::string> systems_out = {eq_system_name_};
34!
3886
  exo.write_discontinuous_exodusII(
17✔
3887
    filename + ".e", *equation_systems_, &systems_out);
34✔
3888
}
17✔
3889

3890
void LibMesh::bins_crossed(Position r0, Position r1, const Direction& u,
3891
  vector<int>& bins, vector<double>& lengths) const
3892
{
3893
  // TODO: Implement triangle crossings here
3894
  fatal_error("Tracklength tallies on libMesh instances are not implemented.");
3895
}
3896

3897
int LibMesh::get_bin(Position r) const
2,340,604✔
3898
{
3899
  // look-up a tet using the point locator
3900
  libMesh::Point p(r.x, r.y, r.z);
2,340,604!
3901

3902
  if (length_multiplier_ > 0.0) {
2,340,604!
3903
    // Scale the point down
3904
    p /= length_multiplier_;
2,340,604✔
3905
  }
3906

3907
  // quick rejection check
3908
  if (!bbox_.contains_point(p)) {
2,340,604✔
3909
    return -1;
3910
  }
3911

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

3914
  const auto elem_ptr = (*point_locator)(p);
1,421,808✔
3915
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
1,421,808✔
3916
}
2,340,604✔
3917

3918
int LibMesh::get_bin_from_element(const libMesh::Elem* elem) const
1,520,434✔
3919
{
3920
  int bin = elem->id() - first_element_id_;
1,520,434✔
3921
  if (bin >= n_bins() || bin < 0) {
1,520,434!
3922
    fatal_error(fmt::format("Invalid bin: {}", bin));
3923
  }
3924
  return bin;
1,520,434✔
3925
}
3926

3927
std::pair<vector<double>, vector<double>> LibMesh::plot(
3928
  Position plot_ll, Position plot_ur) const
3929
{
3930
  return {};
3931
}
3932

3933
const libMesh::Elem& LibMesh::get_element_from_bin(int bin) const
769,460✔
3934
{
3935
  return m_->elem_ref(bin);
769,460✔
3936
}
3937

3938
double LibMesh::volume(int bin) const
368,640✔
3939
{
3940
  return this->get_element_from_bin(bin).volume() * length_multiplier_ *
368,640✔
3941
         length_multiplier_ * length_multiplier_;
368,640✔
3942
}
3943

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

3971
int AdaptiveLibMesh::n_bins() const
3972
{
3973
  return num_active_;
3974
}
3975

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

3983
void AdaptiveLibMesh::set_score_data(const std::string& var_name,
3984
  const vector<double>& values, const vector<double>& std_dev)
3985
{
3986
  warning(fmt::format(
×
3987
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3988
    this->id_));
3989
}
3990

3991
void AdaptiveLibMesh::write(const std::string& filename) const
3992
{
3993
  warning(fmt::format(
×
3994
    "Exodus output cannot be provided as unstructured mesh {} is adaptive.",
3995
    this->id_));
3996
}
3997

3998
int AdaptiveLibMesh::get_bin(Position r) const
3999
{
4000
  // look-up a tet using the point locator
4001
  libMesh::Point p(r.x, r.y, r.z);
×
4002

4003
  if (length_multiplier_ > 0.0) {
×
4004
    // Scale the point down
4005
    p /= length_multiplier_;
4006
  }
4007

4008
  // quick rejection check
4009
  if (!bbox_.contains_point(p)) {
×
4010
    return -1;
4011
  }
4012

4013
  const auto& point_locator = pl_.at(thread_num());
×
4014

4015
  const auto elem_ptr = (*point_locator)(p, &block_ids_);
×
4016
  return elem_ptr ? get_bin_from_element(elem_ptr) : -1;
×
4017
}
4018

4019
int AdaptiveLibMesh::get_bin_from_element(const libMesh::Elem* elem) const
4020
{
4021
  int bin = elem_to_bin_map_[elem->id()];
4022
  if (bin >= n_bins() || bin < 0) {
×
4023
    fatal_error(fmt::format("Invalid bin: {}", bin));
4024
  }
4025
  return bin;
4026
}
4027

4028
const libMesh::Elem& AdaptiveLibMesh::get_element_from_bin(int bin) const
4029
{
4030
  return m_->elem_ref(bin_to_elem_map_.at(bin));
4031
}
4032

4033
#endif // OPENMC_LIBMESH_ENABLED
4034

4035
//==============================================================================
4036
// Non-member functions
4037
//==============================================================================
4038

4039
void read_meshes(pugi::xml_node root)
14,027✔
4040
{
4041
  std::unordered_set<int> mesh_ids;
14,027✔
4042

4043
  for (auto node : root.children("mesh")) {
17,443✔
4044
    // Check to make sure multiple meshes in the same file don't share IDs
4045
    int id = std::stoi(get_node_value(node, "id"));
6,832✔
4046
    if (contains(mesh_ids, id)) {
6,832!
UNCOV
4047
      fatal_error(fmt::format("Two or more meshes use the same unique ID "
×
4048
                              "'{}' in the same input file",
4049
        id));
4050
    }
4051
    mesh_ids.insert(id);
3,416✔
4052

4053
    // If we've already read a mesh with the same ID in a *different* file,
4054
    // assume it is the same here
4055
    if (model::mesh_map.find(id) != model::mesh_map.end()) {
3,416!
UNCOV
4056
      warning(fmt::format("Mesh with ID={} appears in multiple files.", id));
×
UNCOV
4057
      continue;
×
4058
    }
4059

4060
    std::string mesh_type;
3,416✔
4061
    if (check_for_node(node, "type")) {
3,416✔
4062
      mesh_type = get_node_value(node, "type", true, true);
983✔
4063
    } else {
4064
      mesh_type = "regular";
2,433✔
4065
    }
4066

4067
    // determine the mesh library to use
4068
    std::string mesh_lib;
3,416✔
4069
    if (check_for_node(node, "library")) {
3,416✔
4070
      mesh_lib = get_node_value(node, "library", true, true);
49!
4071
    }
4072

4073
    Mesh::create(node, mesh_type, mesh_lib);
3,416✔
4074
  }
3,416✔
4075
}
14,027✔
4076

4077
void read_meshes(hid_t group)
48✔
4078
{
4079
  std::unordered_set<int> mesh_ids;
48✔
4080

4081
  std::vector<int> ids;
48✔
4082
  read_attribute(group, "ids", ids);
48✔
4083

4084
  for (auto id : ids) {
107✔
4085

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

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

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

4104
    std::string mesh_type;
26✔
4105
    if (object_exists(mesh_group, "type")) {
26!
4106
      read_dataset(mesh_group, "type", mesh_type);
26✔
4107
    } else {
UNCOV
4108
      mesh_type = "regular";
×
4109
    }
4110

4111
    // determine the mesh library to use
4112
    std::string mesh_lib;
26✔
4113
    if (object_exists(mesh_group, "library")) {
26!
UNCOV
4114
      read_dataset(mesh_group, "library", mesh_lib);
×
4115
    }
4116

4117
    Mesh::create(mesh_group, mesh_type, mesh_lib);
26✔
4118
  }
26✔
4119
}
96✔
4120

4121
void meshes_to_hdf5(hid_t group)
7,899✔
4122
{
4123
  // Write number of meshes
4124
  hid_t meshes_group = create_group(group, "meshes");
7,899✔
4125
  int32_t n_meshes = model::meshes.size();
7,899✔
4126
  write_attribute(meshes_group, "n_meshes", n_meshes);
7,899✔
4127

4128
  if (n_meshes > 0) {
7,899✔
4129
    // Write IDs of meshes
4130
    vector<int> ids;
2,436✔
4131
    for (const auto& m : model::meshes) {
5,616✔
4132
      m->to_hdf5(meshes_group);
3,180✔
4133
      ids.push_back(m->id_);
3,180✔
4134
    }
4135
    write_attribute(meshes_group, "ids", ids);
2,436✔
4136
  }
2,436✔
4137

4138
  close_group(meshes_group);
7,899✔
4139
}
7,899✔
4140

4141
void free_memory_mesh()
9,159✔
4142
{
4143
  model::meshes.clear();
9,159✔
4144
  model::mesh_map.clear();
9,159✔
4145
}
9,159✔
4146

4147
extern "C" int n_meshes()
308✔
4148
{
4149
  return model::meshes.size();
308✔
4150
}
4151

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