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

openmc-dev / openmc / 30591285242

30 Jul 2026 11:41PM UTC coverage: 81.457% (+0.003%) from 81.454%
30591285242

push

github

web-flow
Fix get_index_in_direction for regular meshes (#3948)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

18400 of 26629 branches covered (69.1%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

60059 of 69691 relevant lines covered (86.18%)

49193815.99 hits per line

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

71.03
/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,573✔
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,573✔
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,579,725✔
143
{
144
  To out;
145
  std::memcpy(&out, &value, sizeof(To));
37,125✔
146
  return out;
147
}
148

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

192
inline void atomic_min_double(double* ptr, double value)
19,289,736✔
193
{
194
  atomic_update_double(ptr, value, true);
6,429,912✔
195
}
196

197
namespace detail {
198

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

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

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

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

238
    // Slot appears to be empty; attempt to claim
239
    if (current_val == EMPTY) {
1,573!
240
      // Attempt compare-and-swap from EMPTY to index_material
241
      int32_t expected_val = EMPTY;
1,573✔
242
      bool claimed_slot =
1,573✔
243
        atomic_cas_int32(slot_ptr, expected_val, index_material);
1,573✔
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,573!
248
#pragma omp atomic
869✔
249
        this->volumes(index_elem, slot) += volume;
1,573✔
250
        if (bbox) {
1,573✔
251
          atomic_min_double(&this->bboxes(index_elem, slot, 0), bbox->min.x);
175✔
252
          atomic_min_double(&this->bboxes(index_elem, slot, 1), bbox->min.y);
175✔
253
          atomic_min_double(&this->bboxes(index_elem, slot, 2), bbox->min.z);
175✔
254
          atomic_max_double(&this->bboxes(index_elem, slot, 3), bbox->max.x);
175✔
255
          atomic_max_double(&this->bboxes(index_elem, slot, 4), bbox->max.y);
175✔
256
          atomic_max_double(&this->bboxes(index_elem, slot, 5), bbox->max.z);
175✔
257
        }
258
        return;
1,573✔
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,772,003✔
559
            // Ray trace from r_start to r_end
560
            Position r0 = p.r();
3,897,459✔
561
            double max_distance = bbox.max[axis] - r0[axis];
3,897,459✔
562

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

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

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

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

586
              if (compute_bboxes) {
4,116,109✔
587
                double axis_start = r0[axis] + distance * cumulative_frac;
2,910,024✔
588
                double axis_end = axis_start + length;
2,910,024✔
589
                cumulative_frac += length_fractions[i_bin];
2,910,024✔
590

591
                Position contrib_min = site.r;
2,910,024✔
592
                Position contrib_max = site.r;
2,910,024✔
593

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

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

604
                result.add_volume(
2,910,024✔
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,897,459✔
613
              break;
614

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

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

625
            if (boundary.lattice_translation()[0] != 0 ||
874,544!
626
                boundary.lattice_translation()[1] != 0 ||
874,544!
627
                boundary.lattice_translation()[2] != 0) {
874,544!
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()};
874,544✔
633
              p.cross_surface(*surf);
874,544✔
634
            }
635
          }
874,544✔
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,924,143✔
1045
  Position r, bool& in_mesh) const
1046
{
1047
  MeshIndex ijk;
1,790,924,143✔
1048
  in_mesh = true;
1,790,924,143✔
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,924,143✔
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(
×
1158
    cnt.data(), counts.data(), total, MPI_DOUBLE, MPI_SUM, 0, mpi::intracomm);
×
1159

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

1170
  return counts;
×
1171
}
×
1172

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

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

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

1196
  const int n = n_dimension_;
1,207,718,926✔
1197

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

1201
  // Position is r = r0 + u * traveled_distance, start at r0
1202
  double traveled_distance {0.0};
1,207,718,926✔
1203

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

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

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

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

1226
    if (in_mesh) {
2,067,932,872✔
1227

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

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

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

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

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

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

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

1260
    } else { // not inside mesh
1261

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1648
  return counts;
7,820✔
1649
}
7,820✔
1650

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

1656
//==============================================================================
1657
// RectilinearMesh implementation
1658
//==============================================================================
1659

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

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

1668
  if (int err = set_grid()) {
144!
1669
    fatal_error(openmc_err_msg);
×
1670
  }
1671
}
144✔
1672

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

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

1681
  if (int err = set_grid()) {
11!
1682
    fatal_error(openmc_err_msg);
×
1683
  }
1684
}
11✔
1685

1686
const std::string RectilinearMesh::mesh_type = "rectilinear";
1687

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

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

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

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

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

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

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

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

1748
  return 0;
199✔
1749
}
1750

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

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

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

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

1783
  return {axis_lines[0], axis_lines[1]};
22✔
1784
}
1785

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

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

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

1803
//==============================================================================
1804
// CylindricalMesh implementation
1805
//==============================================================================
1806

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

1816
  if (int err = set_grid()) {
411!
1817
    fatal_error(openmc_err_msg);
×
1818
  }
1819
}
411✔
1820

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

1829
  if (int err = set_grid()) {
11!
1830
    fatal_error(openmc_err_msg);
×
1831
  }
1832
}
11✔
1833

1834
const std::string CylindricalMesh::mesh_type = "cylindrical";
1835

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

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

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

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

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

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

1865
  idx[1] = sanitize_phi(idx[1]);
47,732,102✔
1866

1867
  return idx;
47,732,102✔
1868
}
1869

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1922
  if (D < 0.0)
117,479,510✔
1923
    return INFTY;
1924

1925
  D = std::sqrt(D);
107,743,388✔
1926

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

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

1937
  return INFTY;
1938
}
1939

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

1947
  shell = sanitize_phi(shell);
43,970,718✔
1948

1949
  const double p0 = grid_[1][shell];
43,970,718✔
1950

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

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

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

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

1970
  return INFTY;
1971
}
1972

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

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

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

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

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

2004
  } else if (i == 1) {
73,923,971✔
2005

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

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

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

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

2049
    return OPENMC_E_INVALID_ARGUMENT;
×
2050
  }
2051

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

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

2059
  return 0;
444✔
2060
}
2061

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

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

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

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

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

2090
  double phi_i = grid_[1][ijk[1] - 1];
792✔
2091
  double phi_o = grid_[1][ijk[1]];
792✔
2092

2093
  double z_i = grid_[2][ijk[2] - 1];
792✔
2094
  double z_o = grid_[2][ijk[2]];
792✔
2095

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

2099
//==============================================================================
2100
// SphericalMesh implementation
2101
//==============================================================================
2102

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

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

2113
  if (int err = set_grid()) {
356!
2114
    fatal_error(openmc_err_msg);
×
2115
  }
2116
}
356✔
2117

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

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

2127
  if (int err = set_grid()) {
11!
2128
    fatal_error(openmc_err_msg);
×
2129
  }
2130
}
11✔
2131

2132
const std::string SphericalMesh::mesh_type = "spherical";
2133

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

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

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

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

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

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

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

2167
  return idx;
68,592,139✔
2168
}
2169

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

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

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

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

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

2195
  return origin_ + Position(x, y, z);
110✔
2196
}
2197

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

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

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

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

2226
  return INFTY;
2227
}
2228

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

2236
  shell = sanitize_theta(shell);
38,358,540✔
2237

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

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

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

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

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

2267
    // no crossing is possible
2268
    return INFTY;
2269
  }
2270

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

2274
  if (D < 0.0)
37,875,992✔
2275
    return INFTY;
2276

2277
  D = std::sqrt(D);
26,921,004✔
2278

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

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

2290
  return INFTY;
2291
}
2292

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

2300
  shell = sanitize_phi(shell);
39,948,018✔
2301

2302
  const double p0 = grid_[2][shell];
39,948,018✔
2303

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

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

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

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

2323
  return INFTY;
2324
}
2325

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

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

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

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

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

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

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

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

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

2393
  return 0;
389✔
2394
}
2395

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

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

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

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

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

2424
  double theta_i = grid_[1][ijk[1] - 1];
935✔
2425
  double theta_o = grid_[1][ijk[1]];
935✔
2426

2427
  double phi_i = grid_[2][ijk[2] - 1];
935✔
2428
  double phi_o = grid_[2][ijk[2]];
935✔
2429

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

2434
//==============================================================================
2435
// Helper functions for the C API
2436
//==============================================================================
2437

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

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

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

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

2468
//==============================================================================
2469
// C API functions
2470
//==============================================================================
2471

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

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

2480
  return 0;
1,496✔
2481
}
2482

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

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

2507
  return 0;
253✔
2508
}
253✔
2509

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

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

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

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

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

2543
  return 0;
2544
}
×
2545

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

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

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

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

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

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

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

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

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

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

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

2635
  return 0;
2636
}
2637

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

2645
  int pixel_width = pixels[0];
44✔
2646
  int pixel_height = pixels[1];
44✔
2647

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

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

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

2678
#pragma omp parallel
24✔
2679
  {
20✔
2680
    Position r = xyz;
20✔
2681

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

2692
  return 0;
44✔
2693
}
2694

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

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

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

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

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

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

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

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

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

2772
  // Set material volumes
2773

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

2782
  return 0;
2783
}
220✔
2784

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

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

2796
  m->n_dimension_ = 3;
88✔
2797

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

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

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

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

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

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

2837
  return 0;
385✔
2838
}
2839

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

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

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

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

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

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

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

2893
#ifdef OPENMC_DAGMC_ENABLED
2894

2895
const std::string MOABMesh::mesh_lib_type = "moab";
2896

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

2902
MOABMesh::MOABMesh(hid_t group) : UnstructuredMesh(group)
×
2903
{
2904
  initialize();
×
2905
}
×
2906

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

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

2923
void MOABMesh::initialize()
25✔
2924
{
2925

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

2929
  // Initialise MOAB error code
2930
  moab::ErrorCode rval = moab::MB_SUCCESS;
25✔
2931

2932
  // Set the dimension
2933
  n_dimension_ = 3;
25✔
2934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3106
  start -= TINY_BIT * dir;
1,543,584✔
3107
  end += TINY_BIT * dir;
1,543,584✔
3108

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

3112
  bins.clear();
1,543,584!
3113
  lengths.clear();
1,543,584!
3114

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

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

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

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

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

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

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

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

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

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

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

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

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

3210
  moab::EntityHandle tet_ent = get_ent_handle_from_bin(bin);
200,410✔
3211

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

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

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

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

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

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

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

3266
  baryc_data_.clear();
21!
3267
  baryc_data_.resize(tets.size());
21✔
3268

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

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

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

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

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

3296
  moab::ErrorCode rval;
260,208,426✔
3297

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

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

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

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

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

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

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

3343
int MOABMesh::get_index_from_bin(int bin) const
3344
{
3345
  return bin;
3346
}
3347

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

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

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

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

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

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

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

3404
  auto tet = this->get_ent_handle_from_bin(bin);
3405

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

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

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

3429
  return {centroid[0], centroid[1], centroid[2]};
3430
}
3431

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

3437
Position MOABMesh::vertex(int id) const
86,227✔
3438
{
3439

3440
  moab::ErrorCode rval;
86,227✔
3441

3442
  moab::EntityHandle vert = verts_[id];
86,227✔
3443

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

3450
  return {coords[0], coords[1], coords[2]};
86,227✔
3451
}
3452

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

3457
  auto tet = get_ent_handle_from_bin(bin);
203,880✔
3458

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

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

3472
  return verts;
203,880✔
3473
}
203,880✔
3474

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

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

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

3510
  // return the populated tag handles
3511
  return {value_tag, error_tag};
3512
}
3513

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

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

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

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

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

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

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

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

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

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

3600
#endif
3601

3602
#ifdef OPENMC_LIBMESH_ENABLED
3603

3604
const std::string LibMesh::mesh_lib_type = "libmesh";
3605

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

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

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

3632
  m_ = &input_mesh;
3633
  set_length_multiplier(length_multiplier);
×
3634
  initialize();
×
3635
}
3636

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3837
  auto& eqn_sys = equation_systems_->get_system(eq_system_name_);
17✔
3838

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

3843
  const libMesh::DofMap& dof_map = eqn_sys.get_dof_map();
17✔
3844

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

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

3858
    auto bin = get_bin_from_element(*it);
99,856✔
3859

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3973
int AdaptiveLibMesh::n_bins() const
3974
{
3975
  return num_active_;
3976
}
3977

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

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

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

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

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

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

4015
  const auto& point_locator = pl_.at(thread_num());
×
4016

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

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

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

4035
#endif // OPENMC_LIBMESH_ENABLED
4036

4037
//==============================================================================
4038
// Non-member functions
4039
//==============================================================================
4040

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

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

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

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

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

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

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

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

4086
  for (auto id : ids) {
107✔
4087

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

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

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

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

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

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

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

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

4140
  close_group(meshes_group);
7,899✔
4141
}
7,899✔
4142

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

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

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